repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
tjstyle/FIH-Kernel | arch/ia64/kvm/process.c | 1581 | 25111 | /*
* process.c: handle interruption inject for guests.
* Copyright (c) 2005, Intel Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307 USA.
*
* Shaofan Li (Susue Li) <susie.li@intel.com>
* Xiaoyan Feng (Fleming Feng) <fleming.feng@intel.com>
* Xuefei Xu (Anthony Xu) (Anthony.xu@intel.com)
* Xiantao Zhang (xiantao.zhang@intel.com)
*/
#include "vcpu.h"
#include <asm/pal.h>
#include <asm/sal.h>
#include <asm/fpswa.h>
#include <asm/kregs.h>
#include <asm/tlb.h>
fpswa_interface_t *vmm_fpswa_interface;
#define IA64_VHPT_TRANS_VECTOR 0x0000
#define IA64_INST_TLB_VECTOR 0x0400
#define IA64_DATA_TLB_VECTOR 0x0800
#define IA64_ALT_INST_TLB_VECTOR 0x0c00
#define IA64_ALT_DATA_TLB_VECTOR 0x1000
#define IA64_DATA_NESTED_TLB_VECTOR 0x1400
#define IA64_INST_KEY_MISS_VECTOR 0x1800
#define IA64_DATA_KEY_MISS_VECTOR 0x1c00
#define IA64_DIRTY_BIT_VECTOR 0x2000
#define IA64_INST_ACCESS_BIT_VECTOR 0x2400
#define IA64_DATA_ACCESS_BIT_VECTOR 0x2800
#define IA64_BREAK_VECTOR 0x2c00
#define IA64_EXTINT_VECTOR 0x3000
#define IA64_PAGE_NOT_PRESENT_VECTOR 0x5000
#define IA64_KEY_PERMISSION_VECTOR 0x5100
#define IA64_INST_ACCESS_RIGHTS_VECTOR 0x5200
#define IA64_DATA_ACCESS_RIGHTS_VECTOR 0x5300
#define IA64_GENEX_VECTOR 0x5400
#define IA64_DISABLED_FPREG_VECTOR 0x5500
#define IA64_NAT_CONSUMPTION_VECTOR 0x5600
#define IA64_SPECULATION_VECTOR 0x5700 /* UNUSED */
#define IA64_DEBUG_VECTOR 0x5900
#define IA64_UNALIGNED_REF_VECTOR 0x5a00
#define IA64_UNSUPPORTED_DATA_REF_VECTOR 0x5b00
#define IA64_FP_FAULT_VECTOR 0x5c00
#define IA64_FP_TRAP_VECTOR 0x5d00
#define IA64_LOWERPRIV_TRANSFER_TRAP_VECTOR 0x5e00
#define IA64_TAKEN_BRANCH_TRAP_VECTOR 0x5f00
#define IA64_SINGLE_STEP_TRAP_VECTOR 0x6000
/* SDM vol2 5.5 - IVA based interruption handling */
#define INITIAL_PSR_VALUE_AT_INTERRUPTION (IA64_PSR_UP | IA64_PSR_MFL |\
IA64_PSR_MFH | IA64_PSR_PK | IA64_PSR_DT | \
IA64_PSR_RT | IA64_PSR_MC|IA64_PSR_IT)
#define DOMN_PAL_REQUEST 0x110000
#define DOMN_SAL_REQUEST 0x110001
static u64 vec2off[68] = {0x0, 0x400, 0x800, 0xc00, 0x1000, 0x1400, 0x1800,
0x1c00, 0x2000, 0x2400, 0x2800, 0x2c00, 0x3000, 0x3400, 0x3800, 0x3c00,
0x4000, 0x4400, 0x4800, 0x4c00, 0x5000, 0x5100, 0x5200, 0x5300, 0x5400,
0x5500, 0x5600, 0x5700, 0x5800, 0x5900, 0x5a00, 0x5b00, 0x5c00, 0x5d00,
0x5e00, 0x5f00, 0x6000, 0x6100, 0x6200, 0x6300, 0x6400, 0x6500, 0x6600,
0x6700, 0x6800, 0x6900, 0x6a00, 0x6b00, 0x6c00, 0x6d00, 0x6e00, 0x6f00,
0x7000, 0x7100, 0x7200, 0x7300, 0x7400, 0x7500, 0x7600, 0x7700, 0x7800,
0x7900, 0x7a00, 0x7b00, 0x7c00, 0x7d00, 0x7e00, 0x7f00
};
static void collect_interruption(struct kvm_vcpu *vcpu)
{
u64 ipsr;
u64 vdcr;
u64 vifs;
unsigned long vpsr;
struct kvm_pt_regs *regs = vcpu_regs(vcpu);
vpsr = vcpu_get_psr(vcpu);
vcpu_bsw0(vcpu);
if (vpsr & IA64_PSR_IC) {
/* Sync mpsr id/da/dd/ss/ed bits to vipsr
* since after guest do rfi, we still want these bits on in
* mpsr
*/
ipsr = regs->cr_ipsr;
vpsr = vpsr | (ipsr & (IA64_PSR_ID | IA64_PSR_DA
| IA64_PSR_DD | IA64_PSR_SS
| IA64_PSR_ED));
vcpu_set_ipsr(vcpu, vpsr);
/* Currently, for trap, we do not advance IIP to next
* instruction. That's because we assume caller already
* set up IIP correctly
*/
vcpu_set_iip(vcpu , regs->cr_iip);
/* set vifs.v to zero */
vifs = VCPU(vcpu, ifs);
vifs &= ~IA64_IFS_V;
vcpu_set_ifs(vcpu, vifs);
vcpu_set_iipa(vcpu, VMX(vcpu, cr_iipa));
}
vdcr = VCPU(vcpu, dcr);
/* Set guest psr
* up/mfl/mfh/pk/dt/rt/mc/it keeps unchanged
* be: set to the value of dcr.be
* pp: set to the value of dcr.pp
*/
vpsr &= INITIAL_PSR_VALUE_AT_INTERRUPTION;
vpsr |= (vdcr & IA64_DCR_BE);
/* VDCR pp bit position is different from VPSR pp bit */
if (vdcr & IA64_DCR_PP) {
vpsr |= IA64_PSR_PP;
} else {
vpsr &= ~IA64_PSR_PP;
}
vcpu_set_psr(vcpu, vpsr);
}
void inject_guest_interruption(struct kvm_vcpu *vcpu, u64 vec)
{
u64 viva;
struct kvm_pt_regs *regs;
union ia64_isr pt_isr;
regs = vcpu_regs(vcpu);
/* clear cr.isr.ir (incomplete register frame)*/
pt_isr.val = VMX(vcpu, cr_isr);
pt_isr.ir = 0;
VMX(vcpu, cr_isr) = pt_isr.val;
collect_interruption(vcpu);
viva = vcpu_get_iva(vcpu);
regs->cr_iip = viva + vec;
}
static u64 vcpu_get_itir_on_fault(struct kvm_vcpu *vcpu, u64 ifa)
{
union ia64_rr rr, rr1;
rr.val = vcpu_get_rr(vcpu, ifa);
rr1.val = 0;
rr1.ps = rr.ps;
rr1.rid = rr.rid;
return (rr1.val);
}
/*
* Set vIFA & vITIR & vIHA, when vPSR.ic =1
* Parameter:
* set_ifa: if true, set vIFA
* set_itir: if true, set vITIR
* set_iha: if true, set vIHA
*/
void set_ifa_itir_iha(struct kvm_vcpu *vcpu, u64 vadr,
int set_ifa, int set_itir, int set_iha)
{
long vpsr;
u64 value;
vpsr = VCPU(vcpu, vpsr);
/* Vol2, Table 8-1 */
if (vpsr & IA64_PSR_IC) {
if (set_ifa)
vcpu_set_ifa(vcpu, vadr);
if (set_itir) {
value = vcpu_get_itir_on_fault(vcpu, vadr);
vcpu_set_itir(vcpu, value);
}
if (set_iha) {
value = vcpu_thash(vcpu, vadr);
vcpu_set_iha(vcpu, value);
}
}
}
/*
* Data TLB Fault
* @ Data TLB vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void dtlb_fault(struct kvm_vcpu *vcpu, u64 vadr)
{
/* If vPSR.ic, IFA, ITIR, IHA */
set_ifa_itir_iha(vcpu, vadr, 1, 1, 1);
inject_guest_interruption(vcpu, IA64_DATA_TLB_VECTOR);
}
/*
* Instruction TLB Fault
* @ Instruction TLB vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void itlb_fault(struct kvm_vcpu *vcpu, u64 vadr)
{
/* If vPSR.ic, IFA, ITIR, IHA */
set_ifa_itir_iha(vcpu, vadr, 1, 1, 1);
inject_guest_interruption(vcpu, IA64_INST_TLB_VECTOR);
}
/*
* Data Nested TLB Fault
* @ Data Nested TLB Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void nested_dtlb(struct kvm_vcpu *vcpu)
{
inject_guest_interruption(vcpu, IA64_DATA_NESTED_TLB_VECTOR);
}
/*
* Alternate Data TLB Fault
* @ Alternate Data TLB vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void alt_dtlb(struct kvm_vcpu *vcpu, u64 vadr)
{
set_ifa_itir_iha(vcpu, vadr, 1, 1, 0);
inject_guest_interruption(vcpu, IA64_ALT_DATA_TLB_VECTOR);
}
/*
* Data TLB Fault
* @ Data TLB vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void alt_itlb(struct kvm_vcpu *vcpu, u64 vadr)
{
set_ifa_itir_iha(vcpu, vadr, 1, 1, 0);
inject_guest_interruption(vcpu, IA64_ALT_INST_TLB_VECTOR);
}
/* Deal with:
* VHPT Translation Vector
*/
static void _vhpt_fault(struct kvm_vcpu *vcpu, u64 vadr)
{
/* If vPSR.ic, IFA, ITIR, IHA*/
set_ifa_itir_iha(vcpu, vadr, 1, 1, 1);
inject_guest_interruption(vcpu, IA64_VHPT_TRANS_VECTOR);
}
/*
* VHPT Instruction Fault
* @ VHPT Translation vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void ivhpt_fault(struct kvm_vcpu *vcpu, u64 vadr)
{
_vhpt_fault(vcpu, vadr);
}
/*
* VHPT Data Fault
* @ VHPT Translation vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void dvhpt_fault(struct kvm_vcpu *vcpu, u64 vadr)
{
_vhpt_fault(vcpu, vadr);
}
/*
* Deal with:
* General Exception vector
*/
void _general_exception(struct kvm_vcpu *vcpu)
{
inject_guest_interruption(vcpu, IA64_GENEX_VECTOR);
}
/*
* Illegal Operation Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void illegal_op(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/*
* Illegal Dependency Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void illegal_dep(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/*
* Reserved Register/Field Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void rsv_reg_field(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/*
* Privileged Operation Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void privilege_op(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/*
* Unimplement Data Address Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void unimpl_daddr(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/*
* Privileged Register Fault
* @ General Exception Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void privilege_reg(struct kvm_vcpu *vcpu)
{
_general_exception(vcpu);
}
/* Deal with
* Nat consumption vector
* Parameter:
* vaddr: Optional, if t == REGISTER
*/
static void _nat_consumption_fault(struct kvm_vcpu *vcpu, u64 vadr,
enum tlb_miss_type t)
{
/* If vPSR.ic && t == DATA/INST, IFA */
if (t == DATA || t == INSTRUCTION) {
/* IFA */
set_ifa_itir_iha(vcpu, vadr, 1, 0, 0);
}
inject_guest_interruption(vcpu, IA64_NAT_CONSUMPTION_VECTOR);
}
/*
* Instruction Nat Page Consumption Fault
* @ Nat Consumption Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void inat_page_consumption(struct kvm_vcpu *vcpu, u64 vadr)
{
_nat_consumption_fault(vcpu, vadr, INSTRUCTION);
}
/*
* Register Nat Consumption Fault
* @ Nat Consumption Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void rnat_consumption(struct kvm_vcpu *vcpu)
{
_nat_consumption_fault(vcpu, 0, REGISTER);
}
/*
* Data Nat Page Consumption Fault
* @ Nat Consumption Vector
* Refer to SDM Vol2 Table 5-6 & 8-1
*/
void dnat_page_consumption(struct kvm_vcpu *vcpu, u64 vadr)
{
_nat_consumption_fault(vcpu, vadr, DATA);
}
/* Deal with
* Page not present vector
*/
static void __page_not_present(struct kvm_vcpu *vcpu, u64 vadr)
{
/* If vPSR.ic, IFA, ITIR */
set_ifa_itir_iha(vcpu, vadr, 1, 1, 0);
inject_guest_interruption(vcpu, IA64_PAGE_NOT_PRESENT_VECTOR);
}
void data_page_not_present(struct kvm_vcpu *vcpu, u64 vadr)
{
__page_not_present(vcpu, vadr);
}
void inst_page_not_present(struct kvm_vcpu *vcpu, u64 vadr)
{
__page_not_present(vcpu, vadr);
}
/* Deal with
* Data access rights vector
*/
void data_access_rights(struct kvm_vcpu *vcpu, u64 vadr)
{
/* If vPSR.ic, IFA, ITIR */
set_ifa_itir_iha(vcpu, vadr, 1, 1, 0);
inject_guest_interruption(vcpu, IA64_DATA_ACCESS_RIGHTS_VECTOR);
}
fpswa_ret_t vmm_fp_emulate(int fp_fault, void *bundle, unsigned long *ipsr,
unsigned long *fpsr, unsigned long *isr, unsigned long *pr,
unsigned long *ifs, struct kvm_pt_regs *regs)
{
fp_state_t fp_state;
fpswa_ret_t ret;
struct kvm_vcpu *vcpu = current_vcpu;
uint64_t old_rr7 = ia64_get_rr(7UL<<61);
if (!vmm_fpswa_interface)
return (fpswa_ret_t) {-1, 0, 0, 0};
memset(&fp_state, 0, sizeof(fp_state_t));
/*
* compute fp_state. only FP registers f6 - f11 are used by the
* vmm, so set those bits in the mask and set the low volatile
* pointer to point to these registers.
*/
fp_state.bitmask_low64 = 0xfc0; /* bit6..bit11 */
fp_state.fp_state_low_volatile = (fp_state_low_volatile_t *) ®s->f6;
/*
* unsigned long (*EFI_FPSWA) (
* unsigned long trap_type,
* void *Bundle,
* unsigned long *pipsr,
* unsigned long *pfsr,
* unsigned long *pisr,
* unsigned long *ppreds,
* unsigned long *pifs,
* void *fp_state);
*/
/*Call host fpswa interface directly to virtualize
*guest fpswa request!
*/
ia64_set_rr(7UL << 61, vcpu->arch.host.rr[7]);
ia64_srlz_d();
ret = (*vmm_fpswa_interface->fpswa) (fp_fault, bundle,
ipsr, fpsr, isr, pr, ifs, &fp_state);
ia64_set_rr(7UL << 61, old_rr7);
ia64_srlz_d();
return ret;
}
/*
* Handle floating-point assist faults and traps for domain.
*/
unsigned long vmm_handle_fpu_swa(int fp_fault, struct kvm_pt_regs *regs,
unsigned long isr)
{
struct kvm_vcpu *v = current_vcpu;
IA64_BUNDLE bundle;
unsigned long fault_ip;
fpswa_ret_t ret;
fault_ip = regs->cr_iip;
/*
* When the FP trap occurs, the trapping instruction is completed.
* If ipsr.ri == 0, there is the trapping instruction in previous
* bundle.
*/
if (!fp_fault && (ia64_psr(regs)->ri == 0))
fault_ip -= 16;
if (fetch_code(v, fault_ip, &bundle))
return -EAGAIN;
if (!bundle.i64[0] && !bundle.i64[1])
return -EACCES;
ret = vmm_fp_emulate(fp_fault, &bundle, ®s->cr_ipsr, ®s->ar_fpsr,
&isr, ®s->pr, ®s->cr_ifs, regs);
return ret.status;
}
void reflect_interruption(u64 ifa, u64 isr, u64 iim,
u64 vec, struct kvm_pt_regs *regs)
{
u64 vector;
int status ;
struct kvm_vcpu *vcpu = current_vcpu;
u64 vpsr = VCPU(vcpu, vpsr);
vector = vec2off[vec];
if (!(vpsr & IA64_PSR_IC) && (vector != IA64_DATA_NESTED_TLB_VECTOR)) {
panic_vm(vcpu, "Interruption with vector :0x%lx occurs "
"with psr.ic = 0\n", vector);
return;
}
switch (vec) {
case 32: /*IA64_FP_FAULT_VECTOR*/
status = vmm_handle_fpu_swa(1, regs, isr);
if (!status) {
vcpu_increment_iip(vcpu);
return;
} else if (-EAGAIN == status)
return;
break;
case 33: /*IA64_FP_TRAP_VECTOR*/
status = vmm_handle_fpu_swa(0, regs, isr);
if (!status)
return ;
break;
}
VCPU(vcpu, isr) = isr;
VCPU(vcpu, iipa) = regs->cr_iip;
if (vector == IA64_BREAK_VECTOR || vector == IA64_SPECULATION_VECTOR)
VCPU(vcpu, iim) = iim;
else
set_ifa_itir_iha(vcpu, ifa, 1, 1, 1);
inject_guest_interruption(vcpu, vector);
}
static unsigned long kvm_trans_pal_call_args(struct kvm_vcpu *vcpu,
unsigned long arg)
{
struct thash_data *data;
unsigned long gpa, poff;
if (!is_physical_mode(vcpu)) {
/* Depends on caller to provide the DTR or DTC mapping.*/
data = vtlb_lookup(vcpu, arg, D_TLB);
if (data)
gpa = data->page_flags & _PAGE_PPN_MASK;
else {
data = vhpt_lookup(arg);
if (!data)
return 0;
gpa = data->gpaddr & _PAGE_PPN_MASK;
}
poff = arg & (PSIZE(data->ps) - 1);
arg = PAGEALIGN(gpa, data->ps) | poff;
}
arg = kvm_gpa_to_mpa(arg << 1 >> 1);
return (unsigned long)__va(arg);
}
static void set_pal_call_data(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
unsigned long gr28 = vcpu_get_gr(vcpu, 28);
unsigned long gr29 = vcpu_get_gr(vcpu, 29);
unsigned long gr30 = vcpu_get_gr(vcpu, 30);
/*FIXME:For static and stacked convention, firmware
* has put the parameters in gr28-gr31 before
* break to vmm !!*/
switch (gr28) {
case PAL_PERF_MON_INFO:
case PAL_HALT_INFO:
p->u.pal_data.gr29 = kvm_trans_pal_call_args(vcpu, gr29);
p->u.pal_data.gr30 = vcpu_get_gr(vcpu, 30);
break;
case PAL_BRAND_INFO:
p->u.pal_data.gr29 = gr29;
p->u.pal_data.gr30 = kvm_trans_pal_call_args(vcpu, gr30);
break;
default:
p->u.pal_data.gr29 = gr29;
p->u.pal_data.gr30 = vcpu_get_gr(vcpu, 30);
}
p->u.pal_data.gr28 = gr28;
p->u.pal_data.gr31 = vcpu_get_gr(vcpu, 31);
p->exit_reason = EXIT_REASON_PAL_CALL;
}
static void get_pal_call_result(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
if (p->exit_reason == EXIT_REASON_PAL_CALL) {
vcpu_set_gr(vcpu, 8, p->u.pal_data.ret.status, 0);
vcpu_set_gr(vcpu, 9, p->u.pal_data.ret.v0, 0);
vcpu_set_gr(vcpu, 10, p->u.pal_data.ret.v1, 0);
vcpu_set_gr(vcpu, 11, p->u.pal_data.ret.v2, 0);
} else
panic_vm(vcpu, "Mis-set for exit reason!\n");
}
static void set_sal_call_data(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
p->u.sal_data.in0 = vcpu_get_gr(vcpu, 32);
p->u.sal_data.in1 = vcpu_get_gr(vcpu, 33);
p->u.sal_data.in2 = vcpu_get_gr(vcpu, 34);
p->u.sal_data.in3 = vcpu_get_gr(vcpu, 35);
p->u.sal_data.in4 = vcpu_get_gr(vcpu, 36);
p->u.sal_data.in5 = vcpu_get_gr(vcpu, 37);
p->u.sal_data.in6 = vcpu_get_gr(vcpu, 38);
p->u.sal_data.in7 = vcpu_get_gr(vcpu, 39);
p->exit_reason = EXIT_REASON_SAL_CALL;
}
static void get_sal_call_result(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
if (p->exit_reason == EXIT_REASON_SAL_CALL) {
vcpu_set_gr(vcpu, 8, p->u.sal_data.ret.r8, 0);
vcpu_set_gr(vcpu, 9, p->u.sal_data.ret.r9, 0);
vcpu_set_gr(vcpu, 10, p->u.sal_data.ret.r10, 0);
vcpu_set_gr(vcpu, 11, p->u.sal_data.ret.r11, 0);
} else
panic_vm(vcpu, "Mis-set for exit reason!\n");
}
void kvm_ia64_handle_break(unsigned long ifa, struct kvm_pt_regs *regs,
unsigned long isr, unsigned long iim)
{
struct kvm_vcpu *v = current_vcpu;
long psr;
if (ia64_psr(regs)->cpl == 0) {
/* Allow hypercalls only when cpl = 0. */
if (iim == DOMN_PAL_REQUEST) {
local_irq_save(psr);
set_pal_call_data(v);
vmm_transition(v);
get_pal_call_result(v);
vcpu_increment_iip(v);
local_irq_restore(psr);
return;
} else if (iim == DOMN_SAL_REQUEST) {
local_irq_save(psr);
set_sal_call_data(v);
vmm_transition(v);
get_sal_call_result(v);
vcpu_increment_iip(v);
local_irq_restore(psr);
return;
}
}
reflect_interruption(ifa, isr, iim, 11, regs);
}
void check_pending_irq(struct kvm_vcpu *vcpu)
{
int mask, h_pending, h_inservice;
u64 isr;
unsigned long vpsr;
struct kvm_pt_regs *regs = vcpu_regs(vcpu);
h_pending = highest_pending_irq(vcpu);
if (h_pending == NULL_VECTOR) {
update_vhpi(vcpu, NULL_VECTOR);
return;
}
h_inservice = highest_inservice_irq(vcpu);
vpsr = VCPU(vcpu, vpsr);
mask = irq_masked(vcpu, h_pending, h_inservice);
if ((vpsr & IA64_PSR_I) && IRQ_NO_MASKED == mask) {
isr = vpsr & IA64_PSR_RI;
update_vhpi(vcpu, h_pending);
reflect_interruption(0, isr, 0, 12, regs); /* EXT IRQ */
} else if (mask == IRQ_MASKED_BY_INSVC) {
if (VCPU(vcpu, vhpi))
update_vhpi(vcpu, NULL_VECTOR);
} else {
/* masked by vpsr.i or vtpr.*/
update_vhpi(vcpu, h_pending);
}
}
static void generate_exirq(struct kvm_vcpu *vcpu)
{
unsigned vpsr;
uint64_t isr;
struct kvm_pt_regs *regs = vcpu_regs(vcpu);
vpsr = VCPU(vcpu, vpsr);
isr = vpsr & IA64_PSR_RI;
if (!(vpsr & IA64_PSR_IC))
panic_vm(vcpu, "Trying to inject one IRQ with psr.ic=0\n");
reflect_interruption(0, isr, 0, 12, regs); /* EXT IRQ */
}
void vhpi_detection(struct kvm_vcpu *vcpu)
{
uint64_t threshold, vhpi;
union ia64_tpr vtpr;
struct ia64_psr vpsr;
vpsr = *(struct ia64_psr *)&VCPU(vcpu, vpsr);
vtpr.val = VCPU(vcpu, tpr);
threshold = ((!vpsr.i) << 5) | (vtpr.mmi << 4) | vtpr.mic;
vhpi = VCPU(vcpu, vhpi);
if (vhpi > threshold) {
/* interrupt actived*/
generate_exirq(vcpu);
}
}
void leave_hypervisor_tail(void)
{
struct kvm_vcpu *v = current_vcpu;
if (VMX(v, timer_check)) {
VMX(v, timer_check) = 0;
if (VMX(v, itc_check)) {
if (vcpu_get_itc(v) > VCPU(v, itm)) {
if (!(VCPU(v, itv) & (1 << 16))) {
vcpu_pend_interrupt(v, VCPU(v, itv)
& 0xff);
VMX(v, itc_check) = 0;
} else {
v->arch.timer_pending = 1;
}
VMX(v, last_itc) = VCPU(v, itm) + 1;
}
}
}
rmb();
if (v->arch.irq_new_pending) {
v->arch.irq_new_pending = 0;
VMX(v, irq_check) = 0;
check_pending_irq(v);
return;
}
if (VMX(v, irq_check)) {
VMX(v, irq_check) = 0;
vhpi_detection(v);
}
}
static inline void handle_lds(struct kvm_pt_regs *regs)
{
regs->cr_ipsr |= IA64_PSR_ED;
}
void physical_tlb_miss(struct kvm_vcpu *vcpu, unsigned long vadr, int type)
{
unsigned long pte;
union ia64_rr rr;
rr.val = ia64_get_rr(vadr);
pte = vadr & _PAGE_PPN_MASK;
pte = pte | PHY_PAGE_WB;
thash_vhpt_insert(vcpu, pte, (u64)(rr.ps << 2), vadr, type);
return;
}
void kvm_page_fault(u64 vadr , u64 vec, struct kvm_pt_regs *regs)
{
unsigned long vpsr;
int type;
u64 vhpt_adr, gppa, pteval, rr, itir;
union ia64_isr misr;
union ia64_pta vpta;
struct thash_data *data;
struct kvm_vcpu *v = current_vcpu;
vpsr = VCPU(v, vpsr);
misr.val = VMX(v, cr_isr);
type = vec;
if (is_physical_mode(v) && (!(vadr << 1 >> 62))) {
if (vec == 2) {
if (__gpfn_is_io((vadr << 1) >> (PAGE_SHIFT + 1))) {
emulate_io_inst(v, ((vadr << 1) >> 1), 4);
return;
}
}
physical_tlb_miss(v, vadr, type);
return;
}
data = vtlb_lookup(v, vadr, type);
if (data != 0) {
if (type == D_TLB) {
gppa = (vadr & ((1UL << data->ps) - 1))
+ (data->ppn >> (data->ps - 12) << data->ps);
if (__gpfn_is_io(gppa >> PAGE_SHIFT)) {
if (data->pl >= ((regs->cr_ipsr >>
IA64_PSR_CPL0_BIT) & 3))
emulate_io_inst(v, gppa, data->ma);
else {
vcpu_set_isr(v, misr.val);
data_access_rights(v, vadr);
}
return ;
}
}
thash_vhpt_insert(v, data->page_flags, data->itir, vadr, type);
} else if (type == D_TLB) {
if (misr.sp) {
handle_lds(regs);
return;
}
rr = vcpu_get_rr(v, vadr);
itir = rr & (RR_RID_MASK | RR_PS_MASK);
if (!vhpt_enabled(v, vadr, misr.rs ? RSE_REF : DATA_REF)) {
if (vpsr & IA64_PSR_IC) {
vcpu_set_isr(v, misr.val);
alt_dtlb(v, vadr);
} else {
nested_dtlb(v);
}
return ;
}
vpta.val = vcpu_get_pta(v);
/* avoid recursively walking (short format) VHPT */
vhpt_adr = vcpu_thash(v, vadr);
if (!guest_vhpt_lookup(vhpt_adr, &pteval)) {
/* VHPT successfully read. */
if (!(pteval & _PAGE_P)) {
if (vpsr & IA64_PSR_IC) {
vcpu_set_isr(v, misr.val);
dtlb_fault(v, vadr);
} else {
nested_dtlb(v);
}
} else if ((pteval & _PAGE_MA_MASK) != _PAGE_MA_ST) {
thash_purge_and_insert(v, pteval, itir,
vadr, D_TLB);
} else if (vpsr & IA64_PSR_IC) {
vcpu_set_isr(v, misr.val);
dtlb_fault(v, vadr);
} else {
nested_dtlb(v);
}
} else {
/* Can't read VHPT. */
if (vpsr & IA64_PSR_IC) {
vcpu_set_isr(v, misr.val);
dvhpt_fault(v, vadr);
} else {
nested_dtlb(v);
}
}
} else if (type == I_TLB) {
if (!(vpsr & IA64_PSR_IC))
misr.ni = 1;
if (!vhpt_enabled(v, vadr, INST_REF)) {
vcpu_set_isr(v, misr.val);
alt_itlb(v, vadr);
return;
}
vpta.val = vcpu_get_pta(v);
vhpt_adr = vcpu_thash(v, vadr);
if (!guest_vhpt_lookup(vhpt_adr, &pteval)) {
/* VHPT successfully read. */
if (pteval & _PAGE_P) {
if ((pteval & _PAGE_MA_MASK) == _PAGE_MA_ST) {
vcpu_set_isr(v, misr.val);
itlb_fault(v, vadr);
return ;
}
rr = vcpu_get_rr(v, vadr);
itir = rr & (RR_RID_MASK | RR_PS_MASK);
thash_purge_and_insert(v, pteval, itir,
vadr, I_TLB);
} else {
vcpu_set_isr(v, misr.val);
inst_page_not_present(v, vadr);
}
} else {
vcpu_set_isr(v, misr.val);
ivhpt_fault(v, vadr);
}
}
}
void kvm_vexirq(struct kvm_vcpu *vcpu)
{
u64 vpsr, isr;
struct kvm_pt_regs *regs;
regs = vcpu_regs(vcpu);
vpsr = VCPU(vcpu, vpsr);
isr = vpsr & IA64_PSR_RI;
reflect_interruption(0, isr, 0, 12, regs); /*EXT IRQ*/
}
void kvm_ia64_handle_irq(struct kvm_vcpu *v)
{
struct exit_ctl_data *p = &v->arch.exit_data;
long psr;
local_irq_save(psr);
p->exit_reason = EXIT_REASON_EXTERNAL_INTERRUPT;
vmm_transition(v);
local_irq_restore(psr);
VMX(v, timer_check) = 1;
}
static void ptc_ga_remote_func(struct kvm_vcpu *v, int pos)
{
u64 oldrid, moldrid, oldpsbits, vaddr;
struct kvm_ptc_g *p = &v->arch.ptc_g_data[pos];
vaddr = p->vaddr;
oldrid = VMX(v, vrr[0]);
VMX(v, vrr[0]) = p->rr;
oldpsbits = VMX(v, psbits[0]);
VMX(v, psbits[0]) = VMX(v, psbits[REGION_NUMBER(vaddr)]);
moldrid = ia64_get_rr(0x0);
ia64_set_rr(0x0, vrrtomrr(p->rr));
ia64_srlz_d();
vaddr = PAGEALIGN(vaddr, p->ps);
thash_purge_entries_remote(v, vaddr, p->ps);
VMX(v, vrr[0]) = oldrid;
VMX(v, psbits[0]) = oldpsbits;
ia64_set_rr(0x0, moldrid);
ia64_dv_serialize_data();
}
static void vcpu_do_resume(struct kvm_vcpu *vcpu)
{
/*Re-init VHPT and VTLB once from resume*/
vcpu->arch.vhpt.num = VHPT_NUM_ENTRIES;
thash_init(&vcpu->arch.vhpt, VHPT_SHIFT);
vcpu->arch.vtlb.num = VTLB_NUM_ENTRIES;
thash_init(&vcpu->arch.vtlb, VTLB_SHIFT);
ia64_set_pta(vcpu->arch.vhpt.pta.val);
}
static void vmm_sanity_check(struct kvm_vcpu *vcpu)
{
struct exit_ctl_data *p = &vcpu->arch.exit_data;
if (!vmm_sanity && p->exit_reason != EXIT_REASON_DEBUG) {
panic_vm(vcpu, "Failed to do vmm sanity check,"
"it maybe caused by crashed vmm!!\n\n");
}
}
static void kvm_do_resume_op(struct kvm_vcpu *vcpu)
{
vmm_sanity_check(vcpu); /*Guarantee vcpu runing on healthy vmm!*/
if (test_and_clear_bit(KVM_REQ_RESUME, &vcpu->requests)) {
vcpu_do_resume(vcpu);
return;
}
if (unlikely(test_and_clear_bit(KVM_REQ_TLB_FLUSH, &vcpu->requests))) {
thash_purge_all(vcpu);
return;
}
if (test_and_clear_bit(KVM_REQ_PTC_G, &vcpu->requests)) {
while (vcpu->arch.ptc_g_count > 0)
ptc_ga_remote_func(vcpu, --vcpu->arch.ptc_g_count);
}
}
void vmm_transition(struct kvm_vcpu *vcpu)
{
ia64_call_vsa(PAL_VPS_SAVE, (unsigned long)vcpu->arch.vpd,
1, 0, 0, 0, 0, 0);
vmm_trampoline(&vcpu->arch.guest, &vcpu->arch.host);
ia64_call_vsa(PAL_VPS_RESTORE, (unsigned long)vcpu->arch.vpd,
1, 0, 0, 0, 0, 0);
kvm_do_resume_op(vcpu);
}
void vmm_panic_handler(u64 vec)
{
struct kvm_vcpu *vcpu = current_vcpu;
vmm_sanity = 0;
panic_vm(vcpu, "Unexpected interruption occurs in VMM, vector:0x%lx\n",
vec2off[vec]);
}
| gpl-2.0 |
kyapa/linux-3.0.y | security/selinux/hooks.c | 1837 | 144771 | /*
* NSA Security-Enhanced Linux (SELinux) security module
*
* This file contains the SELinux hook function implementations.
*
* Authors: Stephen Smalley, <sds@epoch.ncsc.mil>
* Chris Vance, <cvance@nai.com>
* Wayne Salamon, <wsalamon@nai.com>
* James Morris <jmorris@redhat.com>
*
* Copyright (C) 2001,2002 Networks Associates Technology, Inc.
* Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
* Eric Paris <eparis@redhat.com>
* Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
* <dgoeddel@trustedcs.com>
* Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
* Paul Moore <paul.moore@hp.com>
* Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
* Yuichi Nakamura <ynakam@hitachisoft.jp>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kd.h>
#include <linux/kernel.h>
#include <linux/tracehook.h>
#include <linux/errno.h>
#include <linux/ext2_fs.h>
#include <linux/sched.h>
#include <linux/security.h>
#include <linux/xattr.h>
#include <linux/capability.h>
#include <linux/unistd.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/slab.h>
#include <linux/pagemap.h>
#include <linux/proc_fs.h>
#include <linux/swap.h>
#include <linux/spinlock.h>
#include <linux/syscalls.h>
#include <linux/dcache.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/namei.h>
#include <linux/mount.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netfilter_ipv6.h>
#include <linux/tty.h>
#include <net/icmp.h>
#include <net/ip.h> /* for local_port_range[] */
#include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
#include <net/net_namespace.h>
#include <net/netlabel.h>
#include <linux/uaccess.h>
#include <asm/ioctls.h>
#include <asm/atomic.h>
#include <linux/bitops.h>
#include <linux/interrupt.h>
#include <linux/netdevice.h> /* for network interface checks */
#include <linux/netlink.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/dccp.h>
#include <linux/quota.h>
#include <linux/un.h> /* for Unix socket types */
#include <net/af_unix.h> /* for Unix socket types */
#include <linux/parser.h>
#include <linux/nfs_mount.h>
#include <net/ipv6.h>
#include <linux/hugetlb.h>
#include <linux/personality.h>
#include <linux/audit.h>
#include <linux/string.h>
#include <linux/selinux.h>
#include <linux/mutex.h>
#include <linux/posix-timers.h>
#include <linux/syslog.h>
#include <linux/user_namespace.h>
#include "avc.h"
#include "objsec.h"
#include "netif.h"
#include "netnode.h"
#include "netport.h"
#include "xfrm.h"
#include "netlabel.h"
#include "audit.h"
#define NUM_SEL_MNT_OPTS 5
extern int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm);
extern struct security_operations *security_ops;
/* SECMARK reference count */
atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
#ifdef CONFIG_SECURITY_SELINUX_DEVELOP
int selinux_enforcing;
static int __init enforcing_setup(char *str)
{
unsigned long enforcing;
if (!strict_strtoul(str, 0, &enforcing))
selinux_enforcing = enforcing ? 1 : 0;
return 1;
}
__setup("enforcing=", enforcing_setup);
#endif
#ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE;
static int __init selinux_enabled_setup(char *str)
{
unsigned long enabled;
if (!strict_strtoul(str, 0, &enabled))
selinux_enabled = enabled ? 1 : 0;
return 1;
}
__setup("selinux=", selinux_enabled_setup);
#else
int selinux_enabled = 1;
#endif
static struct kmem_cache *sel_inode_cache;
/**
* selinux_secmark_enabled - Check to see if SECMARK is currently enabled
*
* Description:
* This function checks the SECMARK reference counter to see if any SECMARK
* targets are currently configured, if the reference counter is greater than
* zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
* enabled, false (0) if SECMARK is disabled.
*
*/
static int selinux_secmark_enabled(void)
{
return (atomic_read(&selinux_secmark_refcount) > 0);
}
/*
* initialise the security for the init task
*/
static void cred_init_security(void)
{
struct cred *cred = (struct cred *) current->real_cred;
struct task_security_struct *tsec;
tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL);
if (!tsec)
panic("SELinux: Failed to initialize initial task.\n");
tsec->osid = tsec->sid = SECINITSID_KERNEL;
cred->security = tsec;
}
/*
* get the security ID of a set of credentials
*/
static inline u32 cred_sid(const struct cred *cred)
{
const struct task_security_struct *tsec;
tsec = cred->security;
return tsec->sid;
}
/*
* get the objective security ID of a task
*/
static inline u32 task_sid(const struct task_struct *task)
{
u32 sid;
rcu_read_lock();
sid = cred_sid(__task_cred(task));
rcu_read_unlock();
return sid;
}
/*
* get the subjective security ID of the current task
*/
static inline u32 current_sid(void)
{
const struct task_security_struct *tsec = current_security();
return tsec->sid;
}
/* Allocate and free functions for each kind of security blob. */
static int inode_alloc_security(struct inode *inode)
{
struct inode_security_struct *isec;
u32 sid = current_sid();
isec = kmem_cache_zalloc(sel_inode_cache, GFP_NOFS);
if (!isec)
return -ENOMEM;
mutex_init(&isec->lock);
INIT_LIST_HEAD(&isec->list);
isec->inode = inode;
isec->sid = SECINITSID_UNLABELED;
isec->sclass = SECCLASS_FILE;
isec->task_sid = sid;
inode->i_security = isec;
return 0;
}
static void inode_free_security(struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
struct superblock_security_struct *sbsec = inode->i_sb->s_security;
spin_lock(&sbsec->isec_lock);
if (!list_empty(&isec->list))
list_del_init(&isec->list);
spin_unlock(&sbsec->isec_lock);
inode->i_security = NULL;
kmem_cache_free(sel_inode_cache, isec);
}
static int file_alloc_security(struct file *file)
{
struct file_security_struct *fsec;
u32 sid = current_sid();
fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL);
if (!fsec)
return -ENOMEM;
fsec->sid = sid;
fsec->fown_sid = sid;
file->f_security = fsec;
return 0;
}
static void file_free_security(struct file *file)
{
struct file_security_struct *fsec = file->f_security;
file->f_security = NULL;
kfree(fsec);
}
static int superblock_alloc_security(struct super_block *sb)
{
struct superblock_security_struct *sbsec;
sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
if (!sbsec)
return -ENOMEM;
mutex_init(&sbsec->lock);
INIT_LIST_HEAD(&sbsec->isec_head);
spin_lock_init(&sbsec->isec_lock);
sbsec->sb = sb;
sbsec->sid = SECINITSID_UNLABELED;
sbsec->def_sid = SECINITSID_FILE;
sbsec->mntpoint_sid = SECINITSID_UNLABELED;
sb->s_security = sbsec;
return 0;
}
static void superblock_free_security(struct super_block *sb)
{
struct superblock_security_struct *sbsec = sb->s_security;
sb->s_security = NULL;
kfree(sbsec);
}
/* The security server must be initialized before
any labeling or access decisions can be provided. */
extern int ss_initialized;
/* The file system's label must be initialized prior to use. */
static const char *labeling_behaviors[6] = {
"uses xattr",
"uses transition SIDs",
"uses task SIDs",
"uses genfs_contexts",
"not configured for labeling",
"uses mountpoint labeling",
};
static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
static inline int inode_doinit(struct inode *inode)
{
return inode_doinit_with_dentry(inode, NULL);
}
enum {
Opt_error = -1,
Opt_context = 1,
Opt_fscontext = 2,
Opt_defcontext = 3,
Opt_rootcontext = 4,
Opt_labelsupport = 5,
};
static const match_table_t tokens = {
{Opt_context, CONTEXT_STR "%s"},
{Opt_fscontext, FSCONTEXT_STR "%s"},
{Opt_defcontext, DEFCONTEXT_STR "%s"},
{Opt_rootcontext, ROOTCONTEXT_STR "%s"},
{Opt_labelsupport, LABELSUPP_STR},
{Opt_error, NULL},
};
#define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
static int may_context_mount_sb_relabel(u32 sid,
struct superblock_security_struct *sbsec,
const struct cred *cred)
{
const struct task_security_struct *tsec = cred->security;
int rc;
rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELFROM, NULL);
if (rc)
return rc;
rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELTO, NULL);
return rc;
}
static int may_context_mount_inode_relabel(u32 sid,
struct superblock_security_struct *sbsec,
const struct cred *cred)
{
const struct task_security_struct *tsec = cred->security;
int rc;
rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__RELABELFROM, NULL);
if (rc)
return rc;
rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE, NULL);
return rc;
}
static int sb_finish_set_opts(struct super_block *sb)
{
struct superblock_security_struct *sbsec = sb->s_security;
struct dentry *root = sb->s_root;
struct inode *root_inode = root->d_inode;
int rc = 0;
if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
/* Make sure that the xattr handler exists and that no
error other than -ENODATA is returned by getxattr on
the root directory. -ENODATA is ok, as this may be
the first boot of the SELinux kernel before we have
assigned xattr values to the filesystem. */
if (!root_inode->i_op->getxattr) {
printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
"xattr support\n", sb->s_id, sb->s_type->name);
rc = -EOPNOTSUPP;
goto out;
}
rc = root_inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
if (rc < 0 && rc != -ENODATA) {
if (rc == -EOPNOTSUPP)
printk(KERN_WARNING "SELinux: (dev %s, type "
"%s) has no security xattr handler\n",
sb->s_id, sb->s_type->name);
else
printk(KERN_WARNING "SELinux: (dev %s, type "
"%s) getxattr errno %d\n", sb->s_id,
sb->s_type->name, -rc);
goto out;
}
}
sbsec->flags |= (SE_SBINITIALIZED | SE_SBLABELSUPP);
if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n",
sb->s_id, sb->s_type->name);
else
printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n",
sb->s_id, sb->s_type->name,
labeling_behaviors[sbsec->behavior-1]);
if (sbsec->behavior == SECURITY_FS_USE_GENFS ||
sbsec->behavior == SECURITY_FS_USE_MNTPOINT ||
sbsec->behavior == SECURITY_FS_USE_NONE ||
sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
sbsec->flags &= ~SE_SBLABELSUPP;
/* Special handling for sysfs. Is genfs but also has setxattr handler*/
if (strncmp(sb->s_type->name, "sysfs", sizeof("sysfs")) == 0)
sbsec->flags |= SE_SBLABELSUPP;
/* Initialize the root inode. */
rc = inode_doinit_with_dentry(root_inode, root);
/* Initialize any other inodes associated with the superblock, e.g.
inodes created prior to initial policy load or inodes created
during get_sb by a pseudo filesystem that directly
populates itself. */
spin_lock(&sbsec->isec_lock);
next_inode:
if (!list_empty(&sbsec->isec_head)) {
struct inode_security_struct *isec =
list_entry(sbsec->isec_head.next,
struct inode_security_struct, list);
struct inode *inode = isec->inode;
spin_unlock(&sbsec->isec_lock);
inode = igrab(inode);
if (inode) {
if (!IS_PRIVATE(inode))
inode_doinit(inode);
iput(inode);
}
spin_lock(&sbsec->isec_lock);
list_del_init(&isec->list);
goto next_inode;
}
spin_unlock(&sbsec->isec_lock);
out:
return rc;
}
/*
* This function should allow an FS to ask what it's mount security
* options were so it can use those later for submounts, displaying
* mount options, or whatever.
*/
static int selinux_get_mnt_opts(const struct super_block *sb,
struct security_mnt_opts *opts)
{
int rc = 0, i;
struct superblock_security_struct *sbsec = sb->s_security;
char *context = NULL;
u32 len;
char tmp;
security_init_mnt_opts(opts);
if (!(sbsec->flags & SE_SBINITIALIZED))
return -EINVAL;
if (!ss_initialized)
return -EINVAL;
tmp = sbsec->flags & SE_MNTMASK;
/* count the number of mount options for this sb */
for (i = 0; i < 8; i++) {
if (tmp & 0x01)
opts->num_mnt_opts++;
tmp >>= 1;
}
/* Check if the Label support flag is set */
if (sbsec->flags & SE_SBLABELSUPP)
opts->num_mnt_opts++;
opts->mnt_opts = kcalloc(opts->num_mnt_opts, sizeof(char *), GFP_ATOMIC);
if (!opts->mnt_opts) {
rc = -ENOMEM;
goto out_free;
}
opts->mnt_opts_flags = kcalloc(opts->num_mnt_opts, sizeof(int), GFP_ATOMIC);
if (!opts->mnt_opts_flags) {
rc = -ENOMEM;
goto out_free;
}
i = 0;
if (sbsec->flags & FSCONTEXT_MNT) {
rc = security_sid_to_context(sbsec->sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = FSCONTEXT_MNT;
}
if (sbsec->flags & CONTEXT_MNT) {
rc = security_sid_to_context(sbsec->mntpoint_sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = CONTEXT_MNT;
}
if (sbsec->flags & DEFCONTEXT_MNT) {
rc = security_sid_to_context(sbsec->def_sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = DEFCONTEXT_MNT;
}
if (sbsec->flags & ROOTCONTEXT_MNT) {
struct inode *root = sbsec->sb->s_root->d_inode;
struct inode_security_struct *isec = root->i_security;
rc = security_sid_to_context(isec->sid, &context, &len);
if (rc)
goto out_free;
opts->mnt_opts[i] = context;
opts->mnt_opts_flags[i++] = ROOTCONTEXT_MNT;
}
if (sbsec->flags & SE_SBLABELSUPP) {
opts->mnt_opts[i] = NULL;
opts->mnt_opts_flags[i++] = SE_SBLABELSUPP;
}
BUG_ON(i != opts->num_mnt_opts);
return 0;
out_free:
security_free_mnt_opts(opts);
return rc;
}
static int bad_option(struct superblock_security_struct *sbsec, char flag,
u32 old_sid, u32 new_sid)
{
char mnt_flags = sbsec->flags & SE_MNTMASK;
/* check if the old mount command had the same options */
if (sbsec->flags & SE_SBINITIALIZED)
if (!(sbsec->flags & flag) ||
(old_sid != new_sid))
return 1;
/* check if we were passed the same options twice,
* aka someone passed context=a,context=b
*/
if (!(sbsec->flags & SE_SBINITIALIZED))
if (mnt_flags & flag)
return 1;
return 0;
}
/*
* Allow filesystems with binary mount data to explicitly set mount point
* labeling information.
*/
static int selinux_set_mnt_opts(struct super_block *sb,
struct security_mnt_opts *opts)
{
const struct cred *cred = current_cred();
int rc = 0, i;
struct superblock_security_struct *sbsec = sb->s_security;
const char *name = sb->s_type->name;
struct inode *inode = sbsec->sb->s_root->d_inode;
struct inode_security_struct *root_isec = inode->i_security;
u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
u32 defcontext_sid = 0;
char **mount_options = opts->mnt_opts;
int *flags = opts->mnt_opts_flags;
int num_opts = opts->num_mnt_opts;
mutex_lock(&sbsec->lock);
if (!ss_initialized) {
if (!num_opts) {
/* Defer initialization until selinux_complete_init,
after the initial policy is loaded and the security
server is ready to handle calls. */
goto out;
}
rc = -EINVAL;
printk(KERN_WARNING "SELinux: Unable to set superblock options "
"before the security server is initialized\n");
goto out;
}
/*
* Binary mount data FS will come through this function twice. Once
* from an explicit call and once from the generic calls from the vfs.
* Since the generic VFS calls will not contain any security mount data
* we need to skip the double mount verification.
*
* This does open a hole in which we will not notice if the first
* mount using this sb set explict options and a second mount using
* this sb does not set any security options. (The first options
* will be used for both mounts)
*/
if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
&& (num_opts == 0))
goto out;
/*
* parse the mount options, check if they are valid sids.
* also check if someone is trying to mount the same sb more
* than once with different security options.
*/
for (i = 0; i < num_opts; i++) {
u32 sid;
if (flags[i] == SE_SBLABELSUPP)
continue;
rc = security_context_to_sid(mount_options[i],
strlen(mount_options[i]), &sid);
if (rc) {
printk(KERN_WARNING "SELinux: security_context_to_sid"
"(%s) failed for (dev %s, type %s) errno=%d\n",
mount_options[i], sb->s_id, name, rc);
goto out;
}
switch (flags[i]) {
case FSCONTEXT_MNT:
fscontext_sid = sid;
if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
fscontext_sid))
goto out_double_mount;
sbsec->flags |= FSCONTEXT_MNT;
break;
case CONTEXT_MNT:
context_sid = sid;
if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
context_sid))
goto out_double_mount;
sbsec->flags |= CONTEXT_MNT;
break;
case ROOTCONTEXT_MNT:
rootcontext_sid = sid;
if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
rootcontext_sid))
goto out_double_mount;
sbsec->flags |= ROOTCONTEXT_MNT;
break;
case DEFCONTEXT_MNT:
defcontext_sid = sid;
if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
defcontext_sid))
goto out_double_mount;
sbsec->flags |= DEFCONTEXT_MNT;
break;
default:
rc = -EINVAL;
goto out;
}
}
if (sbsec->flags & SE_SBINITIALIZED) {
/* previously mounted with options, but not on this attempt? */
if ((sbsec->flags & SE_MNTMASK) && !num_opts)
goto out_double_mount;
rc = 0;
goto out;
}
if (strcmp(sb->s_type->name, "proc") == 0)
sbsec->flags |= SE_SBPROC;
/* Determine the labeling behavior to use for this filesystem type. */
rc = security_fs_use((sbsec->flags & SE_SBPROC) ? "proc" : sb->s_type->name, &sbsec->behavior, &sbsec->sid);
if (rc) {
printk(KERN_WARNING "%s: security_fs_use(%s) returned %d\n",
__func__, sb->s_type->name, rc);
goto out;
}
/* sets the context of the superblock for the fs being mounted. */
if (fscontext_sid) {
rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
if (rc)
goto out;
sbsec->sid = fscontext_sid;
}
/*
* Switch to using mount point labeling behavior.
* sets the label used on all file below the mountpoint, and will set
* the superblock context if not already set.
*/
if (context_sid) {
if (!fscontext_sid) {
rc = may_context_mount_sb_relabel(context_sid, sbsec,
cred);
if (rc)
goto out;
sbsec->sid = context_sid;
} else {
rc = may_context_mount_inode_relabel(context_sid, sbsec,
cred);
if (rc)
goto out;
}
if (!rootcontext_sid)
rootcontext_sid = context_sid;
sbsec->mntpoint_sid = context_sid;
sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
}
if (rootcontext_sid) {
rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
cred);
if (rc)
goto out;
root_isec->sid = rootcontext_sid;
root_isec->initialized = 1;
}
if (defcontext_sid) {
if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
rc = -EINVAL;
printk(KERN_WARNING "SELinux: defcontext option is "
"invalid for this filesystem type\n");
goto out;
}
if (defcontext_sid != sbsec->def_sid) {
rc = may_context_mount_inode_relabel(defcontext_sid,
sbsec, cred);
if (rc)
goto out;
}
sbsec->def_sid = defcontext_sid;
}
rc = sb_finish_set_opts(sb);
out:
mutex_unlock(&sbsec->lock);
return rc;
out_double_mount:
rc = -EINVAL;
printk(KERN_WARNING "SELinux: mount invalid. Same superblock, different "
"security settings for (dev %s, type %s)\n", sb->s_id, name);
goto out;
}
static void selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
struct super_block *newsb)
{
const struct superblock_security_struct *oldsbsec = oldsb->s_security;
struct superblock_security_struct *newsbsec = newsb->s_security;
int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
int set_context = (oldsbsec->flags & CONTEXT_MNT);
int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
/*
* if the parent was able to be mounted it clearly had no special lsm
* mount options. thus we can safely deal with this superblock later
*/
if (!ss_initialized)
return;
/* how can we clone if the old one wasn't set up?? */
BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
/* if fs is reusing a sb, just let its options stand... */
if (newsbsec->flags & SE_SBINITIALIZED)
return;
mutex_lock(&newsbsec->lock);
newsbsec->flags = oldsbsec->flags;
newsbsec->sid = oldsbsec->sid;
newsbsec->def_sid = oldsbsec->def_sid;
newsbsec->behavior = oldsbsec->behavior;
if (set_context) {
u32 sid = oldsbsec->mntpoint_sid;
if (!set_fscontext)
newsbsec->sid = sid;
if (!set_rootcontext) {
struct inode *newinode = newsb->s_root->d_inode;
struct inode_security_struct *newisec = newinode->i_security;
newisec->sid = sid;
}
newsbsec->mntpoint_sid = sid;
}
if (set_rootcontext) {
const struct inode *oldinode = oldsb->s_root->d_inode;
const struct inode_security_struct *oldisec = oldinode->i_security;
struct inode *newinode = newsb->s_root->d_inode;
struct inode_security_struct *newisec = newinode->i_security;
newisec->sid = oldisec->sid;
}
sb_finish_set_opts(newsb);
mutex_unlock(&newsbsec->lock);
}
static int selinux_parse_opts_str(char *options,
struct security_mnt_opts *opts)
{
char *p;
char *context = NULL, *defcontext = NULL;
char *fscontext = NULL, *rootcontext = NULL;
int rc, num_mnt_opts = 0;
opts->num_mnt_opts = 0;
/* Standard string-based options. */
while ((p = strsep(&options, "|")) != NULL) {
int token;
substring_t args[MAX_OPT_ARGS];
if (!*p)
continue;
token = match_token(p, tokens, args);
switch (token) {
case Opt_context:
if (context || defcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
context = match_strdup(&args[0]);
if (!context) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_fscontext:
if (fscontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
fscontext = match_strdup(&args[0]);
if (!fscontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_rootcontext:
if (rootcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
rootcontext = match_strdup(&args[0]);
if (!rootcontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_defcontext:
if (context || defcontext) {
rc = -EINVAL;
printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
goto out_err;
}
defcontext = match_strdup(&args[0]);
if (!defcontext) {
rc = -ENOMEM;
goto out_err;
}
break;
case Opt_labelsupport:
break;
default:
rc = -EINVAL;
printk(KERN_WARNING "SELinux: unknown mount option\n");
goto out_err;
}
}
rc = -ENOMEM;
opts->mnt_opts = kcalloc(NUM_SEL_MNT_OPTS, sizeof(char *), GFP_ATOMIC);
if (!opts->mnt_opts)
goto out_err;
opts->mnt_opts_flags = kcalloc(NUM_SEL_MNT_OPTS, sizeof(int), GFP_ATOMIC);
if (!opts->mnt_opts_flags) {
kfree(opts->mnt_opts);
goto out_err;
}
if (fscontext) {
opts->mnt_opts[num_mnt_opts] = fscontext;
opts->mnt_opts_flags[num_mnt_opts++] = FSCONTEXT_MNT;
}
if (context) {
opts->mnt_opts[num_mnt_opts] = context;
opts->mnt_opts_flags[num_mnt_opts++] = CONTEXT_MNT;
}
if (rootcontext) {
opts->mnt_opts[num_mnt_opts] = rootcontext;
opts->mnt_opts_flags[num_mnt_opts++] = ROOTCONTEXT_MNT;
}
if (defcontext) {
opts->mnt_opts[num_mnt_opts] = defcontext;
opts->mnt_opts_flags[num_mnt_opts++] = DEFCONTEXT_MNT;
}
opts->num_mnt_opts = num_mnt_opts;
return 0;
out_err:
kfree(context);
kfree(defcontext);
kfree(fscontext);
kfree(rootcontext);
return rc;
}
/*
* string mount options parsing and call set the sbsec
*/
static int superblock_doinit(struct super_block *sb, void *data)
{
int rc = 0;
char *options = data;
struct security_mnt_opts opts;
security_init_mnt_opts(&opts);
if (!data)
goto out;
BUG_ON(sb->s_type->fs_flags & FS_BINARY_MOUNTDATA);
rc = selinux_parse_opts_str(options, &opts);
if (rc)
goto out_err;
out:
rc = selinux_set_mnt_opts(sb, &opts);
out_err:
security_free_mnt_opts(&opts);
return rc;
}
static void selinux_write_opts(struct seq_file *m,
struct security_mnt_opts *opts)
{
int i;
char *prefix;
for (i = 0; i < opts->num_mnt_opts; i++) {
char *has_comma;
if (opts->mnt_opts[i])
has_comma = strchr(opts->mnt_opts[i], ',');
else
has_comma = NULL;
switch (opts->mnt_opts_flags[i]) {
case CONTEXT_MNT:
prefix = CONTEXT_STR;
break;
case FSCONTEXT_MNT:
prefix = FSCONTEXT_STR;
break;
case ROOTCONTEXT_MNT:
prefix = ROOTCONTEXT_STR;
break;
case DEFCONTEXT_MNT:
prefix = DEFCONTEXT_STR;
break;
case SE_SBLABELSUPP:
seq_putc(m, ',');
seq_puts(m, LABELSUPP_STR);
continue;
default:
BUG();
return;
};
/* we need a comma before each option */
seq_putc(m, ',');
seq_puts(m, prefix);
if (has_comma)
seq_putc(m, '\"');
seq_puts(m, opts->mnt_opts[i]);
if (has_comma)
seq_putc(m, '\"');
}
}
static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
{
struct security_mnt_opts opts;
int rc;
rc = selinux_get_mnt_opts(sb, &opts);
if (rc) {
/* before policy load we may get EINVAL, don't show anything */
if (rc == -EINVAL)
rc = 0;
return rc;
}
selinux_write_opts(m, &opts);
security_free_mnt_opts(&opts);
return rc;
}
static inline u16 inode_mode_to_security_class(umode_t mode)
{
switch (mode & S_IFMT) {
case S_IFSOCK:
return SECCLASS_SOCK_FILE;
case S_IFLNK:
return SECCLASS_LNK_FILE;
case S_IFREG:
return SECCLASS_FILE;
case S_IFBLK:
return SECCLASS_BLK_FILE;
case S_IFDIR:
return SECCLASS_DIR;
case S_IFCHR:
return SECCLASS_CHR_FILE;
case S_IFIFO:
return SECCLASS_FIFO_FILE;
}
return SECCLASS_FILE;
}
static inline int default_protocol_stream(int protocol)
{
return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
}
static inline int default_protocol_dgram(int protocol)
{
return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
}
static inline u16 socket_type_to_security_class(int family, int type, int protocol)
{
switch (family) {
case PF_UNIX:
switch (type) {
case SOCK_STREAM:
case SOCK_SEQPACKET:
return SECCLASS_UNIX_STREAM_SOCKET;
case SOCK_DGRAM:
return SECCLASS_UNIX_DGRAM_SOCKET;
}
break;
case PF_INET:
case PF_INET6:
switch (type) {
case SOCK_STREAM:
if (default_protocol_stream(protocol))
return SECCLASS_TCP_SOCKET;
else
return SECCLASS_RAWIP_SOCKET;
case SOCK_DGRAM:
if (default_protocol_dgram(protocol))
return SECCLASS_UDP_SOCKET;
else
return SECCLASS_RAWIP_SOCKET;
case SOCK_DCCP:
return SECCLASS_DCCP_SOCKET;
default:
return SECCLASS_RAWIP_SOCKET;
}
break;
case PF_NETLINK:
switch (protocol) {
case NETLINK_ROUTE:
return SECCLASS_NETLINK_ROUTE_SOCKET;
case NETLINK_FIREWALL:
return SECCLASS_NETLINK_FIREWALL_SOCKET;
case NETLINK_INET_DIAG:
return SECCLASS_NETLINK_TCPDIAG_SOCKET;
case NETLINK_NFLOG:
return SECCLASS_NETLINK_NFLOG_SOCKET;
case NETLINK_XFRM:
return SECCLASS_NETLINK_XFRM_SOCKET;
case NETLINK_SELINUX:
return SECCLASS_NETLINK_SELINUX_SOCKET;
case NETLINK_AUDIT:
return SECCLASS_NETLINK_AUDIT_SOCKET;
case NETLINK_IP6_FW:
return SECCLASS_NETLINK_IP6FW_SOCKET;
case NETLINK_DNRTMSG:
return SECCLASS_NETLINK_DNRT_SOCKET;
case NETLINK_KOBJECT_UEVENT:
return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
default:
return SECCLASS_NETLINK_SOCKET;
}
case PF_PACKET:
return SECCLASS_PACKET_SOCKET;
case PF_KEY:
return SECCLASS_KEY_SOCKET;
case PF_APPLETALK:
return SECCLASS_APPLETALK_SOCKET;
}
return SECCLASS_SOCKET;
}
#ifdef CONFIG_PROC_FS
static int selinux_proc_get_sid(struct dentry *dentry,
u16 tclass,
u32 *sid)
{
int rc;
char *buffer, *path;
buffer = (char *)__get_free_page(GFP_KERNEL);
if (!buffer)
return -ENOMEM;
path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
if (IS_ERR(path))
rc = PTR_ERR(path);
else {
/* each process gets a /proc/PID/ entry. Strip off the
* PID part to get a valid selinux labeling.
* e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
while (path[1] >= '0' && path[1] <= '9') {
path[1] = '/';
path++;
}
rc = security_genfs_sid("proc", path, tclass, sid);
}
free_page((unsigned long)buffer);
return rc;
}
#else
static int selinux_proc_get_sid(struct dentry *dentry,
u16 tclass,
u32 *sid)
{
return -EINVAL;
}
#endif
/* The inode's security attributes must be initialized before first use. */
static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
{
struct superblock_security_struct *sbsec = NULL;
struct inode_security_struct *isec = inode->i_security;
u32 sid;
struct dentry *dentry;
#define INITCONTEXTLEN 255
char *context = NULL;
unsigned len = 0;
int rc = 0;
if (isec->initialized)
goto out;
mutex_lock(&isec->lock);
if (isec->initialized)
goto out_unlock;
sbsec = inode->i_sb->s_security;
if (!(sbsec->flags & SE_SBINITIALIZED)) {
/* Defer initialization until selinux_complete_init,
after the initial policy is loaded and the security
server is ready to handle calls. */
spin_lock(&sbsec->isec_lock);
if (list_empty(&isec->list))
list_add(&isec->list, &sbsec->isec_head);
spin_unlock(&sbsec->isec_lock);
goto out_unlock;
}
switch (sbsec->behavior) {
case SECURITY_FS_USE_XATTR:
if (!inode->i_op->getxattr) {
isec->sid = sbsec->def_sid;
break;
}
/* Need a dentry, since the xattr API requires one.
Life would be simpler if we could just pass the inode. */
if (opt_dentry) {
/* Called from d_instantiate or d_splice_alias. */
dentry = dget(opt_dentry);
} else {
/* Called from selinux_complete_init, try to find a dentry. */
dentry = d_find_alias(inode);
}
if (!dentry) {
/*
* this is can be hit on boot when a file is accessed
* before the policy is loaded. When we load policy we
* may find inodes that have no dentry on the
* sbsec->isec_head list. No reason to complain as these
* will get fixed up the next time we go through
* inode_doinit with a dentry, before these inodes could
* be used again by userspace.
*/
goto out_unlock;
}
len = INITCONTEXTLEN;
context = kmalloc(len+1, GFP_NOFS);
if (!context) {
rc = -ENOMEM;
dput(dentry);
goto out_unlock;
}
context[len] = '\0';
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
context, len);
if (rc == -ERANGE) {
kfree(context);
/* Need a larger buffer. Query for the right size. */
rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
NULL, 0);
if (rc < 0) {
dput(dentry);
goto out_unlock;
}
len = rc;
context = kmalloc(len+1, GFP_NOFS);
if (!context) {
rc = -ENOMEM;
dput(dentry);
goto out_unlock;
}
context[len] = '\0';
rc = inode->i_op->getxattr(dentry,
XATTR_NAME_SELINUX,
context, len);
}
dput(dentry);
if (rc < 0) {
if (rc != -ENODATA) {
printk(KERN_WARNING "SELinux: %s: getxattr returned "
"%d for dev=%s ino=%ld\n", __func__,
-rc, inode->i_sb->s_id, inode->i_ino);
kfree(context);
goto out_unlock;
}
/* Map ENODATA to the default file SID */
sid = sbsec->def_sid;
rc = 0;
} else {
rc = security_context_to_sid_default(context, rc, &sid,
sbsec->def_sid,
GFP_NOFS);
if (rc) {
char *dev = inode->i_sb->s_id;
unsigned long ino = inode->i_ino;
if (rc == -EINVAL) {
if (printk_ratelimit())
printk(KERN_NOTICE "SELinux: inode=%lu on dev=%s was found to have an invalid "
"context=%s. This indicates you may need to relabel the inode or the "
"filesystem in question.\n", ino, dev, context);
} else {
printk(KERN_WARNING "SELinux: %s: context_to_sid(%s) "
"returned %d for dev=%s ino=%ld\n",
__func__, context, -rc, dev, ino);
}
kfree(context);
/* Leave with the unlabeled SID */
rc = 0;
break;
}
}
kfree(context);
isec->sid = sid;
break;
case SECURITY_FS_USE_TASK:
isec->sid = isec->task_sid;
break;
case SECURITY_FS_USE_TRANS:
/* Default to the fs SID. */
isec->sid = sbsec->sid;
/* Try to obtain a transition SID. */
isec->sclass = inode_mode_to_security_class(inode->i_mode);
rc = security_transition_sid(isec->task_sid, sbsec->sid,
isec->sclass, NULL, &sid);
if (rc)
goto out_unlock;
isec->sid = sid;
break;
case SECURITY_FS_USE_MNTPOINT:
isec->sid = sbsec->mntpoint_sid;
break;
default:
/* Default to the fs superblock SID. */
isec->sid = sbsec->sid;
if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) {
if (opt_dentry) {
isec->sclass = inode_mode_to_security_class(inode->i_mode);
rc = selinux_proc_get_sid(opt_dentry,
isec->sclass,
&sid);
if (rc)
goto out_unlock;
isec->sid = sid;
}
}
break;
}
isec->initialized = 1;
out_unlock:
mutex_unlock(&isec->lock);
out:
if (isec->sclass == SECCLASS_FILE)
isec->sclass = inode_mode_to_security_class(inode->i_mode);
return rc;
}
/* Convert a Linux signal to an access vector. */
static inline u32 signal_to_av(int sig)
{
u32 perm = 0;
switch (sig) {
case SIGCHLD:
/* Commonly granted from child to parent. */
perm = PROCESS__SIGCHLD;
break;
case SIGKILL:
/* Cannot be caught or ignored */
perm = PROCESS__SIGKILL;
break;
case SIGSTOP:
/* Cannot be caught or ignored */
perm = PROCESS__SIGSTOP;
break;
default:
/* All other signals. */
perm = PROCESS__SIGNAL;
break;
}
return perm;
}
/*
* Check permission between a pair of credentials
* fork check, ptrace check, etc.
*/
static int cred_has_perm(const struct cred *actor,
const struct cred *target,
u32 perms)
{
u32 asid = cred_sid(actor), tsid = cred_sid(target);
return avc_has_perm(asid, tsid, SECCLASS_PROCESS, perms, NULL);
}
/*
* Check permission between a pair of tasks, e.g. signal checks,
* fork check, ptrace check, etc.
* tsk1 is the actor and tsk2 is the target
* - this uses the default subjective creds of tsk1
*/
static int task_has_perm(const struct task_struct *tsk1,
const struct task_struct *tsk2,
u32 perms)
{
const struct task_security_struct *__tsec1, *__tsec2;
u32 sid1, sid2;
rcu_read_lock();
__tsec1 = __task_cred(tsk1)->security; sid1 = __tsec1->sid;
__tsec2 = __task_cred(tsk2)->security; sid2 = __tsec2->sid;
rcu_read_unlock();
return avc_has_perm(sid1, sid2, SECCLASS_PROCESS, perms, NULL);
}
/*
* Check permission between current and another task, e.g. signal checks,
* fork check, ptrace check, etc.
* current is the actor and tsk2 is the target
* - this uses current's subjective creds
*/
static int current_has_perm(const struct task_struct *tsk,
u32 perms)
{
u32 sid, tsid;
sid = current_sid();
tsid = task_sid(tsk);
return avc_has_perm(sid, tsid, SECCLASS_PROCESS, perms, NULL);
}
#if CAP_LAST_CAP > 63
#error Fix SELinux to handle capabilities > 63.
#endif
/* Check whether a task is allowed to use a capability. */
static int task_has_capability(struct task_struct *tsk,
const struct cred *cred,
int cap, int audit)
{
struct common_audit_data ad;
struct av_decision avd;
u16 sclass;
u32 sid = cred_sid(cred);
u32 av = CAP_TO_MASK(cap);
int rc;
COMMON_AUDIT_DATA_INIT(&ad, CAP);
ad.tsk = tsk;
ad.u.cap = cap;
switch (CAP_TO_INDEX(cap)) {
case 0:
sclass = SECCLASS_CAPABILITY;
break;
case 1:
sclass = SECCLASS_CAPABILITY2;
break;
default:
printk(KERN_ERR
"SELinux: out of range capability %d\n", cap);
BUG();
return -EINVAL;
}
rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
if (audit == SECURITY_CAP_AUDIT) {
int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad, 0);
if (rc2)
return rc2;
}
return rc;
}
/* Check whether a task is allowed to use a system operation. */
static int task_has_system(struct task_struct *tsk,
u32 perms)
{
u32 sid = task_sid(tsk);
return avc_has_perm(sid, SECINITSID_KERNEL,
SECCLASS_SYSTEM, perms, NULL);
}
/* Check whether a task has a particular permission to an inode.
The 'adp' parameter is optional and allows other audit
data to be passed (e.g. the dentry). */
static int inode_has_perm(const struct cred *cred,
struct inode *inode,
u32 perms,
struct common_audit_data *adp,
unsigned flags)
{
struct inode_security_struct *isec;
u32 sid;
validate_creds(cred);
if (unlikely(IS_PRIVATE(inode)))
return 0;
sid = cred_sid(cred);
isec = inode->i_security;
return avc_has_perm_flags(sid, isec->sid, isec->sclass, perms, adp, flags);
}
static int inode_has_perm_noadp(const struct cred *cred,
struct inode *inode,
u32 perms,
unsigned flags)
{
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, INODE);
ad.u.inode = inode;
return inode_has_perm(cred, inode, perms, &ad, flags);
}
/* Same as inode_has_perm, but pass explicit audit data containing
the dentry to help the auditing code to more easily generate the
pathname if needed. */
static inline int dentry_has_perm(const struct cred *cred,
struct dentry *dentry,
u32 av)
{
struct inode *inode = dentry->d_inode;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
return inode_has_perm(cred, inode, av, &ad, 0);
}
/* Same as inode_has_perm, but pass explicit audit data containing
the path to help the auditing code to more easily generate the
pathname if needed. */
static inline int path_has_perm(const struct cred *cred,
struct path *path,
u32 av)
{
struct inode *inode = path->dentry->d_inode;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = *path;
return inode_has_perm(cred, inode, av, &ad, 0);
}
/* Check whether a task can use an open file descriptor to
access an inode in a given way. Check access to the
descriptor itself, and then use dentry_has_perm to
check a particular permission to the file.
Access to the descriptor is implicitly granted if it
has the same SID as the process. If av is zero, then
access to the file is not checked, e.g. for cases
where only the descriptor is affected like seek. */
static int file_has_perm(const struct cred *cred,
struct file *file,
u32 av)
{
struct file_security_struct *fsec = file->f_security;
struct inode *inode = file->f_path.dentry->d_inode;
struct common_audit_data ad;
u32 sid = cred_sid(cred);
int rc;
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = file->f_path;
if (sid != fsec->sid) {
rc = avc_has_perm(sid, fsec->sid,
SECCLASS_FD,
FD__USE,
&ad);
if (rc)
goto out;
}
/* av is zero if only checking access to the descriptor. */
rc = 0;
if (av)
rc = inode_has_perm(cred, inode, av, &ad, 0);
out:
return rc;
}
/* Check whether a task can create a file. */
static int may_create(struct inode *dir,
struct dentry *dentry,
u16 tclass)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *dsec;
struct superblock_security_struct *sbsec;
u32 sid, newsid;
struct common_audit_data ad;
int rc;
dsec = dir->i_security;
sbsec = dir->i_sb->s_security;
sid = tsec->sid;
newsid = tsec->create_sid;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
DIR__ADD_NAME | DIR__SEARCH,
&ad);
if (rc)
return rc;
if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
rc = security_transition_sid(sid, dsec->sid, tclass,
&dentry->d_name, &newsid);
if (rc)
return rc;
}
rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
if (rc)
return rc;
return avc_has_perm(newsid, sbsec->sid,
SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE, &ad);
}
/* Check whether a task can create a key. */
static int may_create_key(u32 ksid,
struct task_struct *ctx)
{
u32 sid = task_sid(ctx);
return avc_has_perm(sid, ksid, SECCLASS_KEY, KEY__CREATE, NULL);
}
#define MAY_LINK 0
#define MAY_UNLINK 1
#define MAY_RMDIR 2
/* Check whether a task can link, unlink, or rmdir a file/directory. */
static int may_link(struct inode *dir,
struct dentry *dentry,
int kind)
{
struct inode_security_struct *dsec, *isec;
struct common_audit_data ad;
u32 sid = current_sid();
u32 av;
int rc;
dsec = dir->i_security;
isec = dentry->d_inode->i_security;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
av = DIR__SEARCH;
av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
if (rc)
return rc;
switch (kind) {
case MAY_LINK:
av = FILE__LINK;
break;
case MAY_UNLINK:
av = FILE__UNLINK;
break;
case MAY_RMDIR:
av = DIR__RMDIR;
break;
default:
printk(KERN_WARNING "SELinux: %s: unrecognized kind %d\n",
__func__, kind);
return 0;
}
rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
return rc;
}
static inline int may_rename(struct inode *old_dir,
struct dentry *old_dentry,
struct inode *new_dir,
struct dentry *new_dentry)
{
struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
struct common_audit_data ad;
u32 sid = current_sid();
u32 av;
int old_is_dir, new_is_dir;
int rc;
old_dsec = old_dir->i_security;
old_isec = old_dentry->d_inode->i_security;
old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
new_dsec = new_dir->i_security;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = old_dentry;
rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
DIR__REMOVE_NAME | DIR__SEARCH, &ad);
if (rc)
return rc;
rc = avc_has_perm(sid, old_isec->sid,
old_isec->sclass, FILE__RENAME, &ad);
if (rc)
return rc;
if (old_is_dir && new_dir != old_dir) {
rc = avc_has_perm(sid, old_isec->sid,
old_isec->sclass, DIR__REPARENT, &ad);
if (rc)
return rc;
}
ad.u.dentry = new_dentry;
av = DIR__ADD_NAME | DIR__SEARCH;
if (new_dentry->d_inode)
av |= DIR__REMOVE_NAME;
rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
if (rc)
return rc;
if (new_dentry->d_inode) {
new_isec = new_dentry->d_inode->i_security;
new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
rc = avc_has_perm(sid, new_isec->sid,
new_isec->sclass,
(new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
if (rc)
return rc;
}
return 0;
}
/* Check whether a task can perform a filesystem operation. */
static int superblock_has_perm(const struct cred *cred,
struct super_block *sb,
u32 perms,
struct common_audit_data *ad)
{
struct superblock_security_struct *sbsec;
u32 sid = cred_sid(cred);
sbsec = sb->s_security;
return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
}
/* Convert a Linux mode and permission mask to an access vector. */
static inline u32 file_mask_to_av(int mode, int mask)
{
u32 av = 0;
if ((mode & S_IFMT) != S_IFDIR) {
if (mask & MAY_EXEC)
av |= FILE__EXECUTE;
if (mask & MAY_READ)
av |= FILE__READ;
if (mask & MAY_APPEND)
av |= FILE__APPEND;
else if (mask & MAY_WRITE)
av |= FILE__WRITE;
} else {
if (mask & MAY_EXEC)
av |= DIR__SEARCH;
if (mask & MAY_WRITE)
av |= DIR__WRITE;
if (mask & MAY_READ)
av |= DIR__READ;
}
return av;
}
/* Convert a Linux file to an access vector. */
static inline u32 file_to_av(struct file *file)
{
u32 av = 0;
if (file->f_mode & FMODE_READ)
av |= FILE__READ;
if (file->f_mode & FMODE_WRITE) {
if (file->f_flags & O_APPEND)
av |= FILE__APPEND;
else
av |= FILE__WRITE;
}
if (!av) {
/*
* Special file opened with flags 3 for ioctl-only use.
*/
av = FILE__IOCTL;
}
return av;
}
/*
* Convert a file to an access vector and include the correct open
* open permission.
*/
static inline u32 open_file_to_av(struct file *file)
{
u32 av = file_to_av(file);
if (selinux_policycap_openperm)
av |= FILE__OPEN;
return av;
}
/* Hook functions begin here. */
static int selinux_ptrace_access_check(struct task_struct *child,
unsigned int mode)
{
int rc;
rc = cap_ptrace_access_check(child, mode);
if (rc)
return rc;
if (mode == PTRACE_MODE_READ) {
u32 sid = current_sid();
u32 csid = task_sid(child);
return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ, NULL);
}
return current_has_perm(child, PROCESS__PTRACE);
}
static int selinux_ptrace_traceme(struct task_struct *parent)
{
int rc;
rc = cap_ptrace_traceme(parent);
if (rc)
return rc;
return task_has_perm(parent, current, PROCESS__PTRACE);
}
static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
kernel_cap_t *inheritable, kernel_cap_t *permitted)
{
int error;
error = current_has_perm(target, PROCESS__GETCAP);
if (error)
return error;
return cap_capget(target, effective, inheritable, permitted);
}
static int selinux_capset(struct cred *new, const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted)
{
int error;
error = cap_capset(new, old,
effective, inheritable, permitted);
if (error)
return error;
return cred_has_perm(old, new, PROCESS__SETCAP);
}
/*
* (This comment used to live with the selinux_task_setuid hook,
* which was removed).
*
* Since setuid only affects the current process, and since the SELinux
* controls are not based on the Linux identity attributes, SELinux does not
* need to control this operation. However, SELinux does control the use of
* the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
*/
static int selinux_capable(struct task_struct *tsk, const struct cred *cred,
struct user_namespace *ns, int cap, int audit)
{
int rc;
rc = cap_capable(tsk, cred, ns, cap, audit);
if (rc)
return rc;
return task_has_capability(tsk, cred, cap, audit);
}
static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
{
const struct cred *cred = current_cred();
int rc = 0;
if (!sb)
return 0;
switch (cmds) {
case Q_SYNC:
case Q_QUOTAON:
case Q_QUOTAOFF:
case Q_SETINFO:
case Q_SETQUOTA:
rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
break;
case Q_GETFMT:
case Q_GETINFO:
case Q_GETQUOTA:
rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
break;
default:
rc = 0; /* let the kernel handle invalid cmds */
break;
}
return rc;
}
static int selinux_quota_on(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__QUOTAON);
}
static int selinux_syslog(int type)
{
int rc;
switch (type) {
case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
rc = task_has_system(current, SYSTEM__SYSLOG_READ);
break;
case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
/* Set level of messages printed to console */
case SYSLOG_ACTION_CONSOLE_LEVEL:
rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
break;
case SYSLOG_ACTION_CLOSE: /* Close log */
case SYSLOG_ACTION_OPEN: /* Open log */
case SYSLOG_ACTION_READ: /* Read from log */
case SYSLOG_ACTION_READ_CLEAR: /* Read/clear last kernel messages */
case SYSLOG_ACTION_CLEAR: /* Clear ring buffer */
default:
rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
break;
}
return rc;
}
/*
* Check that a process has enough memory to allocate a new virtual
* mapping. 0 means there is enough memory for the allocation to
* succeed and -ENOMEM implies there is not.
*
* Do not audit the selinux permission check, as this is applied to all
* processes that allocate mappings.
*/
static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
{
int rc, cap_sys_admin = 0;
rc = selinux_capable(current, current_cred(),
&init_user_ns, CAP_SYS_ADMIN,
SECURITY_CAP_NOAUDIT);
if (rc == 0)
cap_sys_admin = 1;
return __vm_enough_memory(mm, pages, cap_sys_admin);
}
/* binprm security operations */
static int selinux_bprm_set_creds(struct linux_binprm *bprm)
{
const struct task_security_struct *old_tsec;
struct task_security_struct *new_tsec;
struct inode_security_struct *isec;
struct common_audit_data ad;
struct inode *inode = bprm->file->f_path.dentry->d_inode;
int rc;
rc = cap_bprm_set_creds(bprm);
if (rc)
return rc;
/* SELinux context only depends on initial program or script and not
* the script interpreter */
if (bprm->cred_prepared)
return 0;
old_tsec = current_security();
new_tsec = bprm->cred->security;
isec = inode->i_security;
/* Default to the current task SID. */
new_tsec->sid = old_tsec->sid;
new_tsec->osid = old_tsec->sid;
/* Reset fs, key, and sock SIDs on execve. */
new_tsec->create_sid = 0;
new_tsec->keycreate_sid = 0;
new_tsec->sockcreate_sid = 0;
if (old_tsec->exec_sid) {
new_tsec->sid = old_tsec->exec_sid;
/* Reset exec SID on execve. */
new_tsec->exec_sid = 0;
} else {
/* Check for a default transition on this program. */
rc = security_transition_sid(old_tsec->sid, isec->sid,
SECCLASS_PROCESS, NULL,
&new_tsec->sid);
if (rc)
return rc;
}
COMMON_AUDIT_DATA_INIT(&ad, PATH);
ad.u.path = bprm->file->f_path;
if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
new_tsec->sid = old_tsec->sid;
if (new_tsec->sid == old_tsec->sid) {
rc = avc_has_perm(old_tsec->sid, isec->sid,
SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
if (rc)
return rc;
} else {
/* Check permissions for the transition. */
rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
if (rc)
return rc;
rc = avc_has_perm(new_tsec->sid, isec->sid,
SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
if (rc)
return rc;
/* Check for shared state */
if (bprm->unsafe & LSM_UNSAFE_SHARE) {
rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
SECCLASS_PROCESS, PROCESS__SHARE,
NULL);
if (rc)
return -EPERM;
}
/* Make sure that anyone attempting to ptrace over a task that
* changes its SID has the appropriate permit */
if (bprm->unsafe &
(LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
struct task_struct *tracer;
struct task_security_struct *sec;
u32 ptsid = 0;
rcu_read_lock();
tracer = tracehook_tracer_task(current);
if (likely(tracer != NULL)) {
sec = __task_cred(tracer)->security;
ptsid = sec->sid;
}
rcu_read_unlock();
if (ptsid != 0) {
rc = avc_has_perm(ptsid, new_tsec->sid,
SECCLASS_PROCESS,
PROCESS__PTRACE, NULL);
if (rc)
return -EPERM;
}
}
/* Clear any possibly unsafe personality bits on exec: */
bprm->per_clear |= PER_CLEAR_ON_SETID;
}
return 0;
}
static int selinux_bprm_secureexec(struct linux_binprm *bprm)
{
const struct task_security_struct *tsec = current_security();
u32 sid, osid;
int atsecure = 0;
sid = tsec->sid;
osid = tsec->osid;
if (osid != sid) {
/* Enable secure mode for SIDs transitions unless
the noatsecure permission is granted between
the two SIDs, i.e. ahp returns 0. */
atsecure = avc_has_perm(osid, sid,
SECCLASS_PROCESS,
PROCESS__NOATSECURE, NULL);
}
return (atsecure || cap_bprm_secureexec(bprm));
}
extern struct vfsmount *selinuxfs_mount;
extern struct dentry *selinux_null;
/* Derived from fs/exec.c:flush_old_files. */
static inline void flush_unauthorized_files(const struct cred *cred,
struct files_struct *files)
{
struct common_audit_data ad;
struct file *file, *devnull = NULL;
struct tty_struct *tty;
struct fdtable *fdt;
long j = -1;
int drop_tty = 0;
tty = get_current_tty();
if (tty) {
spin_lock(&tty_files_lock);
if (!list_empty(&tty->tty_files)) {
struct tty_file_private *file_priv;
struct inode *inode;
/* Revalidate access to controlling tty.
Use inode_has_perm on the tty inode directly rather
than using file_has_perm, as this particular open
file may belong to another process and we are only
interested in the inode-based check here. */
file_priv = list_first_entry(&tty->tty_files,
struct tty_file_private, list);
file = file_priv->file;
inode = file->f_path.dentry->d_inode;
if (inode_has_perm_noadp(cred, inode,
FILE__READ | FILE__WRITE, 0)) {
drop_tty = 1;
}
}
spin_unlock(&tty_files_lock);
tty_kref_put(tty);
}
/* Reset controlling tty. */
if (drop_tty)
no_tty();
/* Revalidate access to inherited open files. */
COMMON_AUDIT_DATA_INIT(&ad, INODE);
spin_lock(&files->file_lock);
for (;;) {
unsigned long set, i;
int fd;
j++;
i = j * __NFDBITS;
fdt = files_fdtable(files);
if (i >= fdt->max_fds)
break;
set = fdt->open_fds->fds_bits[j];
if (!set)
continue;
spin_unlock(&files->file_lock);
for ( ; set ; i++, set >>= 1) {
if (set & 1) {
file = fget(i);
if (!file)
continue;
if (file_has_perm(cred,
file,
file_to_av(file))) {
sys_close(i);
fd = get_unused_fd();
if (fd != i) {
if (fd >= 0)
put_unused_fd(fd);
fput(file);
continue;
}
if (devnull) {
get_file(devnull);
} else {
devnull = dentry_open(
dget(selinux_null),
mntget(selinuxfs_mount),
O_RDWR, cred);
if (IS_ERR(devnull)) {
devnull = NULL;
put_unused_fd(fd);
fput(file);
continue;
}
}
fd_install(fd, devnull);
}
fput(file);
}
}
spin_lock(&files->file_lock);
}
spin_unlock(&files->file_lock);
}
/*
* Prepare a process for imminent new credential changes due to exec
*/
static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
{
struct task_security_struct *new_tsec;
struct rlimit *rlim, *initrlim;
int rc, i;
new_tsec = bprm->cred->security;
if (new_tsec->sid == new_tsec->osid)
return;
/* Close files for which the new task SID is not authorized. */
flush_unauthorized_files(bprm->cred, current->files);
/* Always clear parent death signal on SID transitions. */
current->pdeath_signal = 0;
/* Check whether the new SID can inherit resource limits from the old
* SID. If not, reset all soft limits to the lower of the current
* task's hard limit and the init task's soft limit.
*
* Note that the setting of hard limits (even to lower them) can be
* controlled by the setrlimit check. The inclusion of the init task's
* soft limit into the computation is to avoid resetting soft limits
* higher than the default soft limit for cases where the default is
* lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
*/
rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
PROCESS__RLIMITINH, NULL);
if (rc) {
/* protect against do_prlimit() */
task_lock(current);
for (i = 0; i < RLIM_NLIMITS; i++) {
rlim = current->signal->rlim + i;
initrlim = init_task.signal->rlim + i;
rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
}
task_unlock(current);
update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
}
}
/*
* Clean up the process immediately after the installation of new credentials
* due to exec
*/
static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
{
const struct task_security_struct *tsec = current_security();
struct itimerval itimer;
u32 osid, sid;
int rc, i;
osid = tsec->osid;
sid = tsec->sid;
if (sid == osid)
return;
/* Check whether the new SID can inherit signal state from the old SID.
* If not, clear itimers to avoid subsequent signal generation and
* flush and unblock signals.
*
* This must occur _after_ the task SID has been updated so that any
* kill done after the flush will be checked against the new SID.
*/
rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
if (rc) {
memset(&itimer, 0, sizeof itimer);
for (i = 0; i < 3; i++)
do_setitimer(i, &itimer, NULL);
spin_lock_irq(¤t->sighand->siglock);
if (!(current->signal->flags & SIGNAL_GROUP_EXIT)) {
__flush_signals(current);
flush_signal_handlers(current, 1);
sigemptyset(¤t->blocked);
}
spin_unlock_irq(¤t->sighand->siglock);
}
/* Wake up the parent if it is waiting so that it can recheck
* wait permission to the new task SID. */
read_lock(&tasklist_lock);
__wake_up_parent(current, current->real_parent);
read_unlock(&tasklist_lock);
}
/* superblock security operations */
static int selinux_sb_alloc_security(struct super_block *sb)
{
return superblock_alloc_security(sb);
}
static void selinux_sb_free_security(struct super_block *sb)
{
superblock_free_security(sb);
}
static inline int match_prefix(char *prefix, int plen, char *option, int olen)
{
if (plen > olen)
return 0;
return !memcmp(prefix, option, plen);
}
static inline int selinux_option(char *option, int len)
{
return (match_prefix(CONTEXT_STR, sizeof(CONTEXT_STR)-1, option, len) ||
match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, len) ||
match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, len) ||
match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, option, len) ||
match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, len));
}
static inline void take_option(char **to, char *from, int *first, int len)
{
if (!*first) {
**to = ',';
*to += 1;
} else
*first = 0;
memcpy(*to, from, len);
*to += len;
}
static inline void take_selinux_option(char **to, char *from, int *first,
int len)
{
int current_size = 0;
if (!*first) {
**to = '|';
*to += 1;
} else
*first = 0;
while (current_size < len) {
if (*from != '"') {
**to = *from;
*to += 1;
}
from += 1;
current_size += 1;
}
}
static int selinux_sb_copy_data(char *orig, char *copy)
{
int fnosec, fsec, rc = 0;
char *in_save, *in_curr, *in_end;
char *sec_curr, *nosec_save, *nosec;
int open_quote = 0;
in_curr = orig;
sec_curr = copy;
nosec = (char *)get_zeroed_page(GFP_KERNEL);
if (!nosec) {
rc = -ENOMEM;
goto out;
}
nosec_save = nosec;
fnosec = fsec = 1;
in_save = in_end = orig;
do {
if (*in_end == '"')
open_quote = !open_quote;
if ((*in_end == ',' && open_quote == 0) ||
*in_end == '\0') {
int len = in_end - in_curr;
if (selinux_option(in_curr, len))
take_selinux_option(&sec_curr, in_curr, &fsec, len);
else
take_option(&nosec, in_curr, &fnosec, len);
in_curr = in_end + 1;
}
} while (*in_end++);
strcpy(in_save, nosec_save);
free_page((unsigned long)nosec_save);
out:
return rc;
}
static int selinux_sb_remount(struct super_block *sb, void *data)
{
int rc, i, *flags;
struct security_mnt_opts opts;
char *secdata, **mount_options;
struct superblock_security_struct *sbsec = sb->s_security;
if (!(sbsec->flags & SE_SBINITIALIZED))
return 0;
if (!data)
return 0;
if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
return 0;
security_init_mnt_opts(&opts);
secdata = alloc_secdata();
if (!secdata)
return -ENOMEM;
rc = selinux_sb_copy_data(data, secdata);
if (rc)
goto out_free_secdata;
rc = selinux_parse_opts_str(secdata, &opts);
if (rc)
goto out_free_secdata;
mount_options = opts.mnt_opts;
flags = opts.mnt_opts_flags;
for (i = 0; i < opts.num_mnt_opts; i++) {
u32 sid;
size_t len;
if (flags[i] == SE_SBLABELSUPP)
continue;
len = strlen(mount_options[i]);
rc = security_context_to_sid(mount_options[i], len, &sid);
if (rc) {
printk(KERN_WARNING "SELinux: security_context_to_sid"
"(%s) failed for (dev %s, type %s) errno=%d\n",
mount_options[i], sb->s_id, sb->s_type->name, rc);
goto out_free_opts;
}
rc = -EINVAL;
switch (flags[i]) {
case FSCONTEXT_MNT:
if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
goto out_bad_option;
break;
case CONTEXT_MNT:
if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
goto out_bad_option;
break;
case ROOTCONTEXT_MNT: {
struct inode_security_struct *root_isec;
root_isec = sb->s_root->d_inode->i_security;
if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
goto out_bad_option;
break;
}
case DEFCONTEXT_MNT:
if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
goto out_bad_option;
break;
default:
goto out_free_opts;
}
}
rc = 0;
out_free_opts:
security_free_mnt_opts(&opts);
out_free_secdata:
free_secdata(secdata);
return rc;
out_bad_option:
printk(KERN_WARNING "SELinux: unable to change security options "
"during remount (dev %s, type=%s)\n", sb->s_id,
sb->s_type->name);
goto out_free_opts;
}
static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
int rc;
rc = superblock_doinit(sb, data);
if (rc)
return rc;
/* Allow all mounts performed by the kernel */
if (flags & MS_KERNMOUNT)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = sb->s_root;
return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
}
static int selinux_sb_statfs(struct dentry *dentry)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry->d_sb->s_root;
return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
}
static int selinux_mount(char *dev_name,
struct path *path,
char *type,
unsigned long flags,
void *data)
{
const struct cred *cred = current_cred();
if (flags & MS_REMOUNT)
return superblock_has_perm(cred, path->mnt->mnt_sb,
FILESYSTEM__REMOUNT, NULL);
else
return path_has_perm(cred, path, FILE__MOUNTON);
}
static int selinux_umount(struct vfsmount *mnt, int flags)
{
const struct cred *cred = current_cred();
return superblock_has_perm(cred, mnt->mnt_sb,
FILESYSTEM__UNMOUNT, NULL);
}
/* inode security operations */
static int selinux_inode_alloc_security(struct inode *inode)
{
return inode_alloc_security(inode);
}
static void selinux_inode_free_security(struct inode *inode)
{
inode_free_security(inode);
}
static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr, char **name,
void **value, size_t *len)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *dsec;
struct superblock_security_struct *sbsec;
u32 sid, newsid, clen;
int rc;
char *namep = NULL, *context;
dsec = dir->i_security;
sbsec = dir->i_sb->s_security;
sid = tsec->sid;
newsid = tsec->create_sid;
if ((sbsec->flags & SE_SBINITIALIZED) &&
(sbsec->behavior == SECURITY_FS_USE_MNTPOINT))
newsid = sbsec->mntpoint_sid;
else if (!newsid || !(sbsec->flags & SE_SBLABELSUPP)) {
rc = security_transition_sid(sid, dsec->sid,
inode_mode_to_security_class(inode->i_mode),
qstr, &newsid);
if (rc) {
printk(KERN_WARNING "%s: "
"security_transition_sid failed, rc=%d (dev=%s "
"ino=%ld)\n",
__func__,
-rc, inode->i_sb->s_id, inode->i_ino);
return rc;
}
}
/* Possibly defer initialization to selinux_complete_init. */
if (sbsec->flags & SE_SBINITIALIZED) {
struct inode_security_struct *isec = inode->i_security;
isec->sclass = inode_mode_to_security_class(inode->i_mode);
isec->sid = newsid;
isec->initialized = 1;
}
if (!ss_initialized || !(sbsec->flags & SE_SBLABELSUPP))
return -EOPNOTSUPP;
if (name) {
namep = kstrdup(XATTR_SELINUX_SUFFIX, GFP_NOFS);
if (!namep)
return -ENOMEM;
*name = namep;
}
if (value && len) {
rc = security_sid_to_context_force(newsid, &context, &clen);
if (rc) {
kfree(namep);
return rc;
}
*value = context;
*len = clen;
}
return 0;
}
static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask)
{
return may_create(dir, dentry, SECCLASS_FILE);
}
static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
{
return may_link(dir, old_dentry, MAY_LINK);
}
static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
{
return may_link(dir, dentry, MAY_UNLINK);
}
static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
{
return may_create(dir, dentry, SECCLASS_LNK_FILE);
}
static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask)
{
return may_create(dir, dentry, SECCLASS_DIR);
}
static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
{
return may_link(dir, dentry, MAY_RMDIR);
}
static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
{
return may_create(dir, dentry, inode_mode_to_security_class(mode));
}
static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
struct inode *new_inode, struct dentry *new_dentry)
{
return may_rename(old_inode, old_dentry, new_inode, new_dentry);
}
static int selinux_inode_readlink(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__READ);
}
static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__READ);
}
static int selinux_inode_permission(struct inode *inode, int mask, unsigned flags)
{
const struct cred *cred = current_cred();
struct common_audit_data ad;
u32 perms;
bool from_access;
from_access = mask & MAY_ACCESS;
mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
/* No permission to check. Existence test. */
if (!mask)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, INODE);
ad.u.inode = inode;
if (from_access)
ad.selinux_audit_data.auditdeny |= FILE__AUDIT_ACCESS;
perms = file_mask_to_av(inode->i_mode, mask);
return inode_has_perm(cred, inode, perms, &ad, flags);
}
static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
{
const struct cred *cred = current_cred();
unsigned int ia_valid = iattr->ia_valid;
/* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
if (ia_valid & ATTR_FORCE) {
ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
ATTR_FORCE);
if (!ia_valid)
return 0;
}
if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
return dentry_has_perm(cred, dentry, FILE__SETATTR);
return dentry_has_perm(cred, dentry, FILE__WRITE);
}
static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
{
const struct cred *cred = current_cred();
struct path path;
path.dentry = dentry;
path.mnt = mnt;
return path_has_perm(cred, &path, FILE__GETATTR);
}
static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
{
const struct cred *cred = current_cred();
if (!strncmp(name, XATTR_SECURITY_PREFIX,
sizeof XATTR_SECURITY_PREFIX - 1)) {
if (!strcmp(name, XATTR_NAME_CAPS)) {
if (!capable(CAP_SETFCAP))
return -EPERM;
} else if (!capable(CAP_SYS_ADMIN)) {
/* A different attribute in the security namespace.
Restrict to administrator. */
return -EPERM;
}
}
/* Not an attribute we recognize, so just check the
ordinary setattr permission. */
return dentry_has_perm(cred, dentry, FILE__SETATTR);
}
static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags)
{
struct inode *inode = dentry->d_inode;
struct inode_security_struct *isec = inode->i_security;
struct superblock_security_struct *sbsec;
struct common_audit_data ad;
u32 newsid, sid = current_sid();
int rc = 0;
if (strcmp(name, XATTR_NAME_SELINUX))
return selinux_inode_setotherxattr(dentry, name);
sbsec = inode->i_sb->s_security;
if (!(sbsec->flags & SE_SBLABELSUPP))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
COMMON_AUDIT_DATA_INIT(&ad, DENTRY);
ad.u.dentry = dentry;
rc = avc_has_perm(sid, isec->sid, isec->sclass,
FILE__RELABELFROM, &ad);
if (rc)
return rc;
rc = security_context_to_sid(value, size, &newsid);
if (rc == -EINVAL) {
if (!capable(CAP_MAC_ADMIN))
return rc;
rc = security_context_to_sid_force(value, size, &newsid);
}
if (rc)
return rc;
rc = avc_has_perm(sid, newsid, isec->sclass,
FILE__RELABELTO, &ad);
if (rc)
return rc;
rc = security_validate_transition(isec->sid, newsid, sid,
isec->sclass);
if (rc)
return rc;
return avc_has_perm(newsid,
sbsec->sid,
SECCLASS_FILESYSTEM,
FILESYSTEM__ASSOCIATE,
&ad);
}
static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size,
int flags)
{
struct inode *inode = dentry->d_inode;
struct inode_security_struct *isec = inode->i_security;
u32 newsid;
int rc;
if (strcmp(name, XATTR_NAME_SELINUX)) {
/* Not an attribute we recognize, so nothing to do. */
return;
}
rc = security_context_to_sid_force(value, size, &newsid);
if (rc) {
printk(KERN_ERR "SELinux: unable to map context to SID"
"for (%s, %lu), rc=%d\n",
inode->i_sb->s_id, inode->i_ino, -rc);
return;
}
isec->sid = newsid;
return;
}
static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__GETATTR);
}
static int selinux_inode_listxattr(struct dentry *dentry)
{
const struct cred *cred = current_cred();
return dentry_has_perm(cred, dentry, FILE__GETATTR);
}
static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
{
if (strcmp(name, XATTR_NAME_SELINUX))
return selinux_inode_setotherxattr(dentry, name);
/* No one is allowed to remove a SELinux security label.
You can change the label, but all data must be labeled. */
return -EACCES;
}
/*
* Copy the inode security context value to the user.
*
* Permission check is handled by selinux_inode_getxattr hook.
*/
static int selinux_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc)
{
u32 size;
int error;
char *context = NULL;
struct inode_security_struct *isec = inode->i_security;
if (strcmp(name, XATTR_SELINUX_SUFFIX))
return -EOPNOTSUPP;
/*
* If the caller has CAP_MAC_ADMIN, then get the raw context
* value even if it is not defined by current policy; otherwise,
* use the in-core value under current policy.
* Use the non-auditing forms of the permission checks since
* getxattr may be called by unprivileged processes commonly
* and lack of permission just means that we fall back to the
* in-core context value, not a denial.
*/
error = selinux_capable(current, current_cred(),
&init_user_ns, CAP_MAC_ADMIN,
SECURITY_CAP_NOAUDIT);
if (!error)
error = security_sid_to_context_force(isec->sid, &context,
&size);
else
error = security_sid_to_context(isec->sid, &context, &size);
if (error)
return error;
error = size;
if (alloc) {
*buffer = context;
goto out_nofree;
}
kfree(context);
out_nofree:
return error;
}
static int selinux_inode_setsecurity(struct inode *inode, const char *name,
const void *value, size_t size, int flags)
{
struct inode_security_struct *isec = inode->i_security;
u32 newsid;
int rc;
if (strcmp(name, XATTR_SELINUX_SUFFIX))
return -EOPNOTSUPP;
if (!value || !size)
return -EACCES;
rc = security_context_to_sid((void *)value, size, &newsid);
if (rc)
return rc;
isec->sid = newsid;
isec->initialized = 1;
return 0;
}
static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
{
const int len = sizeof(XATTR_NAME_SELINUX);
if (buffer && len <= buffer_size)
memcpy(buffer, XATTR_NAME_SELINUX, len);
return len;
}
static void selinux_inode_getsecid(const struct inode *inode, u32 *secid)
{
struct inode_security_struct *isec = inode->i_security;
*secid = isec->sid;
}
/* file security operations */
static int selinux_revalidate_file_permission(struct file *file, int mask)
{
const struct cred *cred = current_cred();
struct inode *inode = file->f_path.dentry->d_inode;
/* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
mask |= MAY_APPEND;
return file_has_perm(cred, file,
file_mask_to_av(inode->i_mode, mask));
}
static int selinux_file_permission(struct file *file, int mask)
{
struct inode *inode = file->f_path.dentry->d_inode;
struct file_security_struct *fsec = file->f_security;
struct inode_security_struct *isec = inode->i_security;
u32 sid = current_sid();
if (!mask)
/* No permission to check. Existence test. */
return 0;
if (sid == fsec->sid && fsec->isid == isec->sid &&
fsec->pseqno == avc_policy_seqno())
/* No change since dentry_open check. */
return 0;
return selinux_revalidate_file_permission(file, mask);
}
static int selinux_file_alloc_security(struct file *file)
{
return file_alloc_security(file);
}
static void selinux_file_free_security(struct file *file)
{
file_free_security(file);
}
static int selinux_file_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const struct cred *cred = current_cred();
int error = 0;
switch (cmd) {
case FIONREAD:
/* fall through */
case FIBMAP:
/* fall through */
case FIGETBSZ:
/* fall through */
case EXT2_IOC_GETFLAGS:
/* fall through */
case EXT2_IOC_GETVERSION:
error = file_has_perm(cred, file, FILE__GETATTR);
break;
case EXT2_IOC_SETFLAGS:
/* fall through */
case EXT2_IOC_SETVERSION:
error = file_has_perm(cred, file, FILE__SETATTR);
break;
/* sys_ioctl() checks */
case FIONBIO:
/* fall through */
case FIOASYNC:
error = file_has_perm(cred, file, 0);
break;
case KDSKBENT:
case KDSKBSENT:
error = task_has_capability(current, cred, CAP_SYS_TTY_CONFIG,
SECURITY_CAP_AUDIT);
break;
/* default case assumes that the command will go
* to the file's ioctl() function.
*/
default:
error = file_has_perm(cred, file, FILE__IOCTL);
}
return error;
}
static int default_noexec;
static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
{
const struct cred *cred = current_cred();
int rc = 0;
if (default_noexec &&
(prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) {
/*
* We are making executable an anonymous mapping or a
* private file mapping that will also be writable.
* This has an additional check.
*/
rc = cred_has_perm(cred, cred, PROCESS__EXECMEM);
if (rc)
goto error;
}
if (file) {
/* read access is always possible with a mapping */
u32 av = FILE__READ;
/* write access only matters if the mapping is shared */
if (shared && (prot & PROT_WRITE))
av |= FILE__WRITE;
if (prot & PROT_EXEC)
av |= FILE__EXECUTE;
return file_has_perm(cred, file, av);
}
error:
return rc;
}
static int selinux_file_mmap(struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags,
unsigned long addr, unsigned long addr_only)
{
int rc = 0;
u32 sid = current_sid();
/*
* notice that we are intentionally putting the SELinux check before
* the secondary cap_file_mmap check. This is such a likely attempt
* at bad behaviour/exploit that we always want to get the AVC, even
* if DAC would have also denied the operation.
*/
if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
MEMPROTECT__MMAP_ZERO, NULL);
if (rc)
return rc;
}
/* do DAC check on address space usage */
rc = cap_file_mmap(file, reqprot, prot, flags, addr, addr_only);
if (rc || addr_only)
return rc;
if (selinux_checkreqprot)
prot = reqprot;
return file_map_prot_check(file, prot,
(flags & MAP_TYPE) == MAP_SHARED);
}
static int selinux_file_mprotect(struct vm_area_struct *vma,
unsigned long reqprot,
unsigned long prot)
{
const struct cred *cred = current_cred();
if (selinux_checkreqprot)
prot = reqprot;
if (default_noexec &&
(prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
int rc = 0;
if (vma->vm_start >= vma->vm_mm->start_brk &&
vma->vm_end <= vma->vm_mm->brk) {
rc = cred_has_perm(cred, cred, PROCESS__EXECHEAP);
} else if (!vma->vm_file &&
vma->vm_start <= vma->vm_mm->start_stack &&
vma->vm_end >= vma->vm_mm->start_stack) {
rc = current_has_perm(current, PROCESS__EXECSTACK);
} else if (vma->vm_file && vma->anon_vma) {
/*
* We are making executable a file mapping that has
* had some COW done. Since pages might have been
* written, check ability to execute the possibly
* modified content. This typically should only
* occur for text relocations.
*/
rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
}
if (rc)
return rc;
}
return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
}
static int selinux_file_lock(struct file *file, unsigned int cmd)
{
const struct cred *cred = current_cred();
return file_has_perm(cred, file, FILE__LOCK);
}
static int selinux_file_fcntl(struct file *file, unsigned int cmd,
unsigned long arg)
{
const struct cred *cred = current_cred();
int err = 0;
switch (cmd) {
case F_SETFL:
if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
err = -EINVAL;
break;
}
if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
err = file_has_perm(cred, file, FILE__WRITE);
break;
}
/* fall through */
case F_SETOWN:
case F_SETSIG:
case F_GETFL:
case F_GETOWN:
case F_GETSIG:
/* Just check FD__USE permission */
err = file_has_perm(cred, file, 0);
break;
case F_GETLK:
case F_SETLK:
case F_SETLKW:
#if BITS_PER_LONG == 32
case F_GETLK64:
case F_SETLK64:
case F_SETLKW64:
#endif
if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
err = -EINVAL;
break;
}
err = file_has_perm(cred, file, FILE__LOCK);
break;
}
return err;
}
static int selinux_file_set_fowner(struct file *file)
{
struct file_security_struct *fsec;
fsec = file->f_security;
fsec->fown_sid = current_sid();
return 0;
}
static int selinux_file_send_sigiotask(struct task_struct *tsk,
struct fown_struct *fown, int signum)
{
struct file *file;
u32 sid = task_sid(tsk);
u32 perm;
struct file_security_struct *fsec;
/* struct fown_struct is never outside the context of a struct file */
file = container_of(fown, struct file, f_owner);
fsec = file->f_security;
if (!signum)
perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
else
perm = signal_to_av(signum);
return avc_has_perm(fsec->fown_sid, sid,
SECCLASS_PROCESS, perm, NULL);
}
static int selinux_file_receive(struct file *file)
{
const struct cred *cred = current_cred();
return file_has_perm(cred, file, file_to_av(file));
}
static int selinux_dentry_open(struct file *file, const struct cred *cred)
{
struct file_security_struct *fsec;
struct inode *inode;
struct inode_security_struct *isec;
inode = file->f_path.dentry->d_inode;
fsec = file->f_security;
isec = inode->i_security;
/*
* Save inode label and policy sequence number
* at open-time so that selinux_file_permission
* can determine whether revalidation is necessary.
* Task label is already saved in the file security
* struct as its SID.
*/
fsec->isid = isec->sid;
fsec->pseqno = avc_policy_seqno();
/*
* Since the inode label or policy seqno may have changed
* between the selinux_inode_permission check and the saving
* of state above, recheck that access is still permitted.
* Otherwise, access might never be revalidated against the
* new inode label or new policy.
* This check is not redundant - do not remove.
*/
return inode_has_perm_noadp(cred, inode, open_file_to_av(file), 0);
}
/* task security operations */
static int selinux_task_create(unsigned long clone_flags)
{
return current_has_perm(current, PROCESS__FORK);
}
/*
* allocate the SELinux part of blank credentials
*/
static int selinux_cred_alloc_blank(struct cred *cred, gfp_t gfp)
{
struct task_security_struct *tsec;
tsec = kzalloc(sizeof(struct task_security_struct), gfp);
if (!tsec)
return -ENOMEM;
cred->security = tsec;
return 0;
}
/*
* detach and free the LSM part of a set of credentials
*/
static void selinux_cred_free(struct cred *cred)
{
struct task_security_struct *tsec = cred->security;
/*
* cred->security == NULL if security_cred_alloc_blank() or
* security_prepare_creds() returned an error.
*/
BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE);
cred->security = (void *) 0x7UL;
kfree(tsec);
}
/*
* prepare a new set of credentials for modification
*/
static int selinux_cred_prepare(struct cred *new, const struct cred *old,
gfp_t gfp)
{
const struct task_security_struct *old_tsec;
struct task_security_struct *tsec;
old_tsec = old->security;
tsec = kmemdup(old_tsec, sizeof(struct task_security_struct), gfp);
if (!tsec)
return -ENOMEM;
new->security = tsec;
return 0;
}
/*
* transfer the SELinux data to a blank set of creds
*/
static void selinux_cred_transfer(struct cred *new, const struct cred *old)
{
const struct task_security_struct *old_tsec = old->security;
struct task_security_struct *tsec = new->security;
*tsec = *old_tsec;
}
/*
* set the security data for a kernel service
* - all the creation contexts are set to unlabelled
*/
static int selinux_kernel_act_as(struct cred *new, u32 secid)
{
struct task_security_struct *tsec = new->security;
u32 sid = current_sid();
int ret;
ret = avc_has_perm(sid, secid,
SECCLASS_KERNEL_SERVICE,
KERNEL_SERVICE__USE_AS_OVERRIDE,
NULL);
if (ret == 0) {
tsec->sid = secid;
tsec->create_sid = 0;
tsec->keycreate_sid = 0;
tsec->sockcreate_sid = 0;
}
return ret;
}
/*
* set the file creation context in a security record to the same as the
* objective context of the specified inode
*/
static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
struct task_security_struct *tsec = new->security;
u32 sid = current_sid();
int ret;
ret = avc_has_perm(sid, isec->sid,
SECCLASS_KERNEL_SERVICE,
KERNEL_SERVICE__CREATE_FILES_AS,
NULL);
if (ret == 0)
tsec->create_sid = isec->sid;
return ret;
}
static int selinux_kernel_module_request(char *kmod_name)
{
u32 sid;
struct common_audit_data ad;
sid = task_sid(current);
COMMON_AUDIT_DATA_INIT(&ad, KMOD);
ad.u.kmod_name = kmod_name;
return avc_has_perm(sid, SECINITSID_KERNEL, SECCLASS_SYSTEM,
SYSTEM__MODULE_REQUEST, &ad);
}
static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
{
return current_has_perm(p, PROCESS__SETPGID);
}
static int selinux_task_getpgid(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETPGID);
}
static int selinux_task_getsid(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSESSION);
}
static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
{
*secid = task_sid(p);
}
static int selinux_task_setnice(struct task_struct *p, int nice)
{
int rc;
rc = cap_task_setnice(p, nice);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_setioprio(struct task_struct *p, int ioprio)
{
int rc;
rc = cap_task_setioprio(p, ioprio);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_getioprio(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSCHED);
}
static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
struct rlimit *new_rlim)
{
struct rlimit *old_rlim = p->signal->rlim + resource;
/* Control the ability to change the hard limit (whether
lowering or raising it), so that the hard limit can
later be used as a safe reset point for the soft limit
upon context transitions. See selinux_bprm_committing_creds. */
if (old_rlim->rlim_max != new_rlim->rlim_max)
return current_has_perm(p, PROCESS__SETRLIMIT);
return 0;
}
static int selinux_task_setscheduler(struct task_struct *p)
{
int rc;
rc = cap_task_setscheduler(p);
if (rc)
return rc;
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_getscheduler(struct task_struct *p)
{
return current_has_perm(p, PROCESS__GETSCHED);
}
static int selinux_task_movememory(struct task_struct *p)
{
return current_has_perm(p, PROCESS__SETSCHED);
}
static int selinux_task_kill(struct task_struct *p, struct siginfo *info,
int sig, u32 secid)
{
u32 perm;
int rc;
if (!sig)
perm = PROCESS__SIGNULL; /* null signal; existence test */
else
perm = signal_to_av(sig);
if (secid)
rc = avc_has_perm(secid, task_sid(p),
SECCLASS_PROCESS, perm, NULL);
else
rc = current_has_perm(p, perm);
return rc;
}
static int selinux_task_wait(struct task_struct *p)
{
return task_has_perm(p, current, PROCESS__SIGCHLD);
}
static void selinux_task_to_inode(struct task_struct *p,
struct inode *inode)
{
struct inode_security_struct *isec = inode->i_security;
u32 sid = task_sid(p);
isec->sid = sid;
isec->initialized = 1;
}
/* Returns error only if unable to parse addresses */
static int selinux_parse_skb_ipv4(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
{
int offset, ihlen, ret = -EINVAL;
struct iphdr _iph, *ih;
offset = skb_network_offset(skb);
ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
if (ih == NULL)
goto out;
ihlen = ih->ihl * 4;
if (ihlen < sizeof(_iph))
goto out;
ad->u.net.v4info.saddr = ih->saddr;
ad->u.net.v4info.daddr = ih->daddr;
ret = 0;
if (proto)
*proto = ih->protocol;
switch (ih->protocol) {
case IPPROTO_TCP: {
struct tcphdr _tcph, *th;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
if (th == NULL)
break;
ad->u.net.sport = th->source;
ad->u.net.dport = th->dest;
break;
}
case IPPROTO_UDP: {
struct udphdr _udph, *uh;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
if (uh == NULL)
break;
ad->u.net.sport = uh->source;
ad->u.net.dport = uh->dest;
break;
}
case IPPROTO_DCCP: {
struct dccp_hdr _dccph, *dh;
if (ntohs(ih->frag_off) & IP_OFFSET)
break;
offset += ihlen;
dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
if (dh == NULL)
break;
ad->u.net.sport = dh->dccph_sport;
ad->u.net.dport = dh->dccph_dport;
break;
}
default:
break;
}
out:
return ret;
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
/* Returns error only if unable to parse addresses */
static int selinux_parse_skb_ipv6(struct sk_buff *skb,
struct common_audit_data *ad, u8 *proto)
{
u8 nexthdr;
int ret = -EINVAL, offset;
struct ipv6hdr _ipv6h, *ip6;
offset = skb_network_offset(skb);
ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
if (ip6 == NULL)
goto out;
ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr);
ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr);
ret = 0;
nexthdr = ip6->nexthdr;
offset += sizeof(_ipv6h);
offset = ipv6_skip_exthdr(skb, offset, &nexthdr);
if (offset < 0)
goto out;
if (proto)
*proto = nexthdr;
switch (nexthdr) {
case IPPROTO_TCP: {
struct tcphdr _tcph, *th;
th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
if (th == NULL)
break;
ad->u.net.sport = th->source;
ad->u.net.dport = th->dest;
break;
}
case IPPROTO_UDP: {
struct udphdr _udph, *uh;
uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
if (uh == NULL)
break;
ad->u.net.sport = uh->source;
ad->u.net.dport = uh->dest;
break;
}
case IPPROTO_DCCP: {
struct dccp_hdr _dccph, *dh;
dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
if (dh == NULL)
break;
ad->u.net.sport = dh->dccph_sport;
ad->u.net.dport = dh->dccph_dport;
break;
}
/* includes fragments */
default:
break;
}
out:
return ret;
}
#endif /* IPV6 */
static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
char **_addrp, int src, u8 *proto)
{
char *addrp;
int ret;
switch (ad->u.net.family) {
case PF_INET:
ret = selinux_parse_skb_ipv4(skb, ad, proto);
if (ret)
goto parse_error;
addrp = (char *)(src ? &ad->u.net.v4info.saddr :
&ad->u.net.v4info.daddr);
goto okay;
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
case PF_INET6:
ret = selinux_parse_skb_ipv6(skb, ad, proto);
if (ret)
goto parse_error;
addrp = (char *)(src ? &ad->u.net.v6info.saddr :
&ad->u.net.v6info.daddr);
goto okay;
#endif /* IPV6 */
default:
addrp = NULL;
goto okay;
}
parse_error:
printk(KERN_WARNING
"SELinux: failure in selinux_parse_skb(),"
" unable to parse packet\n");
return ret;
okay:
if (_addrp)
*_addrp = addrp;
return 0;
}
/**
* selinux_skb_peerlbl_sid - Determine the peer label of a packet
* @skb: the packet
* @family: protocol family
* @sid: the packet's peer label SID
*
* Description:
* Check the various different forms of network peer labeling and determine
* the peer label/SID for the packet; most of the magic actually occurs in
* the security server function security_net_peersid_cmp(). The function
* returns zero if the value in @sid is valid (although it may be SECSID_NULL)
* or -EACCES if @sid is invalid due to inconsistencies with the different
* peer labels.
*
*/
static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
{
int err;
u32 xfrm_sid;
u32 nlbl_sid;
u32 nlbl_type;
selinux_skb_xfrm_sid(skb, &xfrm_sid);
selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid);
if (unlikely(err)) {
printk(KERN_WARNING
"SELinux: failure in selinux_skb_peerlbl_sid(),"
" unable to determine packet's peer label\n");
return -EACCES;
}
return 0;
}
/* socket security operations */
static int socket_sockcreate_sid(const struct task_security_struct *tsec,
u16 secclass, u32 *socksid)
{
if (tsec->sockcreate_sid > SECSID_NULL) {
*socksid = tsec->sockcreate_sid;
return 0;
}
return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL,
socksid);
}
static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms)
{
struct sk_security_struct *sksec = sk->sk_security;
struct common_audit_data ad;
u32 tsid = task_sid(task);
if (sksec->sid == SECINITSID_KERNEL)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = sk;
return avc_has_perm(tsid, sksec->sid, sksec->sclass, perms, &ad);
}
static int selinux_socket_create(int family, int type,
int protocol, int kern)
{
const struct task_security_struct *tsec = current_security();
u32 newsid;
u16 secclass;
int rc;
if (kern)
return 0;
secclass = socket_type_to_security_class(family, type, protocol);
rc = socket_sockcreate_sid(tsec, secclass, &newsid);
if (rc)
return rc;
return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
}
static int selinux_socket_post_create(struct socket *sock, int family,
int type, int protocol, int kern)
{
const struct task_security_struct *tsec = current_security();
struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
struct sk_security_struct *sksec;
int err = 0;
isec->sclass = socket_type_to_security_class(family, type, protocol);
if (kern)
isec->sid = SECINITSID_KERNEL;
else {
err = socket_sockcreate_sid(tsec, isec->sclass, &(isec->sid));
if (err)
return err;
}
isec->initialized = 1;
if (sock->sk) {
sksec = sock->sk->sk_security;
sksec->sid = isec->sid;
sksec->sclass = isec->sclass;
err = selinux_netlbl_socket_post_create(sock->sk, family);
}
return err;
}
/* Range of port numbers used to automatically bind.
Need to determine whether we should perform a name_bind
permission check between the socket and the port number. */
static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
{
struct sock *sk = sock->sk;
u16 family;
int err;
err = sock_has_perm(current, sk, SOCKET__BIND);
if (err)
goto out;
/*
* If PF_INET or PF_INET6, check name_bind permission for the port.
* Multiple address binding for SCTP is not supported yet: we just
* check the first address now.
*/
family = sk->sk_family;
if (family == PF_INET || family == PF_INET6) {
char *addrp;
struct sk_security_struct *sksec = sk->sk_security;
struct common_audit_data ad;
struct sockaddr_in *addr4 = NULL;
struct sockaddr_in6 *addr6 = NULL;
unsigned short snum;
u32 sid, node_perm;
if (family == PF_INET) {
addr4 = (struct sockaddr_in *)address;
snum = ntohs(addr4->sin_port);
addrp = (char *)&addr4->sin_addr.s_addr;
} else {
addr6 = (struct sockaddr_in6 *)address;
snum = ntohs(addr6->sin6_port);
addrp = (char *)&addr6->sin6_addr.s6_addr;
}
if (snum) {
int low, high;
inet_get_local_port_range(&low, &high);
if (snum < max(PROT_SOCK, low) || snum > high) {
err = sel_netport_sid(sk->sk_protocol,
snum, &sid);
if (err)
goto out;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sport = htons(snum);
ad.u.net.family = family;
err = avc_has_perm(sksec->sid, sid,
sksec->sclass,
SOCKET__NAME_BIND, &ad);
if (err)
goto out;
}
}
switch (sksec->sclass) {
case SECCLASS_TCP_SOCKET:
node_perm = TCP_SOCKET__NODE_BIND;
break;
case SECCLASS_UDP_SOCKET:
node_perm = UDP_SOCKET__NODE_BIND;
break;
case SECCLASS_DCCP_SOCKET:
node_perm = DCCP_SOCKET__NODE_BIND;
break;
default:
node_perm = RAWIP_SOCKET__NODE_BIND;
break;
}
err = sel_netnode_sid(addrp, family, &sid);
if (err)
goto out;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sport = htons(snum);
ad.u.net.family = family;
if (family == PF_INET)
ad.u.net.v4info.saddr = addr4->sin_addr.s_addr;
else
ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr);
err = avc_has_perm(sksec->sid, sid,
sksec->sclass, node_perm, &ad);
if (err)
goto out;
}
out:
return err;
}
static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
{
struct sock *sk = sock->sk;
struct sk_security_struct *sksec = sk->sk_security;
int err;
err = sock_has_perm(current, sk, SOCKET__CONNECT);
if (err)
return err;
/*
* If a TCP or DCCP socket, check name_connect permission for the port.
*/
if (sksec->sclass == SECCLASS_TCP_SOCKET ||
sksec->sclass == SECCLASS_DCCP_SOCKET) {
struct common_audit_data ad;
struct sockaddr_in *addr4 = NULL;
struct sockaddr_in6 *addr6 = NULL;
unsigned short snum;
u32 sid, perm;
if (sk->sk_family == PF_INET) {
addr4 = (struct sockaddr_in *)address;
if (addrlen < sizeof(struct sockaddr_in))
return -EINVAL;
snum = ntohs(addr4->sin_port);
} else {
addr6 = (struct sockaddr_in6 *)address;
if (addrlen < SIN6_LEN_RFC2133)
return -EINVAL;
snum = ntohs(addr6->sin6_port);
}
err = sel_netport_sid(sk->sk_protocol, snum, &sid);
if (err)
goto out;
perm = (sksec->sclass == SECCLASS_TCP_SOCKET) ?
TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.dport = htons(snum);
ad.u.net.family = sk->sk_family;
err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
if (err)
goto out;
}
err = selinux_netlbl_socket_connect(sk, address);
out:
return err;
}
static int selinux_socket_listen(struct socket *sock, int backlog)
{
return sock_has_perm(current, sock->sk, SOCKET__LISTEN);
}
static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
{
int err;
struct inode_security_struct *isec;
struct inode_security_struct *newisec;
err = sock_has_perm(current, sock->sk, SOCKET__ACCEPT);
if (err)
return err;
newisec = SOCK_INODE(newsock)->i_security;
isec = SOCK_INODE(sock)->i_security;
newisec->sclass = isec->sclass;
newisec->sid = isec->sid;
newisec->initialized = 1;
return 0;
}
static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
int size)
{
return sock_has_perm(current, sock->sk, SOCKET__WRITE);
}
static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
int size, int flags)
{
return sock_has_perm(current, sock->sk, SOCKET__READ);
}
static int selinux_socket_getsockname(struct socket *sock)
{
return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
}
static int selinux_socket_getpeername(struct socket *sock)
{
return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
}
static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
{
int err;
err = sock_has_perm(current, sock->sk, SOCKET__SETOPT);
if (err)
return err;
return selinux_netlbl_socket_setsockopt(sock, level, optname);
}
static int selinux_socket_getsockopt(struct socket *sock, int level,
int optname)
{
return sock_has_perm(current, sock->sk, SOCKET__GETOPT);
}
static int selinux_socket_shutdown(struct socket *sock, int how)
{
return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN);
}
static int selinux_socket_unix_stream_connect(struct sock *sock,
struct sock *other,
struct sock *newsk)
{
struct sk_security_struct *sksec_sock = sock->sk_security;
struct sk_security_struct *sksec_other = other->sk_security;
struct sk_security_struct *sksec_new = newsk->sk_security;
struct common_audit_data ad;
int err;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = other;
err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
sksec_other->sclass,
UNIX_STREAM_SOCKET__CONNECTTO, &ad);
if (err)
return err;
/* server child socket */
sksec_new->peer_sid = sksec_sock->sid;
err = security_sid_mls_copy(sksec_other->sid, sksec_sock->sid,
&sksec_new->sid);
if (err)
return err;
/* connecting socket */
sksec_sock->peer_sid = sksec_new->sid;
return 0;
}
static int selinux_socket_unix_may_send(struct socket *sock,
struct socket *other)
{
struct sk_security_struct *ssec = sock->sk->sk_security;
struct sk_security_struct *osec = other->sk->sk_security;
struct common_audit_data ad;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.sk = other->sk;
return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
&ad);
}
static int selinux_inet_sys_rcv_skb(int ifindex, char *addrp, u16 family,
u32 peer_sid,
struct common_audit_data *ad)
{
int err;
u32 if_sid;
u32 node_sid;
err = sel_netif_sid(ifindex, &if_sid);
if (err)
return err;
err = avc_has_perm(peer_sid, if_sid,
SECCLASS_NETIF, NETIF__INGRESS, ad);
if (err)
return err;
err = sel_netnode_sid(addrp, family, &node_sid);
if (err)
return err;
return avc_has_perm(peer_sid, node_sid,
SECCLASS_NODE, NODE__RECVFROM, ad);
}
static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
u16 family)
{
int err = 0;
struct sk_security_struct *sksec = sk->sk_security;
u32 sk_sid = sksec->sid;
struct common_audit_data ad;
char *addrp;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = skb->skb_iif;
ad.u.net.family = family;
err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
if (err)
return err;
if (selinux_secmark_enabled()) {
err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
PACKET__RECV, &ad);
if (err)
return err;
}
err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
if (err)
return err;
err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
return err;
}
static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
{
int err;
struct sk_security_struct *sksec = sk->sk_security;
u16 family = sk->sk_family;
u32 sk_sid = sksec->sid;
struct common_audit_data ad;
char *addrp;
u8 secmark_active;
u8 peerlbl_active;
if (family != PF_INET && family != PF_INET6)
return 0;
/* Handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
/* If any sort of compatibility mode is enabled then handoff processing
* to the selinux_sock_rcv_skb_compat() function to deal with the
* special handling. We do this in an attempt to keep this function
* as fast and as clean as possible. */
if (!selinux_policycap_netpeer)
return selinux_sock_rcv_skb_compat(sk, skb, family);
secmark_active = selinux_secmark_enabled();
peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return 0;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = skb->skb_iif;
ad.u.net.family = family;
err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
if (err)
return err;
if (peerlbl_active) {
u32 peer_sid;
err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
if (err)
return err;
err = selinux_inet_sys_rcv_skb(skb->skb_iif, addrp, family,
peer_sid, &ad);
if (err) {
selinux_netlbl_err(skb, err, 0);
return err;
}
err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
PEER__RECV, &ad);
if (err)
selinux_netlbl_err(skb, err, 0);
}
if (secmark_active) {
err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
PACKET__RECV, &ad);
if (err)
return err;
}
return err;
}
static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
int __user *optlen, unsigned len)
{
int err = 0;
char *scontext;
u32 scontext_len;
struct sk_security_struct *sksec = sock->sk->sk_security;
u32 peer_sid = SECSID_NULL;
if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
sksec->sclass == SECCLASS_TCP_SOCKET)
peer_sid = sksec->peer_sid;
if (peer_sid == SECSID_NULL)
return -ENOPROTOOPT;
err = security_sid_to_context(peer_sid, &scontext, &scontext_len);
if (err)
return err;
if (scontext_len > len) {
err = -ERANGE;
goto out_len;
}
if (copy_to_user(optval, scontext, scontext_len))
err = -EFAULT;
out_len:
if (put_user(scontext_len, optlen))
err = -EFAULT;
kfree(scontext);
return err;
}
static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
{
u32 peer_secid = SECSID_NULL;
u16 family;
if (skb && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
else if (skb && skb->protocol == htons(ETH_P_IPV6))
family = PF_INET6;
else if (sock)
family = sock->sk->sk_family;
else
goto out;
if (sock && family == PF_UNIX)
selinux_inode_getsecid(SOCK_INODE(sock), &peer_secid);
else if (skb)
selinux_skb_peerlbl_sid(skb, family, &peer_secid);
out:
*secid = peer_secid;
if (peer_secid == SECSID_NULL)
return -EINVAL;
return 0;
}
static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
{
struct sk_security_struct *sksec;
sksec = kzalloc(sizeof(*sksec), priority);
if (!sksec)
return -ENOMEM;
sksec->peer_sid = SECINITSID_UNLABELED;
sksec->sid = SECINITSID_UNLABELED;
selinux_netlbl_sk_security_reset(sksec);
sk->sk_security = sksec;
return 0;
}
static void selinux_sk_free_security(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
sk->sk_security = NULL;
selinux_netlbl_sk_security_free(sksec);
kfree(sksec);
}
static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
{
struct sk_security_struct *sksec = sk->sk_security;
struct sk_security_struct *newsksec = newsk->sk_security;
newsksec->sid = sksec->sid;
newsksec->peer_sid = sksec->peer_sid;
newsksec->sclass = sksec->sclass;
selinux_netlbl_sk_security_reset(newsksec);
}
static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
{
if (!sk)
*secid = SECINITSID_ANY_SOCKET;
else {
struct sk_security_struct *sksec = sk->sk_security;
*secid = sksec->sid;
}
}
static void selinux_sock_graft(struct sock *sk, struct socket *parent)
{
struct inode_security_struct *isec = SOCK_INODE(parent)->i_security;
struct sk_security_struct *sksec = sk->sk_security;
if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
sk->sk_family == PF_UNIX)
isec->sid = sksec->sid;
sksec->sclass = isec->sclass;
}
static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
struct request_sock *req)
{
struct sk_security_struct *sksec = sk->sk_security;
int err;
u16 family = sk->sk_family;
u32 newsid;
u32 peersid;
/* handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
err = selinux_skb_peerlbl_sid(skb, family, &peersid);
if (err)
return err;
if (peersid == SECSID_NULL) {
req->secid = sksec->sid;
req->peer_secid = SECSID_NULL;
} else {
err = security_sid_mls_copy(sksec->sid, peersid, &newsid);
if (err)
return err;
req->secid = newsid;
req->peer_secid = peersid;
}
return selinux_netlbl_inet_conn_request(req, family);
}
static void selinux_inet_csk_clone(struct sock *newsk,
const struct request_sock *req)
{
struct sk_security_struct *newsksec = newsk->sk_security;
newsksec->sid = req->secid;
newsksec->peer_sid = req->peer_secid;
/* NOTE: Ideally, we should also get the isec->sid for the
new socket in sync, but we don't have the isec available yet.
So we will wait until sock_graft to do it, by which
time it will have been created and available. */
/* We don't need to take any sort of lock here as we are the only
* thread with access to newsksec */
selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
}
static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
{
u16 family = sk->sk_family;
struct sk_security_struct *sksec = sk->sk_security;
/* handle mapped IPv4 packets arriving via IPv6 sockets */
if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
family = PF_INET;
selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
}
static int selinux_secmark_relabel_packet(u32 sid)
{
const struct task_security_struct *__tsec;
u32 tsid;
__tsec = current_security();
tsid = __tsec->sid;
return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL);
}
static void selinux_secmark_refcount_inc(void)
{
atomic_inc(&selinux_secmark_refcount);
}
static void selinux_secmark_refcount_dec(void)
{
atomic_dec(&selinux_secmark_refcount);
}
static void selinux_req_classify_flow(const struct request_sock *req,
struct flowi *fl)
{
fl->flowi_secid = req->secid;
}
static int selinux_tun_dev_create(void)
{
u32 sid = current_sid();
/* we aren't taking into account the "sockcreate" SID since the socket
* that is being created here is not a socket in the traditional sense,
* instead it is a private sock, accessible only to the kernel, and
* representing a wide range of network traffic spanning multiple
* connections unlike traditional sockets - check the TUN driver to
* get a better understanding of why this socket is special */
return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
NULL);
}
static void selinux_tun_dev_post_create(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
/* we don't currently perform any NetLabel based labeling here and it
* isn't clear that we would want to do so anyway; while we could apply
* labeling without the support of the TUN user the resulting labeled
* traffic from the other end of the connection would almost certainly
* cause confusion to the TUN user that had no idea network labeling
* protocols were being used */
/* see the comments in selinux_tun_dev_create() about why we don't use
* the sockcreate SID here */
sksec->sid = current_sid();
sksec->sclass = SECCLASS_TUN_SOCKET;
}
static int selinux_tun_dev_attach(struct sock *sk)
{
struct sk_security_struct *sksec = sk->sk_security;
u32 sid = current_sid();
int err;
err = avc_has_perm(sid, sksec->sid, SECCLASS_TUN_SOCKET,
TUN_SOCKET__RELABELFROM, NULL);
if (err)
return err;
err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
TUN_SOCKET__RELABELTO, NULL);
if (err)
return err;
sksec->sid = sid;
return 0;
}
static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
{
int err = 0;
u32 perm;
struct nlmsghdr *nlh;
struct sk_security_struct *sksec = sk->sk_security;
if (skb->len < NLMSG_SPACE(0)) {
err = -EINVAL;
goto out;
}
nlh = nlmsg_hdr(skb);
err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);
if (err) {
if (err == -EINVAL) {
audit_log(current->audit_context, GFP_KERNEL, AUDIT_SELINUX_ERR,
"SELinux: unrecognized netlink message"
" type=%hu for sclass=%hu\n",
nlh->nlmsg_type, sksec->sclass);
if (!selinux_enforcing || security_get_allow_unknown())
err = 0;
}
/* Ignore */
if (err == -ENOENT)
err = 0;
goto out;
}
err = sock_has_perm(current, sk, perm);
out:
return err;
}
#ifdef CONFIG_NETFILTER
static unsigned int selinux_ip_forward(struct sk_buff *skb, int ifindex,
u16 family)
{
int err;
char *addrp;
u32 peer_sid;
struct common_audit_data ad;
u8 secmark_active;
u8 netlbl_active;
u8 peerlbl_active;
if (!selinux_policycap_netpeer)
return NF_ACCEPT;
secmark_active = selinux_secmark_enabled();
netlbl_active = netlbl_enabled();
peerlbl_active = netlbl_active || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return NF_ACCEPT;
if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
return NF_DROP;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
return NF_DROP;
if (peerlbl_active) {
err = selinux_inet_sys_rcv_skb(ifindex, addrp, family,
peer_sid, &ad);
if (err) {
selinux_netlbl_err(skb, err, 1);
return NF_DROP;
}
}
if (secmark_active)
if (avc_has_perm(peer_sid, skb->secmark,
SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
return NF_DROP;
if (netlbl_active)
/* we do this in the FORWARD path and not the POST_ROUTING
* path because we want to make sure we apply the necessary
* labeling before IPsec is applied so we can leverage AH
* protection */
if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
return NF_DROP;
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_forward(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_forward(skb, in->ifindex, PF_INET);
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static unsigned int selinux_ipv6_forward(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_forward(skb, in->ifindex, PF_INET6);
}
#endif /* IPV6 */
static unsigned int selinux_ip_output(struct sk_buff *skb,
u16 family)
{
u32 sid;
if (!netlbl_enabled())
return NF_ACCEPT;
/* we do this in the LOCAL_OUT path and not the POST_ROUTING path
* because we want to make sure we apply the necessary labeling
* before IPsec is applied so we can leverage AH protection */
if (skb->sk) {
struct sk_security_struct *sksec = skb->sk->sk_security;
sid = sksec->sid;
} else
sid = SECINITSID_KERNEL;
if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
return NF_DROP;
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_output(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_output(skb, PF_INET);
}
static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
int ifindex,
u16 family)
{
struct sock *sk = skb->sk;
struct sk_security_struct *sksec;
struct common_audit_data ad;
char *addrp;
u8 proto;
if (sk == NULL)
return NF_ACCEPT;
sksec = sk->sk_security;
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
return NF_DROP;
if (selinux_secmark_enabled())
if (avc_has_perm(sksec->sid, skb->secmark,
SECCLASS_PACKET, PACKET__SEND, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
return NF_DROP_ERR(-ECONNREFUSED);
return NF_ACCEPT;
}
static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
u16 family)
{
u32 secmark_perm;
u32 peer_sid;
struct sock *sk;
struct common_audit_data ad;
char *addrp;
u8 secmark_active;
u8 peerlbl_active;
/* If any sort of compatibility mode is enabled then handoff processing
* to the selinux_ip_postroute_compat() function to deal with the
* special handling. We do this in an attempt to keep this function
* as fast and as clean as possible. */
if (!selinux_policycap_netpeer)
return selinux_ip_postroute_compat(skb, ifindex, family);
#ifdef CONFIG_XFRM
/* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
* packet transformation so allow the packet to pass without any checks
* since we'll have another chance to perform access control checks
* when the packet is on it's final way out.
* NOTE: there appear to be some IPv6 multicast cases where skb->dst
* is NULL, in this case go ahead and apply access control. */
if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL)
return NF_ACCEPT;
#endif
secmark_active = selinux_secmark_enabled();
peerlbl_active = netlbl_enabled() || selinux_xfrm_enabled();
if (!secmark_active && !peerlbl_active)
return NF_ACCEPT;
/* if the packet is being forwarded then get the peer label from the
* packet itself; otherwise check to see if it is from a local
* application or the kernel, if from an application get the peer label
* from the sending socket, otherwise use the kernel's sid */
sk = skb->sk;
if (sk == NULL) {
if (skb->skb_iif) {
secmark_perm = PACKET__FORWARD_OUT;
if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
return NF_DROP;
} else {
secmark_perm = PACKET__SEND;
peer_sid = SECINITSID_KERNEL;
}
} else {
struct sk_security_struct *sksec = sk->sk_security;
peer_sid = sksec->sid;
secmark_perm = PACKET__SEND;
}
COMMON_AUDIT_DATA_INIT(&ad, NET);
ad.u.net.netif = ifindex;
ad.u.net.family = family;
if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
return NF_DROP;
if (secmark_active)
if (avc_has_perm(peer_sid, skb->secmark,
SECCLASS_PACKET, secmark_perm, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (peerlbl_active) {
u32 if_sid;
u32 node_sid;
if (sel_netif_sid(ifindex, &if_sid))
return NF_DROP;
if (avc_has_perm(peer_sid, if_sid,
SECCLASS_NETIF, NETIF__EGRESS, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
if (sel_netnode_sid(addrp, family, &node_sid))
return NF_DROP;
if (avc_has_perm(peer_sid, node_sid,
SECCLASS_NODE, NODE__SENDTO, &ad))
return NF_DROP_ERR(-ECONNREFUSED);
}
return NF_ACCEPT;
}
static unsigned int selinux_ipv4_postroute(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_postroute(skb, out->ifindex, PF_INET);
}
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static unsigned int selinux_ipv6_postroute(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return selinux_ip_postroute(skb, out->ifindex, PF_INET6);
}
#endif /* IPV6 */
#endif /* CONFIG_NETFILTER */
static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
{
int err;
err = cap_netlink_send(sk, skb);
if (err)
return err;
return selinux_nlmsg_perm(sk, skb);
}
static int selinux_netlink_recv(struct sk_buff *skb, int capability)
{
int err;
struct common_audit_data ad;
u32 sid;
err = cap_netlink_recv(skb, capability);
if (err)
return err;
COMMON_AUDIT_DATA_INIT(&ad, CAP);
ad.u.cap = capability;
security_task_getsecid(current, &sid);
return avc_has_perm(sid, sid, SECCLASS_CAPABILITY,
CAP_TO_MASK(capability), &ad);
}
static int ipc_alloc_security(struct task_struct *task,
struct kern_ipc_perm *perm,
u16 sclass)
{
struct ipc_security_struct *isec;
u32 sid;
isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
if (!isec)
return -ENOMEM;
sid = task_sid(task);
isec->sclass = sclass;
isec->sid = sid;
perm->security = isec;
return 0;
}
static void ipc_free_security(struct kern_ipc_perm *perm)
{
struct ipc_security_struct *isec = perm->security;
perm->security = NULL;
kfree(isec);
}
static int msg_msg_alloc_security(struct msg_msg *msg)
{
struct msg_security_struct *msec;
msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
if (!msec)
return -ENOMEM;
msec->sid = SECINITSID_UNLABELED;
msg->security = msec;
return 0;
}
static void msg_msg_free_security(struct msg_msg *msg)
{
struct msg_security_struct *msec = msg->security;
msg->security = NULL;
kfree(msec);
}
static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
u32 perms)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = ipc_perms->security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = ipc_perms->key;
return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
}
static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
{
return msg_msg_alloc_security(msg);
}
static void selinux_msg_msg_free_security(struct msg_msg *msg)
{
msg_msg_free_security(msg);
}
/* message queue security operations */
static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ);
if (rc)
return rc;
isec = msq->q_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__CREATE, &ad);
if (rc) {
ipc_free_security(&msq->q_perm);
return rc;
}
return 0;
}
static void selinux_msg_queue_free_security(struct msg_queue *msq)
{
ipc_free_security(&msq->q_perm);
}
static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = msq->q_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__ASSOCIATE, &ad);
}
static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
{
int err;
int perms;
switch (cmd) {
case IPC_INFO:
case MSG_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case IPC_STAT:
case MSG_STAT:
perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
break;
case IPC_SET:
perms = MSGQ__SETATTR;
break;
case IPC_RMID:
perms = MSGQ__DESTROY;
break;
default:
return 0;
}
err = ipc_has_perm(&msq->q_perm, perms);
return err;
}
static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
{
struct ipc_security_struct *isec;
struct msg_security_struct *msec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
isec = msq->q_perm.security;
msec = msg->security;
/*
* First time through, need to assign label to the message
*/
if (msec->sid == SECINITSID_UNLABELED) {
/*
* Compute new sid based on current process and
* message queue this message will be stored in
*/
rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG,
NULL, &msec->sid);
if (rc)
return rc;
}
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
/* Can this process write to the queue? */
rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
MSGQ__WRITE, &ad);
if (!rc)
/* Can this process send the message */
rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
MSG__SEND, &ad);
if (!rc)
/* Can the message be put in the queue? */
rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
MSGQ__ENQUEUE, &ad);
return rc;
}
static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
struct task_struct *target,
long type, int mode)
{
struct ipc_security_struct *isec;
struct msg_security_struct *msec;
struct common_audit_data ad;
u32 sid = task_sid(target);
int rc;
isec = msq->q_perm.security;
msec = msg->security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = msq->q_perm.key;
rc = avc_has_perm(sid, isec->sid,
SECCLASS_MSGQ, MSGQ__READ, &ad);
if (!rc)
rc = avc_has_perm(sid, msec->sid,
SECCLASS_MSG, MSG__RECEIVE, &ad);
return rc;
}
/* Shared Memory security operations */
static int selinux_shm_alloc_security(struct shmid_kernel *shp)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM);
if (rc)
return rc;
isec = shp->shm_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = shp->shm_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_SHM,
SHM__CREATE, &ad);
if (rc) {
ipc_free_security(&shp->shm_perm);
return rc;
}
return 0;
}
static void selinux_shm_free_security(struct shmid_kernel *shp)
{
ipc_free_security(&shp->shm_perm);
}
static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = shp->shm_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = shp->shm_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
SHM__ASSOCIATE, &ad);
}
/* Note, at this point, shp is locked down */
static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
{
int perms;
int err;
switch (cmd) {
case IPC_INFO:
case SHM_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case IPC_STAT:
case SHM_STAT:
perms = SHM__GETATTR | SHM__ASSOCIATE;
break;
case IPC_SET:
perms = SHM__SETATTR;
break;
case SHM_LOCK:
case SHM_UNLOCK:
perms = SHM__LOCK;
break;
case IPC_RMID:
perms = SHM__DESTROY;
break;
default:
return 0;
}
err = ipc_has_perm(&shp->shm_perm, perms);
return err;
}
static int selinux_shm_shmat(struct shmid_kernel *shp,
char __user *shmaddr, int shmflg)
{
u32 perms;
if (shmflg & SHM_RDONLY)
perms = SHM__READ;
else
perms = SHM__READ | SHM__WRITE;
return ipc_has_perm(&shp->shm_perm, perms);
}
/* Semaphore security operations */
static int selinux_sem_alloc_security(struct sem_array *sma)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
int rc;
rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM);
if (rc)
return rc;
isec = sma->sem_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = sma->sem_perm.key;
rc = avc_has_perm(sid, isec->sid, SECCLASS_SEM,
SEM__CREATE, &ad);
if (rc) {
ipc_free_security(&sma->sem_perm);
return rc;
}
return 0;
}
static void selinux_sem_free_security(struct sem_array *sma)
{
ipc_free_security(&sma->sem_perm);
}
static int selinux_sem_associate(struct sem_array *sma, int semflg)
{
struct ipc_security_struct *isec;
struct common_audit_data ad;
u32 sid = current_sid();
isec = sma->sem_perm.security;
COMMON_AUDIT_DATA_INIT(&ad, IPC);
ad.u.ipc_id = sma->sem_perm.key;
return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
SEM__ASSOCIATE, &ad);
}
/* Note, at this point, sma is locked down */
static int selinux_sem_semctl(struct sem_array *sma, int cmd)
{
int err;
u32 perms;
switch (cmd) {
case IPC_INFO:
case SEM_INFO:
/* No specific object, just general system-wide information. */
return task_has_system(current, SYSTEM__IPC_INFO);
case GETPID:
case GETNCNT:
case GETZCNT:
perms = SEM__GETATTR;
break;
case GETVAL:
case GETALL:
perms = SEM__READ;
break;
case SETVAL:
case SETALL:
perms = SEM__WRITE;
break;
case IPC_RMID:
perms = SEM__DESTROY;
break;
case IPC_SET:
perms = SEM__SETATTR;
break;
case IPC_STAT:
case SEM_STAT:
perms = SEM__GETATTR | SEM__ASSOCIATE;
break;
default:
return 0;
}
err = ipc_has_perm(&sma->sem_perm, perms);
return err;
}
static int selinux_sem_semop(struct sem_array *sma,
struct sembuf *sops, unsigned nsops, int alter)
{
u32 perms;
if (alter)
perms = SEM__READ | SEM__WRITE;
else
perms = SEM__READ;
return ipc_has_perm(&sma->sem_perm, perms);
}
static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
{
u32 av = 0;
av = 0;
if (flag & S_IRUGO)
av |= IPC__UNIX_READ;
if (flag & S_IWUGO)
av |= IPC__UNIX_WRITE;
if (av == 0)
return 0;
return ipc_has_perm(ipcp, av);
}
static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
{
struct ipc_security_struct *isec = ipcp->security;
*secid = isec->sid;
}
static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
{
if (inode)
inode_doinit_with_dentry(inode, dentry);
}
static int selinux_getprocattr(struct task_struct *p,
char *name, char **value)
{
const struct task_security_struct *__tsec;
u32 sid;
int error;
unsigned len;
if (current != p) {
error = current_has_perm(p, PROCESS__GETATTR);
if (error)
return error;
}
rcu_read_lock();
__tsec = __task_cred(p)->security;
if (!strcmp(name, "current"))
sid = __tsec->sid;
else if (!strcmp(name, "prev"))
sid = __tsec->osid;
else if (!strcmp(name, "exec"))
sid = __tsec->exec_sid;
else if (!strcmp(name, "fscreate"))
sid = __tsec->create_sid;
else if (!strcmp(name, "keycreate"))
sid = __tsec->keycreate_sid;
else if (!strcmp(name, "sockcreate"))
sid = __tsec->sockcreate_sid;
else
goto invalid;
rcu_read_unlock();
if (!sid)
return 0;
error = security_sid_to_context(sid, value, &len);
if (error)
return error;
return len;
invalid:
rcu_read_unlock();
return -EINVAL;
}
static int selinux_setprocattr(struct task_struct *p,
char *name, void *value, size_t size)
{
struct task_security_struct *tsec;
struct task_struct *tracer;
struct cred *new;
u32 sid = 0, ptsid;
int error;
char *str = value;
if (current != p) {
/* SELinux only allows a process to change its own
security attributes. */
return -EACCES;
}
/*
* Basic control over ability to set these attributes at all.
* current == p, but we'll pass them separately in case the
* above restriction is ever removed.
*/
if (!strcmp(name, "exec"))
error = current_has_perm(p, PROCESS__SETEXEC);
else if (!strcmp(name, "fscreate"))
error = current_has_perm(p, PROCESS__SETFSCREATE);
else if (!strcmp(name, "keycreate"))
error = current_has_perm(p, PROCESS__SETKEYCREATE);
else if (!strcmp(name, "sockcreate"))
error = current_has_perm(p, PROCESS__SETSOCKCREATE);
else if (!strcmp(name, "current"))
error = current_has_perm(p, PROCESS__SETCURRENT);
else
error = -EINVAL;
if (error)
return error;
/* Obtain a SID for the context, if one was specified. */
if (size && str[1] && str[1] != '\n') {
if (str[size-1] == '\n') {
str[size-1] = 0;
size--;
}
error = security_context_to_sid(value, size, &sid);
if (error == -EINVAL && !strcmp(name, "fscreate")) {
if (!capable(CAP_MAC_ADMIN))
return error;
error = security_context_to_sid_force(value, size,
&sid);
}
if (error)
return error;
}
new = prepare_creds();
if (!new)
return -ENOMEM;
/* Permission checking based on the specified context is
performed during the actual operation (execve,
open/mkdir/...), when we know the full context of the
operation. See selinux_bprm_set_creds for the execve
checks and may_create for the file creation checks. The
operation will then fail if the context is not permitted. */
tsec = new->security;
if (!strcmp(name, "exec")) {
tsec->exec_sid = sid;
} else if (!strcmp(name, "fscreate")) {
tsec->create_sid = sid;
} else if (!strcmp(name, "keycreate")) {
error = may_create_key(sid, p);
if (error)
goto abort_change;
tsec->keycreate_sid = sid;
} else if (!strcmp(name, "sockcreate")) {
tsec->sockcreate_sid = sid;
} else if (!strcmp(name, "current")) {
error = -EINVAL;
if (sid == 0)
goto abort_change;
/* Only allow single threaded processes to change context */
error = -EPERM;
if (!current_is_single_threaded()) {
error = security_bounded_transition(tsec->sid, sid);
if (error)
goto abort_change;
}
/* Check permissions for the transition. */
error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
PROCESS__DYNTRANSITION, NULL);
if (error)
goto abort_change;
/* Check for ptracing, and update the task SID if ok.
Otherwise, leave SID unchanged and fail. */
ptsid = 0;
task_lock(p);
tracer = tracehook_tracer_task(p);
if (tracer)
ptsid = task_sid(tracer);
task_unlock(p);
if (tracer) {
error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
PROCESS__PTRACE, NULL);
if (error)
goto abort_change;
}
tsec->sid = sid;
} else {
error = -EINVAL;
goto abort_change;
}
commit_creds(new);
return size;
abort_change:
abort_creds(new);
return error;
}
static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
{
return security_sid_to_context(secid, secdata, seclen);
}
static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
{
return security_context_to_sid(secdata, seclen, secid);
}
static void selinux_release_secctx(char *secdata, u32 seclen)
{
kfree(secdata);
}
/*
* called with inode->i_mutex locked
*/
static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
{
return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, ctxlen, 0);
}
/*
* called with inode->i_mutex locked
*/
static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
{
return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
}
static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
{
int len = 0;
len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
ctx, true);
if (len < 0)
return len;
*ctxlen = len;
return 0;
}
#ifdef CONFIG_KEYS
static int selinux_key_alloc(struct key *k, const struct cred *cred,
unsigned long flags)
{
const struct task_security_struct *tsec;
struct key_security_struct *ksec;
ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
if (!ksec)
return -ENOMEM;
tsec = cred->security;
if (tsec->keycreate_sid)
ksec->sid = tsec->keycreate_sid;
else
ksec->sid = tsec->sid;
k->security = ksec;
return 0;
}
static void selinux_key_free(struct key *k)
{
struct key_security_struct *ksec = k->security;
k->security = NULL;
kfree(ksec);
}
static int selinux_key_permission(key_ref_t key_ref,
const struct cred *cred,
key_perm_t perm)
{
struct key *key;
struct key_security_struct *ksec;
u32 sid;
/* if no specific permissions are requested, we skip the
permission check. No serious, additional covert channels
appear to be created. */
if (perm == 0)
return 0;
sid = cred_sid(cred);
key = key_ref_to_ptr(key_ref);
ksec = key->security;
return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
}
static int selinux_key_getsecurity(struct key *key, char **_buffer)
{
struct key_security_struct *ksec = key->security;
char *context = NULL;
unsigned len;
int rc;
rc = security_sid_to_context(ksec->sid, &context, &len);
if (!rc)
rc = len;
*_buffer = context;
return rc;
}
#endif
static struct security_operations selinux_ops = {
.name = "selinux",
.ptrace_access_check = selinux_ptrace_access_check,
.ptrace_traceme = selinux_ptrace_traceme,
.capget = selinux_capget,
.capset = selinux_capset,
.capable = selinux_capable,
.quotactl = selinux_quotactl,
.quota_on = selinux_quota_on,
.syslog = selinux_syslog,
.vm_enough_memory = selinux_vm_enough_memory,
.netlink_send = selinux_netlink_send,
.netlink_recv = selinux_netlink_recv,
.bprm_set_creds = selinux_bprm_set_creds,
.bprm_committing_creds = selinux_bprm_committing_creds,
.bprm_committed_creds = selinux_bprm_committed_creds,
.bprm_secureexec = selinux_bprm_secureexec,
.sb_alloc_security = selinux_sb_alloc_security,
.sb_free_security = selinux_sb_free_security,
.sb_copy_data = selinux_sb_copy_data,
.sb_remount = selinux_sb_remount,
.sb_kern_mount = selinux_sb_kern_mount,
.sb_show_options = selinux_sb_show_options,
.sb_statfs = selinux_sb_statfs,
.sb_mount = selinux_mount,
.sb_umount = selinux_umount,
.sb_set_mnt_opts = selinux_set_mnt_opts,
.sb_clone_mnt_opts = selinux_sb_clone_mnt_opts,
.sb_parse_opts_str = selinux_parse_opts_str,
.inode_alloc_security = selinux_inode_alloc_security,
.inode_free_security = selinux_inode_free_security,
.inode_init_security = selinux_inode_init_security,
.inode_create = selinux_inode_create,
.inode_link = selinux_inode_link,
.inode_unlink = selinux_inode_unlink,
.inode_symlink = selinux_inode_symlink,
.inode_mkdir = selinux_inode_mkdir,
.inode_rmdir = selinux_inode_rmdir,
.inode_mknod = selinux_inode_mknod,
.inode_rename = selinux_inode_rename,
.inode_readlink = selinux_inode_readlink,
.inode_follow_link = selinux_inode_follow_link,
.inode_permission = selinux_inode_permission,
.inode_setattr = selinux_inode_setattr,
.inode_getattr = selinux_inode_getattr,
.inode_setxattr = selinux_inode_setxattr,
.inode_post_setxattr = selinux_inode_post_setxattr,
.inode_getxattr = selinux_inode_getxattr,
.inode_listxattr = selinux_inode_listxattr,
.inode_removexattr = selinux_inode_removexattr,
.inode_getsecurity = selinux_inode_getsecurity,
.inode_setsecurity = selinux_inode_setsecurity,
.inode_listsecurity = selinux_inode_listsecurity,
.inode_getsecid = selinux_inode_getsecid,
.file_permission = selinux_file_permission,
.file_alloc_security = selinux_file_alloc_security,
.file_free_security = selinux_file_free_security,
.file_ioctl = selinux_file_ioctl,
.file_mmap = selinux_file_mmap,
.file_mprotect = selinux_file_mprotect,
.file_lock = selinux_file_lock,
.file_fcntl = selinux_file_fcntl,
.file_set_fowner = selinux_file_set_fowner,
.file_send_sigiotask = selinux_file_send_sigiotask,
.file_receive = selinux_file_receive,
.dentry_open = selinux_dentry_open,
.task_create = selinux_task_create,
.cred_alloc_blank = selinux_cred_alloc_blank,
.cred_free = selinux_cred_free,
.cred_prepare = selinux_cred_prepare,
.cred_transfer = selinux_cred_transfer,
.kernel_act_as = selinux_kernel_act_as,
.kernel_create_files_as = selinux_kernel_create_files_as,
.kernel_module_request = selinux_kernel_module_request,
.task_setpgid = selinux_task_setpgid,
.task_getpgid = selinux_task_getpgid,
.task_getsid = selinux_task_getsid,
.task_getsecid = selinux_task_getsecid,
.task_setnice = selinux_task_setnice,
.task_setioprio = selinux_task_setioprio,
.task_getioprio = selinux_task_getioprio,
.task_setrlimit = selinux_task_setrlimit,
.task_setscheduler = selinux_task_setscheduler,
.task_getscheduler = selinux_task_getscheduler,
.task_movememory = selinux_task_movememory,
.task_kill = selinux_task_kill,
.task_wait = selinux_task_wait,
.task_to_inode = selinux_task_to_inode,
.ipc_permission = selinux_ipc_permission,
.ipc_getsecid = selinux_ipc_getsecid,
.msg_msg_alloc_security = selinux_msg_msg_alloc_security,
.msg_msg_free_security = selinux_msg_msg_free_security,
.msg_queue_alloc_security = selinux_msg_queue_alloc_security,
.msg_queue_free_security = selinux_msg_queue_free_security,
.msg_queue_associate = selinux_msg_queue_associate,
.msg_queue_msgctl = selinux_msg_queue_msgctl,
.msg_queue_msgsnd = selinux_msg_queue_msgsnd,
.msg_queue_msgrcv = selinux_msg_queue_msgrcv,
.shm_alloc_security = selinux_shm_alloc_security,
.shm_free_security = selinux_shm_free_security,
.shm_associate = selinux_shm_associate,
.shm_shmctl = selinux_shm_shmctl,
.shm_shmat = selinux_shm_shmat,
.sem_alloc_security = selinux_sem_alloc_security,
.sem_free_security = selinux_sem_free_security,
.sem_associate = selinux_sem_associate,
.sem_semctl = selinux_sem_semctl,
.sem_semop = selinux_sem_semop,
.d_instantiate = selinux_d_instantiate,
.getprocattr = selinux_getprocattr,
.setprocattr = selinux_setprocattr,
.secid_to_secctx = selinux_secid_to_secctx,
.secctx_to_secid = selinux_secctx_to_secid,
.release_secctx = selinux_release_secctx,
.inode_notifysecctx = selinux_inode_notifysecctx,
.inode_setsecctx = selinux_inode_setsecctx,
.inode_getsecctx = selinux_inode_getsecctx,
.unix_stream_connect = selinux_socket_unix_stream_connect,
.unix_may_send = selinux_socket_unix_may_send,
.socket_create = selinux_socket_create,
.socket_post_create = selinux_socket_post_create,
.socket_bind = selinux_socket_bind,
.socket_connect = selinux_socket_connect,
.socket_listen = selinux_socket_listen,
.socket_accept = selinux_socket_accept,
.socket_sendmsg = selinux_socket_sendmsg,
.socket_recvmsg = selinux_socket_recvmsg,
.socket_getsockname = selinux_socket_getsockname,
.socket_getpeername = selinux_socket_getpeername,
.socket_getsockopt = selinux_socket_getsockopt,
.socket_setsockopt = selinux_socket_setsockopt,
.socket_shutdown = selinux_socket_shutdown,
.socket_sock_rcv_skb = selinux_socket_sock_rcv_skb,
.socket_getpeersec_stream = selinux_socket_getpeersec_stream,
.socket_getpeersec_dgram = selinux_socket_getpeersec_dgram,
.sk_alloc_security = selinux_sk_alloc_security,
.sk_free_security = selinux_sk_free_security,
.sk_clone_security = selinux_sk_clone_security,
.sk_getsecid = selinux_sk_getsecid,
.sock_graft = selinux_sock_graft,
.inet_conn_request = selinux_inet_conn_request,
.inet_csk_clone = selinux_inet_csk_clone,
.inet_conn_established = selinux_inet_conn_established,
.secmark_relabel_packet = selinux_secmark_relabel_packet,
.secmark_refcount_inc = selinux_secmark_refcount_inc,
.secmark_refcount_dec = selinux_secmark_refcount_dec,
.req_classify_flow = selinux_req_classify_flow,
.tun_dev_create = selinux_tun_dev_create,
.tun_dev_post_create = selinux_tun_dev_post_create,
.tun_dev_attach = selinux_tun_dev_attach,
#ifdef CONFIG_SECURITY_NETWORK_XFRM
.xfrm_policy_alloc_security = selinux_xfrm_policy_alloc,
.xfrm_policy_clone_security = selinux_xfrm_policy_clone,
.xfrm_policy_free_security = selinux_xfrm_policy_free,
.xfrm_policy_delete_security = selinux_xfrm_policy_delete,
.xfrm_state_alloc_security = selinux_xfrm_state_alloc,
.xfrm_state_free_security = selinux_xfrm_state_free,
.xfrm_state_delete_security = selinux_xfrm_state_delete,
.xfrm_policy_lookup = selinux_xfrm_policy_lookup,
.xfrm_state_pol_flow_match = selinux_xfrm_state_pol_flow_match,
.xfrm_decode_session = selinux_xfrm_decode_session,
#endif
#ifdef CONFIG_KEYS
.key_alloc = selinux_key_alloc,
.key_free = selinux_key_free,
.key_permission = selinux_key_permission,
.key_getsecurity = selinux_key_getsecurity,
#endif
#ifdef CONFIG_AUDIT
.audit_rule_init = selinux_audit_rule_init,
.audit_rule_known = selinux_audit_rule_known,
.audit_rule_match = selinux_audit_rule_match,
.audit_rule_free = selinux_audit_rule_free,
#endif
};
static __init int selinux_init(void)
{
if (!security_module_enable(&selinux_ops)) {
selinux_enabled = 0;
return 0;
}
if (!selinux_enabled) {
printk(KERN_INFO "SELinux: Disabled at boot.\n");
return 0;
}
printk(KERN_INFO "SELinux: Initializing.\n");
/* Set the security state for the initial task. */
cred_init_security();
default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
sel_inode_cache = kmem_cache_create("selinux_inode_security",
sizeof(struct inode_security_struct),
0, SLAB_PANIC, NULL);
avc_init();
if (register_security(&selinux_ops))
panic("SELinux: Unable to register with kernel.\n");
if (selinux_enforcing)
printk(KERN_DEBUG "SELinux: Starting in enforcing mode\n");
else
printk(KERN_DEBUG "SELinux: Starting in permissive mode\n");
return 0;
}
static void delayed_superblock_init(struct super_block *sb, void *unused)
{
superblock_doinit(sb, NULL);
}
void selinux_complete_init(void)
{
printk(KERN_DEBUG "SELinux: Completing initialization.\n");
/* Set up any superblocks initialized prior to the policy load. */
printk(KERN_DEBUG "SELinux: Setting up existing superblocks.\n");
iterate_supers(delayed_superblock_init, NULL);
}
/* SELinux requires early initialization in order to label
all processes and objects when they are created. */
security_initcall(selinux_init);
#if defined(CONFIG_NETFILTER)
static struct nf_hook_ops selinux_ipv4_ops[] = {
{
.hook = selinux_ipv4_postroute,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_POST_ROUTING,
.priority = NF_IP_PRI_SELINUX_LAST,
},
{
.hook = selinux_ipv4_forward,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_FORWARD,
.priority = NF_IP_PRI_SELINUX_FIRST,
},
{
.hook = selinux_ipv4_output,
.owner = THIS_MODULE,
.pf = PF_INET,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP_PRI_SELINUX_FIRST,
}
};
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
static struct nf_hook_ops selinux_ipv6_ops[] = {
{
.hook = selinux_ipv6_postroute,
.owner = THIS_MODULE,
.pf = PF_INET6,
.hooknum = NF_INET_POST_ROUTING,
.priority = NF_IP6_PRI_SELINUX_LAST,
},
{
.hook = selinux_ipv6_forward,
.owner = THIS_MODULE,
.pf = PF_INET6,
.hooknum = NF_INET_FORWARD,
.priority = NF_IP6_PRI_SELINUX_FIRST,
}
};
#endif /* IPV6 */
static int __init selinux_nf_ip_init(void)
{
int err = 0;
if (!selinux_enabled)
goto out;
printk(KERN_DEBUG "SELinux: Registering netfilter hooks\n");
err = nf_register_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
if (err)
panic("SELinux: nf_register_hooks for IPv4: error %d\n", err);
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
err = nf_register_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
if (err)
panic("SELinux: nf_register_hooks for IPv6: error %d\n", err);
#endif /* IPV6 */
out:
return err;
}
__initcall(selinux_nf_ip_init);
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
static void selinux_nf_ip_exit(void)
{
printk(KERN_DEBUG "SELinux: Unregistering netfilter hooks\n");
nf_unregister_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
#if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
nf_unregister_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
#endif /* IPV6 */
}
#endif
#else /* CONFIG_NETFILTER */
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
#define selinux_nf_ip_exit()
#endif
#endif /* CONFIG_NETFILTER */
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
static int selinux_disabled;
int selinux_disable(void)
{
extern void exit_sel_fs(void);
if (ss_initialized) {
/* Not permitted after initial policy load. */
return -EINVAL;
}
if (selinux_disabled) {
/* Only do this once. */
return -EINVAL;
}
printk(KERN_INFO "SELinux: Disabled at runtime.\n");
selinux_disabled = 1;
selinux_enabled = 0;
reset_security_ops();
/* Try to destroy the avc node cache */
avc_disable();
/* Unregister netfilter hooks. */
selinux_nf_ip_exit();
/* Unregister selinuxfs. */
exit_sel_fs();
return 0;
}
#endif
| gpl-2.0 |
ouya/ouya_1_1-kernel | fs/sysv/namei.c | 3117 | 6236 | /*
* linux/fs/sysv/namei.c
*
* minix/namei.c
* Copyright (C) 1991, 1992 Linus Torvalds
*
* coh/namei.c
* Copyright (C) 1993 Pascal Haible, Bruno Haible
*
* sysv/namei.c
* Copyright (C) 1993 Bruno Haible
* Copyright (C) 1997, 1998 Krzysztof G. Baranowski
*/
#include <linux/pagemap.h>
#include "sysv.h"
static int add_nondir(struct dentry *dentry, struct inode *inode)
{
int err = sysv_add_link(dentry, inode);
if (!err) {
d_instantiate(dentry, inode);
return 0;
}
inode_dec_link_count(inode);
iput(inode);
return err;
}
static int sysv_hash(const struct dentry *dentry, const struct inode *inode,
struct qstr *qstr)
{
/* Truncate the name in place, avoids having to define a compare
function. */
if (qstr->len > SYSV_NAMELEN) {
qstr->len = SYSV_NAMELEN;
qstr->hash = full_name_hash(qstr->name, qstr->len);
}
return 0;
}
const struct dentry_operations sysv_dentry_operations = {
.d_hash = sysv_hash,
};
static struct dentry *sysv_lookup(struct inode * dir, struct dentry * dentry, struct nameidata *nd)
{
struct inode * inode = NULL;
ino_t ino;
if (dentry->d_name.len > SYSV_NAMELEN)
return ERR_PTR(-ENAMETOOLONG);
ino = sysv_inode_by_name(dentry);
if (ino) {
inode = sysv_iget(dir->i_sb, ino);
if (IS_ERR(inode))
return ERR_CAST(inode);
}
d_add(dentry, inode);
return NULL;
}
static int sysv_mknod(struct inode * dir, struct dentry * dentry, int mode, dev_t rdev)
{
struct inode * inode;
int err;
if (!old_valid_dev(rdev))
return -EINVAL;
inode = sysv_new_inode(dir, mode);
err = PTR_ERR(inode);
if (!IS_ERR(inode)) {
sysv_set_inode(inode, rdev);
mark_inode_dirty(inode);
err = add_nondir(dentry, inode);
}
return err;
}
static int sysv_create(struct inode * dir, struct dentry * dentry, int mode, struct nameidata *nd)
{
return sysv_mknod(dir, dentry, mode, 0);
}
static int sysv_symlink(struct inode * dir, struct dentry * dentry,
const char * symname)
{
int err = -ENAMETOOLONG;
int l = strlen(symname)+1;
struct inode * inode;
if (l > dir->i_sb->s_blocksize)
goto out;
inode = sysv_new_inode(dir, S_IFLNK|0777);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out;
sysv_set_inode(inode, 0);
err = page_symlink(inode, symname, l);
if (err)
goto out_fail;
mark_inode_dirty(inode);
err = add_nondir(dentry, inode);
out:
return err;
out_fail:
inode_dec_link_count(inode);
iput(inode);
goto out;
}
static int sysv_link(struct dentry * old_dentry, struct inode * dir,
struct dentry * dentry)
{
struct inode *inode = old_dentry->d_inode;
if (inode->i_nlink >= SYSV_SB(inode->i_sb)->s_link_max)
return -EMLINK;
inode->i_ctime = CURRENT_TIME_SEC;
inode_inc_link_count(inode);
ihold(inode);
return add_nondir(dentry, inode);
}
static int sysv_mkdir(struct inode * dir, struct dentry *dentry, int mode)
{
struct inode * inode;
int err = -EMLINK;
if (dir->i_nlink >= SYSV_SB(dir->i_sb)->s_link_max)
goto out;
inode_inc_link_count(dir);
inode = sysv_new_inode(dir, S_IFDIR|mode);
err = PTR_ERR(inode);
if (IS_ERR(inode))
goto out_dir;
sysv_set_inode(inode, 0);
inode_inc_link_count(inode);
err = sysv_make_empty(inode, dir);
if (err)
goto out_fail;
err = sysv_add_link(dentry, inode);
if (err)
goto out_fail;
d_instantiate(dentry, inode);
out:
return err;
out_fail:
inode_dec_link_count(inode);
inode_dec_link_count(inode);
iput(inode);
out_dir:
inode_dec_link_count(dir);
goto out;
}
static int sysv_unlink(struct inode * dir, struct dentry * dentry)
{
struct inode * inode = dentry->d_inode;
struct page * page;
struct sysv_dir_entry * de;
int err = -ENOENT;
de = sysv_find_entry(dentry, &page);
if (!de)
goto out;
err = sysv_delete_entry (de, page);
if (err)
goto out;
inode->i_ctime = dir->i_ctime;
inode_dec_link_count(inode);
out:
return err;
}
static int sysv_rmdir(struct inode * dir, struct dentry * dentry)
{
struct inode *inode = dentry->d_inode;
int err = -ENOTEMPTY;
if (sysv_empty_dir(inode)) {
err = sysv_unlink(dir, dentry);
if (!err) {
inode->i_size = 0;
inode_dec_link_count(inode);
inode_dec_link_count(dir);
}
}
return err;
}
/*
* Anybody can rename anything with this: the permission checks are left to the
* higher-level routines.
*/
static int sysv_rename(struct inode * old_dir, struct dentry * old_dentry,
struct inode * new_dir, struct dentry * new_dentry)
{
struct inode * old_inode = old_dentry->d_inode;
struct inode * new_inode = new_dentry->d_inode;
struct page * dir_page = NULL;
struct sysv_dir_entry * dir_de = NULL;
struct page * old_page;
struct sysv_dir_entry * old_de;
int err = -ENOENT;
old_de = sysv_find_entry(old_dentry, &old_page);
if (!old_de)
goto out;
if (S_ISDIR(old_inode->i_mode)) {
err = -EIO;
dir_de = sysv_dotdot(old_inode, &dir_page);
if (!dir_de)
goto out_old;
}
if (new_inode) {
struct page * new_page;
struct sysv_dir_entry * new_de;
err = -ENOTEMPTY;
if (dir_de && !sysv_empty_dir(new_inode))
goto out_dir;
err = -ENOENT;
new_de = sysv_find_entry(new_dentry, &new_page);
if (!new_de)
goto out_dir;
sysv_set_link(new_de, new_page, old_inode);
new_inode->i_ctime = CURRENT_TIME_SEC;
if (dir_de)
drop_nlink(new_inode);
inode_dec_link_count(new_inode);
} else {
if (dir_de) {
err = -EMLINK;
if (new_dir->i_nlink >= SYSV_SB(new_dir->i_sb)->s_link_max)
goto out_dir;
}
err = sysv_add_link(new_dentry, old_inode);
if (err)
goto out_dir;
if (dir_de)
inode_inc_link_count(new_dir);
}
sysv_delete_entry(old_de, old_page);
mark_inode_dirty(old_inode);
if (dir_de) {
sysv_set_link(dir_de, dir_page, new_dir);
inode_dec_link_count(old_dir);
}
return 0;
out_dir:
if (dir_de) {
kunmap(dir_page);
page_cache_release(dir_page);
}
out_old:
kunmap(old_page);
page_cache_release(old_page);
out:
return err;
}
/*
* directories can handle most operations...
*/
const struct inode_operations sysv_dir_inode_operations = {
.create = sysv_create,
.lookup = sysv_lookup,
.link = sysv_link,
.unlink = sysv_unlink,
.symlink = sysv_symlink,
.mkdir = sysv_mkdir,
.rmdir = sysv_rmdir,
.mknod = sysv_mknod,
.rename = sysv_rename,
.getattr = sysv_getattr,
};
| gpl-2.0 |
barome/me102a | drivers/leds/leds-sunfire.c | 3629 | 6112 | /* leds-sunfire.c: SUNW,Ultra-Enterprise LED driver.
*
* Copyright (C) 2008 David S. Miller <davem@davemloft.net>
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/leds.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <asm/fhc.h>
#include <asm/upa.h>
#define DRIVER_NAME "leds-sunfire"
#define PFX DRIVER_NAME ": "
MODULE_AUTHOR("David S. Miller (davem@davemloft.net)");
MODULE_DESCRIPTION("Sun Fire LED driver");
MODULE_LICENSE("GPL");
struct sunfire_led {
struct led_classdev led_cdev;
void __iomem *reg;
};
#define to_sunfire_led(d) container_of(d, struct sunfire_led, led_cdev)
static void __clockboard_set(struct led_classdev *led_cdev,
enum led_brightness led_val, u8 bit)
{
struct sunfire_led *p = to_sunfire_led(led_cdev);
u8 reg = upa_readb(p->reg);
switch (bit) {
case CLOCK_CTRL_LLED:
if (led_val)
reg &= ~bit;
else
reg |= bit;
break;
default:
if (led_val)
reg |= bit;
else
reg &= ~bit;
break;
}
upa_writeb(reg, p->reg);
}
static void clockboard_left_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__clockboard_set(led_cdev, led_val, CLOCK_CTRL_LLED);
}
static void clockboard_middle_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__clockboard_set(led_cdev, led_val, CLOCK_CTRL_MLED);
}
static void clockboard_right_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__clockboard_set(led_cdev, led_val, CLOCK_CTRL_RLED);
}
static void __fhc_set(struct led_classdev *led_cdev,
enum led_brightness led_val, u32 bit)
{
struct sunfire_led *p = to_sunfire_led(led_cdev);
u32 reg = upa_readl(p->reg);
switch (bit) {
case FHC_CONTROL_LLED:
if (led_val)
reg &= ~bit;
else
reg |= bit;
break;
default:
if (led_val)
reg |= bit;
else
reg &= ~bit;
break;
}
upa_writel(reg, p->reg);
}
static void fhc_left_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__fhc_set(led_cdev, led_val, FHC_CONTROL_LLED);
}
static void fhc_middle_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__fhc_set(led_cdev, led_val, FHC_CONTROL_MLED);
}
static void fhc_right_set(struct led_classdev *led_cdev,
enum led_brightness led_val)
{
__fhc_set(led_cdev, led_val, FHC_CONTROL_RLED);
}
typedef void (*set_handler)(struct led_classdev *, enum led_brightness);
struct led_type {
const char *name;
set_handler handler;
const char *default_trigger;
};
#define NUM_LEDS_PER_BOARD 3
struct sunfire_drvdata {
struct sunfire_led leds[NUM_LEDS_PER_BOARD];
};
static int __devinit sunfire_led_generic_probe(struct platform_device *pdev,
struct led_type *types)
{
struct sunfire_drvdata *p;
int i, err = -EINVAL;
if (pdev->num_resources != 1) {
printk(KERN_ERR PFX "Wrong number of resources %d, should be 1\n",
pdev->num_resources);
goto out;
}
p = kzalloc(sizeof(*p), GFP_KERNEL);
if (!p) {
printk(KERN_ERR PFX "Could not allocate struct sunfire_drvdata\n");
goto out;
}
for (i = 0; i < NUM_LEDS_PER_BOARD; i++) {
struct led_classdev *lp = &p->leds[i].led_cdev;
p->leds[i].reg = (void __iomem *) pdev->resource[0].start;
lp->name = types[i].name;
lp->brightness = LED_FULL;
lp->brightness_set = types[i].handler;
lp->default_trigger = types[i].default_trigger;
err = led_classdev_register(&pdev->dev, lp);
if (err) {
printk(KERN_ERR PFX "Could not register %s LED\n",
lp->name);
goto out_unregister_led_cdevs;
}
}
dev_set_drvdata(&pdev->dev, p);
err = 0;
out:
return err;
out_unregister_led_cdevs:
for (i--; i >= 0; i--)
led_classdev_unregister(&p->leds[i].led_cdev);
goto out;
}
static int __devexit sunfire_led_generic_remove(struct platform_device *pdev)
{
struct sunfire_drvdata *p = dev_get_drvdata(&pdev->dev);
int i;
for (i = 0; i < NUM_LEDS_PER_BOARD; i++)
led_classdev_unregister(&p->leds[i].led_cdev);
kfree(p);
return 0;
}
static struct led_type clockboard_led_types[NUM_LEDS_PER_BOARD] = {
{
.name = "clockboard-left",
.handler = clockboard_left_set,
},
{
.name = "clockboard-middle",
.handler = clockboard_middle_set,
},
{
.name = "clockboard-right",
.handler = clockboard_right_set,
.default_trigger= "heartbeat",
},
};
static int __devinit sunfire_clockboard_led_probe(struct platform_device *pdev)
{
return sunfire_led_generic_probe(pdev, clockboard_led_types);
}
static struct led_type fhc_led_types[NUM_LEDS_PER_BOARD] = {
{
.name = "fhc-left",
.handler = fhc_left_set,
},
{
.name = "fhc-middle",
.handler = fhc_middle_set,
},
{
.name = "fhc-right",
.handler = fhc_right_set,
.default_trigger= "heartbeat",
},
};
static int __devinit sunfire_fhc_led_probe(struct platform_device *pdev)
{
return sunfire_led_generic_probe(pdev, fhc_led_types);
}
MODULE_ALIAS("platform:sunfire-clockboard-leds");
MODULE_ALIAS("platform:sunfire-fhc-leds");
static struct platform_driver sunfire_clockboard_led_driver = {
.probe = sunfire_clockboard_led_probe,
.remove = __devexit_p(sunfire_led_generic_remove),
.driver = {
.name = "sunfire-clockboard-leds",
.owner = THIS_MODULE,
},
};
static struct platform_driver sunfire_fhc_led_driver = {
.probe = sunfire_fhc_led_probe,
.remove = __devexit_p(sunfire_led_generic_remove),
.driver = {
.name = "sunfire-fhc-leds",
.owner = THIS_MODULE,
},
};
static int __init sunfire_leds_init(void)
{
int err = platform_driver_register(&sunfire_clockboard_led_driver);
if (err) {
printk(KERN_ERR PFX "Could not register clock board LED driver\n");
return err;
}
err = platform_driver_register(&sunfire_fhc_led_driver);
if (err) {
printk(KERN_ERR PFX "Could not register FHC LED driver\n");
platform_driver_unregister(&sunfire_clockboard_led_driver);
}
return err;
}
static void __exit sunfire_leds_exit(void)
{
platform_driver_unregister(&sunfire_clockboard_led_driver);
platform_driver_unregister(&sunfire_fhc_led_driver);
}
module_init(sunfire_leds_init);
module_exit(sunfire_leds_exit);
| gpl-2.0 |
mdeejay/virtuous-s4v-kernel | drivers/ide/gayle.c | 4141 | 4767 | /*
* Amiga Gayle IDE Driver
*
* Created 9 Jul 1997 by Geert Uytterhoeven
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/interrupt.h>
#include <linux/blkdev.h>
#include <linux/ide.h>
#include <linux/init.h>
#include <linux/zorro.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <asm/setup.h>
#include <asm/amigahw.h>
#include <asm/amigaints.h>
#include <asm/amigayle.h>
/*
* Offsets from one of the above bases
*/
#define GAYLE_CONTROL 0x101a
/*
* These are at different offsets from the base
*/
#define GAYLE_IRQ_4000 0xdd3020 /* MSB = 1, Harddisk is source of */
#define GAYLE_IRQ_1200 0xda9000 /* interrupt */
/*
* Offset of the secondary port for IDE doublers
* Note that GAYLE_CONTROL is NOT available then!
*/
#define GAYLE_NEXT_PORT 0x1000
#define GAYLE_NUM_HWIFS 2
#define GAYLE_NUM_PROBE_HWIFS (ide_doubler ? GAYLE_NUM_HWIFS : \
GAYLE_NUM_HWIFS-1)
#define GAYLE_HAS_CONTROL_REG (!ide_doubler)
static int ide_doubler;
module_param_named(doubler, ide_doubler, bool, 0);
MODULE_PARM_DESC(doubler, "enable support for IDE doublers");
/*
* Check and acknowledge the interrupt status
*/
static int gayle_test_irq(ide_hwif_t *hwif)
{
unsigned char ch;
ch = z_readb(hwif->io_ports.irq_addr);
if (!(ch & GAYLE_IRQ_IDE))
return 0;
return 1;
}
static void gayle_a1200_clear_irq(ide_drive_t *drive)
{
ide_hwif_t *hwif = drive->hwif;
(void)z_readb(hwif->io_ports.status_addr);
z_writeb(0x7c, hwif->io_ports.irq_addr);
}
static void __init gayle_setup_ports(struct ide_hw *hw, unsigned long base,
unsigned long ctl, unsigned long irq_port)
{
int i;
memset(hw, 0, sizeof(*hw));
hw->io_ports.data_addr = base;
for (i = 1; i < 8; i++)
hw->io_ports_array[i] = base + 2 + i * 4;
hw->io_ports.ctl_addr = ctl;
hw->io_ports.irq_addr = irq_port;
hw->irq = IRQ_AMIGA_PORTS;
}
static const struct ide_port_ops gayle_a4000_port_ops = {
.test_irq = gayle_test_irq,
};
static const struct ide_port_ops gayle_a1200_port_ops = {
.clear_irq = gayle_a1200_clear_irq,
.test_irq = gayle_test_irq,
};
static const struct ide_port_info gayle_port_info = {
.host_flags = IDE_HFLAG_MMIO | IDE_HFLAG_SERIALIZE |
IDE_HFLAG_NO_DMA,
.irq_flags = IRQF_SHARED,
.chipset = ide_generic,
};
/*
* Probe for a Gayle IDE interface (and optionally for an IDE doubler)
*/
static int __init amiga_gayle_ide_probe(struct platform_device *pdev)
{
struct resource *res;
struct gayle_ide_platform_data *pdata;
unsigned long base, ctrlport, irqport;
unsigned int i;
int error;
struct ide_hw hw[GAYLE_NUM_HWIFS], *hws[GAYLE_NUM_HWIFS];
struct ide_port_info d = gayle_port_info;
struct ide_host *host;
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -ENODEV;
if (!request_mem_region(res->start, resource_size(res), "IDE"))
return -EBUSY;
pdata = pdev->dev.platform_data;
pr_info("ide: Gayle IDE controller (A%u style%s)\n",
pdata->explicit_ack ? 1200 : 4000,
ide_doubler ? ", IDE doubler" : "");
base = (unsigned long)ZTWO_VADDR(pdata->base);
ctrlport = 0;
irqport = (unsigned long)ZTWO_VADDR(pdata->irqport);
if (pdata->explicit_ack)
d.port_ops = &gayle_a1200_port_ops;
else
d.port_ops = &gayle_a4000_port_ops;
for (i = 0; i < GAYLE_NUM_PROBE_HWIFS; i++, base += GAYLE_NEXT_PORT) {
if (GAYLE_HAS_CONTROL_REG)
ctrlport = base + GAYLE_CONTROL;
gayle_setup_ports(&hw[i], base, ctrlport, irqport);
hws[i] = &hw[i];
}
error = ide_host_add(&d, hws, i, &host);
if (error)
goto out;
platform_set_drvdata(pdev, host);
return 0;
out:
release_mem_region(res->start, resource_size(res));
return error;
}
static int __exit amiga_gayle_ide_remove(struct platform_device *pdev)
{
struct ide_host *host = platform_get_drvdata(pdev);
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
ide_host_remove(host);
release_mem_region(res->start, resource_size(res));
return 0;
}
static struct platform_driver amiga_gayle_ide_driver = {
.remove = __exit_p(amiga_gayle_ide_remove),
.driver = {
.name = "amiga-gayle-ide",
.owner = THIS_MODULE,
},
};
static int __init amiga_gayle_ide_init(void)
{
return platform_driver_probe(&amiga_gayle_ide_driver,
amiga_gayle_ide_probe);
}
module_init(amiga_gayle_ide_init);
static void __exit amiga_gayle_ide_exit(void)
{
platform_driver_unregister(&amiga_gayle_ide_driver);
}
module_exit(amiga_gayle_ide_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:amiga-gayle-ide");
| gpl-2.0 |
danielpanzella/P900-kernel-source | arch/arm/mach-sa1100/leds-assabet.c | 4909 | 2332 | /*
* linux/arch/arm/mach-sa1100/leds-assabet.c
*
* Copyright (C) 2000 John Dorsey <john+@cs.cmu.edu>
*
* Original (leds-footbridge.c) by Russell King
*
* Assabet uses the LEDs as follows:
* - Green - toggles state every 50 timer interrupts
* - Red - on if system is not idle
*/
#include <linux/init.h>
#include <mach/hardware.h>
#include <asm/leds.h>
#include <mach/assabet.h>
#include "leds.h"
#define LED_STATE_ENABLED 1
#define LED_STATE_CLAIMED 2
static unsigned int led_state;
static unsigned int hw_led_state;
#define ASSABET_BCR_LED_MASK (ASSABET_BCR_LED_GREEN | ASSABET_BCR_LED_RED)
void assabet_leds_event(led_event_t evt)
{
unsigned long flags;
local_irq_save(flags);
switch (evt) {
case led_start:
hw_led_state = ASSABET_BCR_LED_RED | ASSABET_BCR_LED_GREEN;
led_state = LED_STATE_ENABLED;
break;
case led_stop:
led_state &= ~LED_STATE_ENABLED;
hw_led_state = ASSABET_BCR_LED_RED | ASSABET_BCR_LED_GREEN;
ASSABET_BCR_frob(ASSABET_BCR_LED_MASK, hw_led_state);
break;
case led_claim:
led_state |= LED_STATE_CLAIMED;
hw_led_state = ASSABET_BCR_LED_RED | ASSABET_BCR_LED_GREEN;
break;
case led_release:
led_state &= ~LED_STATE_CLAIMED;
hw_led_state = ASSABET_BCR_LED_RED | ASSABET_BCR_LED_GREEN;
break;
#ifdef CONFIG_LEDS_TIMER
case led_timer:
if (!(led_state & LED_STATE_CLAIMED))
hw_led_state ^= ASSABET_BCR_LED_GREEN;
break;
#endif
#ifdef CONFIG_LEDS_CPU
case led_idle_start:
if (!(led_state & LED_STATE_CLAIMED))
hw_led_state |= ASSABET_BCR_LED_RED;
break;
case led_idle_end:
if (!(led_state & LED_STATE_CLAIMED))
hw_led_state &= ~ASSABET_BCR_LED_RED;
break;
#endif
case led_halted:
break;
case led_green_on:
if (led_state & LED_STATE_CLAIMED)
hw_led_state &= ~ASSABET_BCR_LED_GREEN;
break;
case led_green_off:
if (led_state & LED_STATE_CLAIMED)
hw_led_state |= ASSABET_BCR_LED_GREEN;
break;
case led_amber_on:
break;
case led_amber_off:
break;
case led_red_on:
if (led_state & LED_STATE_CLAIMED)
hw_led_state &= ~ASSABET_BCR_LED_RED;
break;
case led_red_off:
if (led_state & LED_STATE_CLAIMED)
hw_led_state |= ASSABET_BCR_LED_RED;
break;
default:
break;
}
if (led_state & LED_STATE_ENABLED)
ASSABET_BCR_frob(ASSABET_BCR_LED_MASK, hw_led_state);
local_irq_restore(flags);
}
| gpl-2.0 |
johnweber/bbxm-kernel | arch/powerpc/kernel/nvram_64.c | 7725 | 13956 | /*
* c 2001 PPC 64 Team, IBM Corp
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*
* /dev/nvram driver for PPC64
*
* This perhaps should live in drivers/char
*
* TODO: Split the /dev/nvram part (that one can use
* drivers/char/generic_nvram.c) from the arch & partition
* parsing code.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/fcntl.h>
#include <linux/nvram.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <asm/uaccess.h>
#include <asm/nvram.h>
#include <asm/rtas.h>
#include <asm/prom.h>
#include <asm/machdep.h>
#undef DEBUG_NVRAM
#define NVRAM_HEADER_LEN sizeof(struct nvram_header)
#define NVRAM_BLOCK_LEN NVRAM_HEADER_LEN
/* If change this size, then change the size of NVNAME_LEN */
struct nvram_header {
unsigned char signature;
unsigned char checksum;
unsigned short length;
/* Terminating null required only for names < 12 chars. */
char name[12];
};
struct nvram_partition {
struct list_head partition;
struct nvram_header header;
unsigned int index;
};
static LIST_HEAD(nvram_partitions);
static loff_t dev_nvram_llseek(struct file *file, loff_t offset, int origin)
{
int size;
if (ppc_md.nvram_size == NULL)
return -ENODEV;
size = ppc_md.nvram_size();
switch (origin) {
case 1:
offset += file->f_pos;
break;
case 2:
offset += size;
break;
}
if (offset < 0)
return -EINVAL;
file->f_pos = offset;
return file->f_pos;
}
static ssize_t dev_nvram_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
ssize_t ret;
char *tmp = NULL;
ssize_t size;
ret = -ENODEV;
if (!ppc_md.nvram_size)
goto out;
ret = 0;
size = ppc_md.nvram_size();
if (*ppos >= size || size < 0)
goto out;
count = min_t(size_t, count, size - *ppos);
count = min(count, PAGE_SIZE);
ret = -ENOMEM;
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp)
goto out;
ret = ppc_md.nvram_read(tmp, count, ppos);
if (ret <= 0)
goto out;
if (copy_to_user(buf, tmp, ret))
ret = -EFAULT;
out:
kfree(tmp);
return ret;
}
static ssize_t dev_nvram_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
ssize_t ret;
char *tmp = NULL;
ssize_t size;
ret = -ENODEV;
if (!ppc_md.nvram_size)
goto out;
ret = 0;
size = ppc_md.nvram_size();
if (*ppos >= size || size < 0)
goto out;
count = min_t(size_t, count, size - *ppos);
count = min(count, PAGE_SIZE);
ret = -ENOMEM;
tmp = kmalloc(count, GFP_KERNEL);
if (!tmp)
goto out;
ret = -EFAULT;
if (copy_from_user(tmp, buf, count))
goto out;
ret = ppc_md.nvram_write(tmp, count, ppos);
out:
kfree(tmp);
return ret;
}
static long dev_nvram_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
switch(cmd) {
#ifdef CONFIG_PPC_PMAC
case OBSOLETE_PMAC_NVRAM_GET_OFFSET:
printk(KERN_WARNING "nvram: Using obsolete PMAC_NVRAM_GET_OFFSET ioctl\n");
case IOC_NVRAM_GET_OFFSET: {
int part, offset;
if (!machine_is(powermac))
return -EINVAL;
if (copy_from_user(&part, (void __user*)arg, sizeof(part)) != 0)
return -EFAULT;
if (part < pmac_nvram_OF || part > pmac_nvram_NR)
return -EINVAL;
offset = pmac_get_partition(part);
if (offset < 0)
return offset;
if (copy_to_user((void __user*)arg, &offset, sizeof(offset)) != 0)
return -EFAULT;
return 0;
}
#endif /* CONFIG_PPC_PMAC */
default:
return -EINVAL;
}
}
const struct file_operations nvram_fops = {
.owner = THIS_MODULE,
.llseek = dev_nvram_llseek,
.read = dev_nvram_read,
.write = dev_nvram_write,
.unlocked_ioctl = dev_nvram_ioctl,
};
static struct miscdevice nvram_dev = {
NVRAM_MINOR,
"nvram",
&nvram_fops
};
#ifdef DEBUG_NVRAM
static void __init nvram_print_partitions(char * label)
{
struct nvram_partition * tmp_part;
printk(KERN_WARNING "--------%s---------\n", label);
printk(KERN_WARNING "indx\t\tsig\tchks\tlen\tname\n");
list_for_each_entry(tmp_part, &nvram_partitions, partition) {
printk(KERN_WARNING "%4d \t%02x\t%02x\t%d\t%12s\n",
tmp_part->index, tmp_part->header.signature,
tmp_part->header.checksum, tmp_part->header.length,
tmp_part->header.name);
}
}
#endif
static int __init nvram_write_header(struct nvram_partition * part)
{
loff_t tmp_index;
int rc;
tmp_index = part->index;
rc = ppc_md.nvram_write((char *)&part->header, NVRAM_HEADER_LEN, &tmp_index);
return rc;
}
static unsigned char __init nvram_checksum(struct nvram_header *p)
{
unsigned int c_sum, c_sum2;
unsigned short *sp = (unsigned short *)p->name; /* assume 6 shorts */
c_sum = p->signature + p->length + sp[0] + sp[1] + sp[2] + sp[3] + sp[4] + sp[5];
/* The sum may have spilled into the 3rd byte. Fold it back. */
c_sum = ((c_sum & 0xffff) + (c_sum >> 16)) & 0xffff;
/* The sum cannot exceed 2 bytes. Fold it into a checksum */
c_sum2 = (c_sum >> 8) + (c_sum << 8);
c_sum = ((c_sum + c_sum2) >> 8) & 0xff;
return c_sum;
}
/*
* Per the criteria passed via nvram_remove_partition(), should this
* partition be removed? 1=remove, 0=keep
*/
static int nvram_can_remove_partition(struct nvram_partition *part,
const char *name, int sig, const char *exceptions[])
{
if (part->header.signature != sig)
return 0;
if (name) {
if (strncmp(name, part->header.name, 12))
return 0;
} else if (exceptions) {
const char **except;
for (except = exceptions; *except; except++) {
if (!strncmp(*except, part->header.name, 12))
return 0;
}
}
return 1;
}
/**
* nvram_remove_partition - Remove one or more partitions in nvram
* @name: name of the partition to remove, or NULL for a
* signature only match
* @sig: signature of the partition(s) to remove
* @exceptions: When removing all partitions with a matching signature,
* leave these alone.
*/
int __init nvram_remove_partition(const char *name, int sig,
const char *exceptions[])
{
struct nvram_partition *part, *prev, *tmp;
int rc;
list_for_each_entry(part, &nvram_partitions, partition) {
if (!nvram_can_remove_partition(part, name, sig, exceptions))
continue;
/* Make partition a free partition */
part->header.signature = NVRAM_SIG_FREE;
strncpy(part->header.name, "wwwwwwwwwwww", 12);
part->header.checksum = nvram_checksum(&part->header);
rc = nvram_write_header(part);
if (rc <= 0) {
printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
return rc;
}
}
/* Merge contiguous ones */
prev = NULL;
list_for_each_entry_safe(part, tmp, &nvram_partitions, partition) {
if (part->header.signature != NVRAM_SIG_FREE) {
prev = NULL;
continue;
}
if (prev) {
prev->header.length += part->header.length;
prev->header.checksum = nvram_checksum(&part->header);
rc = nvram_write_header(part);
if (rc <= 0) {
printk(KERN_ERR "nvram_remove_partition: nvram_write failed (%d)\n", rc);
return rc;
}
list_del(&part->partition);
kfree(part);
} else
prev = part;
}
return 0;
}
/**
* nvram_create_partition - Create a partition in nvram
* @name: name of the partition to create
* @sig: signature of the partition to create
* @req_size: size of data to allocate in bytes
* @min_size: minimum acceptable size (0 means req_size)
*
* Returns a negative error code or a positive nvram index
* of the beginning of the data area of the newly created
* partition. If you provided a min_size smaller than req_size
* you need to query for the actual size yourself after the
* call using nvram_partition_get_size().
*/
loff_t __init nvram_create_partition(const char *name, int sig,
int req_size, int min_size)
{
struct nvram_partition *part;
struct nvram_partition *new_part;
struct nvram_partition *free_part = NULL;
static char nv_init_vals[16];
loff_t tmp_index;
long size = 0;
int rc;
/* Convert sizes from bytes to blocks */
req_size = _ALIGN_UP(req_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
min_size = _ALIGN_UP(min_size, NVRAM_BLOCK_LEN) / NVRAM_BLOCK_LEN;
/* If no minimum size specified, make it the same as the
* requested size
*/
if (min_size == 0)
min_size = req_size;
if (min_size > req_size)
return -EINVAL;
/* Now add one block to each for the header */
req_size += 1;
min_size += 1;
/* Find a free partition that will give us the maximum needed size
If can't find one that will give us the minimum size needed */
list_for_each_entry(part, &nvram_partitions, partition) {
if (part->header.signature != NVRAM_SIG_FREE)
continue;
if (part->header.length >= req_size) {
size = req_size;
free_part = part;
break;
}
if (part->header.length > size &&
part->header.length >= min_size) {
size = part->header.length;
free_part = part;
}
}
if (!size)
return -ENOSPC;
/* Create our OS partition */
new_part = kmalloc(sizeof(*new_part), GFP_KERNEL);
if (!new_part) {
pr_err("nvram_create_os_partition: kmalloc failed\n");
return -ENOMEM;
}
new_part->index = free_part->index;
new_part->header.signature = sig;
new_part->header.length = size;
strncpy(new_part->header.name, name, 12);
new_part->header.checksum = nvram_checksum(&new_part->header);
rc = nvram_write_header(new_part);
if (rc <= 0) {
pr_err("nvram_create_os_partition: nvram_write_header "
"failed (%d)\n", rc);
return rc;
}
list_add_tail(&new_part->partition, &free_part->partition);
/* Adjust or remove the partition we stole the space from */
if (free_part->header.length > size) {
free_part->index += size * NVRAM_BLOCK_LEN;
free_part->header.length -= size;
free_part->header.checksum = nvram_checksum(&free_part->header);
rc = nvram_write_header(free_part);
if (rc <= 0) {
pr_err("nvram_create_os_partition: nvram_write_header "
"failed (%d)\n", rc);
return rc;
}
} else {
list_del(&free_part->partition);
kfree(free_part);
}
/* Clear the new partition */
for (tmp_index = new_part->index + NVRAM_HEADER_LEN;
tmp_index < ((size - 1) * NVRAM_BLOCK_LEN);
tmp_index += NVRAM_BLOCK_LEN) {
rc = ppc_md.nvram_write(nv_init_vals, NVRAM_BLOCK_LEN, &tmp_index);
if (rc <= 0) {
pr_err("nvram_create_partition: nvram_write failed (%d)\n", rc);
return rc;
}
}
return new_part->index + NVRAM_HEADER_LEN;
}
/**
* nvram_get_partition_size - Get the data size of an nvram partition
* @data_index: This is the offset of the start of the data of
* the partition. The same value that is returned by
* nvram_create_partition().
*/
int nvram_get_partition_size(loff_t data_index)
{
struct nvram_partition *part;
list_for_each_entry(part, &nvram_partitions, partition) {
if (part->index + NVRAM_HEADER_LEN == data_index)
return (part->header.length - 1) * NVRAM_BLOCK_LEN;
}
return -1;
}
/**
* nvram_find_partition - Find an nvram partition by signature and name
* @name: Name of the partition or NULL for any name
* @sig: Signature to test against
* @out_size: if non-NULL, returns the size of the data part of the partition
*/
loff_t nvram_find_partition(const char *name, int sig, int *out_size)
{
struct nvram_partition *p;
list_for_each_entry(p, &nvram_partitions, partition) {
if (p->header.signature == sig &&
(!name || !strncmp(p->header.name, name, 12))) {
if (out_size)
*out_size = (p->header.length - 1) *
NVRAM_BLOCK_LEN;
return p->index + NVRAM_HEADER_LEN;
}
}
return 0;
}
int __init nvram_scan_partitions(void)
{
loff_t cur_index = 0;
struct nvram_header phead;
struct nvram_partition * tmp_part;
unsigned char c_sum;
char * header;
int total_size;
int err;
if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
return -ENODEV;
total_size = ppc_md.nvram_size();
header = kmalloc(NVRAM_HEADER_LEN, GFP_KERNEL);
if (!header) {
printk(KERN_ERR "nvram_scan_partitions: Failed kmalloc\n");
return -ENOMEM;
}
while (cur_index < total_size) {
err = ppc_md.nvram_read(header, NVRAM_HEADER_LEN, &cur_index);
if (err != NVRAM_HEADER_LEN) {
printk(KERN_ERR "nvram_scan_partitions: Error parsing "
"nvram partitions\n");
goto out;
}
cur_index -= NVRAM_HEADER_LEN; /* nvram_read will advance us */
memcpy(&phead, header, NVRAM_HEADER_LEN);
err = 0;
c_sum = nvram_checksum(&phead);
if (c_sum != phead.checksum) {
printk(KERN_WARNING "WARNING: nvram partition checksum"
" was %02x, should be %02x!\n",
phead.checksum, c_sum);
printk(KERN_WARNING "Terminating nvram partition scan\n");
goto out;
}
if (!phead.length) {
printk(KERN_WARNING "WARNING: nvram corruption "
"detected: 0-length partition\n");
goto out;
}
tmp_part = (struct nvram_partition *)
kmalloc(sizeof(struct nvram_partition), GFP_KERNEL);
err = -ENOMEM;
if (!tmp_part) {
printk(KERN_ERR "nvram_scan_partitions: kmalloc failed\n");
goto out;
}
memcpy(&tmp_part->header, &phead, NVRAM_HEADER_LEN);
tmp_part->index = cur_index;
list_add_tail(&tmp_part->partition, &nvram_partitions);
cur_index += phead.length * NVRAM_BLOCK_LEN;
}
err = 0;
#ifdef DEBUG_NVRAM
nvram_print_partitions("NVRAM Partitions");
#endif
out:
kfree(header);
return err;
}
static int __init nvram_init(void)
{
int rc;
BUILD_BUG_ON(NVRAM_BLOCK_LEN != 16);
if (ppc_md.nvram_size == NULL || ppc_md.nvram_size() <= 0)
return -ENODEV;
rc = misc_register(&nvram_dev);
if (rc != 0) {
printk(KERN_ERR "nvram_init: failed to register device\n");
return rc;
}
return rc;
}
void __exit nvram_cleanup(void)
{
misc_deregister( &nvram_dev );
}
module_init(nvram_init);
module_exit(nvram_cleanup);
MODULE_LICENSE("GPL");
| gpl-2.0 |
davidmueller13/flo_kernel | drivers/i2c/busses/i2c-parport.c | 7981 | 8701 | /* ------------------------------------------------------------------------ *
* i2c-parport.c I2C bus over parallel port *
* ------------------------------------------------------------------------ *
Copyright (C) 2003-2011 Jean Delvare <khali@linux-fr.org>
Based on older i2c-philips-par.c driver
Copyright (C) 1995-2000 Simon G. Vogl
With some changes from:
Frodo Looijaard <frodol@dds.nl>
Kyösti Mälkki <kmalkki@cc.hut.fi>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* ------------------------------------------------------------------------ */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/parport.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/i2c-smbus.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include "i2c-parport.h"
/* ----- Device list ------------------------------------------------------ */
struct i2c_par {
struct pardevice *pdev;
struct i2c_adapter adapter;
struct i2c_algo_bit_data algo_data;
struct i2c_smbus_alert_setup alert_data;
struct i2c_client *ara;
struct list_head node;
};
static LIST_HEAD(adapter_list);
static DEFINE_MUTEX(adapter_list_lock);
/* ----- Low-level parallel port access ----------------------------------- */
static void port_write_data(struct parport *p, unsigned char d)
{
parport_write_data(p, d);
}
static void port_write_control(struct parport *p, unsigned char d)
{
parport_write_control(p, d);
}
static unsigned char port_read_data(struct parport *p)
{
return parport_read_data(p);
}
static unsigned char port_read_status(struct parport *p)
{
return parport_read_status(p);
}
static unsigned char port_read_control(struct parport *p)
{
return parport_read_control(p);
}
static void (* const port_write[])(struct parport *, unsigned char) = {
port_write_data,
NULL,
port_write_control,
};
static unsigned char (* const port_read[])(struct parport *) = {
port_read_data,
port_read_status,
port_read_control,
};
/* ----- Unified line operation functions --------------------------------- */
static inline void line_set(struct parport *data, int state,
const struct lineop *op)
{
u8 oldval = port_read[op->port](data);
/* Touch only the bit(s) needed */
if ((op->inverted && !state) || (!op->inverted && state))
port_write[op->port](data, oldval | op->val);
else
port_write[op->port](data, oldval & ~op->val);
}
static inline int line_get(struct parport *data,
const struct lineop *op)
{
u8 oldval = port_read[op->port](data);
return ((op->inverted && (oldval & op->val) != op->val)
|| (!op->inverted && (oldval & op->val) == op->val));
}
/* ----- I2C algorithm call-back functions and structures ----------------- */
static void parport_setscl(void *data, int state)
{
line_set((struct parport *) data, state, &adapter_parm[type].setscl);
}
static void parport_setsda(void *data, int state)
{
line_set((struct parport *) data, state, &adapter_parm[type].setsda);
}
static int parport_getscl(void *data)
{
return line_get((struct parport *) data, &adapter_parm[type].getscl);
}
static int parport_getsda(void *data)
{
return line_get((struct parport *) data, &adapter_parm[type].getsda);
}
/* Encapsulate the functions above in the correct structure.
Note that this is only a template, from which the real structures are
copied. The attaching code will set getscl to NULL for adapters that
cannot read SCL back, and will also make the data field point to
the parallel port structure. */
static const struct i2c_algo_bit_data parport_algo_data = {
.setsda = parport_setsda,
.setscl = parport_setscl,
.getsda = parport_getsda,
.getscl = parport_getscl,
.udelay = 10, /* ~50 kbps */
.timeout = HZ,
};
/* ----- I2c and parallel port call-back functions and structures --------- */
void i2c_parport_irq(void *data)
{
struct i2c_par *adapter = data;
struct i2c_client *ara = adapter->ara;
if (ara) {
dev_dbg(&ara->dev, "SMBus alert received\n");
i2c_handle_smbus_alert(ara);
} else
dev_dbg(&adapter->adapter.dev,
"SMBus alert received but no ARA client!\n");
}
static void i2c_parport_attach(struct parport *port)
{
struct i2c_par *adapter;
adapter = kzalloc(sizeof(struct i2c_par), GFP_KERNEL);
if (adapter == NULL) {
printk(KERN_ERR "i2c-parport: Failed to kzalloc\n");
return;
}
pr_debug("i2c-parport: attaching to %s\n", port->name);
parport_disable_irq(port);
adapter->pdev = parport_register_device(port, "i2c-parport",
NULL, NULL, i2c_parport_irq, PARPORT_FLAG_EXCL, adapter);
if (!adapter->pdev) {
printk(KERN_ERR "i2c-parport: Unable to register with parport\n");
goto err_free;
}
/* Fill the rest of the structure */
adapter->adapter.owner = THIS_MODULE;
adapter->adapter.class = I2C_CLASS_HWMON;
strlcpy(adapter->adapter.name, "Parallel port adapter",
sizeof(adapter->adapter.name));
adapter->algo_data = parport_algo_data;
/* Slow down if we can't sense SCL */
if (!adapter_parm[type].getscl.val) {
adapter->algo_data.getscl = NULL;
adapter->algo_data.udelay = 50; /* ~10 kbps */
}
adapter->algo_data.data = port;
adapter->adapter.algo_data = &adapter->algo_data;
adapter->adapter.dev.parent = port->physport->dev;
if (parport_claim_or_block(adapter->pdev) < 0) {
printk(KERN_ERR "i2c-parport: Could not claim parallel port\n");
goto err_unregister;
}
/* Reset hardware to a sane state (SCL and SDA high) */
parport_setsda(port, 1);
parport_setscl(port, 1);
/* Other init if needed (power on...) */
if (adapter_parm[type].init.val) {
line_set(port, 1, &adapter_parm[type].init);
/* Give powered devices some time to settle */
msleep(100);
}
if (i2c_bit_add_bus(&adapter->adapter) < 0) {
printk(KERN_ERR "i2c-parport: Unable to register with I2C\n");
goto err_unregister;
}
/* Setup SMBus alert if supported */
if (adapter_parm[type].smbus_alert) {
adapter->alert_data.alert_edge_triggered = 1;
adapter->ara = i2c_setup_smbus_alert(&adapter->adapter,
&adapter->alert_data);
if (adapter->ara)
parport_enable_irq(port);
else
printk(KERN_WARNING "i2c-parport: Failed to register "
"ARA client\n");
}
/* Add the new adapter to the list */
mutex_lock(&adapter_list_lock);
list_add_tail(&adapter->node, &adapter_list);
mutex_unlock(&adapter_list_lock);
return;
err_unregister:
parport_release(adapter->pdev);
parport_unregister_device(adapter->pdev);
err_free:
kfree(adapter);
}
static void i2c_parport_detach(struct parport *port)
{
struct i2c_par *adapter, *_n;
/* Walk the list */
mutex_lock(&adapter_list_lock);
list_for_each_entry_safe(adapter, _n, &adapter_list, node) {
if (adapter->pdev->port == port) {
if (adapter->ara) {
parport_disable_irq(port);
i2c_unregister_device(adapter->ara);
}
i2c_del_adapter(&adapter->adapter);
/* Un-init if needed (power off...) */
if (adapter_parm[type].init.val)
line_set(port, 0, &adapter_parm[type].init);
parport_release(adapter->pdev);
parport_unregister_device(adapter->pdev);
list_del(&adapter->node);
kfree(adapter);
}
}
mutex_unlock(&adapter_list_lock);
}
static struct parport_driver i2c_parport_driver = {
.name = "i2c-parport",
.attach = i2c_parport_attach,
.detach = i2c_parport_detach,
};
/* ----- Module loading, unloading and information ------------------------ */
static int __init i2c_parport_init(void)
{
if (type < 0) {
printk(KERN_WARNING "i2c-parport: adapter type unspecified\n");
return -ENODEV;
}
if (type >= ARRAY_SIZE(adapter_parm)) {
printk(KERN_WARNING "i2c-parport: invalid type (%d)\n", type);
return -ENODEV;
}
return parport_register_driver(&i2c_parport_driver);
}
static void __exit i2c_parport_exit(void)
{
parport_unregister_driver(&i2c_parport_driver);
}
MODULE_AUTHOR("Jean Delvare <khali@linux-fr.org>");
MODULE_DESCRIPTION("I2C bus over parallel port");
MODULE_LICENSE("GPL");
module_init(i2c_parport_init);
module_exit(i2c_parport_exit);
| gpl-2.0 |
boa19861105/android_442_KitKat_kernel_htc_dlxpul | arch/microblaze/pci/xilinx_pci.c | 7981 | 4579 | /*
* PCI support for Xilinx plbv46_pci soft-core which can be used on
* Xilinx Virtex ML410 / ML510 boards.
*
* Copyright 2009 Roderick Colenbrander
* Copyright 2009 Secret Lab Technologies Ltd.
*
* The pci bridge fixup code was copied from ppc4xx_pci.c and was written
* by Benjamin Herrenschmidt.
* Copyright 2007 Ben. Herrenschmidt <benh@kernel.crashing.org>, IBM Corp.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/ioport.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/pci.h>
#include <asm/io.h>
#define XPLB_PCI_ADDR 0x10c
#define XPLB_PCI_DATA 0x110
#define XPLB_PCI_BUS 0x114
#define PCI_HOST_ENABLE_CMD (PCI_COMMAND_SERR | PCI_COMMAND_PARITY | \
PCI_COMMAND_MASTER | PCI_COMMAND_MEMORY)
static struct of_device_id xilinx_pci_match[] = {
{ .compatible = "xlnx,plbv46-pci-1.03.a", },
{}
};
/**
* xilinx_pci_fixup_bridge - Block Xilinx PHB configuration.
*/
static void xilinx_pci_fixup_bridge(struct pci_dev *dev)
{
struct pci_controller *hose;
int i;
if (dev->devfn || dev->bus->self)
return;
hose = pci_bus_to_host(dev->bus);
if (!hose)
return;
if (!of_match_node(xilinx_pci_match, hose->dn))
return;
/* Hide the PCI host BARs from the kernel as their content doesn't
* fit well in the resource management
*/
for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
dev->resource[i].start = 0;
dev->resource[i].end = 0;
dev->resource[i].flags = 0;
}
dev_info(&dev->dev, "Hiding Xilinx plb-pci host bridge resources %s\n",
pci_name(dev));
}
DECLARE_PCI_FIXUP_HEADER(PCI_ANY_ID, PCI_ANY_ID, xilinx_pci_fixup_bridge);
#ifdef DEBUG
/**
* xilinx_pci_exclude_device - Don't do config access for non-root bus
*
* This is a hack. Config access to any bus other than bus 0 does not
* currently work on the ML510 so we prevent it here.
*/
static int
xilinx_pci_exclude_device(struct pci_controller *hose, u_char bus, u8 devfn)
{
return (bus != 0);
}
/**
* xilinx_early_pci_scan - List pci config space for available devices
*
* List pci devices in very early phase.
*/
void __init xilinx_early_pci_scan(struct pci_controller *hose)
{
u32 bus = 0;
u32 val, dev, func, offset;
/* Currently we have only 2 device connected - up-to 32 devices */
for (dev = 0; dev < 2; dev++) {
/* List only first function number - up-to 8 functions */
for (func = 0; func < 1; func++) {
printk(KERN_INFO "%02x:%02x:%02x", bus, dev, func);
/* read the first 64 standardized bytes */
/* Up-to 192 bytes can be list of capabilities */
for (offset = 0; offset < 64; offset += 4) {
early_read_config_dword(hose, bus,
PCI_DEVFN(dev, func), offset, &val);
if (offset == 0 && val == 0xFFFFFFFF) {
printk(KERN_CONT "\nABSENT");
break;
}
if (!(offset % 0x10))
printk(KERN_CONT "\n%04x: ", offset);
printk(KERN_CONT "%08x ", val);
}
printk(KERN_INFO "\n");
}
}
}
#else
void __init xilinx_early_pci_scan(struct pci_controller *hose)
{
}
#endif
/**
* xilinx_pci_init - Find and register a Xilinx PCI host bridge
*/
void __init xilinx_pci_init(void)
{
struct pci_controller *hose;
struct resource r;
void __iomem *pci_reg;
struct device_node *pci_node;
pci_node = of_find_matching_node(NULL, xilinx_pci_match);
if (!pci_node)
return;
if (of_address_to_resource(pci_node, 0, &r)) {
pr_err("xilinx-pci: cannot resolve base address\n");
return;
}
hose = pcibios_alloc_controller(pci_node);
if (!hose) {
pr_err("xilinx-pci: pcibios_alloc_controller() failed\n");
return;
}
/* Setup config space */
setup_indirect_pci(hose, r.start + XPLB_PCI_ADDR,
r.start + XPLB_PCI_DATA,
INDIRECT_TYPE_SET_CFG_TYPE);
/* According to the xilinx plbv46_pci documentation the soft-core starts
* a self-init when the bus master enable bit is set. Without this bit
* set the pci bus can't be scanned.
*/
early_write_config_word(hose, 0, 0, PCI_COMMAND, PCI_HOST_ENABLE_CMD);
/* Set the max latency timer to 255 */
early_write_config_byte(hose, 0, 0, PCI_LATENCY_TIMER, 0xff);
/* Set the max bus number to 255, and bus/subbus no's to 0 */
pci_reg = of_iomap(pci_node, 0);
out_be32(pci_reg + XPLB_PCI_BUS, 0x000000ff);
iounmap(pci_reg);
/* Register the host bridge with the linux kernel! */
pci_process_bridge_OF_ranges(hose, pci_node,
INDIRECT_TYPE_SET_CFG_TYPE);
pr_info("xilinx-pci: Registered PCI host bridge\n");
xilinx_early_pci_scan(hose);
}
| gpl-2.0 |
XePeleato/ALE-L21_ESAL | drivers/media/usb/sn9c102/sn9c102_hv7131r.c | 12845 | 10697 | /***************************************************************************
* Plug-in for HV7131R image sensor connected to the SN9C1xx PC Camera *
* Controllers *
* *
* Copyright (C) 2007 by Luca Risolia <luca.risolia@studio.unibo.it> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the Free Software *
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. *
***************************************************************************/
#include "sn9c102_sensor.h"
#include "sn9c102_devtable.h"
static int hv7131r_init(struct sn9c102_device* cam)
{
int err = 0;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C103:
err = sn9c102_write_const_regs(cam, {0x00, 0x03}, {0x1a, 0x04},
{0x20, 0x05}, {0x20, 0x06},
{0x03, 0x10}, {0x00, 0x14},
{0x60, 0x17}, {0x0a, 0x18},
{0xf0, 0x19}, {0x1d, 0x1a},
{0x10, 0x1b}, {0x02, 0x1c},
{0x03, 0x1d}, {0x0f, 0x1e},
{0x0c, 0x1f}, {0x00, 0x20},
{0x10, 0x21}, {0x20, 0x22},
{0x30, 0x23}, {0x40, 0x24},
{0x50, 0x25}, {0x60, 0x26},
{0x70, 0x27}, {0x80, 0x28},
{0x90, 0x29}, {0xa0, 0x2a},
{0xb0, 0x2b}, {0xc0, 0x2c},
{0xd0, 0x2d}, {0xe0, 0x2e},
{0xf0, 0x2f}, {0xff, 0x30});
break;
case BRIDGE_SN9C105:
case BRIDGE_SN9C120:
err = sn9c102_write_const_regs(cam, {0x44, 0x01}, {0x40, 0x02},
{0x00, 0x03}, {0x1a, 0x04},
{0x44, 0x05}, {0x3e, 0x06},
{0x1a, 0x07}, {0x03, 0x10},
{0x08, 0x14}, {0xa3, 0x17},
{0x4b, 0x18}, {0x00, 0x19},
{0x1d, 0x1a}, {0x10, 0x1b},
{0x02, 0x1c}, {0x03, 0x1d},
{0x0f, 0x1e}, {0x0c, 0x1f},
{0x00, 0x20}, {0x29, 0x21},
{0x40, 0x22}, {0x54, 0x23},
{0x66, 0x24}, {0x76, 0x25},
{0x85, 0x26}, {0x94, 0x27},
{0xa1, 0x28}, {0xae, 0x29},
{0xbb, 0x2a}, {0xc7, 0x2b},
{0xd3, 0x2c}, {0xde, 0x2d},
{0xea, 0x2e}, {0xf4, 0x2f},
{0xff, 0x30}, {0x00, 0x3F},
{0xC7, 0x40}, {0x01, 0x41},
{0x44, 0x42}, {0x00, 0x43},
{0x44, 0x44}, {0x00, 0x45},
{0x44, 0x46}, {0x00, 0x47},
{0xC7, 0x48}, {0x01, 0x49},
{0xC7, 0x4A}, {0x01, 0x4B},
{0xC7, 0x4C}, {0x01, 0x4D},
{0x44, 0x4E}, {0x00, 0x4F},
{0x44, 0x50}, {0x00, 0x51},
{0x44, 0x52}, {0x00, 0x53},
{0xC7, 0x54}, {0x01, 0x55},
{0xC7, 0x56}, {0x01, 0x57},
{0xC7, 0x58}, {0x01, 0x59},
{0x44, 0x5A}, {0x00, 0x5B},
{0x44, 0x5C}, {0x00, 0x5D},
{0x44, 0x5E}, {0x00, 0x5F},
{0xC7, 0x60}, {0x01, 0x61},
{0xC7, 0x62}, {0x01, 0x63},
{0xC7, 0x64}, {0x01, 0x65},
{0x44, 0x66}, {0x00, 0x67},
{0x44, 0x68}, {0x00, 0x69},
{0x44, 0x6A}, {0x00, 0x6B},
{0xC7, 0x6C}, {0x01, 0x6D},
{0xC7, 0x6E}, {0x01, 0x6F},
{0xC7, 0x70}, {0x01, 0x71},
{0x44, 0x72}, {0x00, 0x73},
{0x44, 0x74}, {0x00, 0x75},
{0x44, 0x76}, {0x00, 0x77},
{0xC7, 0x78}, {0x01, 0x79},
{0xC7, 0x7A}, {0x01, 0x7B},
{0xC7, 0x7C}, {0x01, 0x7D},
{0x44, 0x7E}, {0x00, 0x7F},
{0x14, 0x84}, {0x00, 0x85},
{0x27, 0x86}, {0x00, 0x87},
{0x07, 0x88}, {0x00, 0x89},
{0xEC, 0x8A}, {0x0f, 0x8B},
{0xD8, 0x8C}, {0x0f, 0x8D},
{0x3D, 0x8E}, {0x00, 0x8F},
{0x3D, 0x90}, {0x00, 0x91},
{0xCD, 0x92}, {0x0f, 0x93},
{0xf7, 0x94}, {0x0f, 0x95},
{0x0C, 0x96}, {0x00, 0x97},
{0x00, 0x98}, {0x66, 0x99},
{0x05, 0x9A}, {0x00, 0x9B},
{0x04, 0x9C}, {0x00, 0x9D},
{0x08, 0x9E}, {0x00, 0x9F},
{0x2D, 0xC0}, {0x2D, 0xC1},
{0x3A, 0xC2}, {0x05, 0xC3},
{0x04, 0xC4}, {0x3F, 0xC5},
{0x00, 0xC6}, {0x00, 0xC7},
{0x50, 0xC8}, {0x3C, 0xC9},
{0x28, 0xCA}, {0xD8, 0xCB},
{0x14, 0xCC}, {0xEC, 0xCD},
{0x32, 0xCE}, {0xDD, 0xCF},
{0x32, 0xD0}, {0xDD, 0xD1},
{0x6A, 0xD2}, {0x50, 0xD3},
{0x00, 0xD4}, {0x00, 0xD5},
{0x00, 0xD6});
break;
default:
break;
}
err += sn9c102_i2c_write(cam, 0x20, 0x00);
err += sn9c102_i2c_write(cam, 0x21, 0xd6);
err += sn9c102_i2c_write(cam, 0x25, 0x06);
return err;
}
static int hv7131r_get_ctrl(struct sn9c102_device* cam,
struct v4l2_control* ctrl)
{
switch (ctrl->id) {
case V4L2_CID_GAIN:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x30)) < 0)
return -EIO;
return 0;
case V4L2_CID_RED_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x31)) < 0)
return -EIO;
ctrl->value = ctrl->value & 0x3f;
return 0;
case V4L2_CID_BLUE_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x33)) < 0)
return -EIO;
ctrl->value = ctrl->value & 0x3f;
return 0;
case SN9C102_V4L2_CID_GREEN_BALANCE:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x32)) < 0)
return -EIO;
ctrl->value = ctrl->value & 0x3f;
return 0;
case V4L2_CID_BLACK_LEVEL:
if ((ctrl->value = sn9c102_i2c_read(cam, 0x01)) < 0)
return -EIO;
ctrl->value = (ctrl->value & 0x08) ? 1 : 0;
return 0;
default:
return -EINVAL;
}
}
static int hv7131r_set_ctrl(struct sn9c102_device* cam,
const struct v4l2_control* ctrl)
{
int err = 0;
switch (ctrl->id) {
case V4L2_CID_GAIN:
err += sn9c102_i2c_write(cam, 0x30, ctrl->value);
break;
case V4L2_CID_RED_BALANCE:
err += sn9c102_i2c_write(cam, 0x31, ctrl->value);
break;
case V4L2_CID_BLUE_BALANCE:
err += sn9c102_i2c_write(cam, 0x33, ctrl->value);
break;
case SN9C102_V4L2_CID_GREEN_BALANCE:
err += sn9c102_i2c_write(cam, 0x32, ctrl->value);
break;
case V4L2_CID_BLACK_LEVEL:
{
int r = sn9c102_i2c_read(cam, 0x01);
if (r < 0)
return -EIO;
err += sn9c102_i2c_write(cam, 0x01,
(ctrl->value<<3) | (r&0xf7));
}
break;
default:
return -EINVAL;
}
return err ? -EIO : 0;
}
static int hv7131r_set_crop(struct sn9c102_device* cam,
const struct v4l2_rect* rect)
{
struct sn9c102_sensor* s = sn9c102_get_sensor(cam);
int err = 0;
u8 h_start = (u8)(rect->left - s->cropcap.bounds.left) + 1,
v_start = (u8)(rect->top - s->cropcap.bounds.top) + 1;
err += sn9c102_write_reg(cam, h_start, 0x12);
err += sn9c102_write_reg(cam, v_start, 0x13);
return err;
}
static int hv7131r_set_pix_format(struct sn9c102_device* cam,
const struct v4l2_pix_format* pix)
{
int err = 0;
switch (sn9c102_get_bridge(cam)) {
case BRIDGE_SN9C103:
if (pix->pixelformat == V4L2_PIX_FMT_SBGGR8) {
err += sn9c102_write_reg(cam, 0xa0, 0x19);
err += sn9c102_i2c_write(cam, 0x01, 0x04);
} else {
err += sn9c102_write_reg(cam, 0x30, 0x19);
err += sn9c102_i2c_write(cam, 0x01, 0x04);
}
break;
case BRIDGE_SN9C105:
case BRIDGE_SN9C120:
if (pix->pixelformat == V4L2_PIX_FMT_SBGGR8) {
err += sn9c102_write_reg(cam, 0xa5, 0x17);
err += sn9c102_i2c_write(cam, 0x01, 0x24);
} else {
err += sn9c102_write_reg(cam, 0xa3, 0x17);
err += sn9c102_i2c_write(cam, 0x01, 0x04);
}
break;
default:
break;
}
return err;
}
static const struct sn9c102_sensor hv7131r = {
.name = "HV7131R",
.maintainer = "Luca Risolia <luca.risolia@studio.unibo.it>",
.supported_bridge = BRIDGE_SN9C103 | BRIDGE_SN9C105 | BRIDGE_SN9C120,
.sysfs_ops = SN9C102_I2C_READ | SN9C102_I2C_WRITE,
.frequency = SN9C102_I2C_100KHZ,
.interface = SN9C102_I2C_2WIRES,
.i2c_slave_id = 0x11,
.init = &hv7131r_init,
.qctrl = {
{
.id = V4L2_CID_GAIN,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "global gain",
.minimum = 0x00,
.maximum = 0xff,
.step = 0x01,
.default_value = 0x40,
.flags = 0,
},
{
.id = V4L2_CID_RED_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "red balance",
.minimum = 0x00,
.maximum = 0x3f,
.step = 0x01,
.default_value = 0x08,
.flags = 0,
},
{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "blue balance",
.minimum = 0x00,
.maximum = 0x3f,
.step = 0x01,
.default_value = 0x1a,
.flags = 0,
},
{
.id = SN9C102_V4L2_CID_GREEN_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "green balance",
.minimum = 0x00,
.maximum = 0x3f,
.step = 0x01,
.default_value = 0x2f,
.flags = 0,
},
{
.id = V4L2_CID_BLACK_LEVEL,
.type = V4L2_CTRL_TYPE_BOOLEAN,
.name = "auto black level compensation",
.minimum = 0x00,
.maximum = 0x01,
.step = 0x01,
.default_value = 0x00,
.flags = 0,
},
},
.get_ctrl = &hv7131r_get_ctrl,
.set_ctrl = &hv7131r_set_ctrl,
.cropcap = {
.bounds = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
.defrect = {
.left = 0,
.top = 0,
.width = 640,
.height = 480,
},
},
.set_crop = &hv7131r_set_crop,
.pix_format = {
.width = 640,
.height = 480,
.pixelformat = V4L2_PIX_FMT_SBGGR8,
.priv = 8,
},
.set_pix_format = &hv7131r_set_pix_format
};
int sn9c102_probe_hv7131r(struct sn9c102_device* cam)
{
int devid, err;
err = sn9c102_write_const_regs(cam, {0x09, 0x01}, {0x44, 0x02},
{0x34, 0x01}, {0x20, 0x17},
{0x34, 0x01}, {0x46, 0x01});
devid = sn9c102_i2c_try_read(cam, &hv7131r, 0x00);
if (err || devid < 0)
return -EIO;
if (devid != 0x02)
return -ENODEV;
sn9c102_attach_sensor(cam, &hv7131r);
return 0;
}
| gpl-2.0 |
SlimLG2/android_kernel_motorola_msm8992 | sound/oss/midi_synth.c | 13101 | 15125 | /*
* sound/oss/midi_synth.c
*
* High level midi sequencer manager for dumb MIDI interfaces.
*/
/*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*/
/*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* Andrew Veliath : fixed running status in MIDI input state machine
*/
#define USE_SEQ_MACROS
#define USE_SIMPLE_MACROS
#include "sound_config.h"
#define _MIDI_SYNTH_C_
#include "midi_synth.h"
static int midi2synth[MAX_MIDI_DEV];
static int sysex_state[MAX_MIDI_DEV] =
{0};
static unsigned char prev_out_status[MAX_MIDI_DEV];
#define STORE(cmd) \
{ \
int len; \
unsigned char obuf[8]; \
cmd; \
seq_input_event(obuf, len); \
}
#define _seqbuf obuf
#define _seqbufptr 0
#define _SEQ_ADVBUF(x) len=x
void
do_midi_msg(int synthno, unsigned char *msg, int mlen)
{
switch (msg[0] & 0xf0)
{
case 0x90:
if (msg[2] != 0)
{
STORE(SEQ_START_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
}
msg[2] = 64;
case 0x80:
STORE(SEQ_STOP_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xA0:
STORE(SEQ_KEY_PRESSURE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xB0:
STORE(SEQ_CONTROL(synthno, msg[0] & 0x0f,
msg[1], msg[2]));
break;
case 0xC0:
STORE(SEQ_SET_PATCH(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xD0:
STORE(SEQ_CHN_PRESSURE(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xE0:
STORE(SEQ_BENDER(synthno, msg[0] & 0x0f,
(msg[1] & 0x7f) | ((msg[2] & 0x7f) << 7)));
break;
default:
/* printk( "MPU: Unknown midi channel message %02x\n", msg[0]); */
;
}
}
EXPORT_SYMBOL(do_midi_msg);
static void
midi_outc(int midi_dev, int data)
{
int timeout;
for (timeout = 0; timeout < 3200; timeout++)
if (midi_devs[midi_dev]->outputc(midi_dev, (unsigned char) (data & 0xff)))
{
if (data & 0x80) /*
* Status byte
*/
prev_out_status[midi_dev] =
(unsigned char) (data & 0xff); /*
* Store for running status
*/
return; /*
* Mission complete
*/
}
/*
* Sorry! No space on buffers.
*/
printk("Midi send timed out\n");
}
static int
prefix_cmd(int midi_dev, unsigned char status)
{
if ((char *) midi_devs[midi_dev]->prefix_cmd == NULL)
return 1;
return midi_devs[midi_dev]->prefix_cmd(midi_dev, status);
}
static void
midi_synth_input(int orig_dev, unsigned char data)
{
int dev;
struct midi_input_info *inc;
static unsigned char len_tab[] = /* # of data bytes following a status
*/
{
2, /* 8x */
2, /* 9x */
2, /* Ax */
2, /* Bx */
1, /* Cx */
1, /* Dx */
2, /* Ex */
0 /* Fx */
};
if (orig_dev < 0 || orig_dev > num_midis || midi_devs[orig_dev] == NULL)
return;
if (data == 0xfe) /* Ignore active sensing */
return;
dev = midi2synth[orig_dev];
inc = &midi_devs[orig_dev]->in_info;
switch (inc->m_state)
{
case MST_INIT:
if (data & 0x80) /* MIDI status byte */
{
if ((data & 0xf0) == 0xf0) /* Common message */
{
switch (data)
{
case 0xf0: /* Sysex */
inc->m_state = MST_SYSEX;
break; /* Sysex */
case 0xf1: /* MTC quarter frame */
case 0xf3: /* Song select */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 1;
inc->m_buf[0] = data;
break;
case 0xf2: /* Song position pointer */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 2;
inc->m_buf[0] = data;
break;
default:
inc->m_buf[0] = data;
inc->m_ptr = 1;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
inc->m_left = 0;
}
} else
{
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = len_tab[(data >> 4) - 8];
inc->m_buf[0] = inc->m_prev_status = data;
}
} else if (inc->m_prev_status & 0x80) {
/* Data byte (use running status) */
inc->m_ptr = 2;
inc->m_buf[1] = data;
inc->m_buf[0] = inc->m_prev_status;
inc->m_left = len_tab[(inc->m_buf[0] >> 4) - 8] - 1;
if (inc->m_left > 0)
inc->m_state = MST_DATA; /* Not done yet */
else {
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
}
break; /* MST_INIT */
case MST_DATA:
inc->m_buf[inc->m_ptr++] = data;
if (--inc->m_left <= 0)
{
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
break; /* MST_DATA */
case MST_SYSEX:
if (data == 0xf7) /* Sysex end */
{
inc->m_state = MST_INIT;
inc->m_left = 0;
inc->m_ptr = 0;
}
break; /* MST_SYSEX */
default:
printk("MIDI%d: Unexpected state %d (%02x)\n", orig_dev, inc->m_state, (int) data);
inc->m_state = MST_INIT;
}
}
static void
leave_sysex(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
int timeout = 0;
if (!sysex_state[dev])
return;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, 0xf7) &&
timeout < 1000)
timeout++;
sysex_state[dev] = 0;
}
static void
midi_synth_output(int dev)
{
/*
* Currently NOP
*/
}
int midi_synth_ioctl(int dev, unsigned int cmd, void __user *arg)
{
/*
* int orig_dev = synth_devs[dev]->midi_dev;
*/
switch (cmd) {
case SNDCTL_SYNTH_INFO:
if (__copy_to_user(arg, synth_devs[dev]->info, sizeof(struct synth_info)))
return -EFAULT;
return 0;
case SNDCTL_SYNTH_MEMAVL:
return 0x7fffffff;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(midi_synth_ioctl);
int
midi_synth_kill_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && ((msg == 0x90 && velocity == 64) || msg == 0x80))
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
if (msg == 0x90) /*
* Running status = Note on
*/
midi_outc(orig_dev, 0); /*
* Note on with velocity 0 == note
* off
*/
else
midi_outc(orig_dev, velocity);
} else
{
if (velocity == 64)
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, 0); /*
* Zero G
*/
} else
{
if (!prefix_cmd(orig_dev, 0x80 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x80 | (channel & 0x0f)); /*
* Note off
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
}
return 0;
}
EXPORT_SYMBOL(midi_synth_kill_note);
int
midi_synth_set_instr(int dev, int channel, int instr_no)
{
int orig_dev = synth_devs[dev]->midi_dev;
if (instr_no < 0 || instr_no > 127)
instr_no = 0;
if (channel < 0 || channel > 15)
return 0;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xc0 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0xc0 | (channel & 0x0f)); /*
* Program change
*/
midi_outc(orig_dev, instr_no);
return 0;
}
EXPORT_SYMBOL(midi_synth_set_instr);
int
midi_synth_start_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && msg == 0x90)
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
} else
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
return 0;
}
EXPORT_SYMBOL(midi_synth_start_note);
void
midi_synth_reset(int dev)
{
leave_sysex(dev);
}
EXPORT_SYMBOL(midi_synth_reset);
int
midi_synth_open(int dev, int mode)
{
int orig_dev = synth_devs[dev]->midi_dev;
int err;
struct midi_input_info *inc;
if (orig_dev < 0 || orig_dev >= num_midis || midi_devs[orig_dev] == NULL)
return -ENXIO;
midi2synth[orig_dev] = dev;
sysex_state[dev] = 0;
prev_out_status[orig_dev] = 0;
if ((err = midi_devs[orig_dev]->open(orig_dev, mode,
midi_synth_input, midi_synth_output)) < 0)
return err;
inc = &midi_devs[orig_dev]->in_info;
/* save_flags(flags);
cli();
don't know against what irqhandler to protect*/
inc->m_busy = 0;
inc->m_state = MST_INIT;
inc->m_ptr = 0;
inc->m_left = 0;
inc->m_prev_status = 0x00;
/* restore_flags(flags); */
return 1;
}
EXPORT_SYMBOL(midi_synth_open);
void
midi_synth_close(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
leave_sysex(dev);
/*
* Shut up the synths by sending just single active sensing message.
*/
midi_devs[orig_dev]->outputc(orig_dev, 0xfe);
midi_devs[orig_dev]->close(orig_dev);
}
EXPORT_SYMBOL(midi_synth_close);
void
midi_synth_hw_control(int dev, unsigned char *event)
{
}
EXPORT_SYMBOL(midi_synth_hw_control);
int
midi_synth_load_patch(int dev, int format, const char __user *addr,
int count, int pmgr_flag)
{
int orig_dev = synth_devs[dev]->midi_dev;
struct sysex_info sysex;
int i;
unsigned long left, src_offs, eox_seen = 0;
int first_byte = 1;
int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
/* Invalid patch format */
if (format != SYSEX_PATCH)
return -EINVAL;
/* Patch header too short */
if (count < hdr_size)
return -EINVAL;
count -= hdr_size;
/*
* Copy the header from user space
*/
if (copy_from_user(&sysex, addr, hdr_size))
return -EFAULT;
/* Sysex record too short */
if ((unsigned)count < (unsigned)sysex.len)
sysex.len = count;
left = sysex.len;
src_offs = 0;
for (i = 0; i < left && !signal_pending(current); i++)
{
unsigned char data;
if (get_user(data,
(unsigned char __user *)(addr + hdr_size + i)))
return -EFAULT;
eox_seen = (i > 0 && data & 0x80); /* End of sysex */
if (eox_seen && data != 0xf7)
data = 0xf7;
if (i == 0)
{
if (data != 0xf0)
{
printk(KERN_WARNING "midi_synth: Sysex start missing\n");
return -EINVAL;
}
}
while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&
!signal_pending(current))
schedule();
if (!first_byte && data & 0x80)
return 0;
first_byte = 0;
}
if (!eox_seen)
midi_outc(orig_dev, 0xf7);
return 0;
}
EXPORT_SYMBOL(midi_synth_load_patch);
void midi_synth_panning(int dev, int channel, int pressure)
{
}
EXPORT_SYMBOL(midi_synth_panning);
void midi_synth_aftertouch(int dev, int channel, int pressure)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (pressure < 0 || pressure > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xd0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xd0 | (channel & 0x0f)); /*
* Channel pressure
*/
} else if (!prefix_cmd(orig_dev, pressure))
return;
midi_outc(orig_dev, pressure);
}
EXPORT_SYMBOL(midi_synth_aftertouch);
void
midi_synth_controller(int dev, int channel, int ctrl_num, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int chn, msg;
if (ctrl_num < 0 || ctrl_num > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xb0 || chn != channel)
{
if (!prefix_cmd(orig_dev, 0xb0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xb0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, ctrl_num))
return;
midi_outc(orig_dev, ctrl_num);
midi_outc(orig_dev, value & 0x7f);
}
EXPORT_SYMBOL(midi_synth_controller);
void
midi_synth_bender(int dev, int channel, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, prev_chn;
if (channel < 0 || channel > 15)
return;
if (value < 0 || value > 16383)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
prev_chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || prev_chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xe0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xe0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, value & 0x7f))
return;
midi_outc(orig_dev, value & 0x7f);
midi_outc(orig_dev, (value >> 7) & 0x7f);
}
EXPORT_SYMBOL(midi_synth_bender);
void
midi_synth_setup_voice(int dev, int voice, int channel)
{
}
EXPORT_SYMBOL(midi_synth_setup_voice);
int
midi_synth_send_sysex(int dev, unsigned char *bytes, int len)
{
int orig_dev = synth_devs[dev]->midi_dev;
int i;
for (i = 0; i < len; i++)
{
switch (bytes[i])
{
case 0xf0: /* Start sysex */
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
sysex_state[dev] = 1;
break;
case 0xf7: /* End sysex */
if (!sysex_state[dev]) /* Orphan sysex end */
return 0;
sysex_state[dev] = 0;
break;
default:
if (!sysex_state[dev])
return 0;
if (bytes[i] & 0x80) /* Error. Another message before sysex end */
{
bytes[i] = 0xf7; /* Sysex end */
sysex_state[dev] = 0;
}
}
if (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]))
{
/*
* Hardware level buffer is full. Abort the sysex message.
*/
int timeout = 0;
bytes[i] = 0xf7;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]) &&
timeout < 1000)
timeout++;
}
if (!sysex_state[dev])
return 0;
}
return 0;
}
EXPORT_SYMBOL(midi_synth_send_sysex);
| gpl-2.0 |
kukrimate/A6000_KK_Kernel | sound/oss/midi_synth.c | 13101 | 15125 | /*
* sound/oss/midi_synth.c
*
* High level midi sequencer manager for dumb MIDI interfaces.
*/
/*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*/
/*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* Andrew Veliath : fixed running status in MIDI input state machine
*/
#define USE_SEQ_MACROS
#define USE_SIMPLE_MACROS
#include "sound_config.h"
#define _MIDI_SYNTH_C_
#include "midi_synth.h"
static int midi2synth[MAX_MIDI_DEV];
static int sysex_state[MAX_MIDI_DEV] =
{0};
static unsigned char prev_out_status[MAX_MIDI_DEV];
#define STORE(cmd) \
{ \
int len; \
unsigned char obuf[8]; \
cmd; \
seq_input_event(obuf, len); \
}
#define _seqbuf obuf
#define _seqbufptr 0
#define _SEQ_ADVBUF(x) len=x
void
do_midi_msg(int synthno, unsigned char *msg, int mlen)
{
switch (msg[0] & 0xf0)
{
case 0x90:
if (msg[2] != 0)
{
STORE(SEQ_START_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
}
msg[2] = 64;
case 0x80:
STORE(SEQ_STOP_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xA0:
STORE(SEQ_KEY_PRESSURE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xB0:
STORE(SEQ_CONTROL(synthno, msg[0] & 0x0f,
msg[1], msg[2]));
break;
case 0xC0:
STORE(SEQ_SET_PATCH(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xD0:
STORE(SEQ_CHN_PRESSURE(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xE0:
STORE(SEQ_BENDER(synthno, msg[0] & 0x0f,
(msg[1] & 0x7f) | ((msg[2] & 0x7f) << 7)));
break;
default:
/* printk( "MPU: Unknown midi channel message %02x\n", msg[0]); */
;
}
}
EXPORT_SYMBOL(do_midi_msg);
static void
midi_outc(int midi_dev, int data)
{
int timeout;
for (timeout = 0; timeout < 3200; timeout++)
if (midi_devs[midi_dev]->outputc(midi_dev, (unsigned char) (data & 0xff)))
{
if (data & 0x80) /*
* Status byte
*/
prev_out_status[midi_dev] =
(unsigned char) (data & 0xff); /*
* Store for running status
*/
return; /*
* Mission complete
*/
}
/*
* Sorry! No space on buffers.
*/
printk("Midi send timed out\n");
}
static int
prefix_cmd(int midi_dev, unsigned char status)
{
if ((char *) midi_devs[midi_dev]->prefix_cmd == NULL)
return 1;
return midi_devs[midi_dev]->prefix_cmd(midi_dev, status);
}
static void
midi_synth_input(int orig_dev, unsigned char data)
{
int dev;
struct midi_input_info *inc;
static unsigned char len_tab[] = /* # of data bytes following a status
*/
{
2, /* 8x */
2, /* 9x */
2, /* Ax */
2, /* Bx */
1, /* Cx */
1, /* Dx */
2, /* Ex */
0 /* Fx */
};
if (orig_dev < 0 || orig_dev > num_midis || midi_devs[orig_dev] == NULL)
return;
if (data == 0xfe) /* Ignore active sensing */
return;
dev = midi2synth[orig_dev];
inc = &midi_devs[orig_dev]->in_info;
switch (inc->m_state)
{
case MST_INIT:
if (data & 0x80) /* MIDI status byte */
{
if ((data & 0xf0) == 0xf0) /* Common message */
{
switch (data)
{
case 0xf0: /* Sysex */
inc->m_state = MST_SYSEX;
break; /* Sysex */
case 0xf1: /* MTC quarter frame */
case 0xf3: /* Song select */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 1;
inc->m_buf[0] = data;
break;
case 0xf2: /* Song position pointer */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 2;
inc->m_buf[0] = data;
break;
default:
inc->m_buf[0] = data;
inc->m_ptr = 1;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
inc->m_left = 0;
}
} else
{
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = len_tab[(data >> 4) - 8];
inc->m_buf[0] = inc->m_prev_status = data;
}
} else if (inc->m_prev_status & 0x80) {
/* Data byte (use running status) */
inc->m_ptr = 2;
inc->m_buf[1] = data;
inc->m_buf[0] = inc->m_prev_status;
inc->m_left = len_tab[(inc->m_buf[0] >> 4) - 8] - 1;
if (inc->m_left > 0)
inc->m_state = MST_DATA; /* Not done yet */
else {
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
}
break; /* MST_INIT */
case MST_DATA:
inc->m_buf[inc->m_ptr++] = data;
if (--inc->m_left <= 0)
{
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
break; /* MST_DATA */
case MST_SYSEX:
if (data == 0xf7) /* Sysex end */
{
inc->m_state = MST_INIT;
inc->m_left = 0;
inc->m_ptr = 0;
}
break; /* MST_SYSEX */
default:
printk("MIDI%d: Unexpected state %d (%02x)\n", orig_dev, inc->m_state, (int) data);
inc->m_state = MST_INIT;
}
}
static void
leave_sysex(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
int timeout = 0;
if (!sysex_state[dev])
return;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, 0xf7) &&
timeout < 1000)
timeout++;
sysex_state[dev] = 0;
}
static void
midi_synth_output(int dev)
{
/*
* Currently NOP
*/
}
int midi_synth_ioctl(int dev, unsigned int cmd, void __user *arg)
{
/*
* int orig_dev = synth_devs[dev]->midi_dev;
*/
switch (cmd) {
case SNDCTL_SYNTH_INFO:
if (__copy_to_user(arg, synth_devs[dev]->info, sizeof(struct synth_info)))
return -EFAULT;
return 0;
case SNDCTL_SYNTH_MEMAVL:
return 0x7fffffff;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(midi_synth_ioctl);
int
midi_synth_kill_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && ((msg == 0x90 && velocity == 64) || msg == 0x80))
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
if (msg == 0x90) /*
* Running status = Note on
*/
midi_outc(orig_dev, 0); /*
* Note on with velocity 0 == note
* off
*/
else
midi_outc(orig_dev, velocity);
} else
{
if (velocity == 64)
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, 0); /*
* Zero G
*/
} else
{
if (!prefix_cmd(orig_dev, 0x80 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x80 | (channel & 0x0f)); /*
* Note off
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
}
return 0;
}
EXPORT_SYMBOL(midi_synth_kill_note);
int
midi_synth_set_instr(int dev, int channel, int instr_no)
{
int orig_dev = synth_devs[dev]->midi_dev;
if (instr_no < 0 || instr_no > 127)
instr_no = 0;
if (channel < 0 || channel > 15)
return 0;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xc0 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0xc0 | (channel & 0x0f)); /*
* Program change
*/
midi_outc(orig_dev, instr_no);
return 0;
}
EXPORT_SYMBOL(midi_synth_set_instr);
int
midi_synth_start_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && msg == 0x90)
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
} else
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
return 0;
}
EXPORT_SYMBOL(midi_synth_start_note);
void
midi_synth_reset(int dev)
{
leave_sysex(dev);
}
EXPORT_SYMBOL(midi_synth_reset);
int
midi_synth_open(int dev, int mode)
{
int orig_dev = synth_devs[dev]->midi_dev;
int err;
struct midi_input_info *inc;
if (orig_dev < 0 || orig_dev >= num_midis || midi_devs[orig_dev] == NULL)
return -ENXIO;
midi2synth[orig_dev] = dev;
sysex_state[dev] = 0;
prev_out_status[orig_dev] = 0;
if ((err = midi_devs[orig_dev]->open(orig_dev, mode,
midi_synth_input, midi_synth_output)) < 0)
return err;
inc = &midi_devs[orig_dev]->in_info;
/* save_flags(flags);
cli();
don't know against what irqhandler to protect*/
inc->m_busy = 0;
inc->m_state = MST_INIT;
inc->m_ptr = 0;
inc->m_left = 0;
inc->m_prev_status = 0x00;
/* restore_flags(flags); */
return 1;
}
EXPORT_SYMBOL(midi_synth_open);
void
midi_synth_close(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
leave_sysex(dev);
/*
* Shut up the synths by sending just single active sensing message.
*/
midi_devs[orig_dev]->outputc(orig_dev, 0xfe);
midi_devs[orig_dev]->close(orig_dev);
}
EXPORT_SYMBOL(midi_synth_close);
void
midi_synth_hw_control(int dev, unsigned char *event)
{
}
EXPORT_SYMBOL(midi_synth_hw_control);
int
midi_synth_load_patch(int dev, int format, const char __user *addr,
int count, int pmgr_flag)
{
int orig_dev = synth_devs[dev]->midi_dev;
struct sysex_info sysex;
int i;
unsigned long left, src_offs, eox_seen = 0;
int first_byte = 1;
int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
/* Invalid patch format */
if (format != SYSEX_PATCH)
return -EINVAL;
/* Patch header too short */
if (count < hdr_size)
return -EINVAL;
count -= hdr_size;
/*
* Copy the header from user space
*/
if (copy_from_user(&sysex, addr, hdr_size))
return -EFAULT;
/* Sysex record too short */
if ((unsigned)count < (unsigned)sysex.len)
sysex.len = count;
left = sysex.len;
src_offs = 0;
for (i = 0; i < left && !signal_pending(current); i++)
{
unsigned char data;
if (get_user(data,
(unsigned char __user *)(addr + hdr_size + i)))
return -EFAULT;
eox_seen = (i > 0 && data & 0x80); /* End of sysex */
if (eox_seen && data != 0xf7)
data = 0xf7;
if (i == 0)
{
if (data != 0xf0)
{
printk(KERN_WARNING "midi_synth: Sysex start missing\n");
return -EINVAL;
}
}
while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&
!signal_pending(current))
schedule();
if (!first_byte && data & 0x80)
return 0;
first_byte = 0;
}
if (!eox_seen)
midi_outc(orig_dev, 0xf7);
return 0;
}
EXPORT_SYMBOL(midi_synth_load_patch);
void midi_synth_panning(int dev, int channel, int pressure)
{
}
EXPORT_SYMBOL(midi_synth_panning);
void midi_synth_aftertouch(int dev, int channel, int pressure)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (pressure < 0 || pressure > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xd0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xd0 | (channel & 0x0f)); /*
* Channel pressure
*/
} else if (!prefix_cmd(orig_dev, pressure))
return;
midi_outc(orig_dev, pressure);
}
EXPORT_SYMBOL(midi_synth_aftertouch);
void
midi_synth_controller(int dev, int channel, int ctrl_num, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int chn, msg;
if (ctrl_num < 0 || ctrl_num > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xb0 || chn != channel)
{
if (!prefix_cmd(orig_dev, 0xb0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xb0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, ctrl_num))
return;
midi_outc(orig_dev, ctrl_num);
midi_outc(orig_dev, value & 0x7f);
}
EXPORT_SYMBOL(midi_synth_controller);
void
midi_synth_bender(int dev, int channel, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, prev_chn;
if (channel < 0 || channel > 15)
return;
if (value < 0 || value > 16383)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
prev_chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || prev_chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xe0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xe0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, value & 0x7f))
return;
midi_outc(orig_dev, value & 0x7f);
midi_outc(orig_dev, (value >> 7) & 0x7f);
}
EXPORT_SYMBOL(midi_synth_bender);
void
midi_synth_setup_voice(int dev, int voice, int channel)
{
}
EXPORT_SYMBOL(midi_synth_setup_voice);
int
midi_synth_send_sysex(int dev, unsigned char *bytes, int len)
{
int orig_dev = synth_devs[dev]->midi_dev;
int i;
for (i = 0; i < len; i++)
{
switch (bytes[i])
{
case 0xf0: /* Start sysex */
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
sysex_state[dev] = 1;
break;
case 0xf7: /* End sysex */
if (!sysex_state[dev]) /* Orphan sysex end */
return 0;
sysex_state[dev] = 0;
break;
default:
if (!sysex_state[dev])
return 0;
if (bytes[i] & 0x80) /* Error. Another message before sysex end */
{
bytes[i] = 0xf7; /* Sysex end */
sysex_state[dev] = 0;
}
}
if (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]))
{
/*
* Hardware level buffer is full. Abort the sysex message.
*/
int timeout = 0;
bytes[i] = 0xf7;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]) &&
timeout < 1000)
timeout++;
}
if (!sysex_state[dev])
return 0;
}
return 0;
}
EXPORT_SYMBOL(midi_synth_send_sysex);
| gpl-2.0 |
eugene373/ApexqJB | sound/oss/midi_synth.c | 13101 | 15125 | /*
* sound/oss/midi_synth.c
*
* High level midi sequencer manager for dumb MIDI interfaces.
*/
/*
* Copyright (C) by Hannu Savolainen 1993-1997
*
* OSS/Free for Linux is distributed under the GNU GENERAL PUBLIC LICENSE (GPL)
* Version 2 (June 1991). See the "COPYING" file distributed with this software
* for more info.
*/
/*
* Thomas Sailer : ioctl code reworked (vmalloc/vfree removed)
* Andrew Veliath : fixed running status in MIDI input state machine
*/
#define USE_SEQ_MACROS
#define USE_SIMPLE_MACROS
#include "sound_config.h"
#define _MIDI_SYNTH_C_
#include "midi_synth.h"
static int midi2synth[MAX_MIDI_DEV];
static int sysex_state[MAX_MIDI_DEV] =
{0};
static unsigned char prev_out_status[MAX_MIDI_DEV];
#define STORE(cmd) \
{ \
int len; \
unsigned char obuf[8]; \
cmd; \
seq_input_event(obuf, len); \
}
#define _seqbuf obuf
#define _seqbufptr 0
#define _SEQ_ADVBUF(x) len=x
void
do_midi_msg(int synthno, unsigned char *msg, int mlen)
{
switch (msg[0] & 0xf0)
{
case 0x90:
if (msg[2] != 0)
{
STORE(SEQ_START_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
}
msg[2] = 64;
case 0x80:
STORE(SEQ_STOP_NOTE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xA0:
STORE(SEQ_KEY_PRESSURE(synthno, msg[0] & 0x0f, msg[1], msg[2]));
break;
case 0xB0:
STORE(SEQ_CONTROL(synthno, msg[0] & 0x0f,
msg[1], msg[2]));
break;
case 0xC0:
STORE(SEQ_SET_PATCH(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xD0:
STORE(SEQ_CHN_PRESSURE(synthno, msg[0] & 0x0f, msg[1]));
break;
case 0xE0:
STORE(SEQ_BENDER(synthno, msg[0] & 0x0f,
(msg[1] & 0x7f) | ((msg[2] & 0x7f) << 7)));
break;
default:
/* printk( "MPU: Unknown midi channel message %02x\n", msg[0]); */
;
}
}
EXPORT_SYMBOL(do_midi_msg);
static void
midi_outc(int midi_dev, int data)
{
int timeout;
for (timeout = 0; timeout < 3200; timeout++)
if (midi_devs[midi_dev]->outputc(midi_dev, (unsigned char) (data & 0xff)))
{
if (data & 0x80) /*
* Status byte
*/
prev_out_status[midi_dev] =
(unsigned char) (data & 0xff); /*
* Store for running status
*/
return; /*
* Mission complete
*/
}
/*
* Sorry! No space on buffers.
*/
printk("Midi send timed out\n");
}
static int
prefix_cmd(int midi_dev, unsigned char status)
{
if ((char *) midi_devs[midi_dev]->prefix_cmd == NULL)
return 1;
return midi_devs[midi_dev]->prefix_cmd(midi_dev, status);
}
static void
midi_synth_input(int orig_dev, unsigned char data)
{
int dev;
struct midi_input_info *inc;
static unsigned char len_tab[] = /* # of data bytes following a status
*/
{
2, /* 8x */
2, /* 9x */
2, /* Ax */
2, /* Bx */
1, /* Cx */
1, /* Dx */
2, /* Ex */
0 /* Fx */
};
if (orig_dev < 0 || orig_dev > num_midis || midi_devs[orig_dev] == NULL)
return;
if (data == 0xfe) /* Ignore active sensing */
return;
dev = midi2synth[orig_dev];
inc = &midi_devs[orig_dev]->in_info;
switch (inc->m_state)
{
case MST_INIT:
if (data & 0x80) /* MIDI status byte */
{
if ((data & 0xf0) == 0xf0) /* Common message */
{
switch (data)
{
case 0xf0: /* Sysex */
inc->m_state = MST_SYSEX;
break; /* Sysex */
case 0xf1: /* MTC quarter frame */
case 0xf3: /* Song select */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 1;
inc->m_buf[0] = data;
break;
case 0xf2: /* Song position pointer */
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = 2;
inc->m_buf[0] = data;
break;
default:
inc->m_buf[0] = data;
inc->m_ptr = 1;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
inc->m_left = 0;
}
} else
{
inc->m_state = MST_DATA;
inc->m_ptr = 1;
inc->m_left = len_tab[(data >> 4) - 8];
inc->m_buf[0] = inc->m_prev_status = data;
}
} else if (inc->m_prev_status & 0x80) {
/* Data byte (use running status) */
inc->m_ptr = 2;
inc->m_buf[1] = data;
inc->m_buf[0] = inc->m_prev_status;
inc->m_left = len_tab[(inc->m_buf[0] >> 4) - 8] - 1;
if (inc->m_left > 0)
inc->m_state = MST_DATA; /* Not done yet */
else {
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
}
break; /* MST_INIT */
case MST_DATA:
inc->m_buf[inc->m_ptr++] = data;
if (--inc->m_left <= 0)
{
inc->m_state = MST_INIT;
do_midi_msg(dev, inc->m_buf, inc->m_ptr);
inc->m_ptr = 0;
}
break; /* MST_DATA */
case MST_SYSEX:
if (data == 0xf7) /* Sysex end */
{
inc->m_state = MST_INIT;
inc->m_left = 0;
inc->m_ptr = 0;
}
break; /* MST_SYSEX */
default:
printk("MIDI%d: Unexpected state %d (%02x)\n", orig_dev, inc->m_state, (int) data);
inc->m_state = MST_INIT;
}
}
static void
leave_sysex(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
int timeout = 0;
if (!sysex_state[dev])
return;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, 0xf7) &&
timeout < 1000)
timeout++;
sysex_state[dev] = 0;
}
static void
midi_synth_output(int dev)
{
/*
* Currently NOP
*/
}
int midi_synth_ioctl(int dev, unsigned int cmd, void __user *arg)
{
/*
* int orig_dev = synth_devs[dev]->midi_dev;
*/
switch (cmd) {
case SNDCTL_SYNTH_INFO:
if (__copy_to_user(arg, synth_devs[dev]->info, sizeof(struct synth_info)))
return -EFAULT;
return 0;
case SNDCTL_SYNTH_MEMAVL:
return 0x7fffffff;
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(midi_synth_ioctl);
int
midi_synth_kill_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && ((msg == 0x90 && velocity == 64) || msg == 0x80))
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
if (msg == 0x90) /*
* Running status = Note on
*/
midi_outc(orig_dev, 0); /*
* Note on with velocity 0 == note
* off
*/
else
midi_outc(orig_dev, velocity);
} else
{
if (velocity == 64)
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, 0); /*
* Zero G
*/
} else
{
if (!prefix_cmd(orig_dev, 0x80 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x80 | (channel & 0x0f)); /*
* Note off
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
}
return 0;
}
EXPORT_SYMBOL(midi_synth_kill_note);
int
midi_synth_set_instr(int dev, int channel, int instr_no)
{
int orig_dev = synth_devs[dev]->midi_dev;
if (instr_no < 0 || instr_no > 127)
instr_no = 0;
if (channel < 0 || channel > 15)
return 0;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xc0 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0xc0 | (channel & 0x0f)); /*
* Program change
*/
midi_outc(orig_dev, instr_no);
return 0;
}
EXPORT_SYMBOL(midi_synth_set_instr);
int
midi_synth_start_note(int dev, int channel, int note, int velocity)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (note < 0 || note > 127)
return 0;
if (channel < 0 || channel > 15)
return 0;
if (velocity < 0)
velocity = 0;
if (velocity > 127)
velocity = 127;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (chn == channel && msg == 0x90)
{ /*
* Use running status
*/
if (!prefix_cmd(orig_dev, note))
return 0;
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
} else
{
if (!prefix_cmd(orig_dev, 0x90 | (channel & 0x0f)))
return 0;
midi_outc(orig_dev, 0x90 | (channel & 0x0f)); /*
* Note on
*/
midi_outc(orig_dev, note);
midi_outc(orig_dev, velocity);
}
return 0;
}
EXPORT_SYMBOL(midi_synth_start_note);
void
midi_synth_reset(int dev)
{
leave_sysex(dev);
}
EXPORT_SYMBOL(midi_synth_reset);
int
midi_synth_open(int dev, int mode)
{
int orig_dev = synth_devs[dev]->midi_dev;
int err;
struct midi_input_info *inc;
if (orig_dev < 0 || orig_dev >= num_midis || midi_devs[orig_dev] == NULL)
return -ENXIO;
midi2synth[orig_dev] = dev;
sysex_state[dev] = 0;
prev_out_status[orig_dev] = 0;
if ((err = midi_devs[orig_dev]->open(orig_dev, mode,
midi_synth_input, midi_synth_output)) < 0)
return err;
inc = &midi_devs[orig_dev]->in_info;
/* save_flags(flags);
cli();
don't know against what irqhandler to protect*/
inc->m_busy = 0;
inc->m_state = MST_INIT;
inc->m_ptr = 0;
inc->m_left = 0;
inc->m_prev_status = 0x00;
/* restore_flags(flags); */
return 1;
}
EXPORT_SYMBOL(midi_synth_open);
void
midi_synth_close(int dev)
{
int orig_dev = synth_devs[dev]->midi_dev;
leave_sysex(dev);
/*
* Shut up the synths by sending just single active sensing message.
*/
midi_devs[orig_dev]->outputc(orig_dev, 0xfe);
midi_devs[orig_dev]->close(orig_dev);
}
EXPORT_SYMBOL(midi_synth_close);
void
midi_synth_hw_control(int dev, unsigned char *event)
{
}
EXPORT_SYMBOL(midi_synth_hw_control);
int
midi_synth_load_patch(int dev, int format, const char __user *addr,
int count, int pmgr_flag)
{
int orig_dev = synth_devs[dev]->midi_dev;
struct sysex_info sysex;
int i;
unsigned long left, src_offs, eox_seen = 0;
int first_byte = 1;
int hdr_size = (unsigned long) &sysex.data[0] - (unsigned long) &sysex;
leave_sysex(dev);
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
/* Invalid patch format */
if (format != SYSEX_PATCH)
return -EINVAL;
/* Patch header too short */
if (count < hdr_size)
return -EINVAL;
count -= hdr_size;
/*
* Copy the header from user space
*/
if (copy_from_user(&sysex, addr, hdr_size))
return -EFAULT;
/* Sysex record too short */
if ((unsigned)count < (unsigned)sysex.len)
sysex.len = count;
left = sysex.len;
src_offs = 0;
for (i = 0; i < left && !signal_pending(current); i++)
{
unsigned char data;
if (get_user(data,
(unsigned char __user *)(addr + hdr_size + i)))
return -EFAULT;
eox_seen = (i > 0 && data & 0x80); /* End of sysex */
if (eox_seen && data != 0xf7)
data = 0xf7;
if (i == 0)
{
if (data != 0xf0)
{
printk(KERN_WARNING "midi_synth: Sysex start missing\n");
return -EINVAL;
}
}
while (!midi_devs[orig_dev]->outputc(orig_dev, (unsigned char) (data & 0xff)) &&
!signal_pending(current))
schedule();
if (!first_byte && data & 0x80)
return 0;
first_byte = 0;
}
if (!eox_seen)
midi_outc(orig_dev, 0xf7);
return 0;
}
EXPORT_SYMBOL(midi_synth_load_patch);
void midi_synth_panning(int dev, int channel, int pressure)
{
}
EXPORT_SYMBOL(midi_synth_panning);
void midi_synth_aftertouch(int dev, int channel, int pressure)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, chn;
if (pressure < 0 || pressure > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xd0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xd0 | (channel & 0x0f)); /*
* Channel pressure
*/
} else if (!prefix_cmd(orig_dev, pressure))
return;
midi_outc(orig_dev, pressure);
}
EXPORT_SYMBOL(midi_synth_aftertouch);
void
midi_synth_controller(int dev, int channel, int ctrl_num, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int chn, msg;
if (ctrl_num < 0 || ctrl_num > 127)
return;
if (channel < 0 || channel > 15)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xb0 || chn != channel)
{
if (!prefix_cmd(orig_dev, 0xb0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xb0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, ctrl_num))
return;
midi_outc(orig_dev, ctrl_num);
midi_outc(orig_dev, value & 0x7f);
}
EXPORT_SYMBOL(midi_synth_controller);
void
midi_synth_bender(int dev, int channel, int value)
{
int orig_dev = synth_devs[dev]->midi_dev;
int msg, prev_chn;
if (channel < 0 || channel > 15)
return;
if (value < 0 || value > 16383)
return;
leave_sysex(dev);
msg = prev_out_status[orig_dev] & 0xf0;
prev_chn = prev_out_status[orig_dev] & 0x0f;
if (msg != 0xd0 || prev_chn != channel) /*
* Test for running status
*/
{
if (!prefix_cmd(orig_dev, 0xe0 | (channel & 0x0f)))
return;
midi_outc(orig_dev, 0xe0 | (channel & 0x0f));
} else if (!prefix_cmd(orig_dev, value & 0x7f))
return;
midi_outc(orig_dev, value & 0x7f);
midi_outc(orig_dev, (value >> 7) & 0x7f);
}
EXPORT_SYMBOL(midi_synth_bender);
void
midi_synth_setup_voice(int dev, int voice, int channel)
{
}
EXPORT_SYMBOL(midi_synth_setup_voice);
int
midi_synth_send_sysex(int dev, unsigned char *bytes, int len)
{
int orig_dev = synth_devs[dev]->midi_dev;
int i;
for (i = 0; i < len; i++)
{
switch (bytes[i])
{
case 0xf0: /* Start sysex */
if (!prefix_cmd(orig_dev, 0xf0))
return 0;
sysex_state[dev] = 1;
break;
case 0xf7: /* End sysex */
if (!sysex_state[dev]) /* Orphan sysex end */
return 0;
sysex_state[dev] = 0;
break;
default:
if (!sysex_state[dev])
return 0;
if (bytes[i] & 0x80) /* Error. Another message before sysex end */
{
bytes[i] = 0xf7; /* Sysex end */
sysex_state[dev] = 0;
}
}
if (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]))
{
/*
* Hardware level buffer is full. Abort the sysex message.
*/
int timeout = 0;
bytes[i] = 0xf7;
sysex_state[dev] = 0;
while (!midi_devs[orig_dev]->outputc(orig_dev, bytes[i]) &&
timeout < 1000)
timeout++;
}
if (!sysex_state[dev])
return 0;
}
return 0;
}
EXPORT_SYMBOL(midi_synth_send_sysex);
| gpl-2.0 |
stulluk/chipbox-uboot | board/MAI/bios_emulator/scitech/src/biosemu/bios.c | 46 | 9370 | /****************************************************************************
*
* BIOS emulator and interface
* to Realmode X86 Emulator Library
*
* Copyright (C) 1996-1999 SciTech Software, Inc.
*
* ========================================================================
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of the authors not be used
* in advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. The authors makes no
* representations about the suitability of this software for any purpose.
* It is provided "as is" without express or implied warranty.
*
* THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE AUTHORS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
* USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* ========================================================================
*
* Language: ANSI C
* Environment: Any
* Developer: Kendall Bennett
*
* Description: Module implementing the BIOS specific functions.
*
****************************************************************************/
#include "biosemui.h"
/*----------------------------- Implementation ----------------------------*/
/****************************************************************************
PARAMETERS:
intno - Interrupt number being serviced
REMARKS:
Handler for undefined interrupts.
****************************************************************************/
static void X86API undefined_intr(
int intno)
{
if (BE_rdw(intno * 4 + 2) == BIOS_SEG)
printk("biosEmu: undefined interrupt %xh called!\n",intno);
else
X86EMU_prepareForInt(intno);
}
/****************************************************************************
PARAMETERS:
intno - Interrupt number being serviced
REMARKS:
This function handles the default system BIOS Int 10h (the default is stored
in the Int 42h vector by the system BIOS at bootup). We only need to handle
a small number of special functions used by the BIOS during POST time.
****************************************************************************/
static void X86API int42(
int intno)
{
if (M.x86.R_AH == 0x12 && M.x86.R_BL == 0x32) {
if (M.x86.R_AL == 0) {
/* Enable CPU accesses to video memory */
PM_outpb(0x3c2, PM_inpb(0x3cc) | (u8)0x02);
return;
}
else if (M.x86.R_AL == 1) {
/* Disable CPU accesses to video memory */
PM_outpb(0x3c2, PM_inpb(0x3cc) & (u8)~0x02);
return;
}
#ifdef DEBUG
else {
printk("biosEmu/bios.int42: unknown function AH=0x12, BL=0x32, AL=%#02x\n",M.x86.R_AL);
}
#endif
}
#ifdef DEBUG
else {
printk("biosEmu/bios.int42: unknown function AH=%#02x, AL=%#02x, BL=%#02x\n",M.x86.R_AH, M.x86.R_AL, M.x86.R_BL);
}
#endif
}
/****************************************************************************
PARAMETERS:
intno - Interrupt number being serviced
REMARKS:
This function handles the default system BIOS Int 10h. If the POST code
has not yet re-vectored the Int 10h BIOS interrupt vector, we handle this
by simply calling the int42 interrupt handler above. Very early in the
BIOS POST process, the vector gets replaced and we simply let the real
mode interrupt handler process the interrupt.
****************************************************************************/
static void X86API int10(
int intno)
{
if (BE_rdw(intno * 4 + 2) == BIOS_SEG)
int42(intno);
else
X86EMU_prepareForInt(intno);
}
/* Result codes returned by the PCI BIOS */
#define SUCCESSFUL 0x00
#define FUNC_NOT_SUPPORT 0x81
#define BAD_VENDOR_ID 0x83
#define DEVICE_NOT_FOUND 0x86
#define BAD_REGISTER_NUMBER 0x87
#define SET_FAILED 0x88
#define BUFFER_TOO_SMALL 0x89
/****************************************************************************
PARAMETERS:
intno - Interrupt number being serviced
REMARKS:
This function handles the default Int 1Ah interrupt handler for the real
mode code, which provides support for the PCI BIOS functions. Since we only
want to allow the real mode BIOS code *only* see the PCI config space for
its own device, we only return information for the specific PCI config
space that we have passed in to the init function. This solves problems
when using the BIOS to warm boot a secondary adapter when there is an
identical adapter before it on the bus (some BIOS'es get confused in this
case).
****************************************************************************/
static void X86API int1A(
unused)
{
u16 pciSlot;
/* Fail if no PCI device information has been registered */
if (!_BE_env.vgaInfo.pciInfo)
return;
pciSlot = (u16)(_BE_env.vgaInfo.pciInfo->slot.i >> 8);
switch (M.x86.R_AX) {
case 0xB101: /* PCI bios present? */
M.x86.R_AL = 0x00; /* no config space/special cycle generation support */
M.x86.R_EDX = 0x20494350; /* " ICP" */
M.x86.R_BX = 0x0210; /* Version 2.10 */
M.x86.R_CL = 0; /* Max bus number in system */
CLEAR_FLAG(F_CF);
break;
case 0xB102: /* Find PCI device */
M.x86.R_AH = DEVICE_NOT_FOUND;
if (M.x86.R_DX == _BE_env.vgaInfo.pciInfo->VendorID &&
M.x86.R_CX == _BE_env.vgaInfo.pciInfo->DeviceID &&
M.x86.R_SI == 0) {
M.x86.R_AH = SUCCESSFUL;
M.x86.R_BX = pciSlot;
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB103: /* Find PCI class code */
M.x86.R_AH = DEVICE_NOT_FOUND;
if (M.x86.R_CL == _BE_env.vgaInfo.pciInfo->Interface &&
M.x86.R_CH == _BE_env.vgaInfo.pciInfo->SubClass &&
(u8)(M.x86.R_ECX >> 16) == _BE_env.vgaInfo.pciInfo->BaseClass) {
M.x86.R_AH = SUCCESSFUL;
M.x86.R_BX = pciSlot;
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB108: /* Read configuration byte */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
M.x86.R_CL = (u8)PCI_accessReg(M.x86.R_DI,0,PCI_READ_BYTE,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB109: /* Read configuration word */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
M.x86.R_CX = (u16)PCI_accessReg(M.x86.R_DI,0,PCI_READ_WORD,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB10A: /* Read configuration dword */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
M.x86.R_ECX = (u32)PCI_accessReg(M.x86.R_DI,0,PCI_READ_DWORD,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB10B: /* Write configuration byte */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
PCI_accessReg(M.x86.R_DI,M.x86.R_CL,PCI_WRITE_BYTE,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB10C: /* Write configuration word */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
PCI_accessReg(M.x86.R_DI,M.x86.R_CX,PCI_WRITE_WORD,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
case 0xB10D: /* Write configuration dword */
M.x86.R_AH = BAD_REGISTER_NUMBER;
if (M.x86.R_BX == pciSlot) {
M.x86.R_AH = SUCCESSFUL;
PCI_accessReg(M.x86.R_DI,M.x86.R_ECX,PCI_WRITE_DWORD,_BE_env.vgaInfo.pciInfo);
}
CONDITIONAL_SET_FLAG((M.x86.R_AH != SUCCESSFUL), F_CF);
break;
default:
printk("biosEmu/bios.int1a: unknown function AX=%#04x\n", M.x86.R_AX);
}
}
/****************************************************************************
REMARKS:
This function initialises the BIOS emulation functions for the specific
PCI display device. We insulate the real mode BIOS from any other devices
on the bus, so that it will work correctly thinking that it is the only
device present on the bus (ie: avoiding any adapters present in from of
the device we are trying to control).
****************************************************************************/
void _BE_bios_init(
u32 *intrTab)
{
int i;
X86EMU_intrFuncs bios_intr_tab[256];
for (i = 0; i < 256; ++i) {
intrTab[i] = BIOS_SEG << 16;
bios_intr_tab[i] = undefined_intr;
}
bios_intr_tab[0x10] = int10;
bios_intr_tab[0x1A] = int1A;
bios_intr_tab[0x42] = int42;
X86EMU_setupIntrFuncs(bios_intr_tab);
}
| gpl-2.0 |
FengISU/DEM_project | lib/atc/PhysicsModel.cpp | 46 | 18076 | #include "PhysicsModel.h"
#include "WeakEquation.h"
#include "WeakEquationDiffusion.h"
#include "WeakEquationChargeDiffusion.h"
#include "WeakEquationMassDiffusion.h"
#include "WeakEquationElectronContinuity.h"
#include "WeakEquationElectronMomentum.h"
#include "WeakEquationElectronTemperature.h"
#include "WeakEquationMomentum.h"
#include "WeakEquationPhononTemperature.h"
#include "WeakEquationPoisson.h"
#include "WeakEquationSchrodinger.h"
#include "ATC_Coupling.h" // for tangent operator
#include <iostream>
#include <fstream>
#include <sstream>
#include <utility>
using ATC_Utility::command_line;
using ATC_Utility::to_lower;
using std::fstream;
using std::stringstream;
using std::pair;
using std::string;
using std::map;
using std::set;
using std::vector;
namespace ATC {
//---------------------------------------------------------------------
// PhysicsModel
//---------------------------------------------------------------------
PhysicsModel::PhysicsModel(string fileName)
{
parse_material_file(fileName);
}
PhysicsModel::~PhysicsModel()
{
{
vector< Material* >::iterator iter;
for (iter = materials_.begin(); iter != materials_.end(); iter++) {
Material * mat = *iter;
if (mat) delete mat;
}
}
{
map<FieldName, WeakEquation* >::iterator iter;
for (iter = weakEqns_.begin(); iter != weakEqns_.end(); iter++) {
WeakEquation * weakEq = iter->second;
if (weakEq) delete weakEq;
}
}
}
void PhysicsModel::parse_material_file(string fileName)
{
vector< Material* >::iterator iter;
for (iter = materials_.begin(); iter != materials_.end(); iter++) {
Material * mat = *iter;
if (mat) delete mat;
}
LammpsInterface::UnitsType lammpsUnits = ATC::LammpsInterface::instance()->units_style();
fstream fileId(fileName.c_str(), std::ios::in);
if (!fileId.is_open()) throw ATC_Error("cannot open material file");
vector<string> line;
int index = 0;
while(fileId.good()) {
command_line(fileId, line);
if (line.size() == 0 || line[0] == "#") continue;
if (line[0] == "material") {
string tag = line[1];
Material * mat = new Material(tag,fileId);
materials_.push_back(mat);
materialNameToIndexMap_[tag] = index++;
if (line.size() > 2) {
string units = line[2];
stringstream ss;
ss << "WARNING: material units " << units << " do not match lammps";
if (units == "SI") {
if (lammpsUnits != LammpsInterface::SI)
ATC::LammpsInterface::instance()->print_msg_once(ss.str());
}
else if (units == "real") {
if (lammpsUnits != LammpsInterface::REAL )
ATC::LammpsInterface::instance()->print_msg_once(ss.str());
}
else if (units == "metal") {
if (lammpsUnits != LammpsInterface::METAL )
ATC::LammpsInterface::instance()->print_msg_once(ss.str());
}
else {
throw ATC_Error("unknown units in material file");
}
}
else {
throw ATC_Error("units need to be specfied in material file");
}
}
}
if (int(materials_.size()) == 0) {
throw ATC_Error("No materials were defined"); }
stringstream ss;
ss << int(materials_.size()) << " materials defined from " << fileName;
ATC::LammpsInterface::instance()->print_msg_once(ss.str());
fileId.close();
}
void PhysicsModel::initialize(void)
{
// initialize materials
vector< Material* >::const_iterator iter;
for (iter = materials_.begin(); iter != materials_.end(); iter++) {
Material * mat = *iter;
mat->initialize();
}
// set up null (weakEq, material) registry
null_.reset(ATC::NUM_FIELDS, materials_.size());
null_ = false;
// initialize weak equations
map<FieldName, WeakEquation * >::const_iterator weak;
for (weak = weakEqns_.begin(); weak!=weakEqns_.end(); weak++) {
FieldName fieldName = weak->first;
WeakEquation * weakEq = weak->second;
set<string> needs= weakEq->needs_material_functions();
vector< Material* >::iterator iter;
for (iter = materials_.begin(); iter != materials_.end(); iter++) {
Material * mat = *iter;
if (! (mat->check_registry(needs)) ) {
string tag = mat->label();
int matId = materialNameToIndexMap_[tag];
null_(fieldName,matId) = true;
stringstream ss;
ss << "WARNING: physics model: [" << type_ << "], material: [" << tag
<< "] does not provide all interfaces for <"
<< field_to_string(fieldName)
<< "> physics and will be treated as null ";
ATC::LammpsInterface::instance()->print_msg_once(ss.str());
// if (noNull_)
//throw ATC_Error("material does not provide all interfaces for physics");
}
}
}
}
int PhysicsModel::material_index(const string & name) const
{
string tag = name;
to_lower(tag); // this is an artifact of StringManip parsing
map<string,int>::const_iterator iter;
iter = materialNameToIndexMap_.find(tag);
if (iter == materialNameToIndexMap_.end()) {
throw ATC_Error("No material named "+name+" found");
}
int index = iter->second;
return index;
}
bool PhysicsModel::parameter_value(const string& name, double& value,
const int imat) const
{
// search owned parameters
value = 0.0;
map<string,double>::const_iterator it = parameterValues_.find(name);
if (it != parameterValues_.end()) {
value = it->second;
return true;
}
// interogate material models
bool found = materials_[imat]->parameter(name,value);
return found;
}
void PhysicsModel::num_fields(map<FieldName,int> & fieldSizes,
Array2D<bool> & rhsMask) const
{
map<FieldName, WeakEquation * >::const_iterator itr;
for (itr = weakEqns_.begin(); itr!=weakEqns_.end(); itr++) {
FieldName field = itr->first;
WeakEquation * weakEq = itr->second;
int size = weakEq->field_size();
fieldSizes[field] = size;
rhsMask(field,FLUX) = weakEq->has_B_integrand();
rhsMask(field,SOURCE) = weakEq->has_N_integrand();
}
}
//---------------------------------------------------------------------
// PhysicsModelThermal
//---------------------------------------------------------------------
PhysicsModelThermal::PhysicsModelThermal(string filename):
PhysicsModel(filename)
{
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperature();
}
//---------------------------------------------------------------------
// PhysicsModelElastic
//---------------------------------------------------------------------
PhysicsModelElastic::PhysicsModelElastic(string filename):
PhysicsModel(filename)
{
weakEqns_[VELOCITY] = new WeakEquationMomentum();
}
//---------------------------------------------------------------------
// PhysicsModelThermoElastic
//---------------------------------------------------------------------
PhysicsModelThermoElastic::PhysicsModelThermoElastic(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "thermo-elastic";
weakEqns_[VELOCITY] = new WeakEquationMomentum();
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperature();
}
//---------------------------------------------------------------------
// PhysicsModelShear
//---------------------------------------------------------------------
PhysicsModelShear::PhysicsModelShear(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "shear";
weakEqns_[VELOCITY] = new WeakEquationMomentumDiffusion();
}
//---------------------------------------------------------------------
// PhysicsModelThermoShear
//---------------------------------------------------------------------
PhysicsModelThermoShear::PhysicsModelThermoShear(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "thermo-shear";
weakEqns_[VELOCITY] = new WeakEquationMomentumDiffusion();
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperature();
}
//---------------------------------------------------------------------
// PhysicsModelSpecies
//---------------------------------------------------------------------
PhysicsModelSpecies::PhysicsModelSpecies(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "species";
weakEqns_[MASS_DENSITY] = new WeakEquationMassDiffusion();
weakEqns_[SPECIES_CONCENTRATION] = new WeakEquationDiffusion();
}
//---------------------------------------------------------------------
// PhysicsModelSpeciesElectrostatic
//---------------------------------------------------------------------
PhysicsModelSpeciesElectrostatic::PhysicsModelSpeciesElectrostatic(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "species electrostatic";
weakEqns_[MASS_DENSITY] = new WeakEquationMassDiffusion();
weakEqns_[CHARGE_DENSITY] = new WeakEquationChargeDiffusion();
weakEqns_[SPECIES_CONCENTRATION]= new WeakEquationDiffusion();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
}
//---------------------------------------------------------------------
// PhysicsModelTwoTemperature
//---------------------------------------------------------------------
PhysicsModelTwoTemperature::PhysicsModelTwoTemperature(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "two-temperature";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperature();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusion
//---------------------------------------------------------------------
PhysicsModelDriftDiffusion::PhysicsModelDriftDiffusion(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureJouleHeating();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronContinuity();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionEquilibrium
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionEquilibrium::PhysicsModelDriftDiffusionEquilibrium(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "equilibrium drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureJouleHeating();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoisson();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionSchrodinger
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionSchrodinger::PhysicsModelDriftDiffusionSchrodinger(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "schrodinger drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureJouleHeating();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoisson();
weakEqns_[ELECTRON_WAVEFUNCTION]= new WeakEquationSchrodinger();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionSchrodingerSlice
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionSchrodingerSlice::PhysicsModelDriftDiffusionSchrodingerSlice(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "schrodinger drift-diffusion slice";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureJouleHeating();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
weakEqns_[ELECTRON_WAVEFUNCTION]= new WeakEquationSchrodinger();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionConvection
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionConvection::PhysicsModelDriftDiffusionConvection(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "convection drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureConvection();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronContinuity();
weakEqns_[ELECTRON_VELOCITY] = new WeakEquationElectronMomentumDDM();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionConvectionEquilibrium
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionConvectionEquilibrium::PhysicsModelDriftDiffusionConvectionEquilibrium(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "equilibrium convection drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureConvection();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRON_VELOCITY] = new WeakEquationElectronMomentumDDM();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoisson();
}
//---------------------------------------------------------------------
// PhysicsModelDriftDiffusionConvectionSchrodinger
//---------------------------------------------------------------------
PhysicsModelDriftDiffusionConvectionSchrodinger::PhysicsModelDriftDiffusionConvectionSchrodinger(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "schrodinger convection drift-diffusion";
weakEqns_[TEMPERATURE] = new WeakEquationPhononTemperatureExchange();
weakEqns_[ELECTRON_TEMPERATURE] = new WeakEquationElectronTemperatureConvection();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRON_VELOCITY] = new WeakEquationElectronMomentumDDM();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
weakEqns_[ELECTRON_WAVEFUNCTION] = new WeakEquationSchrodinger();
}
//---------------------------------------------------------------------
// PhysicsModelElectrostatic
//---------------------------------------------------------------------
PhysicsModelElectrostatic::PhysicsModelElectrostatic(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "electrostatic";
weakEqns_[VELOCITY] = new WeakEquationMomentumElectrostatic();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronContinuity();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoissonConstantRHS();
}
//---------------------------------------------------------------------
// PhysicsModelElectrostaticEquilibrium
//---------------------------------------------------------------------
PhysicsModelElectrostaticEquilibrium::PhysicsModelElectrostaticEquilibrium(string filename):
PhysicsModel(filename)
{
PhysicsModel::type_ = "equilibrium electrostatic";
weakEqns_[VELOCITY] = new WeakEquationMomentumElectrostatic();
weakEqns_[ELECTRON_DENSITY] = new WeakEquationElectronEquilibrium();
weakEqns_[ELECTRIC_POTENTIAL] = new WeakEquationPoisson();
}
//-------------------------------------------------------------------
// PhysicsModelTangentOperator
//-------------------------------------------------------------------
PhysicsModelTangentOperator::PhysicsModelTangentOperator(ATC_Coupling * atc,
const PhysicsModel * physicsModel,
Array2D<bool> & rhsMask,
IntegrationDomainType integrationType,
FIELDS & rhs,
FIELDS & fields,
FieldName fieldName,
const int dof)
:TangentOperator(),
atc_(atc),
physicsModel_(physicsModel),
rhsMask_(rhsMask),
integrationType_(integrationType),
rhs_(rhs),
fields_(fields),
fieldName_(fieldName),
dof_(dof)
{
};
PhysicsModelTangentOperator::PhysicsModelTangentOperator(ATC_Coupling * atc,
const PhysicsModel * physicsModel,
Array2D<bool> & rhsMask,
IntegrationDomainType integrationType,
FieldName fieldName,
const int dof)
:TangentOperator(),
atc_(atc),
physicsModel_(physicsModel),
rhsMask_(rhsMask),
integrationType_(integrationType),
rhs_(atc_->rhs()),
fields_(atc_->fields()),
fieldName_(fieldName),
dof_(dof)
{
};
void PhysicsModelTangentOperator::function(const VECTOR & x, DENS_VEC & r)
{
CLON_VEC f = column(fields_[fieldName_].set_quantity(),dof_);
f = x;
atc_->compute_rhs_vector(rhsMask_, fields_, rhs_, integrationType_, physicsModel_);
CLON_VEC rhsv = column(rhs_[fieldName_].quantity(),dof_);
r = rhsv;
}
void PhysicsModelTangentOperator::tangent(const VECTOR & x, DENS_VEC & r,
MATRIX & K)
{
function(x,r);
pair<FieldName,FieldName> row_col(fieldName_,fieldName_);
const FIELDS & fields = fields_;
atc_->compute_rhs_tangent(row_col, rhsMask_, fields , stiffness_, integrationType_, physicsModel_);
K = stiffness_.dense_copy();
}
}; // end namespace
| gpl-2.0 |
vyos-legacy/linux-vyatta | block/cfq-iosched.c | 46 | 101798 | /*
* CFQ, or complete fairness queueing, disk scheduler.
*
* Based on ideas from a previously unfinished io
* scheduler (round robin per-process disk scheduling) and Andrea Arcangeli.
*
* Copyright (C) 2003 Jens Axboe <axboe@kernel.dk>
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/jiffies.h>
#include <linux/rbtree.h>
#include <linux/ioprio.h>
#include <linux/blktrace_api.h>
#include "blk.h"
#include "cfq.h"
/*
* tunables
*/
/* max queue in one round of service */
static const int cfq_quantum = 8;
static const int cfq_fifo_expire[2] = { HZ / 4, HZ / 8 };
/* maximum backwards seek, in KiB */
static const int cfq_back_max = 16 * 1024;
/* penalty of a backwards seek */
static const int cfq_back_penalty = 2;
static const int cfq_slice_sync = HZ / 10;
static int cfq_slice_async = HZ / 25;
static const int cfq_slice_async_rq = 2;
static int cfq_slice_idle = HZ / 125;
static int cfq_group_idle = HZ / 125;
static const int cfq_target_latency = HZ * 3/10; /* 300 ms */
static const int cfq_hist_divisor = 4;
/*
* offset from end of service tree
*/
#define CFQ_IDLE_DELAY (HZ / 5)
/*
* below this threshold, we consider thinktime immediate
*/
#define CFQ_MIN_TT (2)
#define CFQ_SLICE_SCALE (5)
#define CFQ_HW_QUEUE_MIN (5)
#define CFQ_SERVICE_SHIFT 12
#define CFQQ_SEEK_THR (sector_t)(8 * 100)
#define CFQQ_CLOSE_THR (sector_t)(8 * 1024)
#define CFQQ_SECT_THR_NONROT (sector_t)(2 * 32)
#define CFQQ_SEEKY(cfqq) (hweight32(cfqq->seek_history) > 32/8)
#define RQ_CIC(rq) icq_to_cic((rq)->elv.icq)
#define RQ_CFQQ(rq) (struct cfq_queue *) ((rq)->elv.priv[0])
#define RQ_CFQG(rq) (struct cfq_group *) ((rq)->elv.priv[1])
static struct kmem_cache *cfq_pool;
#define CFQ_PRIO_LISTS IOPRIO_BE_NR
#define cfq_class_idle(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_IDLE)
#define cfq_class_rt(cfqq) ((cfqq)->ioprio_class == IOPRIO_CLASS_RT)
#define sample_valid(samples) ((samples) > 80)
#define rb_entry_cfqg(node) rb_entry((node), struct cfq_group, rb_node)
struct cfq_ttime {
unsigned long last_end_request;
unsigned long ttime_total;
unsigned long ttime_samples;
unsigned long ttime_mean;
};
/*
* Most of our rbtree usage is for sorting with min extraction, so
* if we cache the leftmost node we don't have to walk down the tree
* to find it. Idea borrowed from Ingo Molnars CFS scheduler. We should
* move this into the elevator for the rq sorting as well.
*/
struct cfq_rb_root {
struct rb_root rb;
struct rb_node *left;
unsigned count;
unsigned total_weight;
u64 min_vdisktime;
struct cfq_ttime ttime;
};
#define CFQ_RB_ROOT (struct cfq_rb_root) { .rb = RB_ROOT, \
.ttime = {.last_end_request = jiffies,},}
/*
* Per process-grouping structure
*/
struct cfq_queue {
/* reference count */
int ref;
/* various state flags, see below */
unsigned int flags;
/* parent cfq_data */
struct cfq_data *cfqd;
/* service_tree member */
struct rb_node rb_node;
/* service_tree key */
unsigned long rb_key;
/* prio tree member */
struct rb_node p_node;
/* prio tree root we belong to, if any */
struct rb_root *p_root;
/* sorted list of pending requests */
struct rb_root sort_list;
/* if fifo isn't expired, next request to serve */
struct request *next_rq;
/* requests queued in sort_list */
int queued[2];
/* currently allocated requests */
int allocated[2];
/* fifo list of requests in sort_list */
struct list_head fifo;
/* time when queue got scheduled in to dispatch first request. */
unsigned long dispatch_start;
unsigned int allocated_slice;
unsigned int slice_dispatch;
/* time when first request from queue completed and slice started. */
unsigned long slice_start;
unsigned long slice_end;
long slice_resid;
/* pending priority requests */
int prio_pending;
/* number of requests that are on the dispatch list or inside driver */
int dispatched;
/* io prio of this group */
unsigned short ioprio, org_ioprio;
unsigned short ioprio_class;
pid_t pid;
u32 seek_history;
sector_t last_request_pos;
struct cfq_rb_root *service_tree;
struct cfq_queue *new_cfqq;
struct cfq_group *cfqg;
/* Number of sectors dispatched from queue in single dispatch round */
unsigned long nr_sectors;
};
/*
* First index in the service_trees.
* IDLE is handled separately, so it has negative index
*/
enum wl_prio_t {
BE_WORKLOAD = 0,
RT_WORKLOAD = 1,
IDLE_WORKLOAD = 2,
CFQ_PRIO_NR,
};
/*
* Second index in the service_trees.
*/
enum wl_type_t {
ASYNC_WORKLOAD = 0,
SYNC_NOIDLE_WORKLOAD = 1,
SYNC_WORKLOAD = 2
};
/* This is per cgroup per device grouping structure */
struct cfq_group {
/* group service_tree member */
struct rb_node rb_node;
/* group service_tree key */
u64 vdisktime;
unsigned int weight;
unsigned int new_weight;
bool needs_update;
/* number of cfqq currently on this group */
int nr_cfqq;
/*
* Per group busy queues average. Useful for workload slice calc. We
* create the array for each prio class but at run time it is used
* only for RT and BE class and slot for IDLE class remains unused.
* This is primarily done to avoid confusion and a gcc warning.
*/
unsigned int busy_queues_avg[CFQ_PRIO_NR];
/*
* rr lists of queues with requests. We maintain service trees for
* RT and BE classes. These trees are subdivided in subclasses
* of SYNC, SYNC_NOIDLE and ASYNC based on workload type. For IDLE
* class there is no subclassification and all the cfq queues go on
* a single tree service_tree_idle.
* Counts are embedded in the cfq_rb_root
*/
struct cfq_rb_root service_trees[2][3];
struct cfq_rb_root service_tree_idle;
unsigned long saved_workload_slice;
enum wl_type_t saved_workload;
enum wl_prio_t saved_serving_prio;
struct blkio_group blkg;
#ifdef CONFIG_CFQ_GROUP_IOSCHED
struct hlist_node cfqd_node;
int ref;
#endif
/* number of requests that are on the dispatch list or inside driver */
int dispatched;
struct cfq_ttime ttime;
};
struct cfq_io_cq {
struct io_cq icq; /* must be the first member */
struct cfq_queue *cfqq[2];
struct cfq_ttime ttime;
};
/*
* Per block device queue structure
*/
struct cfq_data {
struct request_queue *queue;
/* Root service tree for cfq_groups */
struct cfq_rb_root grp_service_tree;
struct cfq_group root_group;
/*
* The priority currently being served
*/
enum wl_prio_t serving_prio;
enum wl_type_t serving_type;
unsigned long workload_expires;
struct cfq_group *serving_group;
/*
* Each priority tree is sorted by next_request position. These
* trees are used when determining if two or more queues are
* interleaving requests (see cfq_close_cooperator).
*/
struct rb_root prio_trees[CFQ_PRIO_LISTS];
unsigned int busy_queues;
unsigned int busy_sync_queues;
int rq_in_driver;
int rq_in_flight[2];
/*
* queue-depth detection
*/
int rq_queued;
int hw_tag;
/*
* hw_tag can be
* -1 => indeterminate, (cfq will behave as if NCQ is present, to allow better detection)
* 1 => NCQ is present (hw_tag_est_depth is the estimated max depth)
* 0 => no NCQ
*/
int hw_tag_est_depth;
unsigned int hw_tag_samples;
/*
* idle window management
*/
struct timer_list idle_slice_timer;
struct work_struct unplug_work;
struct cfq_queue *active_queue;
struct cfq_io_cq *active_cic;
/*
* async queue for each priority case
*/
struct cfq_queue *async_cfqq[2][IOPRIO_BE_NR];
struct cfq_queue *async_idle_cfqq;
sector_t last_position;
/*
* tunables, see top of file
*/
unsigned int cfq_quantum;
unsigned int cfq_fifo_expire[2];
unsigned int cfq_back_penalty;
unsigned int cfq_back_max;
unsigned int cfq_slice[2];
unsigned int cfq_slice_async_rq;
unsigned int cfq_slice_idle;
unsigned int cfq_group_idle;
unsigned int cfq_latency;
/*
* Fallback dummy cfqq for extreme OOM conditions
*/
struct cfq_queue oom_cfqq;
unsigned long last_delayed_sync;
/* List of cfq groups being managed on this device*/
struct hlist_head cfqg_list;
/* Number of groups which are on blkcg->blkg_list */
unsigned int nr_blkcg_linked_grps;
};
static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd);
static struct cfq_rb_root *service_tree_for(struct cfq_group *cfqg,
enum wl_prio_t prio,
enum wl_type_t type)
{
if (!cfqg)
return NULL;
if (prio == IDLE_WORKLOAD)
return &cfqg->service_tree_idle;
return &cfqg->service_trees[prio][type];
}
enum cfqq_state_flags {
CFQ_CFQQ_FLAG_on_rr = 0, /* on round-robin busy list */
CFQ_CFQQ_FLAG_wait_request, /* waiting for a request */
CFQ_CFQQ_FLAG_must_dispatch, /* must be allowed a dispatch */
CFQ_CFQQ_FLAG_must_alloc_slice, /* per-slice must_alloc flag */
CFQ_CFQQ_FLAG_fifo_expire, /* FIFO checked in this slice */
CFQ_CFQQ_FLAG_idle_window, /* slice idling enabled */
CFQ_CFQQ_FLAG_prio_changed, /* task priority has changed */
CFQ_CFQQ_FLAG_slice_new, /* no requests dispatched in slice */
CFQ_CFQQ_FLAG_sync, /* synchronous queue */
CFQ_CFQQ_FLAG_coop, /* cfqq is shared */
CFQ_CFQQ_FLAG_split_coop, /* shared cfqq will be splitted */
CFQ_CFQQ_FLAG_deep, /* sync cfqq experienced large depth */
CFQ_CFQQ_FLAG_wait_busy, /* Waiting for next request */
};
#define CFQ_CFQQ_FNS(name) \
static inline void cfq_mark_cfqq_##name(struct cfq_queue *cfqq) \
{ \
(cfqq)->flags |= (1 << CFQ_CFQQ_FLAG_##name); \
} \
static inline void cfq_clear_cfqq_##name(struct cfq_queue *cfqq) \
{ \
(cfqq)->flags &= ~(1 << CFQ_CFQQ_FLAG_##name); \
} \
static inline int cfq_cfqq_##name(const struct cfq_queue *cfqq) \
{ \
return ((cfqq)->flags & (1 << CFQ_CFQQ_FLAG_##name)) != 0; \
}
CFQ_CFQQ_FNS(on_rr);
CFQ_CFQQ_FNS(wait_request);
CFQ_CFQQ_FNS(must_dispatch);
CFQ_CFQQ_FNS(must_alloc_slice);
CFQ_CFQQ_FNS(fifo_expire);
CFQ_CFQQ_FNS(idle_window);
CFQ_CFQQ_FNS(prio_changed);
CFQ_CFQQ_FNS(slice_new);
CFQ_CFQQ_FNS(sync);
CFQ_CFQQ_FNS(coop);
CFQ_CFQQ_FNS(split_coop);
CFQ_CFQQ_FNS(deep);
CFQ_CFQQ_FNS(wait_busy);
#undef CFQ_CFQQ_FNS
#ifdef CONFIG_CFQ_GROUP_IOSCHED
#define cfq_log_cfqq(cfqd, cfqq, fmt, args...) \
blk_add_trace_msg((cfqd)->queue, "cfq%d%c %s " fmt, (cfqq)->pid, \
cfq_cfqq_sync((cfqq)) ? 'S' : 'A', \
blkg_path(&(cfqq)->cfqg->blkg), ##args)
#define cfq_log_cfqg(cfqd, cfqg, fmt, args...) \
blk_add_trace_msg((cfqd)->queue, "%s " fmt, \
blkg_path(&(cfqg)->blkg), ##args) \
#else
#define cfq_log_cfqq(cfqd, cfqq, fmt, args...) \
blk_add_trace_msg((cfqd)->queue, "cfq%d " fmt, (cfqq)->pid, ##args)
#define cfq_log_cfqg(cfqd, cfqg, fmt, args...) do {} while (0)
#endif
#define cfq_log(cfqd, fmt, args...) \
blk_add_trace_msg((cfqd)->queue, "cfq " fmt, ##args)
/* Traverses through cfq group service trees */
#define for_each_cfqg_st(cfqg, i, j, st) \
for (i = 0; i <= IDLE_WORKLOAD; i++) \
for (j = 0, st = i < IDLE_WORKLOAD ? &cfqg->service_trees[i][j]\
: &cfqg->service_tree_idle; \
(i < IDLE_WORKLOAD && j <= SYNC_WORKLOAD) || \
(i == IDLE_WORKLOAD && j == 0); \
j++, st = i < IDLE_WORKLOAD ? \
&cfqg->service_trees[i][j]: NULL) \
static inline bool cfq_io_thinktime_big(struct cfq_data *cfqd,
struct cfq_ttime *ttime, bool group_idle)
{
unsigned long slice;
if (!sample_valid(ttime->ttime_samples))
return false;
if (group_idle)
slice = cfqd->cfq_group_idle;
else
slice = cfqd->cfq_slice_idle;
return ttime->ttime_mean > slice;
}
static inline bool iops_mode(struct cfq_data *cfqd)
{
/*
* If we are not idling on queues and it is a NCQ drive, parallel
* execution of requests is on and measuring time is not possible
* in most of the cases until and unless we drive shallower queue
* depths and that becomes a performance bottleneck. In such cases
* switch to start providing fairness in terms of number of IOs.
*/
if (!cfqd->cfq_slice_idle && cfqd->hw_tag)
return true;
else
return false;
}
static inline enum wl_prio_t cfqq_prio(struct cfq_queue *cfqq)
{
if (cfq_class_idle(cfqq))
return IDLE_WORKLOAD;
if (cfq_class_rt(cfqq))
return RT_WORKLOAD;
return BE_WORKLOAD;
}
static enum wl_type_t cfqq_type(struct cfq_queue *cfqq)
{
if (!cfq_cfqq_sync(cfqq))
return ASYNC_WORKLOAD;
if (!cfq_cfqq_idle_window(cfqq))
return SYNC_NOIDLE_WORKLOAD;
return SYNC_WORKLOAD;
}
static inline int cfq_group_busy_queues_wl(enum wl_prio_t wl,
struct cfq_data *cfqd,
struct cfq_group *cfqg)
{
if (wl == IDLE_WORKLOAD)
return cfqg->service_tree_idle.count;
return cfqg->service_trees[wl][ASYNC_WORKLOAD].count
+ cfqg->service_trees[wl][SYNC_NOIDLE_WORKLOAD].count
+ cfqg->service_trees[wl][SYNC_WORKLOAD].count;
}
static inline int cfqg_busy_async_queues(struct cfq_data *cfqd,
struct cfq_group *cfqg)
{
return cfqg->service_trees[RT_WORKLOAD][ASYNC_WORKLOAD].count
+ cfqg->service_trees[BE_WORKLOAD][ASYNC_WORKLOAD].count;
}
static void cfq_dispatch_insert(struct request_queue *, struct request *);
static struct cfq_queue *cfq_get_queue(struct cfq_data *, bool,
struct io_context *, gfp_t);
static inline struct cfq_io_cq *icq_to_cic(struct io_cq *icq)
{
/* cic->icq is the first member, %NULL will convert to %NULL */
return container_of(icq, struct cfq_io_cq, icq);
}
static inline struct cfq_io_cq *cfq_cic_lookup(struct cfq_data *cfqd,
struct io_context *ioc)
{
if (ioc)
return icq_to_cic(ioc_lookup_icq(ioc, cfqd->queue));
return NULL;
}
static inline struct cfq_queue *cic_to_cfqq(struct cfq_io_cq *cic, bool is_sync)
{
return cic->cfqq[is_sync];
}
static inline void cic_set_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq,
bool is_sync)
{
cic->cfqq[is_sync] = cfqq;
}
static inline struct cfq_data *cic_to_cfqd(struct cfq_io_cq *cic)
{
return cic->icq.q->elevator->elevator_data;
}
/*
* We regard a request as SYNC, if it's either a read or has the SYNC bit
* set (in which case it could also be direct WRITE).
*/
static inline bool cfq_bio_sync(struct bio *bio)
{
return bio_data_dir(bio) == READ || (bio->bi_rw & REQ_SYNC);
}
/*
* scheduler run of queue, if there are requests pending and no one in the
* driver that will restart queueing
*/
static inline void cfq_schedule_dispatch(struct cfq_data *cfqd)
{
if (cfqd->busy_queues) {
cfq_log(cfqd, "schedule dispatch");
kblockd_schedule_work(cfqd->queue, &cfqd->unplug_work);
}
}
/*
* Scale schedule slice based on io priority. Use the sync time slice only
* if a queue is marked sync and has sync io queued. A sync queue with async
* io only, should not get full sync slice length.
*/
static inline int cfq_prio_slice(struct cfq_data *cfqd, bool sync,
unsigned short prio)
{
const int base_slice = cfqd->cfq_slice[sync];
WARN_ON(prio >= IOPRIO_BE_NR);
return base_slice + (base_slice/CFQ_SLICE_SCALE * (4 - prio));
}
static inline int
cfq_prio_to_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
return cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio);
}
static inline u64 cfq_scale_slice(unsigned long delta, struct cfq_group *cfqg)
{
u64 d = delta << CFQ_SERVICE_SHIFT;
d = d * BLKIO_WEIGHT_DEFAULT;
do_div(d, cfqg->weight);
return d;
}
static inline u64 max_vdisktime(u64 min_vdisktime, u64 vdisktime)
{
s64 delta = (s64)(vdisktime - min_vdisktime);
if (delta > 0)
min_vdisktime = vdisktime;
return min_vdisktime;
}
static inline u64 min_vdisktime(u64 min_vdisktime, u64 vdisktime)
{
s64 delta = (s64)(vdisktime - min_vdisktime);
if (delta < 0)
min_vdisktime = vdisktime;
return min_vdisktime;
}
static void update_min_vdisktime(struct cfq_rb_root *st)
{
struct cfq_group *cfqg;
if (st->left) {
cfqg = rb_entry_cfqg(st->left);
st->min_vdisktime = max_vdisktime(st->min_vdisktime,
cfqg->vdisktime);
}
}
/*
* get averaged number of queues of RT/BE priority.
* average is updated, with a formula that gives more weight to higher numbers,
* to quickly follows sudden increases and decrease slowly
*/
static inline unsigned cfq_group_get_avg_queues(struct cfq_data *cfqd,
struct cfq_group *cfqg, bool rt)
{
unsigned min_q, max_q;
unsigned mult = cfq_hist_divisor - 1;
unsigned round = cfq_hist_divisor / 2;
unsigned busy = cfq_group_busy_queues_wl(rt, cfqd, cfqg);
min_q = min(cfqg->busy_queues_avg[rt], busy);
max_q = max(cfqg->busy_queues_avg[rt], busy);
cfqg->busy_queues_avg[rt] = (mult * max_q + min_q + round) /
cfq_hist_divisor;
return cfqg->busy_queues_avg[rt];
}
static inline unsigned
cfq_group_slice(struct cfq_data *cfqd, struct cfq_group *cfqg)
{
struct cfq_rb_root *st = &cfqd->grp_service_tree;
return cfq_target_latency * cfqg->weight / st->total_weight;
}
static inline unsigned
cfq_scaled_cfqq_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
unsigned slice = cfq_prio_to_slice(cfqd, cfqq);
if (cfqd->cfq_latency) {
/*
* interested queues (we consider only the ones with the same
* priority class in the cfq group)
*/
unsigned iq = cfq_group_get_avg_queues(cfqd, cfqq->cfqg,
cfq_class_rt(cfqq));
unsigned sync_slice = cfqd->cfq_slice[1];
unsigned expect_latency = sync_slice * iq;
unsigned group_slice = cfq_group_slice(cfqd, cfqq->cfqg);
if (expect_latency > group_slice) {
unsigned base_low_slice = 2 * cfqd->cfq_slice_idle;
/* scale low_slice according to IO priority
* and sync vs async */
unsigned low_slice =
min(slice, base_low_slice * slice / sync_slice);
/* the adapted slice value is scaled to fit all iqs
* into the target latency */
slice = max(slice * group_slice / expect_latency,
low_slice);
}
}
return slice;
}
static inline void
cfq_set_prio_slice(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
unsigned slice = cfq_scaled_cfqq_slice(cfqd, cfqq);
cfqq->slice_start = jiffies;
cfqq->slice_end = jiffies + slice;
cfqq->allocated_slice = slice;
cfq_log_cfqq(cfqd, cfqq, "set_slice=%lu", cfqq->slice_end - jiffies);
}
/*
* We need to wrap this check in cfq_cfqq_slice_new(), since ->slice_end
* isn't valid until the first request from the dispatch is activated
* and the slice time set.
*/
static inline bool cfq_slice_used(struct cfq_queue *cfqq)
{
if (cfq_cfqq_slice_new(cfqq))
return false;
if (time_before(jiffies, cfqq->slice_end))
return false;
return true;
}
/*
* Lifted from AS - choose which of rq1 and rq2 that is best served now.
* We choose the request that is closest to the head right now. Distance
* behind the head is penalized and only allowed to a certain extent.
*/
static struct request *
cfq_choose_req(struct cfq_data *cfqd, struct request *rq1, struct request *rq2, sector_t last)
{
sector_t s1, s2, d1 = 0, d2 = 0;
unsigned long back_max;
#define CFQ_RQ1_WRAP 0x01 /* request 1 wraps */
#define CFQ_RQ2_WRAP 0x02 /* request 2 wraps */
unsigned wrap = 0; /* bit mask: requests behind the disk head? */
if (rq1 == NULL || rq1 == rq2)
return rq2;
if (rq2 == NULL)
return rq1;
if (rq_is_sync(rq1) != rq_is_sync(rq2))
return rq_is_sync(rq1) ? rq1 : rq2;
if ((rq1->cmd_flags ^ rq2->cmd_flags) & REQ_PRIO)
return rq1->cmd_flags & REQ_PRIO ? rq1 : rq2;
s1 = blk_rq_pos(rq1);
s2 = blk_rq_pos(rq2);
/*
* by definition, 1KiB is 2 sectors
*/
back_max = cfqd->cfq_back_max * 2;
/*
* Strict one way elevator _except_ in the case where we allow
* short backward seeks which are biased as twice the cost of a
* similar forward seek.
*/
if (s1 >= last)
d1 = s1 - last;
else if (s1 + back_max >= last)
d1 = (last - s1) * cfqd->cfq_back_penalty;
else
wrap |= CFQ_RQ1_WRAP;
if (s2 >= last)
d2 = s2 - last;
else if (s2 + back_max >= last)
d2 = (last - s2) * cfqd->cfq_back_penalty;
else
wrap |= CFQ_RQ2_WRAP;
/* Found required data */
/*
* By doing switch() on the bit mask "wrap" we avoid having to
* check two variables for all permutations: --> faster!
*/
switch (wrap) {
case 0: /* common case for CFQ: rq1 and rq2 not wrapped */
if (d1 < d2)
return rq1;
else if (d2 < d1)
return rq2;
else {
if (s1 >= s2)
return rq1;
else
return rq2;
}
case CFQ_RQ2_WRAP:
return rq1;
case CFQ_RQ1_WRAP:
return rq2;
case (CFQ_RQ1_WRAP|CFQ_RQ2_WRAP): /* both rqs wrapped */
default:
/*
* Since both rqs are wrapped,
* start with the one that's further behind head
* (--> only *one* back seek required),
* since back seek takes more time than forward.
*/
if (s1 <= s2)
return rq1;
else
return rq2;
}
}
/*
* The below is leftmost cache rbtree addon
*/
static struct cfq_queue *cfq_rb_first(struct cfq_rb_root *root)
{
/* Service tree is empty */
if (!root->count)
return NULL;
if (!root->left)
root->left = rb_first(&root->rb);
if (root->left)
return rb_entry(root->left, struct cfq_queue, rb_node);
return NULL;
}
static struct cfq_group *cfq_rb_first_group(struct cfq_rb_root *root)
{
if (!root->left)
root->left = rb_first(&root->rb);
if (root->left)
return rb_entry_cfqg(root->left);
return NULL;
}
static void rb_erase_init(struct rb_node *n, struct rb_root *root)
{
rb_erase(n, root);
RB_CLEAR_NODE(n);
}
static void cfq_rb_erase(struct rb_node *n, struct cfq_rb_root *root)
{
if (root->left == n)
root->left = NULL;
rb_erase_init(n, &root->rb);
--root->count;
}
/*
* would be nice to take fifo expire time into account as well
*/
static struct request *
cfq_find_next_rq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct request *last)
{
struct rb_node *rbnext = rb_next(&last->rb_node);
struct rb_node *rbprev = rb_prev(&last->rb_node);
struct request *next = NULL, *prev = NULL;
BUG_ON(RB_EMPTY_NODE(&last->rb_node));
if (rbprev)
prev = rb_entry_rq(rbprev);
if (rbnext)
next = rb_entry_rq(rbnext);
else {
rbnext = rb_first(&cfqq->sort_list);
if (rbnext && rbnext != &last->rb_node)
next = rb_entry_rq(rbnext);
}
return cfq_choose_req(cfqd, next, prev, blk_rq_pos(last));
}
static unsigned long cfq_slice_offset(struct cfq_data *cfqd,
struct cfq_queue *cfqq)
{
/*
* just an approximation, should be ok.
*/
return (cfqq->cfqg->nr_cfqq - 1) * (cfq_prio_slice(cfqd, 1, 0) -
cfq_prio_slice(cfqd, cfq_cfqq_sync(cfqq), cfqq->ioprio));
}
static inline s64
cfqg_key(struct cfq_rb_root *st, struct cfq_group *cfqg)
{
return cfqg->vdisktime - st->min_vdisktime;
}
static void
__cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
{
struct rb_node **node = &st->rb.rb_node;
struct rb_node *parent = NULL;
struct cfq_group *__cfqg;
s64 key = cfqg_key(st, cfqg);
int left = 1;
while (*node != NULL) {
parent = *node;
__cfqg = rb_entry_cfqg(parent);
if (key < cfqg_key(st, __cfqg))
node = &parent->rb_left;
else {
node = &parent->rb_right;
left = 0;
}
}
if (left)
st->left = &cfqg->rb_node;
rb_link_node(&cfqg->rb_node, parent, node);
rb_insert_color(&cfqg->rb_node, &st->rb);
}
static void
cfq_update_group_weight(struct cfq_group *cfqg)
{
BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
if (cfqg->needs_update) {
cfqg->weight = cfqg->new_weight;
cfqg->needs_update = false;
}
}
static void
cfq_group_service_tree_add(struct cfq_rb_root *st, struct cfq_group *cfqg)
{
BUG_ON(!RB_EMPTY_NODE(&cfqg->rb_node));
cfq_update_group_weight(cfqg);
__cfq_group_service_tree_add(st, cfqg);
st->total_weight += cfqg->weight;
}
static void
cfq_group_notify_queue_add(struct cfq_data *cfqd, struct cfq_group *cfqg)
{
struct cfq_rb_root *st = &cfqd->grp_service_tree;
struct cfq_group *__cfqg;
struct rb_node *n;
cfqg->nr_cfqq++;
if (!RB_EMPTY_NODE(&cfqg->rb_node))
return;
/*
* Currently put the group at the end. Later implement something
* so that groups get lesser vtime based on their weights, so that
* if group does not loose all if it was not continuously backlogged.
*/
n = rb_last(&st->rb);
if (n) {
__cfqg = rb_entry_cfqg(n);
cfqg->vdisktime = __cfqg->vdisktime + CFQ_IDLE_DELAY;
} else
cfqg->vdisktime = st->min_vdisktime;
cfq_group_service_tree_add(st, cfqg);
}
static void
cfq_group_service_tree_del(struct cfq_rb_root *st, struct cfq_group *cfqg)
{
st->total_weight -= cfqg->weight;
if (!RB_EMPTY_NODE(&cfqg->rb_node))
cfq_rb_erase(&cfqg->rb_node, st);
}
static void
cfq_group_notify_queue_del(struct cfq_data *cfqd, struct cfq_group *cfqg)
{
struct cfq_rb_root *st = &cfqd->grp_service_tree;
BUG_ON(cfqg->nr_cfqq < 1);
cfqg->nr_cfqq--;
/* If there are other cfq queues under this group, don't delete it */
if (cfqg->nr_cfqq)
return;
cfq_log_cfqg(cfqd, cfqg, "del_from_rr group");
cfq_group_service_tree_del(st, cfqg);
cfqg->saved_workload_slice = 0;
cfq_blkiocg_update_dequeue_stats(&cfqg->blkg, 1);
}
static inline unsigned int cfq_cfqq_slice_usage(struct cfq_queue *cfqq,
unsigned int *unaccounted_time)
{
unsigned int slice_used;
/*
* Queue got expired before even a single request completed or
* got expired immediately after first request completion.
*/
if (!cfqq->slice_start || cfqq->slice_start == jiffies) {
/*
* Also charge the seek time incurred to the group, otherwise
* if there are mutiple queues in the group, each can dispatch
* a single request on seeky media and cause lots of seek time
* and group will never know it.
*/
slice_used = max_t(unsigned, (jiffies - cfqq->dispatch_start),
1);
} else {
slice_used = jiffies - cfqq->slice_start;
if (slice_used > cfqq->allocated_slice) {
*unaccounted_time = slice_used - cfqq->allocated_slice;
slice_used = cfqq->allocated_slice;
}
if (time_after(cfqq->slice_start, cfqq->dispatch_start))
*unaccounted_time += cfqq->slice_start -
cfqq->dispatch_start;
}
return slice_used;
}
static void cfq_group_served(struct cfq_data *cfqd, struct cfq_group *cfqg,
struct cfq_queue *cfqq)
{
struct cfq_rb_root *st = &cfqd->grp_service_tree;
unsigned int used_sl, charge, unaccounted_sl = 0;
int nr_sync = cfqg->nr_cfqq - cfqg_busy_async_queues(cfqd, cfqg)
- cfqg->service_tree_idle.count;
BUG_ON(nr_sync < 0);
used_sl = charge = cfq_cfqq_slice_usage(cfqq, &unaccounted_sl);
if (iops_mode(cfqd))
charge = cfqq->slice_dispatch;
else if (!cfq_cfqq_sync(cfqq) && !nr_sync)
charge = cfqq->allocated_slice;
/* Can't update vdisktime while group is on service tree */
cfq_group_service_tree_del(st, cfqg);
cfqg->vdisktime += cfq_scale_slice(charge, cfqg);
/* If a new weight was requested, update now, off tree */
cfq_group_service_tree_add(st, cfqg);
/* This group is being expired. Save the context */
if (time_after(cfqd->workload_expires, jiffies)) {
cfqg->saved_workload_slice = cfqd->workload_expires
- jiffies;
cfqg->saved_workload = cfqd->serving_type;
cfqg->saved_serving_prio = cfqd->serving_prio;
} else
cfqg->saved_workload_slice = 0;
cfq_log_cfqg(cfqd, cfqg, "served: vt=%llu min_vt=%llu", cfqg->vdisktime,
st->min_vdisktime);
cfq_log_cfqq(cfqq->cfqd, cfqq,
"sl_used=%u disp=%u charge=%u iops=%u sect=%lu",
used_sl, cfqq->slice_dispatch, charge,
iops_mode(cfqd), cfqq->nr_sectors);
cfq_blkiocg_update_timeslice_used(&cfqg->blkg, used_sl,
unaccounted_sl);
cfq_blkiocg_set_start_empty_time(&cfqg->blkg);
}
#ifdef CONFIG_CFQ_GROUP_IOSCHED
static inline struct cfq_group *cfqg_of_blkg(struct blkio_group *blkg)
{
if (blkg)
return container_of(blkg, struct cfq_group, blkg);
return NULL;
}
static void cfq_update_blkio_group_weight(void *key, struct blkio_group *blkg,
unsigned int weight)
{
struct cfq_group *cfqg = cfqg_of_blkg(blkg);
cfqg->new_weight = weight;
cfqg->needs_update = true;
}
static void cfq_init_add_cfqg_lists(struct cfq_data *cfqd,
struct cfq_group *cfqg, struct blkio_cgroup *blkcg)
{
struct backing_dev_info *bdi = &cfqd->queue->backing_dev_info;
unsigned int major, minor;
/*
* Add group onto cgroup list. It might happen that bdi->dev is
* not initialized yet. Initialize this new group without major
* and minor info and this info will be filled in once a new thread
* comes for IO.
*/
if (bdi->dev) {
sscanf(dev_name(bdi->dev), "%u:%u", &major, &minor);
cfq_blkiocg_add_blkio_group(blkcg, &cfqg->blkg,
(void *)cfqd, MKDEV(major, minor));
} else
cfq_blkiocg_add_blkio_group(blkcg, &cfqg->blkg,
(void *)cfqd, 0);
cfqd->nr_blkcg_linked_grps++;
cfqg->weight = blkcg_get_weight(blkcg, cfqg->blkg.dev);
/* Add group on cfqd list */
hlist_add_head(&cfqg->cfqd_node, &cfqd->cfqg_list);
}
/*
* Should be called from sleepable context. No request queue lock as per
* cpu stats are allocated dynamically and alloc_percpu needs to be called
* from sleepable context.
*/
static struct cfq_group * cfq_alloc_cfqg(struct cfq_data *cfqd)
{
struct cfq_group *cfqg = NULL;
int i, j, ret;
struct cfq_rb_root *st;
cfqg = kzalloc_node(sizeof(*cfqg), GFP_ATOMIC, cfqd->queue->node);
if (!cfqg)
return NULL;
for_each_cfqg_st(cfqg, i, j, st)
*st = CFQ_RB_ROOT;
RB_CLEAR_NODE(&cfqg->rb_node);
cfqg->ttime.last_end_request = jiffies;
/*
* Take the initial reference that will be released on destroy
* This can be thought of a joint reference by cgroup and
* elevator which will be dropped by either elevator exit
* or cgroup deletion path depending on who is exiting first.
*/
cfqg->ref = 1;
ret = blkio_alloc_blkg_stats(&cfqg->blkg);
if (ret) {
kfree(cfqg);
return NULL;
}
return cfqg;
}
static struct cfq_group *
cfq_find_cfqg(struct cfq_data *cfqd, struct blkio_cgroup *blkcg)
{
struct cfq_group *cfqg = NULL;
void *key = cfqd;
struct backing_dev_info *bdi = &cfqd->queue->backing_dev_info;
unsigned int major, minor;
/*
* This is the common case when there are no blkio cgroups.
* Avoid lookup in this case
*/
if (blkcg == &blkio_root_cgroup)
cfqg = &cfqd->root_group;
else
cfqg = cfqg_of_blkg(blkiocg_lookup_group(blkcg, key));
if (cfqg && !cfqg->blkg.dev && bdi->dev && dev_name(bdi->dev)) {
sscanf(dev_name(bdi->dev), "%u:%u", &major, &minor);
cfqg->blkg.dev = MKDEV(major, minor);
}
return cfqg;
}
/*
* Search for the cfq group current task belongs to. request_queue lock must
* be held.
*/
static struct cfq_group *cfq_get_cfqg(struct cfq_data *cfqd)
{
struct blkio_cgroup *blkcg;
struct cfq_group *cfqg = NULL, *__cfqg = NULL;
struct request_queue *q = cfqd->queue;
rcu_read_lock();
blkcg = task_blkio_cgroup(current);
cfqg = cfq_find_cfqg(cfqd, blkcg);
if (cfqg) {
rcu_read_unlock();
return cfqg;
}
/*
* Need to allocate a group. Allocation of group also needs allocation
* of per cpu stats which in-turn takes a mutex() and can block. Hence
* we need to drop rcu lock and queue_lock before we call alloc.
*
* Not taking any queue reference here and assuming that queue is
* around by the time we return. CFQ queue allocation code does
* the same. It might be racy though.
*/
rcu_read_unlock();
spin_unlock_irq(q->queue_lock);
cfqg = cfq_alloc_cfqg(cfqd);
spin_lock_irq(q->queue_lock);
rcu_read_lock();
blkcg = task_blkio_cgroup(current);
/*
* If some other thread already allocated the group while we were
* not holding queue lock, free up the group
*/
__cfqg = cfq_find_cfqg(cfqd, blkcg);
if (__cfqg) {
kfree(cfqg);
rcu_read_unlock();
return __cfqg;
}
if (!cfqg)
cfqg = &cfqd->root_group;
cfq_init_add_cfqg_lists(cfqd, cfqg, blkcg);
rcu_read_unlock();
return cfqg;
}
static inline struct cfq_group *cfq_ref_get_cfqg(struct cfq_group *cfqg)
{
cfqg->ref++;
return cfqg;
}
static void cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg)
{
/* Currently, all async queues are mapped to root group */
if (!cfq_cfqq_sync(cfqq))
cfqg = &cfqq->cfqd->root_group;
cfqq->cfqg = cfqg;
/* cfqq reference on cfqg */
cfqq->cfqg->ref++;
}
static void cfq_put_cfqg(struct cfq_group *cfqg)
{
struct cfq_rb_root *st;
int i, j;
BUG_ON(cfqg->ref <= 0);
cfqg->ref--;
if (cfqg->ref)
return;
for_each_cfqg_st(cfqg, i, j, st)
BUG_ON(!RB_EMPTY_ROOT(&st->rb));
free_percpu(cfqg->blkg.stats_cpu);
kfree(cfqg);
}
static void cfq_destroy_cfqg(struct cfq_data *cfqd, struct cfq_group *cfqg)
{
/* Something wrong if we are trying to remove same group twice */
BUG_ON(hlist_unhashed(&cfqg->cfqd_node));
hlist_del_init(&cfqg->cfqd_node);
BUG_ON(cfqd->nr_blkcg_linked_grps <= 0);
cfqd->nr_blkcg_linked_grps--;
/*
* Put the reference taken at the time of creation so that when all
* queues are gone, group can be destroyed.
*/
cfq_put_cfqg(cfqg);
}
static void cfq_release_cfq_groups(struct cfq_data *cfqd)
{
struct hlist_node *pos, *n;
struct cfq_group *cfqg;
hlist_for_each_entry_safe(cfqg, pos, n, &cfqd->cfqg_list, cfqd_node) {
/*
* If cgroup removal path got to blk_group first and removed
* it from cgroup list, then it will take care of destroying
* cfqg also.
*/
if (!cfq_blkiocg_del_blkio_group(&cfqg->blkg))
cfq_destroy_cfqg(cfqd, cfqg);
}
}
/*
* Blk cgroup controller notification saying that blkio_group object is being
* delinked as associated cgroup object is going away. That also means that
* no new IO will come in this group. So get rid of this group as soon as
* any pending IO in the group is finished.
*
* This function is called under rcu_read_lock(). key is the rcu protected
* pointer. That means "key" is a valid cfq_data pointer as long as we are rcu
* read lock.
*
* "key" was fetched from blkio_group under blkio_cgroup->lock. That means
* it should not be NULL as even if elevator was exiting, cgroup deltion
* path got to it first.
*/
static void cfq_unlink_blkio_group(void *key, struct blkio_group *blkg)
{
unsigned long flags;
struct cfq_data *cfqd = key;
spin_lock_irqsave(cfqd->queue->queue_lock, flags);
cfq_destroy_cfqg(cfqd, cfqg_of_blkg(blkg));
spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
}
#else /* GROUP_IOSCHED */
static struct cfq_group *cfq_get_cfqg(struct cfq_data *cfqd)
{
return &cfqd->root_group;
}
static inline struct cfq_group *cfq_ref_get_cfqg(struct cfq_group *cfqg)
{
return cfqg;
}
static inline void
cfq_link_cfqq_cfqg(struct cfq_queue *cfqq, struct cfq_group *cfqg) {
cfqq->cfqg = cfqg;
}
static void cfq_release_cfq_groups(struct cfq_data *cfqd) {}
static inline void cfq_put_cfqg(struct cfq_group *cfqg) {}
#endif /* GROUP_IOSCHED */
/*
* The cfqd->service_trees holds all pending cfq_queue's that have
* requests waiting to be processed. It is sorted in the order that
* we will service the queues.
*/
static void cfq_service_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq,
bool add_front)
{
struct rb_node **p, *parent;
struct cfq_queue *__cfqq;
unsigned long rb_key;
struct cfq_rb_root *service_tree;
int left;
int new_cfqq = 1;
service_tree = service_tree_for(cfqq->cfqg, cfqq_prio(cfqq),
cfqq_type(cfqq));
if (cfq_class_idle(cfqq)) {
rb_key = CFQ_IDLE_DELAY;
parent = rb_last(&service_tree->rb);
if (parent && parent != &cfqq->rb_node) {
__cfqq = rb_entry(parent, struct cfq_queue, rb_node);
rb_key += __cfqq->rb_key;
} else
rb_key += jiffies;
} else if (!add_front) {
/*
* Get our rb key offset. Subtract any residual slice
* value carried from last service. A negative resid
* count indicates slice overrun, and this should position
* the next service time further away in the tree.
*/
rb_key = cfq_slice_offset(cfqd, cfqq) + jiffies;
rb_key -= cfqq->slice_resid;
cfqq->slice_resid = 0;
} else {
rb_key = -HZ;
__cfqq = cfq_rb_first(service_tree);
rb_key += __cfqq ? __cfqq->rb_key : jiffies;
}
if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
new_cfqq = 0;
/*
* same position, nothing more to do
*/
if (rb_key == cfqq->rb_key &&
cfqq->service_tree == service_tree)
return;
cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
cfqq->service_tree = NULL;
}
left = 1;
parent = NULL;
cfqq->service_tree = service_tree;
p = &service_tree->rb.rb_node;
while (*p) {
struct rb_node **n;
parent = *p;
__cfqq = rb_entry(parent, struct cfq_queue, rb_node);
/*
* sort by key, that represents service time.
*/
if (time_before(rb_key, __cfqq->rb_key))
n = &(*p)->rb_left;
else {
n = &(*p)->rb_right;
left = 0;
}
p = n;
}
if (left)
service_tree->left = &cfqq->rb_node;
cfqq->rb_key = rb_key;
rb_link_node(&cfqq->rb_node, parent, p);
rb_insert_color(&cfqq->rb_node, &service_tree->rb);
service_tree->count++;
if (add_front || !new_cfqq)
return;
cfq_group_notify_queue_add(cfqd, cfqq->cfqg);
}
static struct cfq_queue *
cfq_prio_tree_lookup(struct cfq_data *cfqd, struct rb_root *root,
sector_t sector, struct rb_node **ret_parent,
struct rb_node ***rb_link)
{
struct rb_node **p, *parent;
struct cfq_queue *cfqq = NULL;
parent = NULL;
p = &root->rb_node;
while (*p) {
struct rb_node **n;
parent = *p;
cfqq = rb_entry(parent, struct cfq_queue, p_node);
/*
* Sort strictly based on sector. Smallest to the left,
* largest to the right.
*/
if (sector > blk_rq_pos(cfqq->next_rq))
n = &(*p)->rb_right;
else if (sector < blk_rq_pos(cfqq->next_rq))
n = &(*p)->rb_left;
else
break;
p = n;
cfqq = NULL;
}
*ret_parent = parent;
if (rb_link)
*rb_link = p;
return cfqq;
}
static void cfq_prio_tree_add(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
struct rb_node **p, *parent;
struct cfq_queue *__cfqq;
if (cfqq->p_root) {
rb_erase(&cfqq->p_node, cfqq->p_root);
cfqq->p_root = NULL;
}
if (cfq_class_idle(cfqq))
return;
if (!cfqq->next_rq)
return;
cfqq->p_root = &cfqd->prio_trees[cfqq->org_ioprio];
__cfqq = cfq_prio_tree_lookup(cfqd, cfqq->p_root,
blk_rq_pos(cfqq->next_rq), &parent, &p);
if (!__cfqq) {
rb_link_node(&cfqq->p_node, parent, p);
rb_insert_color(&cfqq->p_node, cfqq->p_root);
} else
cfqq->p_root = NULL;
}
/*
* Update cfqq's position in the service tree.
*/
static void cfq_resort_rr_list(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
/*
* Resorting requires the cfqq to be on the RR list already.
*/
if (cfq_cfqq_on_rr(cfqq)) {
cfq_service_tree_add(cfqd, cfqq, 0);
cfq_prio_tree_add(cfqd, cfqq);
}
}
/*
* add to busy list of queues for service, trying to be fair in ordering
* the pending list according to last request service
*/
static void cfq_add_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
cfq_log_cfqq(cfqd, cfqq, "add_to_rr");
BUG_ON(cfq_cfqq_on_rr(cfqq));
cfq_mark_cfqq_on_rr(cfqq);
cfqd->busy_queues++;
if (cfq_cfqq_sync(cfqq))
cfqd->busy_sync_queues++;
cfq_resort_rr_list(cfqd, cfqq);
}
/*
* Called when the cfqq no longer has requests pending, remove it from
* the service tree.
*/
static void cfq_del_cfqq_rr(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
cfq_log_cfqq(cfqd, cfqq, "del_from_rr");
BUG_ON(!cfq_cfqq_on_rr(cfqq));
cfq_clear_cfqq_on_rr(cfqq);
if (!RB_EMPTY_NODE(&cfqq->rb_node)) {
cfq_rb_erase(&cfqq->rb_node, cfqq->service_tree);
cfqq->service_tree = NULL;
}
if (cfqq->p_root) {
rb_erase(&cfqq->p_node, cfqq->p_root);
cfqq->p_root = NULL;
}
cfq_group_notify_queue_del(cfqd, cfqq->cfqg);
BUG_ON(!cfqd->busy_queues);
cfqd->busy_queues--;
if (cfq_cfqq_sync(cfqq))
cfqd->busy_sync_queues--;
}
/*
* rb tree support functions
*/
static void cfq_del_rq_rb(struct request *rq)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
const int sync = rq_is_sync(rq);
BUG_ON(!cfqq->queued[sync]);
cfqq->queued[sync]--;
elv_rb_del(&cfqq->sort_list, rq);
if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list)) {
/*
* Queue will be deleted from service tree when we actually
* expire it later. Right now just remove it from prio tree
* as it is empty.
*/
if (cfqq->p_root) {
rb_erase(&cfqq->p_node, cfqq->p_root);
cfqq->p_root = NULL;
}
}
}
static void cfq_add_rq_rb(struct request *rq)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
struct cfq_data *cfqd = cfqq->cfqd;
struct request *prev;
cfqq->queued[rq_is_sync(rq)]++;
elv_rb_add(&cfqq->sort_list, rq);
if (!cfq_cfqq_on_rr(cfqq))
cfq_add_cfqq_rr(cfqd, cfqq);
/*
* check if this request is a better next-serve candidate
*/
prev = cfqq->next_rq;
cfqq->next_rq = cfq_choose_req(cfqd, cfqq->next_rq, rq, cfqd->last_position);
/*
* adjust priority tree position, if ->next_rq changes
*/
if (prev != cfqq->next_rq)
cfq_prio_tree_add(cfqd, cfqq);
BUG_ON(!cfqq->next_rq);
}
static void cfq_reposition_rq_rb(struct cfq_queue *cfqq, struct request *rq)
{
elv_rb_del(&cfqq->sort_list, rq);
cfqq->queued[rq_is_sync(rq)]--;
cfq_blkiocg_update_io_remove_stats(&(RQ_CFQG(rq))->blkg,
rq_data_dir(rq), rq_is_sync(rq));
cfq_add_rq_rb(rq);
cfq_blkiocg_update_io_add_stats(&(RQ_CFQG(rq))->blkg,
&cfqq->cfqd->serving_group->blkg, rq_data_dir(rq),
rq_is_sync(rq));
}
static struct request *
cfq_find_rq_fmerge(struct cfq_data *cfqd, struct bio *bio)
{
struct task_struct *tsk = current;
struct cfq_io_cq *cic;
struct cfq_queue *cfqq;
cic = cfq_cic_lookup(cfqd, tsk->io_context);
if (!cic)
return NULL;
cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
if (cfqq) {
sector_t sector = bio->bi_sector + bio_sectors(bio);
return elv_rb_find(&cfqq->sort_list, sector);
}
return NULL;
}
static void cfq_activate_request(struct request_queue *q, struct request *rq)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
cfqd->rq_in_driver++;
cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "activate rq, drv=%d",
cfqd->rq_in_driver);
cfqd->last_position = blk_rq_pos(rq) + blk_rq_sectors(rq);
}
static void cfq_deactivate_request(struct request_queue *q, struct request *rq)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
WARN_ON(!cfqd->rq_in_driver);
cfqd->rq_in_driver--;
cfq_log_cfqq(cfqd, RQ_CFQQ(rq), "deactivate rq, drv=%d",
cfqd->rq_in_driver);
}
static void cfq_remove_request(struct request *rq)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
if (cfqq->next_rq == rq)
cfqq->next_rq = cfq_find_next_rq(cfqq->cfqd, cfqq, rq);
list_del_init(&rq->queuelist);
cfq_del_rq_rb(rq);
cfqq->cfqd->rq_queued--;
cfq_blkiocg_update_io_remove_stats(&(RQ_CFQG(rq))->blkg,
rq_data_dir(rq), rq_is_sync(rq));
if (rq->cmd_flags & REQ_PRIO) {
WARN_ON(!cfqq->prio_pending);
cfqq->prio_pending--;
}
}
static int cfq_merge(struct request_queue *q, struct request **req,
struct bio *bio)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct request *__rq;
__rq = cfq_find_rq_fmerge(cfqd, bio);
if (__rq && elv_rq_merge_ok(__rq, bio)) {
*req = __rq;
return ELEVATOR_FRONT_MERGE;
}
return ELEVATOR_NO_MERGE;
}
static void cfq_merged_request(struct request_queue *q, struct request *req,
int type)
{
if (type == ELEVATOR_FRONT_MERGE) {
struct cfq_queue *cfqq = RQ_CFQQ(req);
cfq_reposition_rq_rb(cfqq, req);
}
}
static void cfq_bio_merged(struct request_queue *q, struct request *req,
struct bio *bio)
{
cfq_blkiocg_update_io_merged_stats(&(RQ_CFQG(req))->blkg,
bio_data_dir(bio), cfq_bio_sync(bio));
}
static void
cfq_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
struct cfq_data *cfqd = q->elevator->elevator_data;
/*
* reposition in fifo if next is older than rq
*/
if (!list_empty(&rq->queuelist) && !list_empty(&next->queuelist) &&
time_before(rq_fifo_time(next), rq_fifo_time(rq))) {
list_move(&rq->queuelist, &next->queuelist);
rq_set_fifo_time(rq, rq_fifo_time(next));
}
if (cfqq->next_rq == next)
cfqq->next_rq = rq;
cfq_remove_request(next);
cfq_blkiocg_update_io_merged_stats(&(RQ_CFQG(rq))->blkg,
rq_data_dir(next), rq_is_sync(next));
cfqq = RQ_CFQQ(next);
/*
* all requests of this queue are merged to other queues, delete it
* from the service tree. If it's the active_queue,
* cfq_dispatch_requests() will choose to expire it or do idle
*/
if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list) &&
cfqq != cfqd->active_queue)
cfq_del_cfqq_rr(cfqd, cfqq);
}
static int cfq_allow_merge(struct request_queue *q, struct request *rq,
struct bio *bio)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct cfq_io_cq *cic;
struct cfq_queue *cfqq;
/*
* Disallow merge of a sync bio into an async request.
*/
if (cfq_bio_sync(bio) && !rq_is_sync(rq))
return false;
/*
* Lookup the cfqq that this bio will be queued with and allow
* merge only if rq is queued there.
*/
cic = cfq_cic_lookup(cfqd, current->io_context);
if (!cic)
return false;
cfqq = cic_to_cfqq(cic, cfq_bio_sync(bio));
return cfqq == RQ_CFQQ(rq);
}
static inline void cfq_del_timer(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
del_timer(&cfqd->idle_slice_timer);
cfq_blkiocg_update_idle_time_stats(&cfqq->cfqg->blkg);
}
static void __cfq_set_active_queue(struct cfq_data *cfqd,
struct cfq_queue *cfqq)
{
if (cfqq) {
cfq_log_cfqq(cfqd, cfqq, "set_active wl_prio:%d wl_type:%d",
cfqd->serving_prio, cfqd->serving_type);
cfq_blkiocg_update_avg_queue_size_stats(&cfqq->cfqg->blkg);
cfqq->slice_start = 0;
cfqq->dispatch_start = jiffies;
cfqq->allocated_slice = 0;
cfqq->slice_end = 0;
cfqq->slice_dispatch = 0;
cfqq->nr_sectors = 0;
cfq_clear_cfqq_wait_request(cfqq);
cfq_clear_cfqq_must_dispatch(cfqq);
cfq_clear_cfqq_must_alloc_slice(cfqq);
cfq_clear_cfqq_fifo_expire(cfqq);
cfq_mark_cfqq_slice_new(cfqq);
cfq_del_timer(cfqd, cfqq);
}
cfqd->active_queue = cfqq;
}
/*
* current cfqq expired its slice (or was too idle), select new one
*/
static void
__cfq_slice_expired(struct cfq_data *cfqd, struct cfq_queue *cfqq,
bool timed_out)
{
cfq_log_cfqq(cfqd, cfqq, "slice expired t=%d", timed_out);
if (cfq_cfqq_wait_request(cfqq))
cfq_del_timer(cfqd, cfqq);
cfq_clear_cfqq_wait_request(cfqq);
cfq_clear_cfqq_wait_busy(cfqq);
/*
* If this cfqq is shared between multiple processes, check to
* make sure that those processes are still issuing I/Os within
* the mean seek distance. If not, it may be time to break the
* queues apart again.
*/
if (cfq_cfqq_coop(cfqq) && CFQQ_SEEKY(cfqq))
cfq_mark_cfqq_split_coop(cfqq);
/*
* store what was left of this slice, if the queue idled/timed out
*/
if (timed_out) {
if (cfq_cfqq_slice_new(cfqq))
cfqq->slice_resid = cfq_scaled_cfqq_slice(cfqd, cfqq);
else
cfqq->slice_resid = cfqq->slice_end - jiffies;
cfq_log_cfqq(cfqd, cfqq, "resid=%ld", cfqq->slice_resid);
}
cfq_group_served(cfqd, cfqq->cfqg, cfqq);
if (cfq_cfqq_on_rr(cfqq) && RB_EMPTY_ROOT(&cfqq->sort_list))
cfq_del_cfqq_rr(cfqd, cfqq);
cfq_resort_rr_list(cfqd, cfqq);
if (cfqq == cfqd->active_queue)
cfqd->active_queue = NULL;
if (cfqd->active_cic) {
put_io_context(cfqd->active_cic->icq.ioc);
cfqd->active_cic = NULL;
}
}
static inline void cfq_slice_expired(struct cfq_data *cfqd, bool timed_out)
{
struct cfq_queue *cfqq = cfqd->active_queue;
if (cfqq)
__cfq_slice_expired(cfqd, cfqq, timed_out);
}
/*
* Get next queue for service. Unless we have a queue preemption,
* we'll simply select the first cfqq in the service tree.
*/
static struct cfq_queue *cfq_get_next_queue(struct cfq_data *cfqd)
{
struct cfq_rb_root *service_tree =
service_tree_for(cfqd->serving_group, cfqd->serving_prio,
cfqd->serving_type);
if (!cfqd->rq_queued)
return NULL;
/* There is nothing to dispatch */
if (!service_tree)
return NULL;
if (RB_EMPTY_ROOT(&service_tree->rb))
return NULL;
return cfq_rb_first(service_tree);
}
static struct cfq_queue *cfq_get_next_queue_forced(struct cfq_data *cfqd)
{
struct cfq_group *cfqg;
struct cfq_queue *cfqq;
int i, j;
struct cfq_rb_root *st;
if (!cfqd->rq_queued)
return NULL;
cfqg = cfq_get_next_cfqg(cfqd);
if (!cfqg)
return NULL;
for_each_cfqg_st(cfqg, i, j, st)
if ((cfqq = cfq_rb_first(st)) != NULL)
return cfqq;
return NULL;
}
/*
* Get and set a new active queue for service.
*/
static struct cfq_queue *cfq_set_active_queue(struct cfq_data *cfqd,
struct cfq_queue *cfqq)
{
if (!cfqq)
cfqq = cfq_get_next_queue(cfqd);
__cfq_set_active_queue(cfqd, cfqq);
return cfqq;
}
static inline sector_t cfq_dist_from_last(struct cfq_data *cfqd,
struct request *rq)
{
if (blk_rq_pos(rq) >= cfqd->last_position)
return blk_rq_pos(rq) - cfqd->last_position;
else
return cfqd->last_position - blk_rq_pos(rq);
}
static inline int cfq_rq_close(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct request *rq)
{
return cfq_dist_from_last(cfqd, rq) <= CFQQ_CLOSE_THR;
}
static struct cfq_queue *cfqq_close(struct cfq_data *cfqd,
struct cfq_queue *cur_cfqq)
{
struct rb_root *root = &cfqd->prio_trees[cur_cfqq->org_ioprio];
struct rb_node *parent, *node;
struct cfq_queue *__cfqq;
sector_t sector = cfqd->last_position;
if (RB_EMPTY_ROOT(root))
return NULL;
/*
* First, if we find a request starting at the end of the last
* request, choose it.
*/
__cfqq = cfq_prio_tree_lookup(cfqd, root, sector, &parent, NULL);
if (__cfqq)
return __cfqq;
/*
* If the exact sector wasn't found, the parent of the NULL leaf
* will contain the closest sector.
*/
__cfqq = rb_entry(parent, struct cfq_queue, p_node);
if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
return __cfqq;
if (blk_rq_pos(__cfqq->next_rq) < sector)
node = rb_next(&__cfqq->p_node);
else
node = rb_prev(&__cfqq->p_node);
if (!node)
return NULL;
__cfqq = rb_entry(node, struct cfq_queue, p_node);
if (cfq_rq_close(cfqd, cur_cfqq, __cfqq->next_rq))
return __cfqq;
return NULL;
}
/*
* cfqd - obvious
* cur_cfqq - passed in so that we don't decide that the current queue is
* closely cooperating with itself.
*
* So, basically we're assuming that that cur_cfqq has dispatched at least
* one request, and that cfqd->last_position reflects a position on the disk
* associated with the I/O issued by cur_cfqq. I'm not sure this is a valid
* assumption.
*/
static struct cfq_queue *cfq_close_cooperator(struct cfq_data *cfqd,
struct cfq_queue *cur_cfqq)
{
struct cfq_queue *cfqq;
if (cfq_class_idle(cur_cfqq))
return NULL;
if (!cfq_cfqq_sync(cur_cfqq))
return NULL;
if (CFQQ_SEEKY(cur_cfqq))
return NULL;
/*
* Don't search priority tree if it's the only queue in the group.
*/
if (cur_cfqq->cfqg->nr_cfqq == 1)
return NULL;
/*
* We should notice if some of the queues are cooperating, eg
* working closely on the same area of the disk. In that case,
* we can group them together and don't waste time idling.
*/
cfqq = cfqq_close(cfqd, cur_cfqq);
if (!cfqq)
return NULL;
/* If new queue belongs to different cfq_group, don't choose it */
if (cur_cfqq->cfqg != cfqq->cfqg)
return NULL;
/*
* It only makes sense to merge sync queues.
*/
if (!cfq_cfqq_sync(cfqq))
return NULL;
if (CFQQ_SEEKY(cfqq))
return NULL;
/*
* Do not merge queues of different priority classes
*/
if (cfq_class_rt(cfqq) != cfq_class_rt(cur_cfqq))
return NULL;
return cfqq;
}
/*
* Determine whether we should enforce idle window for this queue.
*/
static bool cfq_should_idle(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
enum wl_prio_t prio = cfqq_prio(cfqq);
struct cfq_rb_root *service_tree = cfqq->service_tree;
BUG_ON(!service_tree);
BUG_ON(!service_tree->count);
if (!cfqd->cfq_slice_idle)
return false;
/* We never do for idle class queues. */
if (prio == IDLE_WORKLOAD)
return false;
/* We do for queues that were marked with idle window flag. */
if (cfq_cfqq_idle_window(cfqq) &&
!(blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag))
return true;
/*
* Otherwise, we do only if they are the last ones
* in their service tree.
*/
if (service_tree->count == 1 && cfq_cfqq_sync(cfqq) &&
!cfq_io_thinktime_big(cfqd, &service_tree->ttime, false))
return true;
cfq_log_cfqq(cfqd, cfqq, "Not idling. st->count:%d",
service_tree->count);
return false;
}
static void cfq_arm_slice_timer(struct cfq_data *cfqd)
{
struct cfq_queue *cfqq = cfqd->active_queue;
struct cfq_io_cq *cic;
unsigned long sl, group_idle = 0;
/*
* SSD device without seek penalty, disable idling. But only do so
* for devices that support queuing, otherwise we still have a problem
* with sync vs async workloads.
*/
if (blk_queue_nonrot(cfqd->queue) && cfqd->hw_tag)
return;
WARN_ON(!RB_EMPTY_ROOT(&cfqq->sort_list));
WARN_ON(cfq_cfqq_slice_new(cfqq));
/*
* idle is disabled, either manually or by past process history
*/
if (!cfq_should_idle(cfqd, cfqq)) {
/* no queue idling. Check for group idling */
if (cfqd->cfq_group_idle)
group_idle = cfqd->cfq_group_idle;
else
return;
}
/*
* still active requests from this queue, don't idle
*/
if (cfqq->dispatched)
return;
/*
* task has exited, don't wait
*/
cic = cfqd->active_cic;
if (!cic || !atomic_read(&cic->icq.ioc->nr_tasks))
return;
/*
* If our average think time is larger than the remaining time
* slice, then don't idle. This avoids overrunning the allotted
* time slice.
*/
if (sample_valid(cic->ttime.ttime_samples) &&
(cfqq->slice_end - jiffies < cic->ttime.ttime_mean)) {
cfq_log_cfqq(cfqd, cfqq, "Not idling. think_time:%lu",
cic->ttime.ttime_mean);
return;
}
/* There are other queues in the group, don't do group idle */
if (group_idle && cfqq->cfqg->nr_cfqq > 1)
return;
cfq_mark_cfqq_wait_request(cfqq);
if (group_idle)
sl = cfqd->cfq_group_idle;
else
sl = cfqd->cfq_slice_idle;
mod_timer(&cfqd->idle_slice_timer, jiffies + sl);
cfq_blkiocg_update_set_idle_time_stats(&cfqq->cfqg->blkg);
cfq_log_cfqq(cfqd, cfqq, "arm_idle: %lu group_idle: %d", sl,
group_idle ? 1 : 0);
}
/*
* Move request from internal lists to the request queue dispatch list.
*/
static void cfq_dispatch_insert(struct request_queue *q, struct request *rq)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct cfq_queue *cfqq = RQ_CFQQ(rq);
cfq_log_cfqq(cfqd, cfqq, "dispatch_insert");
cfqq->next_rq = cfq_find_next_rq(cfqd, cfqq, rq);
cfq_remove_request(rq);
cfqq->dispatched++;
(RQ_CFQG(rq))->dispatched++;
elv_dispatch_sort(q, rq);
cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]++;
cfqq->nr_sectors += blk_rq_sectors(rq);
cfq_blkiocg_update_dispatch_stats(&cfqq->cfqg->blkg, blk_rq_bytes(rq),
rq_data_dir(rq), rq_is_sync(rq));
}
/*
* return expired entry, or NULL to just start from scratch in rbtree
*/
static struct request *cfq_check_fifo(struct cfq_queue *cfqq)
{
struct request *rq = NULL;
if (cfq_cfqq_fifo_expire(cfqq))
return NULL;
cfq_mark_cfqq_fifo_expire(cfqq);
if (list_empty(&cfqq->fifo))
return NULL;
rq = rq_entry_fifo(cfqq->fifo.next);
if (time_before(jiffies, rq_fifo_time(rq)))
rq = NULL;
cfq_log_cfqq(cfqq->cfqd, cfqq, "fifo=%p", rq);
return rq;
}
static inline int
cfq_prio_to_maxrq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
const int base_rq = cfqd->cfq_slice_async_rq;
WARN_ON(cfqq->ioprio >= IOPRIO_BE_NR);
return 2 * base_rq * (IOPRIO_BE_NR - cfqq->ioprio);
}
/*
* Must be called with the queue_lock held.
*/
static int cfqq_process_refs(struct cfq_queue *cfqq)
{
int process_refs, io_refs;
io_refs = cfqq->allocated[READ] + cfqq->allocated[WRITE];
process_refs = cfqq->ref - io_refs;
BUG_ON(process_refs < 0);
return process_refs;
}
static void cfq_setup_merge(struct cfq_queue *cfqq, struct cfq_queue *new_cfqq)
{
int process_refs, new_process_refs;
struct cfq_queue *__cfqq;
/*
* If there are no process references on the new_cfqq, then it is
* unsafe to follow the ->new_cfqq chain as other cfqq's in the
* chain may have dropped their last reference (not just their
* last process reference).
*/
if (!cfqq_process_refs(new_cfqq))
return;
/* Avoid a circular list and skip interim queue merges */
while ((__cfqq = new_cfqq->new_cfqq)) {
if (__cfqq == cfqq)
return;
new_cfqq = __cfqq;
}
process_refs = cfqq_process_refs(cfqq);
new_process_refs = cfqq_process_refs(new_cfqq);
/*
* If the process for the cfqq has gone away, there is no
* sense in merging the queues.
*/
if (process_refs == 0 || new_process_refs == 0)
return;
/*
* Merge in the direction of the lesser amount of work.
*/
if (new_process_refs >= process_refs) {
cfqq->new_cfqq = new_cfqq;
new_cfqq->ref += process_refs;
} else {
new_cfqq->new_cfqq = cfqq;
cfqq->ref += new_process_refs;
}
}
static enum wl_type_t cfq_choose_wl(struct cfq_data *cfqd,
struct cfq_group *cfqg, enum wl_prio_t prio)
{
struct cfq_queue *queue;
int i;
bool key_valid = false;
unsigned long lowest_key = 0;
enum wl_type_t cur_best = SYNC_NOIDLE_WORKLOAD;
for (i = 0; i <= SYNC_WORKLOAD; ++i) {
/* select the one with lowest rb_key */
queue = cfq_rb_first(service_tree_for(cfqg, prio, i));
if (queue &&
(!key_valid || time_before(queue->rb_key, lowest_key))) {
lowest_key = queue->rb_key;
cur_best = i;
key_valid = true;
}
}
return cur_best;
}
static void choose_service_tree(struct cfq_data *cfqd, struct cfq_group *cfqg)
{
unsigned slice;
unsigned count;
struct cfq_rb_root *st;
unsigned group_slice;
enum wl_prio_t original_prio = cfqd->serving_prio;
/* Choose next priority. RT > BE > IDLE */
if (cfq_group_busy_queues_wl(RT_WORKLOAD, cfqd, cfqg))
cfqd->serving_prio = RT_WORKLOAD;
else if (cfq_group_busy_queues_wl(BE_WORKLOAD, cfqd, cfqg))
cfqd->serving_prio = BE_WORKLOAD;
else {
cfqd->serving_prio = IDLE_WORKLOAD;
cfqd->workload_expires = jiffies + 1;
return;
}
if (original_prio != cfqd->serving_prio)
goto new_workload;
/*
* For RT and BE, we have to choose also the type
* (SYNC, SYNC_NOIDLE, ASYNC), and to compute a workload
* expiration time
*/
st = service_tree_for(cfqg, cfqd->serving_prio, cfqd->serving_type);
count = st->count;
/*
* check workload expiration, and that we still have other queues ready
*/
if (count && !time_after(jiffies, cfqd->workload_expires))
return;
new_workload:
/* otherwise select new workload type */
cfqd->serving_type =
cfq_choose_wl(cfqd, cfqg, cfqd->serving_prio);
st = service_tree_for(cfqg, cfqd->serving_prio, cfqd->serving_type);
count = st->count;
/*
* the workload slice is computed as a fraction of target latency
* proportional to the number of queues in that workload, over
* all the queues in the same priority class
*/
group_slice = cfq_group_slice(cfqd, cfqg);
slice = group_slice * count /
max_t(unsigned, cfqg->busy_queues_avg[cfqd->serving_prio],
cfq_group_busy_queues_wl(cfqd->serving_prio, cfqd, cfqg));
if (cfqd->serving_type == ASYNC_WORKLOAD) {
unsigned int tmp;
/*
* Async queues are currently system wide. Just taking
* proportion of queues with-in same group will lead to higher
* async ratio system wide as generally root group is going
* to have higher weight. A more accurate thing would be to
* calculate system wide asnc/sync ratio.
*/
tmp = cfq_target_latency * cfqg_busy_async_queues(cfqd, cfqg);
tmp = tmp/cfqd->busy_queues;
slice = min_t(unsigned, slice, tmp);
/* async workload slice is scaled down according to
* the sync/async slice ratio. */
slice = slice * cfqd->cfq_slice[0] / cfqd->cfq_slice[1];
} else
/* sync workload slice is at least 2 * cfq_slice_idle */
slice = max(slice, 2 * cfqd->cfq_slice_idle);
slice = max_t(unsigned, slice, CFQ_MIN_TT);
cfq_log(cfqd, "workload slice:%d", slice);
cfqd->workload_expires = jiffies + slice;
}
static struct cfq_group *cfq_get_next_cfqg(struct cfq_data *cfqd)
{
struct cfq_rb_root *st = &cfqd->grp_service_tree;
struct cfq_group *cfqg;
if (RB_EMPTY_ROOT(&st->rb))
return NULL;
cfqg = cfq_rb_first_group(st);
update_min_vdisktime(st);
return cfqg;
}
static void cfq_choose_cfqg(struct cfq_data *cfqd)
{
struct cfq_group *cfqg = cfq_get_next_cfqg(cfqd);
cfqd->serving_group = cfqg;
/* Restore the workload type data */
if (cfqg->saved_workload_slice) {
cfqd->workload_expires = jiffies + cfqg->saved_workload_slice;
cfqd->serving_type = cfqg->saved_workload;
cfqd->serving_prio = cfqg->saved_serving_prio;
} else
cfqd->workload_expires = jiffies - 1;
choose_service_tree(cfqd, cfqg);
}
/*
* Select a queue for service. If we have a current active queue,
* check whether to continue servicing it, or retrieve and set a new one.
*/
static struct cfq_queue *cfq_select_queue(struct cfq_data *cfqd)
{
struct cfq_queue *cfqq, *new_cfqq = NULL;
cfqq = cfqd->active_queue;
if (!cfqq)
goto new_queue;
if (!cfqd->rq_queued)
return NULL;
/*
* We were waiting for group to get backlogged. Expire the queue
*/
if (cfq_cfqq_wait_busy(cfqq) && !RB_EMPTY_ROOT(&cfqq->sort_list))
goto expire;
/*
* The active queue has run out of time, expire it and select new.
*/
if (cfq_slice_used(cfqq) && !cfq_cfqq_must_dispatch(cfqq)) {
/*
* If slice had not expired at the completion of last request
* we might not have turned on wait_busy flag. Don't expire
* the queue yet. Allow the group to get backlogged.
*
* The very fact that we have used the slice, that means we
* have been idling all along on this queue and it should be
* ok to wait for this request to complete.
*/
if (cfqq->cfqg->nr_cfqq == 1 && RB_EMPTY_ROOT(&cfqq->sort_list)
&& cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
cfqq = NULL;
goto keep_queue;
} else
goto check_group_idle;
}
/*
* The active queue has requests and isn't expired, allow it to
* dispatch.
*/
if (!RB_EMPTY_ROOT(&cfqq->sort_list))
goto keep_queue;
/*
* If another queue has a request waiting within our mean seek
* distance, let it run. The expire code will check for close
* cooperators and put the close queue at the front of the service
* tree. If possible, merge the expiring queue with the new cfqq.
*/
new_cfqq = cfq_close_cooperator(cfqd, cfqq);
if (new_cfqq) {
if (!cfqq->new_cfqq)
cfq_setup_merge(cfqq, new_cfqq);
goto expire;
}
/*
* No requests pending. If the active queue still has requests in
* flight or is idling for a new request, allow either of these
* conditions to happen (or time out) before selecting a new queue.
*/
if (timer_pending(&cfqd->idle_slice_timer)) {
cfqq = NULL;
goto keep_queue;
}
/*
* This is a deep seek queue, but the device is much faster than
* the queue can deliver, don't idle
**/
if (CFQQ_SEEKY(cfqq) && cfq_cfqq_idle_window(cfqq) &&
(cfq_cfqq_slice_new(cfqq) ||
(cfqq->slice_end - jiffies > jiffies - cfqq->slice_start))) {
cfq_clear_cfqq_deep(cfqq);
cfq_clear_cfqq_idle_window(cfqq);
}
if (cfqq->dispatched && cfq_should_idle(cfqd, cfqq)) {
cfqq = NULL;
goto keep_queue;
}
/*
* If group idle is enabled and there are requests dispatched from
* this group, wait for requests to complete.
*/
check_group_idle:
if (cfqd->cfq_group_idle && cfqq->cfqg->nr_cfqq == 1 &&
cfqq->cfqg->dispatched &&
!cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true)) {
cfqq = NULL;
goto keep_queue;
}
expire:
cfq_slice_expired(cfqd, 0);
new_queue:
/*
* Current queue expired. Check if we have to switch to a new
* service tree
*/
if (!new_cfqq)
cfq_choose_cfqg(cfqd);
cfqq = cfq_set_active_queue(cfqd, new_cfqq);
keep_queue:
return cfqq;
}
static int __cfq_forced_dispatch_cfqq(struct cfq_queue *cfqq)
{
int dispatched = 0;
while (cfqq->next_rq) {
cfq_dispatch_insert(cfqq->cfqd->queue, cfqq->next_rq);
dispatched++;
}
BUG_ON(!list_empty(&cfqq->fifo));
/* By default cfqq is not expired if it is empty. Do it explicitly */
__cfq_slice_expired(cfqq->cfqd, cfqq, 0);
return dispatched;
}
/*
* Drain our current requests. Used for barriers and when switching
* io schedulers on-the-fly.
*/
static int cfq_forced_dispatch(struct cfq_data *cfqd)
{
struct cfq_queue *cfqq;
int dispatched = 0;
/* Expire the timeslice of the current active queue first */
cfq_slice_expired(cfqd, 0);
while ((cfqq = cfq_get_next_queue_forced(cfqd)) != NULL) {
__cfq_set_active_queue(cfqd, cfqq);
dispatched += __cfq_forced_dispatch_cfqq(cfqq);
}
BUG_ON(cfqd->busy_queues);
cfq_log(cfqd, "forced_dispatch=%d", dispatched);
return dispatched;
}
static inline bool cfq_slice_used_soon(struct cfq_data *cfqd,
struct cfq_queue *cfqq)
{
/* the queue hasn't finished any request, can't estimate */
if (cfq_cfqq_slice_new(cfqq))
return true;
if (time_after(jiffies + cfqd->cfq_slice_idle * cfqq->dispatched,
cfqq->slice_end))
return true;
return false;
}
static bool cfq_may_dispatch(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
unsigned int max_dispatch;
/*
* Drain async requests before we start sync IO
*/
if (cfq_should_idle(cfqd, cfqq) && cfqd->rq_in_flight[BLK_RW_ASYNC])
return false;
/*
* If this is an async queue and we have sync IO in flight, let it wait
*/
if (cfqd->rq_in_flight[BLK_RW_SYNC] && !cfq_cfqq_sync(cfqq))
return false;
max_dispatch = max_t(unsigned int, cfqd->cfq_quantum / 2, 1);
if (cfq_class_idle(cfqq))
max_dispatch = 1;
/*
* Does this cfqq already have too much IO in flight?
*/
if (cfqq->dispatched >= max_dispatch) {
bool promote_sync = false;
/*
* idle queue must always only have a single IO in flight
*/
if (cfq_class_idle(cfqq))
return false;
/*
* If there is only one sync queue
* we can ignore async queue here and give the sync
* queue no dispatch limit. The reason is a sync queue can
* preempt async queue, limiting the sync queue doesn't make
* sense. This is useful for aiostress test.
*/
if (cfq_cfqq_sync(cfqq) && cfqd->busy_sync_queues == 1)
promote_sync = true;
/*
* We have other queues, don't allow more IO from this one
*/
if (cfqd->busy_queues > 1 && cfq_slice_used_soon(cfqd, cfqq) &&
!promote_sync)
return false;
/*
* Sole queue user, no limit
*/
if (cfqd->busy_queues == 1 || promote_sync)
max_dispatch = -1;
else
/*
* Normally we start throttling cfqq when cfq_quantum/2
* requests have been dispatched. But we can drive
* deeper queue depths at the beginning of slice
* subjected to upper limit of cfq_quantum.
* */
max_dispatch = cfqd->cfq_quantum;
}
/*
* Async queues must wait a bit before being allowed dispatch.
* We also ramp up the dispatch depth gradually for async IO,
* based on the last sync IO we serviced
*/
if (!cfq_cfqq_sync(cfqq) && cfqd->cfq_latency) {
unsigned long last_sync = jiffies - cfqd->last_delayed_sync;
unsigned int depth;
depth = last_sync / cfqd->cfq_slice[1];
if (!depth && !cfqq->dispatched)
depth = 1;
if (depth < max_dispatch)
max_dispatch = depth;
}
/*
* If we're below the current max, allow a dispatch
*/
return cfqq->dispatched < max_dispatch;
}
/*
* Dispatch a request from cfqq, moving them to the request queue
* dispatch list.
*/
static bool cfq_dispatch_request(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
struct request *rq;
BUG_ON(RB_EMPTY_ROOT(&cfqq->sort_list));
if (!cfq_may_dispatch(cfqd, cfqq))
return false;
/*
* follow expired path, else get first next available
*/
rq = cfq_check_fifo(cfqq);
if (!rq)
rq = cfqq->next_rq;
/*
* insert request into driver dispatch list
*/
cfq_dispatch_insert(cfqd->queue, rq);
if (!cfqd->active_cic) {
struct cfq_io_cq *cic = RQ_CIC(rq);
atomic_long_inc(&cic->icq.ioc->refcount);
cfqd->active_cic = cic;
}
return true;
}
/*
* Find the cfqq that we need to service and move a request from that to the
* dispatch list
*/
static int cfq_dispatch_requests(struct request_queue *q, int force)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct cfq_queue *cfqq;
if (!cfqd->busy_queues)
return 0;
if (unlikely(force))
return cfq_forced_dispatch(cfqd);
cfqq = cfq_select_queue(cfqd);
if (!cfqq)
return 0;
/*
* Dispatch a request from this cfqq, if it is allowed
*/
if (!cfq_dispatch_request(cfqd, cfqq))
return 0;
cfqq->slice_dispatch++;
cfq_clear_cfqq_must_dispatch(cfqq);
/*
* expire an async queue immediately if it has used up its slice. idle
* queue always expire after 1 dispatch round.
*/
if (cfqd->busy_queues > 1 && ((!cfq_cfqq_sync(cfqq) &&
cfqq->slice_dispatch >= cfq_prio_to_maxrq(cfqd, cfqq)) ||
cfq_class_idle(cfqq))) {
cfqq->slice_end = jiffies + 1;
cfq_slice_expired(cfqd, 0);
}
cfq_log_cfqq(cfqd, cfqq, "dispatched a request");
return 1;
}
/*
* task holds one reference to the queue, dropped when task exits. each rq
* in-flight on this queue also holds a reference, dropped when rq is freed.
*
* Each cfq queue took a reference on the parent group. Drop it now.
* queue lock must be held here.
*/
static void cfq_put_queue(struct cfq_queue *cfqq)
{
struct cfq_data *cfqd = cfqq->cfqd;
struct cfq_group *cfqg;
BUG_ON(cfqq->ref <= 0);
cfqq->ref--;
if (cfqq->ref)
return;
cfq_log_cfqq(cfqd, cfqq, "put_queue");
BUG_ON(rb_first(&cfqq->sort_list));
BUG_ON(cfqq->allocated[READ] + cfqq->allocated[WRITE]);
cfqg = cfqq->cfqg;
if (unlikely(cfqd->active_queue == cfqq)) {
__cfq_slice_expired(cfqd, cfqq, 0);
cfq_schedule_dispatch(cfqd);
}
BUG_ON(cfq_cfqq_on_rr(cfqq));
kmem_cache_free(cfq_pool, cfqq);
cfq_put_cfqg(cfqg);
}
static void cfq_put_cooperator(struct cfq_queue *cfqq)
{
struct cfq_queue *__cfqq, *next;
/*
* If this queue was scheduled to merge with another queue, be
* sure to drop the reference taken on that queue (and others in
* the merge chain). See cfq_setup_merge and cfq_merge_cfqqs.
*/
__cfqq = cfqq->new_cfqq;
while (__cfqq) {
if (__cfqq == cfqq) {
WARN(1, "cfqq->new_cfqq loop detected\n");
break;
}
next = __cfqq->new_cfqq;
cfq_put_queue(__cfqq);
__cfqq = next;
}
}
static void cfq_exit_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
if (unlikely(cfqq == cfqd->active_queue)) {
__cfq_slice_expired(cfqd, cfqq, 0);
cfq_schedule_dispatch(cfqd);
}
cfq_put_cooperator(cfqq);
cfq_put_queue(cfqq);
}
static void cfq_init_icq(struct io_cq *icq)
{
struct cfq_io_cq *cic = icq_to_cic(icq);
cic->ttime.last_end_request = jiffies;
}
static void cfq_exit_icq(struct io_cq *icq)
{
struct cfq_io_cq *cic = icq_to_cic(icq);
struct cfq_data *cfqd = cic_to_cfqd(cic);
if (cic->cfqq[BLK_RW_ASYNC]) {
cfq_exit_cfqq(cfqd, cic->cfqq[BLK_RW_ASYNC]);
cic->cfqq[BLK_RW_ASYNC] = NULL;
}
if (cic->cfqq[BLK_RW_SYNC]) {
cfq_exit_cfqq(cfqd, cic->cfqq[BLK_RW_SYNC]);
cic->cfqq[BLK_RW_SYNC] = NULL;
}
}
static void cfq_init_prio_data(struct cfq_queue *cfqq, struct io_context *ioc)
{
struct task_struct *tsk = current;
int ioprio_class;
if (!cfq_cfqq_prio_changed(cfqq))
return;
ioprio_class = IOPRIO_PRIO_CLASS(ioc->ioprio);
switch (ioprio_class) {
default:
printk(KERN_ERR "cfq: bad prio %x\n", ioprio_class);
case IOPRIO_CLASS_NONE:
/*
* no prio set, inherit CPU scheduling settings
*/
cfqq->ioprio = task_nice_ioprio(tsk);
cfqq->ioprio_class = task_nice_ioclass(tsk);
break;
case IOPRIO_CLASS_RT:
cfqq->ioprio = task_ioprio(ioc);
cfqq->ioprio_class = IOPRIO_CLASS_RT;
break;
case IOPRIO_CLASS_BE:
cfqq->ioprio = task_ioprio(ioc);
cfqq->ioprio_class = IOPRIO_CLASS_BE;
break;
case IOPRIO_CLASS_IDLE:
cfqq->ioprio_class = IOPRIO_CLASS_IDLE;
cfqq->ioprio = 7;
cfq_clear_cfqq_idle_window(cfqq);
break;
}
/*
* keep track of original prio settings in case we have to temporarily
* elevate the priority of this queue
*/
cfqq->org_ioprio = cfqq->ioprio;
cfq_clear_cfqq_prio_changed(cfqq);
}
static void changed_ioprio(struct cfq_io_cq *cic)
{
struct cfq_data *cfqd = cic_to_cfqd(cic);
struct cfq_queue *cfqq;
if (unlikely(!cfqd))
return;
cfqq = cic->cfqq[BLK_RW_ASYNC];
if (cfqq) {
struct cfq_queue *new_cfqq;
new_cfqq = cfq_get_queue(cfqd, BLK_RW_ASYNC, cic->icq.ioc,
GFP_ATOMIC);
if (new_cfqq) {
cic->cfqq[BLK_RW_ASYNC] = new_cfqq;
cfq_put_queue(cfqq);
}
}
cfqq = cic->cfqq[BLK_RW_SYNC];
if (cfqq)
cfq_mark_cfqq_prio_changed(cfqq);
}
static void cfq_init_cfqq(struct cfq_data *cfqd, struct cfq_queue *cfqq,
pid_t pid, bool is_sync)
{
RB_CLEAR_NODE(&cfqq->rb_node);
RB_CLEAR_NODE(&cfqq->p_node);
INIT_LIST_HEAD(&cfqq->fifo);
cfqq->ref = 0;
cfqq->cfqd = cfqd;
cfq_mark_cfqq_prio_changed(cfqq);
if (is_sync) {
if (!cfq_class_idle(cfqq))
cfq_mark_cfqq_idle_window(cfqq);
cfq_mark_cfqq_sync(cfqq);
}
cfqq->pid = pid;
}
#ifdef CONFIG_CFQ_GROUP_IOSCHED
static void changed_cgroup(struct cfq_io_cq *cic)
{
struct cfq_queue *sync_cfqq = cic_to_cfqq(cic, 1);
struct cfq_data *cfqd = cic_to_cfqd(cic);
struct request_queue *q;
if (unlikely(!cfqd))
return;
q = cfqd->queue;
if (sync_cfqq) {
/*
* Drop reference to sync queue. A new sync queue will be
* assigned in new group upon arrival of a fresh request.
*/
cfq_log_cfqq(cfqd, sync_cfqq, "changed cgroup");
cic_set_cfqq(cic, NULL, 1);
cfq_put_queue(sync_cfqq);
}
}
#endif /* CONFIG_CFQ_GROUP_IOSCHED */
static struct cfq_queue *
cfq_find_alloc_queue(struct cfq_data *cfqd, bool is_sync,
struct io_context *ioc, gfp_t gfp_mask)
{
struct cfq_queue *cfqq, *new_cfqq = NULL;
struct cfq_io_cq *cic;
struct cfq_group *cfqg;
retry:
cfqg = cfq_get_cfqg(cfqd);
cic = cfq_cic_lookup(cfqd, ioc);
/* cic always exists here */
cfqq = cic_to_cfqq(cic, is_sync);
/*
* Always try a new alloc if we fell back to the OOM cfqq
* originally, since it should just be a temporary situation.
*/
if (!cfqq || cfqq == &cfqd->oom_cfqq) {
cfqq = NULL;
if (new_cfqq) {
cfqq = new_cfqq;
new_cfqq = NULL;
} else if (gfp_mask & __GFP_WAIT) {
spin_unlock_irq(cfqd->queue->queue_lock);
new_cfqq = kmem_cache_alloc_node(cfq_pool,
gfp_mask | __GFP_ZERO,
cfqd->queue->node);
spin_lock_irq(cfqd->queue->queue_lock);
if (new_cfqq)
goto retry;
} else {
cfqq = kmem_cache_alloc_node(cfq_pool,
gfp_mask | __GFP_ZERO,
cfqd->queue->node);
}
if (cfqq) {
cfq_init_cfqq(cfqd, cfqq, current->pid, is_sync);
cfq_init_prio_data(cfqq, ioc);
cfq_link_cfqq_cfqg(cfqq, cfqg);
cfq_log_cfqq(cfqd, cfqq, "alloced");
} else
cfqq = &cfqd->oom_cfqq;
}
if (new_cfqq)
kmem_cache_free(cfq_pool, new_cfqq);
return cfqq;
}
static struct cfq_queue **
cfq_async_queue_prio(struct cfq_data *cfqd, int ioprio_class, int ioprio)
{
switch (ioprio_class) {
case IOPRIO_CLASS_RT:
return &cfqd->async_cfqq[0][ioprio];
case IOPRIO_CLASS_BE:
return &cfqd->async_cfqq[1][ioprio];
case IOPRIO_CLASS_IDLE:
return &cfqd->async_idle_cfqq;
default:
BUG();
}
}
static struct cfq_queue *
cfq_get_queue(struct cfq_data *cfqd, bool is_sync, struct io_context *ioc,
gfp_t gfp_mask)
{
const int ioprio = task_ioprio(ioc);
const int ioprio_class = task_ioprio_class(ioc);
struct cfq_queue **async_cfqq = NULL;
struct cfq_queue *cfqq = NULL;
if (!is_sync) {
async_cfqq = cfq_async_queue_prio(cfqd, ioprio_class, ioprio);
cfqq = *async_cfqq;
}
if (!cfqq)
cfqq = cfq_find_alloc_queue(cfqd, is_sync, ioc, gfp_mask);
/*
* pin the queue now that it's allocated, scheduler exit will prune it
*/
if (!is_sync && !(*async_cfqq)) {
cfqq->ref++;
*async_cfqq = cfqq;
}
cfqq->ref++;
return cfqq;
}
static void
__cfq_update_io_thinktime(struct cfq_ttime *ttime, unsigned long slice_idle)
{
unsigned long elapsed = jiffies - ttime->last_end_request;
elapsed = min(elapsed, 2UL * slice_idle);
ttime->ttime_samples = (7*ttime->ttime_samples + 256) / 8;
ttime->ttime_total = (7*ttime->ttime_total + 256*elapsed) / 8;
ttime->ttime_mean = (ttime->ttime_total + 128) / ttime->ttime_samples;
}
static void
cfq_update_io_thinktime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct cfq_io_cq *cic)
{
if (cfq_cfqq_sync(cfqq)) {
__cfq_update_io_thinktime(&cic->ttime, cfqd->cfq_slice_idle);
__cfq_update_io_thinktime(&cfqq->service_tree->ttime,
cfqd->cfq_slice_idle);
}
#ifdef CONFIG_CFQ_GROUP_IOSCHED
__cfq_update_io_thinktime(&cfqq->cfqg->ttime, cfqd->cfq_group_idle);
#endif
}
static void
cfq_update_io_seektime(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct request *rq)
{
sector_t sdist = 0;
sector_t n_sec = blk_rq_sectors(rq);
if (cfqq->last_request_pos) {
if (cfqq->last_request_pos < blk_rq_pos(rq))
sdist = blk_rq_pos(rq) - cfqq->last_request_pos;
else
sdist = cfqq->last_request_pos - blk_rq_pos(rq);
}
cfqq->seek_history <<= 1;
if (blk_queue_nonrot(cfqd->queue))
cfqq->seek_history |= (n_sec < CFQQ_SECT_THR_NONROT);
else
cfqq->seek_history |= (sdist > CFQQ_SEEK_THR);
}
/*
* Disable idle window if the process thinks too long or seeks so much that
* it doesn't matter
*/
static void
cfq_update_idle_window(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct cfq_io_cq *cic)
{
int old_idle, enable_idle;
/*
* Don't idle for async or idle io prio class
*/
if (!cfq_cfqq_sync(cfqq) || cfq_class_idle(cfqq))
return;
enable_idle = old_idle = cfq_cfqq_idle_window(cfqq);
if (cfqq->queued[0] + cfqq->queued[1] >= 4)
cfq_mark_cfqq_deep(cfqq);
if (cfqq->next_rq && (cfqq->next_rq->cmd_flags & REQ_NOIDLE))
enable_idle = 0;
else if (!atomic_read(&cic->icq.ioc->nr_tasks) ||
!cfqd->cfq_slice_idle ||
(!cfq_cfqq_deep(cfqq) && CFQQ_SEEKY(cfqq)))
enable_idle = 0;
else if (sample_valid(cic->ttime.ttime_samples)) {
if (cic->ttime.ttime_mean > cfqd->cfq_slice_idle)
enable_idle = 0;
else
enable_idle = 1;
}
if (old_idle != enable_idle) {
cfq_log_cfqq(cfqd, cfqq, "idle=%d", enable_idle);
if (enable_idle)
cfq_mark_cfqq_idle_window(cfqq);
else
cfq_clear_cfqq_idle_window(cfqq);
}
}
/*
* Check if new_cfqq should preempt the currently active queue. Return 0 for
* no or if we aren't sure, a 1 will cause a preempt.
*/
static bool
cfq_should_preempt(struct cfq_data *cfqd, struct cfq_queue *new_cfqq,
struct request *rq)
{
struct cfq_queue *cfqq;
cfqq = cfqd->active_queue;
if (!cfqq)
return false;
if (cfq_class_idle(new_cfqq))
return false;
if (cfq_class_idle(cfqq))
return true;
/*
* Don't allow a non-RT request to preempt an ongoing RT cfqq timeslice.
*/
if (cfq_class_rt(cfqq) && !cfq_class_rt(new_cfqq))
return false;
/*
* if the new request is sync, but the currently running queue is
* not, let the sync request have priority.
*/
if (rq_is_sync(rq) && !cfq_cfqq_sync(cfqq))
return true;
if (new_cfqq->cfqg != cfqq->cfqg)
return false;
if (cfq_slice_used(cfqq))
return true;
/* Allow preemption only if we are idling on sync-noidle tree */
if (cfqd->serving_type == SYNC_NOIDLE_WORKLOAD &&
cfqq_type(new_cfqq) == SYNC_NOIDLE_WORKLOAD &&
new_cfqq->service_tree->count == 2 &&
RB_EMPTY_ROOT(&cfqq->sort_list))
return true;
/*
* So both queues are sync. Let the new request get disk time if
* it's a metadata request and the current queue is doing regular IO.
*/
if ((rq->cmd_flags & REQ_PRIO) && !cfqq->prio_pending)
return true;
/*
* Allow an RT request to pre-empt an ongoing non-RT cfqq timeslice.
*/
if (cfq_class_rt(new_cfqq) && !cfq_class_rt(cfqq))
return true;
/* An idle queue should not be idle now for some reason */
if (RB_EMPTY_ROOT(&cfqq->sort_list) && !cfq_should_idle(cfqd, cfqq))
return true;
if (!cfqd->active_cic || !cfq_cfqq_wait_request(cfqq))
return false;
/*
* if this request is as-good as one we would expect from the
* current cfqq, let it preempt
*/
if (cfq_rq_close(cfqd, cfqq, rq))
return true;
return false;
}
/*
* cfqq preempts the active queue. if we allowed preempt with no slice left,
* let it have half of its nominal slice.
*/
static void cfq_preempt_queue(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
enum wl_type_t old_type = cfqq_type(cfqd->active_queue);
cfq_log_cfqq(cfqd, cfqq, "preempt");
cfq_slice_expired(cfqd, 1);
/*
* workload type is changed, don't save slice, otherwise preempt
* doesn't happen
*/
if (old_type != cfqq_type(cfqq))
cfqq->cfqg->saved_workload_slice = 0;
/*
* Put the new queue at the front of the of the current list,
* so we know that it will be selected next.
*/
BUG_ON(!cfq_cfqq_on_rr(cfqq));
cfq_service_tree_add(cfqd, cfqq, 1);
cfqq->slice_end = 0;
cfq_mark_cfqq_slice_new(cfqq);
}
/*
* Called when a new fs request (rq) is added (to cfqq). Check if there's
* something we should do about it
*/
static void
cfq_rq_enqueued(struct cfq_data *cfqd, struct cfq_queue *cfqq,
struct request *rq)
{
struct cfq_io_cq *cic = RQ_CIC(rq);
cfqd->rq_queued++;
if (rq->cmd_flags & REQ_PRIO)
cfqq->prio_pending++;
cfq_update_io_thinktime(cfqd, cfqq, cic);
cfq_update_io_seektime(cfqd, cfqq, rq);
cfq_update_idle_window(cfqd, cfqq, cic);
cfqq->last_request_pos = blk_rq_pos(rq) + blk_rq_sectors(rq);
if (cfqq == cfqd->active_queue) {
/*
* Remember that we saw a request from this process, but
* don't start queuing just yet. Otherwise we risk seeing lots
* of tiny requests, because we disrupt the normal plugging
* and merging. If the request is already larger than a single
* page, let it rip immediately. For that case we assume that
* merging is already done. Ditto for a busy system that
* has other work pending, don't risk delaying until the
* idle timer unplug to continue working.
*/
if (cfq_cfqq_wait_request(cfqq)) {
if (blk_rq_bytes(rq) > PAGE_CACHE_SIZE ||
cfqd->busy_queues > 1) {
cfq_del_timer(cfqd, cfqq);
cfq_clear_cfqq_wait_request(cfqq);
__blk_run_queue(cfqd->queue);
} else {
cfq_blkiocg_update_idle_time_stats(
&cfqq->cfqg->blkg);
cfq_mark_cfqq_must_dispatch(cfqq);
}
}
} else if (cfq_should_preempt(cfqd, cfqq, rq)) {
/*
* not the active queue - expire current slice if it is
* idle and has expired it's mean thinktime or this new queue
* has some old slice time left and is of higher priority or
* this new queue is RT and the current one is BE
*/
cfq_preempt_queue(cfqd, cfqq);
__blk_run_queue(cfqd->queue);
}
}
static void cfq_insert_request(struct request_queue *q, struct request *rq)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct cfq_queue *cfqq = RQ_CFQQ(rq);
cfq_log_cfqq(cfqd, cfqq, "insert_request");
cfq_init_prio_data(cfqq, RQ_CIC(rq)->icq.ioc);
rq_set_fifo_time(rq, jiffies + cfqd->cfq_fifo_expire[rq_is_sync(rq)]);
list_add_tail(&rq->queuelist, &cfqq->fifo);
cfq_add_rq_rb(rq);
cfq_blkiocg_update_io_add_stats(&(RQ_CFQG(rq))->blkg,
&cfqd->serving_group->blkg, rq_data_dir(rq),
rq_is_sync(rq));
cfq_rq_enqueued(cfqd, cfqq, rq);
}
/*
* Update hw_tag based on peak queue depth over 50 samples under
* sufficient load.
*/
static void cfq_update_hw_tag(struct cfq_data *cfqd)
{
struct cfq_queue *cfqq = cfqd->active_queue;
if (cfqd->rq_in_driver > cfqd->hw_tag_est_depth)
cfqd->hw_tag_est_depth = cfqd->rq_in_driver;
if (cfqd->hw_tag == 1)
return;
if (cfqd->rq_queued <= CFQ_HW_QUEUE_MIN &&
cfqd->rq_in_driver <= CFQ_HW_QUEUE_MIN)
return;
/*
* If active queue hasn't enough requests and can idle, cfq might not
* dispatch sufficient requests to hardware. Don't zero hw_tag in this
* case
*/
if (cfqq && cfq_cfqq_idle_window(cfqq) &&
cfqq->dispatched + cfqq->queued[0] + cfqq->queued[1] <
CFQ_HW_QUEUE_MIN && cfqd->rq_in_driver < CFQ_HW_QUEUE_MIN)
return;
if (cfqd->hw_tag_samples++ < 50)
return;
if (cfqd->hw_tag_est_depth >= CFQ_HW_QUEUE_MIN)
cfqd->hw_tag = 1;
else
cfqd->hw_tag = 0;
}
static bool cfq_should_wait_busy(struct cfq_data *cfqd, struct cfq_queue *cfqq)
{
struct cfq_io_cq *cic = cfqd->active_cic;
/* If the queue already has requests, don't wait */
if (!RB_EMPTY_ROOT(&cfqq->sort_list))
return false;
/* If there are other queues in the group, don't wait */
if (cfqq->cfqg->nr_cfqq > 1)
return false;
/* the only queue in the group, but think time is big */
if (cfq_io_thinktime_big(cfqd, &cfqq->cfqg->ttime, true))
return false;
if (cfq_slice_used(cfqq))
return true;
/* if slice left is less than think time, wait busy */
if (cic && sample_valid(cic->ttime.ttime_samples)
&& (cfqq->slice_end - jiffies < cic->ttime.ttime_mean))
return true;
/*
* If think times is less than a jiffy than ttime_mean=0 and above
* will not be true. It might happen that slice has not expired yet
* but will expire soon (4-5 ns) during select_queue(). To cover the
* case where think time is less than a jiffy, mark the queue wait
* busy if only 1 jiffy is left in the slice.
*/
if (cfqq->slice_end - jiffies == 1)
return true;
return false;
}
static void cfq_completed_request(struct request_queue *q, struct request *rq)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
struct cfq_data *cfqd = cfqq->cfqd;
const int sync = rq_is_sync(rq);
unsigned long now;
now = jiffies;
cfq_log_cfqq(cfqd, cfqq, "complete rqnoidle %d",
!!(rq->cmd_flags & REQ_NOIDLE));
cfq_update_hw_tag(cfqd);
WARN_ON(!cfqd->rq_in_driver);
WARN_ON(!cfqq->dispatched);
cfqd->rq_in_driver--;
cfqq->dispatched--;
(RQ_CFQG(rq))->dispatched--;
cfq_blkiocg_update_completion_stats(&cfqq->cfqg->blkg,
rq_start_time_ns(rq), rq_io_start_time_ns(rq),
rq_data_dir(rq), rq_is_sync(rq));
cfqd->rq_in_flight[cfq_cfqq_sync(cfqq)]--;
if (sync) {
struct cfq_rb_root *service_tree;
RQ_CIC(rq)->ttime.last_end_request = now;
if (cfq_cfqq_on_rr(cfqq))
service_tree = cfqq->service_tree;
else
service_tree = service_tree_for(cfqq->cfqg,
cfqq_prio(cfqq), cfqq_type(cfqq));
service_tree->ttime.last_end_request = now;
if (!time_after(rq->start_time + cfqd->cfq_fifo_expire[1], now))
cfqd->last_delayed_sync = now;
}
#ifdef CONFIG_CFQ_GROUP_IOSCHED
cfqq->cfqg->ttime.last_end_request = now;
#endif
/*
* If this is the active queue, check if it needs to be expired,
* or if we want to idle in case it has no pending requests.
*/
if (cfqd->active_queue == cfqq) {
const bool cfqq_empty = RB_EMPTY_ROOT(&cfqq->sort_list);
if (cfq_cfqq_slice_new(cfqq)) {
cfq_set_prio_slice(cfqd, cfqq);
cfq_clear_cfqq_slice_new(cfqq);
}
/*
* Should we wait for next request to come in before we expire
* the queue.
*/
if (cfq_should_wait_busy(cfqd, cfqq)) {
unsigned long extend_sl = cfqd->cfq_slice_idle;
if (!cfqd->cfq_slice_idle)
extend_sl = cfqd->cfq_group_idle;
cfqq->slice_end = jiffies + extend_sl;
cfq_mark_cfqq_wait_busy(cfqq);
cfq_log_cfqq(cfqd, cfqq, "will busy wait");
}
/*
* Idling is not enabled on:
* - expired queues
* - idle-priority queues
* - async queues
* - queues with still some requests queued
* - when there is a close cooperator
*/
if (cfq_slice_used(cfqq) || cfq_class_idle(cfqq))
cfq_slice_expired(cfqd, 1);
else if (sync && cfqq_empty &&
!cfq_close_cooperator(cfqd, cfqq)) {
cfq_arm_slice_timer(cfqd);
}
}
if (!cfqd->rq_in_driver)
cfq_schedule_dispatch(cfqd);
}
static inline int __cfq_may_queue(struct cfq_queue *cfqq)
{
if (cfq_cfqq_wait_request(cfqq) && !cfq_cfqq_must_alloc_slice(cfqq)) {
cfq_mark_cfqq_must_alloc_slice(cfqq);
return ELV_MQUEUE_MUST;
}
return ELV_MQUEUE_MAY;
}
static int cfq_may_queue(struct request_queue *q, int rw)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct task_struct *tsk = current;
struct cfq_io_cq *cic;
struct cfq_queue *cfqq;
/*
* don't force setup of a queue from here, as a call to may_queue
* does not necessarily imply that a request actually will be queued.
* so just lookup a possibly existing queue, or return 'may queue'
* if that fails
*/
cic = cfq_cic_lookup(cfqd, tsk->io_context);
if (!cic)
return ELV_MQUEUE_MAY;
cfqq = cic_to_cfqq(cic, rw_is_sync(rw));
if (cfqq) {
cfq_init_prio_data(cfqq, cic->icq.ioc);
return __cfq_may_queue(cfqq);
}
return ELV_MQUEUE_MAY;
}
/*
* queue lock held here
*/
static void cfq_put_request(struct request *rq)
{
struct cfq_queue *cfqq = RQ_CFQQ(rq);
if (cfqq) {
const int rw = rq_data_dir(rq);
BUG_ON(!cfqq->allocated[rw]);
cfqq->allocated[rw]--;
/* Put down rq reference on cfqg */
cfq_put_cfqg(RQ_CFQG(rq));
rq->elv.priv[0] = NULL;
rq->elv.priv[1] = NULL;
cfq_put_queue(cfqq);
}
}
static struct cfq_queue *
cfq_merge_cfqqs(struct cfq_data *cfqd, struct cfq_io_cq *cic,
struct cfq_queue *cfqq)
{
cfq_log_cfqq(cfqd, cfqq, "merging with queue %p", cfqq->new_cfqq);
cic_set_cfqq(cic, cfqq->new_cfqq, 1);
cfq_mark_cfqq_coop(cfqq->new_cfqq);
cfq_put_queue(cfqq);
return cic_to_cfqq(cic, 1);
}
/*
* Returns NULL if a new cfqq should be allocated, or the old cfqq if this
* was the last process referring to said cfqq.
*/
static struct cfq_queue *
split_cfqq(struct cfq_io_cq *cic, struct cfq_queue *cfqq)
{
if (cfqq_process_refs(cfqq) == 1) {
cfqq->pid = current->pid;
cfq_clear_cfqq_coop(cfqq);
cfq_clear_cfqq_split_coop(cfqq);
return cfqq;
}
cic_set_cfqq(cic, NULL, 1);
cfq_put_cooperator(cfqq);
cfq_put_queue(cfqq);
return NULL;
}
/*
* Allocate cfq data structures associated with this request.
*/
static int
cfq_set_request(struct request_queue *q, struct request *rq, gfp_t gfp_mask)
{
struct cfq_data *cfqd = q->elevator->elevator_data;
struct cfq_io_cq *cic = icq_to_cic(rq->elv.icq);
const int rw = rq_data_dir(rq);
const bool is_sync = rq_is_sync(rq);
struct cfq_queue *cfqq;
unsigned int changed;
might_sleep_if(gfp_mask & __GFP_WAIT);
spin_lock_irq(q->queue_lock);
/* handle changed notifications */
changed = icq_get_changed(&cic->icq);
if (unlikely(changed & ICQ_IOPRIO_CHANGED))
changed_ioprio(cic);
#ifdef CONFIG_CFQ_GROUP_IOSCHED
if (unlikely(changed & ICQ_CGROUP_CHANGED))
changed_cgroup(cic);
#endif
new_queue:
cfqq = cic_to_cfqq(cic, is_sync);
if (!cfqq || cfqq == &cfqd->oom_cfqq) {
cfqq = cfq_get_queue(cfqd, is_sync, cic->icq.ioc, gfp_mask);
cic_set_cfqq(cic, cfqq, is_sync);
} else {
/*
* If the queue was seeky for too long, break it apart.
*/
if (cfq_cfqq_coop(cfqq) && cfq_cfqq_split_coop(cfqq)) {
cfq_log_cfqq(cfqd, cfqq, "breaking apart cfqq");
cfqq = split_cfqq(cic, cfqq);
if (!cfqq)
goto new_queue;
}
/*
* Check to see if this queue is scheduled to merge with
* another, closely cooperating queue. The merging of
* queues happens here as it must be done in process context.
* The reference on new_cfqq was taken in merge_cfqqs.
*/
if (cfqq->new_cfqq)
cfqq = cfq_merge_cfqqs(cfqd, cic, cfqq);
}
cfqq->allocated[rw]++;
cfqq->ref++;
rq->elv.priv[0] = cfqq;
rq->elv.priv[1] = cfq_ref_get_cfqg(cfqq->cfqg);
spin_unlock_irq(q->queue_lock);
return 0;
}
static void cfq_kick_queue(struct work_struct *work)
{
struct cfq_data *cfqd =
container_of(work, struct cfq_data, unplug_work);
struct request_queue *q = cfqd->queue;
spin_lock_irq(q->queue_lock);
__blk_run_queue(cfqd->queue);
spin_unlock_irq(q->queue_lock);
}
/*
* Timer running if the active_queue is currently idling inside its time slice
*/
static void cfq_idle_slice_timer(unsigned long data)
{
struct cfq_data *cfqd = (struct cfq_data *) data;
struct cfq_queue *cfqq;
unsigned long flags;
int timed_out = 1;
cfq_log(cfqd, "idle timer fired");
spin_lock_irqsave(cfqd->queue->queue_lock, flags);
cfqq = cfqd->active_queue;
if (cfqq) {
timed_out = 0;
/*
* We saw a request before the queue expired, let it through
*/
if (cfq_cfqq_must_dispatch(cfqq))
goto out_kick;
/*
* expired
*/
if (cfq_slice_used(cfqq))
goto expire;
/*
* only expire and reinvoke request handler, if there are
* other queues with pending requests
*/
if (!cfqd->busy_queues)
goto out_cont;
/*
* not expired and it has a request pending, let it dispatch
*/
if (!RB_EMPTY_ROOT(&cfqq->sort_list))
goto out_kick;
/*
* Queue depth flag is reset only when the idle didn't succeed
*/
cfq_clear_cfqq_deep(cfqq);
}
expire:
cfq_slice_expired(cfqd, timed_out);
out_kick:
cfq_schedule_dispatch(cfqd);
out_cont:
spin_unlock_irqrestore(cfqd->queue->queue_lock, flags);
}
static void cfq_shutdown_timer_wq(struct cfq_data *cfqd)
{
del_timer_sync(&cfqd->idle_slice_timer);
cancel_work_sync(&cfqd->unplug_work);
}
static void cfq_put_async_queues(struct cfq_data *cfqd)
{
int i;
for (i = 0; i < IOPRIO_BE_NR; i++) {
if (cfqd->async_cfqq[0][i])
cfq_put_queue(cfqd->async_cfqq[0][i]);
if (cfqd->async_cfqq[1][i])
cfq_put_queue(cfqd->async_cfqq[1][i]);
}
if (cfqd->async_idle_cfqq)
cfq_put_queue(cfqd->async_idle_cfqq);
}
static void cfq_exit_queue(struct elevator_queue *e)
{
struct cfq_data *cfqd = e->elevator_data;
struct request_queue *q = cfqd->queue;
bool wait = false;
cfq_shutdown_timer_wq(cfqd);
spin_lock_irq(q->queue_lock);
if (cfqd->active_queue)
__cfq_slice_expired(cfqd, cfqd->active_queue, 0);
cfq_put_async_queues(cfqd);
cfq_release_cfq_groups(cfqd);
/*
* If there are groups which we could not unlink from blkcg list,
* wait for a rcu period for them to be freed.
*/
if (cfqd->nr_blkcg_linked_grps)
wait = true;
spin_unlock_irq(q->queue_lock);
cfq_shutdown_timer_wq(cfqd);
/*
* Wait for cfqg->blkg->key accessors to exit their grace periods.
* Do this wait only if there are other unlinked groups out
* there. This can happen if cgroup deletion path claimed the
* responsibility of cleaning up a group before queue cleanup code
* get to the group.
*
* Do not call synchronize_rcu() unconditionally as there are drivers
* which create/delete request queue hundreds of times during scan/boot
* and synchronize_rcu() can take significant time and slow down boot.
*/
if (wait)
synchronize_rcu();
#ifdef CONFIG_CFQ_GROUP_IOSCHED
/* Free up per cpu stats for root group */
free_percpu(cfqd->root_group.blkg.stats_cpu);
#endif
kfree(cfqd);
}
static void *cfq_init_queue(struct request_queue *q)
{
struct cfq_data *cfqd;
int i, j;
struct cfq_group *cfqg;
struct cfq_rb_root *st;
cfqd = kmalloc_node(sizeof(*cfqd), GFP_KERNEL | __GFP_ZERO, q->node);
if (!cfqd)
return NULL;
/* Init root service tree */
cfqd->grp_service_tree = CFQ_RB_ROOT;
/* Init root group */
cfqg = &cfqd->root_group;
for_each_cfqg_st(cfqg, i, j, st)
*st = CFQ_RB_ROOT;
RB_CLEAR_NODE(&cfqg->rb_node);
/* Give preference to root group over other groups */
cfqg->weight = 2*BLKIO_WEIGHT_DEFAULT;
#ifdef CONFIG_CFQ_GROUP_IOSCHED
/*
* Set root group reference to 2. One reference will be dropped when
* all groups on cfqd->cfqg_list are being deleted during queue exit.
* Other reference will remain there as we don't want to delete this
* group as it is statically allocated and gets destroyed when
* throtl_data goes away.
*/
cfqg->ref = 2;
if (blkio_alloc_blkg_stats(&cfqg->blkg)) {
kfree(cfqg);
kfree(cfqd);
return NULL;
}
rcu_read_lock();
cfq_blkiocg_add_blkio_group(&blkio_root_cgroup, &cfqg->blkg,
(void *)cfqd, 0);
rcu_read_unlock();
cfqd->nr_blkcg_linked_grps++;
/* Add group on cfqd->cfqg_list */
hlist_add_head(&cfqg->cfqd_node, &cfqd->cfqg_list);
#endif
/*
* Not strictly needed (since RB_ROOT just clears the node and we
* zeroed cfqd on alloc), but better be safe in case someone decides
* to add magic to the rb code
*/
for (i = 0; i < CFQ_PRIO_LISTS; i++)
cfqd->prio_trees[i] = RB_ROOT;
/*
* Our fallback cfqq if cfq_find_alloc_queue() runs into OOM issues.
* Grab a permanent reference to it, so that the normal code flow
* will not attempt to free it.
*/
cfq_init_cfqq(cfqd, &cfqd->oom_cfqq, 1, 0);
cfqd->oom_cfqq.ref++;
cfq_link_cfqq_cfqg(&cfqd->oom_cfqq, &cfqd->root_group);
cfqd->queue = q;
init_timer(&cfqd->idle_slice_timer);
cfqd->idle_slice_timer.function = cfq_idle_slice_timer;
cfqd->idle_slice_timer.data = (unsigned long) cfqd;
INIT_WORK(&cfqd->unplug_work, cfq_kick_queue);
cfqd->cfq_quantum = cfq_quantum;
cfqd->cfq_fifo_expire[0] = cfq_fifo_expire[0];
cfqd->cfq_fifo_expire[1] = cfq_fifo_expire[1];
cfqd->cfq_back_max = cfq_back_max;
cfqd->cfq_back_penalty = cfq_back_penalty;
cfqd->cfq_slice[0] = cfq_slice_async;
cfqd->cfq_slice[1] = cfq_slice_sync;
cfqd->cfq_slice_async_rq = cfq_slice_async_rq;
cfqd->cfq_slice_idle = cfq_slice_idle;
cfqd->cfq_group_idle = cfq_group_idle;
cfqd->cfq_latency = 1;
cfqd->hw_tag = -1;
/*
* we optimistically start assuming sync ops weren't delayed in last
* second, in order to have larger depth for async operations.
*/
cfqd->last_delayed_sync = jiffies - HZ;
return cfqd;
}
/*
* sysfs parts below -->
*/
static ssize_t
cfq_var_show(unsigned int var, char *page)
{
return sprintf(page, "%d\n", var);
}
static ssize_t
cfq_var_store(unsigned int *var, const char *page, size_t count)
{
char *p = (char *) page;
*var = simple_strtoul(p, &p, 10);
return count;
}
#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, char *page) \
{ \
struct cfq_data *cfqd = e->elevator_data; \
unsigned int __data = __VAR; \
if (__CONV) \
__data = jiffies_to_msecs(__data); \
return cfq_var_show(__data, (page)); \
}
SHOW_FUNCTION(cfq_quantum_show, cfqd->cfq_quantum, 0);
SHOW_FUNCTION(cfq_fifo_expire_sync_show, cfqd->cfq_fifo_expire[1], 1);
SHOW_FUNCTION(cfq_fifo_expire_async_show, cfqd->cfq_fifo_expire[0], 1);
SHOW_FUNCTION(cfq_back_seek_max_show, cfqd->cfq_back_max, 0);
SHOW_FUNCTION(cfq_back_seek_penalty_show, cfqd->cfq_back_penalty, 0);
SHOW_FUNCTION(cfq_slice_idle_show, cfqd->cfq_slice_idle, 1);
SHOW_FUNCTION(cfq_group_idle_show, cfqd->cfq_group_idle, 1);
SHOW_FUNCTION(cfq_slice_sync_show, cfqd->cfq_slice[1], 1);
SHOW_FUNCTION(cfq_slice_async_show, cfqd->cfq_slice[0], 1);
SHOW_FUNCTION(cfq_slice_async_rq_show, cfqd->cfq_slice_async_rq, 0);
SHOW_FUNCTION(cfq_low_latency_show, cfqd->cfq_latency, 0);
#undef SHOW_FUNCTION
#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, const char *page, size_t count) \
{ \
struct cfq_data *cfqd = e->elevator_data; \
unsigned int __data; \
int ret = cfq_var_store(&__data, (page), count); \
if (__data < (MIN)) \
__data = (MIN); \
else if (__data > (MAX)) \
__data = (MAX); \
if (__CONV) \
*(__PTR) = msecs_to_jiffies(__data); \
else \
*(__PTR) = __data; \
return ret; \
}
STORE_FUNCTION(cfq_quantum_store, &cfqd->cfq_quantum, 1, UINT_MAX, 0);
STORE_FUNCTION(cfq_fifo_expire_sync_store, &cfqd->cfq_fifo_expire[1], 1,
UINT_MAX, 1);
STORE_FUNCTION(cfq_fifo_expire_async_store, &cfqd->cfq_fifo_expire[0], 1,
UINT_MAX, 1);
STORE_FUNCTION(cfq_back_seek_max_store, &cfqd->cfq_back_max, 0, UINT_MAX, 0);
STORE_FUNCTION(cfq_back_seek_penalty_store, &cfqd->cfq_back_penalty, 1,
UINT_MAX, 0);
STORE_FUNCTION(cfq_slice_idle_store, &cfqd->cfq_slice_idle, 0, UINT_MAX, 1);
STORE_FUNCTION(cfq_group_idle_store, &cfqd->cfq_group_idle, 0, UINT_MAX, 1);
STORE_FUNCTION(cfq_slice_sync_store, &cfqd->cfq_slice[1], 1, UINT_MAX, 1);
STORE_FUNCTION(cfq_slice_async_store, &cfqd->cfq_slice[0], 1, UINT_MAX, 1);
STORE_FUNCTION(cfq_slice_async_rq_store, &cfqd->cfq_slice_async_rq, 1,
UINT_MAX, 0);
STORE_FUNCTION(cfq_low_latency_store, &cfqd->cfq_latency, 0, 1, 0);
#undef STORE_FUNCTION
#define CFQ_ATTR(name) \
__ATTR(name, S_IRUGO|S_IWUSR, cfq_##name##_show, cfq_##name##_store)
static struct elv_fs_entry cfq_attrs[] = {
CFQ_ATTR(quantum),
CFQ_ATTR(fifo_expire_sync),
CFQ_ATTR(fifo_expire_async),
CFQ_ATTR(back_seek_max),
CFQ_ATTR(back_seek_penalty),
CFQ_ATTR(slice_sync),
CFQ_ATTR(slice_async),
CFQ_ATTR(slice_async_rq),
CFQ_ATTR(slice_idle),
CFQ_ATTR(group_idle),
CFQ_ATTR(low_latency),
__ATTR_NULL
};
static struct elevator_type iosched_cfq = {
.ops = {
.elevator_merge_fn = cfq_merge,
.elevator_merged_fn = cfq_merged_request,
.elevator_merge_req_fn = cfq_merged_requests,
.elevator_allow_merge_fn = cfq_allow_merge,
.elevator_bio_merged_fn = cfq_bio_merged,
.elevator_dispatch_fn = cfq_dispatch_requests,
.elevator_add_req_fn = cfq_insert_request,
.elevator_activate_req_fn = cfq_activate_request,
.elevator_deactivate_req_fn = cfq_deactivate_request,
.elevator_completed_req_fn = cfq_completed_request,
.elevator_former_req_fn = elv_rb_former_request,
.elevator_latter_req_fn = elv_rb_latter_request,
.elevator_init_icq_fn = cfq_init_icq,
.elevator_exit_icq_fn = cfq_exit_icq,
.elevator_set_req_fn = cfq_set_request,
.elevator_put_req_fn = cfq_put_request,
.elevator_may_queue_fn = cfq_may_queue,
.elevator_init_fn = cfq_init_queue,
.elevator_exit_fn = cfq_exit_queue,
},
.icq_size = sizeof(struct cfq_io_cq),
.icq_align = __alignof__(struct cfq_io_cq),
.elevator_attrs = cfq_attrs,
.elevator_name = "cfq",
.elevator_owner = THIS_MODULE,
};
#ifdef CONFIG_CFQ_GROUP_IOSCHED
static struct blkio_policy_type blkio_policy_cfq = {
.ops = {
.blkio_unlink_group_fn = cfq_unlink_blkio_group,
.blkio_update_group_weight_fn = cfq_update_blkio_group_weight,
},
.plid = BLKIO_POLICY_PROP,
};
#else
static struct blkio_policy_type blkio_policy_cfq;
#endif
static int __init cfq_init(void)
{
int ret;
/*
* could be 0 on HZ < 1000 setups
*/
if (!cfq_slice_async)
cfq_slice_async = 1;
if (!cfq_slice_idle)
cfq_slice_idle = 1;
#ifdef CONFIG_CFQ_GROUP_IOSCHED
if (!cfq_group_idle)
cfq_group_idle = 1;
#else
cfq_group_idle = 0;
#endif
cfq_pool = KMEM_CACHE(cfq_queue, 0);
if (!cfq_pool)
return -ENOMEM;
ret = elv_register(&iosched_cfq);
if (ret) {
kmem_cache_destroy(cfq_pool);
return ret;
}
blkio_policy_register(&blkio_policy_cfq);
return 0;
}
static void __exit cfq_exit(void)
{
blkio_policy_unregister(&blkio_policy_cfq);
elv_unregister(&iosched_cfq);
kmem_cache_destroy(cfq_pool);
}
module_init(cfq_init);
module_exit(cfq_exit);
MODULE_AUTHOR("Jens Axboe");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Completely Fair Queueing IO scheduler");
| gpl-2.0 |
monokoo/lede-source | target/linux/ar71xx/files/arch/mips/ath79/mach-cf-e316n-v2.c | 46 | 12497 | /*
* Support for COMFAST boards:
* - CF-E316N v2 (AR9341)
* - CF-E320N v2 (QCA9531)
* - CF-E380AC v1/v2 (QCA9558)
* - CF-E520N/CF-E530N (QCA9531)
*
* Copyright (C) 2016 Piotr Dymacz <pepe2k@gmail.com>
* Copyright (C) 2016 Gareth Parker <gareth41@orcon.net.nz>
* Copyright (C) 2015 Paul Fertser <fercerpav@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*/
#include <linux/gpio.h>
#include <linux/platform_data/phy-at803x.h>
#include <linux/platform_device.h>
#include <linux/timer.h>
#include <asm/mach-ath79/ath79.h>
#include <asm/mach-ath79/ar71xx_regs.h>
#include "common.h"
#include "dev-ap9x-pci.h"
#include "dev-eth.h"
#include "dev-gpio-buttons.h"
#include "dev-leds-gpio.h"
#include "dev-m25p80.h"
#include "dev-wmac.h"
#include "dev-usb.h"
#include "machtypes.h"
#define CF_EXXXN_KEYS_POLL_INTERVAL 20
#define CF_EXXXN_KEYS_DEBOUNCE_INTERVAL (3 * CF_EXXXN_KEYS_POLL_INTERVAL)
/* CF-E316N v2 */
#define CF_E316N_V2_GPIO_LED_DIAG_B 0
#define CF_E316N_V2_GPIO_LED_DIAG_R 2
#define CF_E316N_V2_GPIO_LED_DIAG_G 3
#define CF_E316N_V2_GPIO_LED_WLAN 12
#define CF_E316N_V2_GPIO_LED_WAN 17
#define CF_E316N_V2_GPIO_LED_LAN 19
#define CF_E316N_V2_GPIO_EXT_WDT 16
#define CF_E316N_V2_GPIO_EXTERNAL_PA0 13
#define CF_E316N_V2_GPIO_EXTERNAL_PA1 14
#define CF_E316N_V2_GPIO_BTN_RESET 20
static struct gpio_led cf_e316n_v2_leds_gpio[] __initdata = {
{
.name = "cf-e316n-v2:blue:diag",
.gpio = CF_E316N_V2_GPIO_LED_DIAG_B,
.active_low = 0,
}, {
.name = "cf-e316n-v2:red:diag",
.gpio = CF_E316N_V2_GPIO_LED_DIAG_R,
.active_low = 0,
}, {
.name = "cf-e316n-v2:green:diag",
.gpio = CF_E316N_V2_GPIO_LED_DIAG_G,
.active_low = 0,
}, {
.name = "cf-e316n-v2:blue:wlan",
.gpio = CF_E316N_V2_GPIO_LED_WLAN,
.active_low = 1,
}, {
.name = "cf-e316n-v2:blue:wan",
.gpio = CF_E316N_V2_GPIO_LED_WAN,
.active_low = 1,
}, {
.name = "cf-e316n-v2:blue:lan",
.gpio = CF_E316N_V2_GPIO_LED_LAN,
.active_low = 1,
},
};
static struct gpio_keys_button cf_e316n_v2_gpio_keys[] __initdata = {
{
.desc = "reset",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = CF_EXXXN_KEYS_DEBOUNCE_INTERVAL,
.gpio = CF_E316N_V2_GPIO_BTN_RESET,
.active_low = 1,
},
};
/* CF-E320N v2 */
#define CF_E320N_V2_GPIO_LED_WLAN 0
#define CF_E320N_V2_GPIO_LED_WAN 2
#define CF_E320N_V2_GPIO_LED_LAN 3
#define CF_E320N_V2_GPIO_HEADER_J9_1 14
#define CF_E320N_V2_GPIO_HEADER_J9_2 12
#define CF_E320N_V2_GPIO_HEADER_J9_3 11
#define CF_E320N_V2_GPIO_HEADER_J9_4 16
#define CF_E320N_V2_GPIO_EXT_WDT 13
#define CF_E320N_V2_GPIO_BTN_RESET 17
static struct gpio_led cf_e320n_v2_leds_gpio[] __initdata = {
{
.name = "cf-e320n-v2:green:lan",
.gpio = CF_E320N_V2_GPIO_LED_LAN,
.active_low = 0,
}, {
.name = "cf-e320n-v2:red:wan",
.gpio = CF_E320N_V2_GPIO_LED_WAN,
.active_low = 0,
}, {
.name = "cf-e320n-v2:blue:wlan",
.gpio = CF_E320N_V2_GPIO_LED_WLAN,
.active_low = 0,
},
};
static struct gpio_keys_button cf_e320n_v2_gpio_keys[] __initdata = {
{
.desc = "Reset button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = CF_EXXXN_KEYS_DEBOUNCE_INTERVAL,
.gpio = CF_E320N_V2_GPIO_BTN_RESET,
.active_low = 1,
},
};
/* CF-E380AC v1/v2 */
#define CF_E380AC_V1V2_GPIO_LED_LAN 0
#define CF_E380AC_V1V2_GPIO_LED_WLAN2G 2
#define CF_E380AC_V1V2_GPIO_LED_WLAN5G 3
#define CF_E380AC_V1V2_GPIO_EXT_WDT 17
#define CF_E380AC_V1V2_GPIO_BTN_RESET 19
static struct gpio_led cf_e380ac_v1_leds_gpio[] __initdata = {
{
.name = "cf-e380ac-v1:green:lan",
.gpio = CF_E380AC_V1V2_GPIO_LED_LAN,
.active_low = 0,
}, {
.name = "cf-e380ac-v1:blue:wlan2g",
.gpio = CF_E380AC_V1V2_GPIO_LED_WLAN2G,
.active_low = 0,
}, {
.name = "cf-e380ac-v1:red:wlan5g",
.gpio = CF_E380AC_V1V2_GPIO_LED_WLAN5G,
.active_low = 0,
},
};
static struct gpio_led cf_e380ac_v2_leds_gpio[] __initdata = {
{
.name = "cf-e380ac-v2:green:lan",
.gpio = CF_E380AC_V1V2_GPIO_LED_LAN,
.active_low = 0,
}, {
.name = "cf-e380ac-v2:blue:wlan2g",
.gpio = CF_E380AC_V1V2_GPIO_LED_WLAN2G,
.active_low = 0,
}, {
.name = "cf-e380ac-v2:red:wlan5g",
.gpio = CF_E380AC_V1V2_GPIO_LED_WLAN5G,
.active_low = 0,
},
};
static struct gpio_keys_button cf_e380ac_v1v2_gpio_keys[] __initdata = {
{
.desc = "Reset button",
.type = EV_KEY,
.code = KEY_RESTART,
.debounce_interval = CF_EXXXN_KEYS_DEBOUNCE_INTERVAL,
.gpio = CF_E380AC_V1V2_GPIO_BTN_RESET,
.active_low = 1,
},
};
static struct at803x_platform_data cf_e380ac_v1v2_at803x_data = {
.disable_smarteee = 1,
};
static struct mdio_board_info cf_e380ac_v1v2_mdio0_info[] = {
{
.bus_id = "ag71xx-mdio.0",
.phy_addr = 0,
.platform_data = &cf_e380ac_v1v2_at803x_data,
},
};
/* CF-E520N/CF-E530N */
#define CF_E5X0N_GPIO_LED_WAN 11
#define CF_E5X0N_GPIO_BTN_RESET 17
static struct gpio_led cf_e520n_leds_gpio[] __initdata = {
{
.name = "cf-e520n:blue:wan",
.gpio = CF_E5X0N_GPIO_LED_WAN,
.active_low = 1,
}
};
static struct gpio_led cf_e530n_leds_gpio[] __initdata = {
{
.name = "cf-e530n:blue:wan",
.gpio = CF_E5X0N_GPIO_LED_WAN,
.active_low = 1,
}
};
/*
* Some COMFAST devices include external hardware watchdog chip,
* Pericon Technology PT7A7514, connected to a selected GPIO
* and WiSoC RESET_L input. Watchdog time-out is ~1.6 s.
*/
#define CF_EXXXN_EXT_WDT_TIMEOUT_MS 500
static struct timer_list gpio_wdt_timer;
static void gpio_wdt_toggle(unsigned long gpio)
{
static int state;
state = !state;
gpio_set_value(gpio, state);
mod_timer(&gpio_wdt_timer,
jiffies + msecs_to_jiffies(CF_EXXXN_EXT_WDT_TIMEOUT_MS));
}
static void __init cf_exxxn_common_setup(unsigned long art_ofs, int gpio_wdt)
{
u8 *art = (u8 *) KSEG1ADDR(0x1f001000 + art_ofs);
if (gpio_wdt > -1) {
gpio_request_one(gpio_wdt, GPIOF_OUT_INIT_HIGH,
"PT7A7514 watchdog");
setup_timer(&gpio_wdt_timer, gpio_wdt_toggle, gpio_wdt);
gpio_wdt_toggle(gpio_wdt);
}
ath79_register_m25p80(NULL);
ath79_register_wmac(art, NULL);
ath79_register_usb();
}
static void __init cf_e316n_v2_setup(void)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f010000);
cf_exxxn_common_setup(0x10000, CF_E316N_V2_GPIO_EXT_WDT);
ath79_setup_ar934x_eth_cfg(AR934X_ETH_CFG_SW_PHY_SWAP);
ath79_register_mdio(1, 0x0);
/* GMAC0 is connected to the PHY0 of the internal switch */
ath79_switch_data.phy4_mii_en = 1;
ath79_switch_data.phy_poll_mask = BIT(0);
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII;
ath79_eth0_data.phy_mask = BIT(0);
ath79_eth0_data.mii_bus_dev = &ath79_mdio1_device.dev;
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 0);
ath79_register_eth(0);
/* GMAC1 is connected to the internal switch */
ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII;
ath79_init_mac(ath79_eth1_data.mac_addr, mac, 2);
ath79_register_eth(1);
/* Enable 2x Skyworks SE2576L WLAN power amplifiers */
gpio_request_one(CF_E316N_V2_GPIO_EXTERNAL_PA0, GPIOF_OUT_INIT_HIGH,
"WLAN PA0");
gpio_request_one(CF_E316N_V2_GPIO_EXTERNAL_PA1, GPIOF_OUT_INIT_HIGH,
"WLAN PA1");
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e316n_v2_leds_gpio),
cf_e316n_v2_leds_gpio);
ath79_register_gpio_keys_polled(1, CF_EXXXN_KEYS_POLL_INTERVAL,
ARRAY_SIZE(cf_e316n_v2_gpio_keys),
cf_e316n_v2_gpio_keys);
}
MIPS_MACHINE(ATH79_MACH_CF_E316N_V2, "CF-E316N-V2", "COMFAST CF-E316N v2",
cf_e316n_v2_setup);
static void __init cf_exxxn_qca953x_eth_setup(void)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f010000);
ath79_setup_ar933x_phy4_switch(false, false);
ath79_register_mdio(0, 0x0);
ath79_switch_data.phy4_mii_en = 1;
ath79_switch_data.phy_poll_mask |= BIT(4);
/* LAN */
ath79_eth1_data.duplex = DUPLEX_FULL;
ath79_eth1_data.phy_if_mode = PHY_INTERFACE_MODE_GMII;
ath79_eth1_data.speed = SPEED_1000;
ath79_init_mac(ath79_eth1_data.mac_addr, mac, 2);
ath79_register_eth(1);
/* WAN */
ath79_eth0_data.duplex = DUPLEX_FULL;
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_MII;
ath79_eth0_data.speed = SPEED_100;
ath79_eth0_data.phy_mask = BIT(4);
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 0);
ath79_register_eth(0);
}
static void __init cf_e320n_v2_setup(void)
{
cf_exxxn_common_setup(0x10000, CF_E320N_V2_GPIO_EXT_WDT);
cf_exxxn_qca953x_eth_setup();
/* Disable JTAG (enables GPIO0-3) */
ath79_gpio_function_enable(AR934X_GPIO_FUNC_JTAG_DISABLE);
ath79_gpio_direction_select(CF_E320N_V2_GPIO_LED_LAN, true);
ath79_gpio_direction_select(CF_E320N_V2_GPIO_LED_WAN, true);
ath79_gpio_direction_select(CF_E320N_V2_GPIO_LED_WLAN, true);
ath79_gpio_output_select(CF_E320N_V2_GPIO_LED_LAN, 0);
ath79_gpio_output_select(CF_E320N_V2_GPIO_LED_WAN, 0);
ath79_gpio_output_select(CF_E320N_V2_GPIO_LED_WLAN, 0);
/* Enable GPIO function for GPIOs in J9 header */
ath79_gpio_output_select(CF_E320N_V2_GPIO_HEADER_J9_1, 0);
ath79_gpio_output_select(CF_E320N_V2_GPIO_HEADER_J9_2, 0);
ath79_gpio_output_select(CF_E320N_V2_GPIO_HEADER_J9_3, 0);
ath79_gpio_output_select(CF_E320N_V2_GPIO_HEADER_J9_4, 0);
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e320n_v2_leds_gpio),
cf_e320n_v2_leds_gpio);
ath79_register_gpio_keys_polled(-1, CF_EXXXN_KEYS_POLL_INTERVAL,
ARRAY_SIZE(cf_e320n_v2_gpio_keys),
cf_e320n_v2_gpio_keys);
}
MIPS_MACHINE(ATH79_MACH_CF_E320N_V2, "CF-E320N-V2", "COMFAST CF-E320N v2",
cf_e320n_v2_setup);
static void __init cf_e380ac_v1v2_common_setup(unsigned long art_ofs)
{
u8 *mac = (u8 *) KSEG1ADDR(0x1f000000 + art_ofs);
cf_exxxn_common_setup(art_ofs, CF_E380AC_V1V2_GPIO_EXT_WDT);
ath79_setup_qca955x_eth_cfg(QCA955X_ETH_CFG_RGMII_EN);
ath79_register_mdio(0, 0x0);
mdiobus_register_board_info(cf_e380ac_v1v2_mdio0_info,
ARRAY_SIZE(cf_e380ac_v1v2_mdio0_info));
/* LAN */
ath79_eth0_data.mii_bus_dev = &ath79_mdio0_device.dev;
ath79_eth0_data.phy_if_mode = PHY_INTERFACE_MODE_RGMII;
ath79_eth0_data.phy_mask = BIT(0);
ath79_eth0_pll_data.pll_1000 = 0xbe000000;
ath79_eth0_pll_data.pll_100 = 0xb0000101;
ath79_eth0_pll_data.pll_10 = 0xb0001313;
ath79_init_mac(ath79_eth0_data.mac_addr, mac, 0);
ath79_register_eth(0);
ap91_pci_init(mac + 0x5000, NULL);
/* Disable JTAG (enables GPIO0-3) */
ath79_gpio_function_enable(AR934X_GPIO_FUNC_JTAG_DISABLE);
ath79_gpio_direction_select(CF_E380AC_V1V2_GPIO_LED_LAN, true);
ath79_gpio_direction_select(CF_E380AC_V1V2_GPIO_LED_WLAN2G, true);
ath79_gpio_direction_select(CF_E380AC_V1V2_GPIO_LED_WLAN5G, true);
ath79_gpio_output_select(CF_E380AC_V1V2_GPIO_LED_LAN, 0);
ath79_gpio_output_select(CF_E380AC_V1V2_GPIO_LED_WLAN2G, 0);
ath79_gpio_output_select(CF_E380AC_V1V2_GPIO_LED_WLAN5G, 0);
/* For J7-4 */
ath79_gpio_function_disable(AR934X_GPIO_FUNC_CLK_OBS4_EN);
ath79_register_gpio_keys_polled(-1, CF_EXXXN_KEYS_POLL_INTERVAL,
ARRAY_SIZE(cf_e380ac_v1v2_gpio_keys),
cf_e380ac_v1v2_gpio_keys);
}
static void __init cf_e380ac_v1_setup(void)
{
cf_e380ac_v1v2_common_setup(0x20000);
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e380ac_v1_leds_gpio),
cf_e380ac_v1_leds_gpio);
}
MIPS_MACHINE(ATH79_MACH_CF_E380AC_V1, "CF-E380AC-V1", "COMFAST CF-E380AC v1",
cf_e380ac_v1_setup);
static void __init cf_e380ac_v2_setup(void)
{
cf_e380ac_v1v2_common_setup(0x40000);
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e380ac_v2_leds_gpio),
cf_e380ac_v2_leds_gpio);
}
MIPS_MACHINE(ATH79_MACH_CF_E380AC_V2, "CF-E380AC-V2", "COMFAST CF-E380AC v2",
cf_e380ac_v2_setup);
static void __init cf_e5x0n_gpio_setup(void)
{
ath79_gpio_direction_select(CF_E5X0N_GPIO_LED_WAN, true);
ath79_gpio_output_select(CF_E5X0N_GPIO_LED_WAN, 0);
ath79_register_gpio_keys_polled(-1, CF_EXXXN_KEYS_POLL_INTERVAL,
ARRAY_SIZE(cf_e320n_v2_gpio_keys),
cf_e320n_v2_gpio_keys);
}
static void __init cf_e520n_setup(void)
{
cf_exxxn_common_setup(0x10000, -1);
cf_exxxn_qca953x_eth_setup();
cf_e5x0n_gpio_setup();
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e520n_leds_gpio),
cf_e520n_leds_gpio);
}
MIPS_MACHINE(ATH79_MACH_CF_E520N, "CF-E520N", "COMFAST CF-E520N",
cf_e520n_setup);
static void __init cf_e530n_setup(void)
{
cf_exxxn_common_setup(0x10000, -1);
cf_exxxn_qca953x_eth_setup();
cf_e5x0n_gpio_setup();
ath79_register_leds_gpio(-1, ARRAY_SIZE(cf_e530n_leds_gpio),
cf_e530n_leds_gpio);
}
MIPS_MACHINE(ATH79_MACH_CF_E530N, "CF-E530N", "COMFAST CF-E530N",
cf_e530n_setup);
| gpl-2.0 |
task650/kernel_htc_msm8974 | arch/arm/mach-msm/display/htc_mec-panel.c | 46 | 11814 | #include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <linux/i2c.h>
#include <asm/mach-types.h>
#include <mach/msm_memtypes.h>
#include <mach/board.h>
#include <mach/debug_display.h>
#include "../../../../drivers/video/msm/mdss/mdss_dsi.h"
#define PANEL_ID_DLX_SHARP_RENESAS 0
#define PANEL_ID_M8_SHARP_NT35595 1
#define PANEL_ID_M8_LG_RENESAS 2
#define PANEL_ID_M8_SHARP_NT35695 3
#define PANEL_ID_M8_LG_NT35695 5
#define PANEL_ID_M8_LG_NT35595 6
struct dsi_power_data {
uint32_t sysrev; /* system revision info */
struct regulator *vddio; /* 1.8v */
struct regulator *vdda; /* 1.2v */
struct regulator *vlcmio; /* 1.8v */
int lcmio;
int lcmp5v;
int lcmn5v;
int lcm_bl_en;
};
#ifdef MODULE
extern struct module __this_module;
#define THIS_MODULE (&__this_module)
#else
#define THIS_MODULE ((struct module *)0)
#endif
static struct i2c_adapter *i2c_bus_adapter = NULL;
struct i2c_dev_info {
uint8_t dev_addr;
struct i2c_client *client;
};
#define I2C_DEV_INFO(addr) \
{.dev_addr = addr >> 1, .client = NULL}
static struct i2c_dev_info device_addresses[] = {
I2C_DEV_INFO(0x7C)
};
static inline int platform_write_i2c_block(struct i2c_adapter *i2c_bus
, u8 page
, u8 offset
, u16 count
, u8 *values
)
{
struct i2c_msg msg;
u8 *buffer;
int ret;
buffer = kmalloc(count + 1, GFP_KERNEL);
if (!buffer) {
printk("%s:%d buffer allocation failed\n",__FUNCTION__,__LINE__);
return -ENOMEM;
}
buffer[0] = offset;
memmove(&buffer[1], values, count);
msg.flags = 0;
msg.addr = page >> 1;
msg.buf = buffer;
msg.len = count + 1;
ret = i2c_transfer(i2c_bus, &msg, 1);
kfree(buffer);
if (ret != 1) {
printk("%s:%d I2c write failed 0x%02x:0x%02x\n"
,__FUNCTION__,__LINE__, page, offset);
ret = -EIO;
} else {
ret = 0;
}
return ret;
}
static int tps_65132_add_i2c(struct i2c_client *client)
{
struct i2c_adapter *adapter = client->adapter;
int idx;
/* "Hotplug" the MHL transmitter device onto the 2nd I2C bus for BB-xM or 4th for pandaboard*/
i2c_bus_adapter = adapter;
if (i2c_bus_adapter == NULL) {
PR_DISP_ERR("%s() failed to get i2c adapter\n", __func__);
return ENODEV;
}
for (idx = 0; idx < ARRAY_SIZE(device_addresses); idx++) {
if(idx == 0)
device_addresses[idx].client = client;
else {
device_addresses[idx].client = i2c_new_dummy(i2c_bus_adapter,
device_addresses[idx].dev_addr);
if (device_addresses[idx].client == NULL){
return ENODEV;
}
}
}
return 0;
}
static int __devinit tps_65132_tx_i2c_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
int ret;
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE_DATA)) {
pr_err("[DISP] %s: Failed to i2c_check_functionality \n", __func__);
return -EIO;
}
if (!client->dev.of_node) {
pr_err("[DISP] %s: client->dev.of_node = NULL\n", __func__);
return -ENOMEM;
}
ret = tps_65132_add_i2c(client);
if(ret < 0) {
pr_err("[DISP] %s: Failed to tps_65132_add_i2c, ret=%d\n", __func__,ret);
return ret;
}
return 0;
}
static const struct i2c_device_id tps_65132_tx_id[] = {
{"tps65132", 0}
};
static struct of_device_id TSP_match_table[] = {
{.compatible = "disp-tps-65132",}
};
static struct i2c_driver tps_65132_tx_i2c_driver = {
.driver = {
.owner = THIS_MODULE,
.name = "tps65132",
.of_match_table = TSP_match_table,
},
.id_table = tps_65132_tx_id,
.probe = tps_65132_tx_i2c_probe,
.command = NULL,
};
static int htc_m8_regulator_init(struct platform_device *pdev)
{
int ret = 0;
struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL;
struct dsi_power_data *pwrdata = NULL;
PR_DISP_INFO("%s\n", __func__);
if (!pdev) {
pr_err("%s: invalid input\n", __func__);
return -EINVAL;
}
ctrl_pdata = platform_get_drvdata(pdev);
if (!ctrl_pdata) {
pr_err("%s: invalid driver data\n", __func__);
return -EINVAL;
}
pwrdata = devm_kzalloc(&pdev->dev,
sizeof(struct dsi_power_data), GFP_KERNEL);
if (!pwrdata) {
pr_err("[DISP] %s: FAILED to alloc pwrdata\n", __func__);
return -ENOMEM;
}
ctrl_pdata->dsi_pwrctrl_data = pwrdata;
pwrdata->vddio = devm_regulator_get(&pdev->dev, "vddio");
if (IS_ERR(pwrdata->vddio)) {
pr_err("%s: could not get vddio reg, rc=%ld\n",
__func__, PTR_ERR(pwrdata->vddio));
return PTR_ERR(pwrdata->vddio);
}
ret = regulator_set_voltage(pwrdata->vddio, 1800000,
1800000);
if (ret) {
pr_err("%s: set voltage failed on vddio vreg, rc=%d\n",
__func__, ret);
return ret;
}
pwrdata->vdda = devm_regulator_get(&pdev->dev, "vdda");
if (IS_ERR(pwrdata->vdda)) {
pr_err("%s: could not get vdda vreg, rc=%ld\n",
__func__, PTR_ERR(pwrdata->vdda));
return PTR_ERR(pwrdata->vdda);
}
ret = regulator_set_voltage(pwrdata->vdda, 1200000,
1200000);
if (ret) {
pr_err("%s: set voltage failed on vdda vreg, rc=%d\n",
__func__, ret);
return ret;
}
pwrdata->lcmio = of_get_named_gpio(pdev->dev.of_node,
"htc,lcm_1v8-gpio", 0);
pwrdata->lcmp5v = of_get_named_gpio(pdev->dev.of_node,
"htc,lcm_p5v-gpio", 0);
pwrdata->lcmn5v = of_get_named_gpio(pdev->dev.of_node,
"htc,lcm_n5v-gpio", 0);
pwrdata->vlcmio = devm_regulator_get(&pdev->dev, "vlcmio");
pwrdata->lcm_bl_en = of_get_named_gpio(pdev->dev.of_node,
"htc,lcm_bl_en-gpio", 0);
if (IS_ERR(pwrdata->vlcmio)) {
pr_err("%s: could not get vlcmio reg, rc=%ld\n",
__func__, PTR_ERR(pwrdata->vlcmio));
return PTR_ERR(pwrdata->vlcmio);
}
ret = i2c_add_driver(&tps_65132_tx_i2c_driver);
if (ret < 0) {
pr_err("[DISP] %s: FAILED to add i2c_add_driver ret=%x\n",
__func__, ret);
}
return 0;
}
static int htc_m8_regulator_deinit(struct platform_device *pdev)
{
/* devm_regulator() will automatically free regulators
while dev detach. */
/* nothing */
return 0;
}
bool htc_m8_renesas_panel_check(int panelID)
{
switch (panelID) {
case PANEL_ID_DLX_SHARP_RENESAS:
case PANEL_ID_M8_LG_RENESAS:
return true;
break;
default:
return false;
break;
}
}
int htc_m8_panel_reset(struct mdss_panel_data *pdata, int enable)
{
struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL;
if (pdata == NULL) {
pr_err("%s: Invalid input data\n", __func__);
return -EINVAL;
}
ctrl_pdata = container_of(pdata, struct mdss_dsi_ctrl_pdata,
panel_data);
if (!gpio_is_valid(ctrl_pdata->disp_en_gpio)) {
pr_debug("%s:%d, reset line not configured\n",
__func__, __LINE__);
}
if (!gpio_is_valid(ctrl_pdata->rst_gpio)) {
pr_debug("%s:%d, reset line not configured\n",
__func__, __LINE__);
return -EINVAL;
}
pr_debug("%s: enable = %d\n", __func__, enable);
if (enable) {
if (pdata->panel_info.first_power_on == 1) {
PR_DISP_INFO("reset already on in first time\n");
return 0;
}
if (!htc_m8_renesas_panel_check(pdata->panel_info.panel_id)) {
gpio_set_value((ctrl_pdata->rst_gpio), 1);
usleep_range(1000,1500);
gpio_set_value((ctrl_pdata->rst_gpio), 0);
usleep_range(1000,1500);
gpio_set_value((ctrl_pdata->rst_gpio), 1);
usleep_range(10000,10500);
} else {
gpio_set_value((ctrl_pdata->rst_gpio), 0);
usleep_range(1000,1500);
gpio_set_value((ctrl_pdata->rst_gpio), 1);
usleep_range(3000,3500);
}
if (gpio_is_valid(ctrl_pdata->disp_en_gpio))
gpio_set_value((ctrl_pdata->disp_en_gpio), 1);
if (ctrl_pdata->ctrl_state & CTRL_STATE_PANEL_INIT) {
pr_debug("%s: Panel Not properly turned OFF\n",
__func__);
ctrl_pdata->ctrl_state &= ~CTRL_STATE_PANEL_INIT;
pr_debug("%s: Reset panel done\n", __func__);
}
} else {
gpio_set_value((ctrl_pdata->rst_gpio), 0);
if (gpio_is_valid(ctrl_pdata->disp_en_gpio))
gpio_set_value((ctrl_pdata->disp_en_gpio), 0);
}
return 0;
}
bool htc_m8_lg_panel_check(int panelID)
{
switch (panelID) {
case PANEL_ID_M8_LG_RENESAS:
case PANEL_ID_M8_LG_NT35695:
case PANEL_ID_M8_LG_NT35595:
return true;
break;
default:
return false;
break;
}
}
static int htc_m8_panel_power_on(struct mdss_panel_data *pdata, int enable)
{
int ret;
struct mdss_dsi_ctrl_pdata *ctrl_pdata = NULL;
struct dsi_power_data *pwrdata = NULL;
PR_DISP_INFO("%s: en=%d\n", __func__, enable);
if (pdata == NULL) {
pr_err("%s: Invalid input data\n", __func__);
return -EINVAL;
}
ctrl_pdata = container_of(pdata, struct mdss_dsi_ctrl_pdata,
panel_data);
pwrdata = ctrl_pdata->dsi_pwrctrl_data;
if (!pwrdata) {
pr_err("%s: pwrdata not initialized\n", __func__);
return -EINVAL;
}
if (enable) {
if (gpio_is_valid(pwrdata->lcmio)) {
/* EVM */
gpio_set_value(pwrdata->lcmio, 1);
} else {
ret = regulator_enable(pwrdata->vlcmio);
if (ret) {
pr_err("%s: Failed to enable regulator.\n",
__func__);
return ret;
}
}
usleep_range(1000,1500);
gpio_set_value(pwrdata->lcmp5v, 1);
if (htc_m8_lg_panel_check(pdata->panel_info.panel_id)){
u8 avdd_level = 0x11;
platform_write_i2c_block(i2c_bus_adapter,0x7C,0x00, 0x01, &avdd_level);
platform_write_i2c_block(i2c_bus_adapter,0x7C,0x01, 0x01, &avdd_level);
}
usleep_range(1000,1500);
gpio_set_value(pwrdata->lcmn5v, 1);
ret = regulator_set_optimum_mode(pwrdata->vddio, 100000);
if (ret < 0) {
pr_err("%s: vddio set opt mode failed.\n",
__func__);
return ret;
}
ret = regulator_set_optimum_mode(pwrdata->vdda, 100000);
if (ret < 0) {
pr_err("%s: vdda set opt mode failed.\n",
__func__);
return ret;
}
ret = regulator_enable(pwrdata->vddio);
if (ret) {
pr_err("%s: Failed to enable regulator.\n",
__func__);
return ret;
}
ret = regulator_enable(pwrdata->vdda);
if (ret) {
pr_err("%s: Failed to enable regulator.\n",
__func__);
return ret;
}
usleep_range(13000,13500);
gpio_set_value(pwrdata->lcm_bl_en, 1);
} else {
gpio_set_value(pwrdata->lcm_bl_en, 0);
if (htc_m8_renesas_panel_check(pdata->panel_info.panel_id))
htc_m8_panel_reset(pdata, 0);
ret = regulator_disable(pwrdata->vdda);
if (ret) {
pr_err("%s: Failed to disable regulator.\n",
__func__);
return ret;
}
ret = regulator_disable(pwrdata->vddio);
if (ret) {
pr_err("%s: Failed to disable regulator.\n",
__func__);
return ret;
}
ret = regulator_set_optimum_mode(pwrdata->vddio, 100);
if (ret < 0) {
pr_err("%s: vdd_io_vreg set opt mode failed.\n",
__func__);
return ret;
}
ret = regulator_set_optimum_mode(pwrdata->vdda, 100);
if (ret < 0) {
pr_err("%s: vdda_vreg set opt mode failed.\n",
__func__);
return ret;
}
gpio_set_value(pwrdata->lcmn5v, 0);
usleep_range(1000,1500);
gpio_set_value(pwrdata->lcmp5v, 0);
if (!htc_m8_renesas_panel_check(pdata->panel_info.panel_id)){
usleep_range(1000,1500);
htc_m8_panel_reset(pdata, 0);
}
if (gpio_is_valid(pwrdata->lcmio)) {
gpio_set_value(pwrdata->lcmio, 0);
} else {
ret = regulator_disable(pwrdata->vlcmio);
if (ret) {
pr_err("%s: Failed to enable regulator.\n",
__func__);
return ret;
}
}
/* Delay 20ms to avoid panel issue when fast power on\off */
usleep_range(20000,20500);
}
PR_DISP_INFO("%s: en=%d done\n", __func__, enable);
return 0;
}
static struct mdss_dsi_pwrctrl dsi_pwrctrl = {
.dsi_regulator_init = htc_m8_regulator_init,
.dsi_regulator_deinit = htc_m8_regulator_deinit,
.dsi_power_on = htc_m8_panel_power_on,
.dsi_panel_reset = htc_m8_panel_reset,
};
static struct platform_device dsi_pwrctrl_device = {
.name = "mdss_dsi_pwrctrl",
.id = -1,
.dev.platform_data = &dsi_pwrctrl,
};
int __init htc_8974_dsi_panel_power_register(void)
{
pr_info("%s#%d\n", __func__, __LINE__);
platform_device_register(&dsi_pwrctrl_device);
return 0;
}
| gpl-2.0 |
cxgbit/cxgbit | drivers/power/ab8500_btemp.c | 814 | 32812 | /*
* Copyright (C) ST-Ericsson SA 2012
*
* Battery temperature driver for AB8500
*
* License Terms: GNU General Public License v2
* Author:
* Johan Palsson <johan.palsson@stericsson.com>
* Karl Komierowski <karl.komierowski@stericsson.com>
* Arun R Murthy <arun.murthy@stericsson.com>
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/power_supply.h>
#include <linux/completion.h>
#include <linux/workqueue.h>
#include <linux/jiffies.h>
#include <linux/of.h>
#include <linux/mfd/core.h>
#include <linux/mfd/abx500.h>
#include <linux/mfd/abx500/ab8500.h>
#include <linux/mfd/abx500/ab8500-bm.h>
#include <linux/mfd/abx500/ab8500-gpadc.h>
#define VTVOUT_V 1800
#define BTEMP_THERMAL_LOW_LIMIT -10
#define BTEMP_THERMAL_MED_LIMIT 0
#define BTEMP_THERMAL_HIGH_LIMIT_52 52
#define BTEMP_THERMAL_HIGH_LIMIT_57 57
#define BTEMP_THERMAL_HIGH_LIMIT_62 62
#define BTEMP_BATCTRL_CURR_SRC_7UA 7
#define BTEMP_BATCTRL_CURR_SRC_20UA 20
#define BTEMP_BATCTRL_CURR_SRC_16UA 16
#define BTEMP_BATCTRL_CURR_SRC_18UA 18
#define BTEMP_BATCTRL_CURR_SRC_60UA 60
#define BTEMP_BATCTRL_CURR_SRC_120UA 120
/**
* struct ab8500_btemp_interrupts - ab8500 interrupts
* @name: name of the interrupt
* @isr function pointer to the isr
*/
struct ab8500_btemp_interrupts {
char *name;
irqreturn_t (*isr)(int irq, void *data);
};
struct ab8500_btemp_events {
bool batt_rem;
bool btemp_high;
bool btemp_medhigh;
bool btemp_lowmed;
bool btemp_low;
bool ac_conn;
bool usb_conn;
};
struct ab8500_btemp_ranges {
int btemp_high_limit;
int btemp_med_limit;
int btemp_low_limit;
};
/**
* struct ab8500_btemp - ab8500 BTEMP device information
* @dev: Pointer to the structure device
* @node: List of AB8500 BTEMPs, hence prepared for reentrance
* @curr_source: What current source we use, in uA
* @bat_temp: Dispatched battery temperature in degree Celcius
* @prev_bat_temp Last measured battery temperature in degree Celcius
* @parent: Pointer to the struct ab8500
* @gpadc: Pointer to the struct gpadc
* @fg: Pointer to the struct fg
* @bm: Platform specific battery management information
* @btemp_psy: Structure for BTEMP specific battery properties
* @events: Structure for information about events triggered
* @btemp_ranges: Battery temperature range structure
* @btemp_wq: Work queue for measuring the temperature periodically
* @btemp_periodic_work: Work for measuring the temperature periodically
* @initialized: True if battery id read.
*/
struct ab8500_btemp {
struct device *dev;
struct list_head node;
int curr_source;
int bat_temp;
int prev_bat_temp;
struct ab8500 *parent;
struct ab8500_gpadc *gpadc;
struct ab8500_fg *fg;
struct abx500_bm_data *bm;
struct power_supply *btemp_psy;
struct ab8500_btemp_events events;
struct ab8500_btemp_ranges btemp_ranges;
struct workqueue_struct *btemp_wq;
struct delayed_work btemp_periodic_work;
bool initialized;
};
/* BTEMP power supply properties */
static enum power_supply_property ab8500_btemp_props[] = {
POWER_SUPPLY_PROP_PRESENT,
POWER_SUPPLY_PROP_ONLINE,
POWER_SUPPLY_PROP_TECHNOLOGY,
POWER_SUPPLY_PROP_TEMP,
};
static LIST_HEAD(ab8500_btemp_list);
/**
* ab8500_btemp_get() - returns a reference to the primary AB8500 BTEMP
* (i.e. the first BTEMP in the instance list)
*/
struct ab8500_btemp *ab8500_btemp_get(void)
{
struct ab8500_btemp *btemp;
btemp = list_first_entry(&ab8500_btemp_list, struct ab8500_btemp, node);
return btemp;
}
EXPORT_SYMBOL(ab8500_btemp_get);
/**
* ab8500_btemp_batctrl_volt_to_res() - convert batctrl voltage to resistance
* @di: pointer to the ab8500_btemp structure
* @v_batctrl: measured batctrl voltage
* @inst_curr: measured instant current
*
* This function returns the battery resistance that is
* derived from the BATCTRL voltage.
* Returns value in Ohms.
*/
static int ab8500_btemp_batctrl_volt_to_res(struct ab8500_btemp *di,
int v_batctrl, int inst_curr)
{
int rbs;
if (is_ab8500_1p1_or_earlier(di->parent)) {
/*
* For ABB cut1.0 and 1.1 BAT_CTRL is internally
* connected to 1.8V through a 450k resistor
*/
return (450000 * (v_batctrl)) / (1800 - v_batctrl);
}
if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL) {
/*
* If the battery has internal NTC, we use the current
* source to calculate the resistance.
*/
rbs = (v_batctrl * 1000
- di->bm->gnd_lift_resistance * inst_curr)
/ di->curr_source;
} else {
/*
* BAT_CTRL is internally
* connected to 1.8V through a 80k resistor
*/
rbs = (80000 * (v_batctrl)) / (1800 - v_batctrl);
}
return rbs;
}
/**
* ab8500_btemp_read_batctrl_voltage() - measure batctrl voltage
* @di: pointer to the ab8500_btemp structure
*
* This function returns the voltage on BATCTRL. Returns value in mV.
*/
static int ab8500_btemp_read_batctrl_voltage(struct ab8500_btemp *di)
{
int vbtemp;
static int prev;
vbtemp = ab8500_gpadc_convert(di->gpadc, BAT_CTRL);
if (vbtemp < 0) {
dev_err(di->dev,
"%s gpadc conversion failed, using previous value",
__func__);
return prev;
}
prev = vbtemp;
return vbtemp;
}
/**
* ab8500_btemp_curr_source_enable() - enable/disable batctrl current source
* @di: pointer to the ab8500_btemp structure
* @enable: enable or disable the current source
*
* Enable or disable the current sources for the BatCtrl AD channel
*/
static int ab8500_btemp_curr_source_enable(struct ab8500_btemp *di,
bool enable)
{
int curr;
int ret = 0;
/*
* BATCTRL current sources are included on AB8500 cut2.0
* and future versions
*/
if (is_ab8500_1p1_or_earlier(di->parent))
return 0;
/* Only do this for batteries with internal NTC */
if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL && enable) {
if (is_ab8540(di->parent)) {
if (di->curr_source == BTEMP_BATCTRL_CURR_SRC_60UA)
curr = BAT_CTRL_60U_ENA;
else
curr = BAT_CTRL_120U_ENA;
} else if (is_ab9540(di->parent) || is_ab8505(di->parent)) {
if (di->curr_source == BTEMP_BATCTRL_CURR_SRC_16UA)
curr = BAT_CTRL_16U_ENA;
else
curr = BAT_CTRL_18U_ENA;
} else {
if (di->curr_source == BTEMP_BATCTRL_CURR_SRC_7UA)
curr = BAT_CTRL_7U_ENA;
else
curr = BAT_CTRL_20U_ENA;
}
dev_dbg(di->dev, "Set BATCTRL %duA\n", di->curr_source);
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
FORCE_BAT_CTRL_CMP_HIGH, FORCE_BAT_CTRL_CMP_HIGH);
if (ret) {
dev_err(di->dev, "%s failed setting cmp_force\n",
__func__);
return ret;
}
/*
* We have to wait one 32kHz cycle before enabling
* the current source, since ForceBatCtrlCmpHigh needs
* to be written in a separate cycle
*/
udelay(32);
ret = abx500_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
FORCE_BAT_CTRL_CMP_HIGH | curr);
if (ret) {
dev_err(di->dev, "%s failed enabling current source\n",
__func__);
goto disable_curr_source;
}
} else if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL && !enable) {
dev_dbg(di->dev, "Disable BATCTRL curr source\n");
if (is_ab8540(di->parent)) {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(
di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_60U_ENA | BAT_CTRL_120U_ENA,
~(BAT_CTRL_60U_ENA | BAT_CTRL_120U_ENA));
} else if (is_ab9540(di->parent) || is_ab8505(di->parent)) {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(
di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_16U_ENA | BAT_CTRL_18U_ENA,
~(BAT_CTRL_16U_ENA | BAT_CTRL_18U_ENA));
} else {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(
di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA,
~(BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA));
}
if (ret) {
dev_err(di->dev, "%s failed disabling current source\n",
__func__);
goto disable_curr_source;
}
/* Enable Pull-Up and comparator */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA,
BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA);
if (ret) {
dev_err(di->dev, "%s failed enabling PU and comp\n",
__func__);
goto enable_pu_comp;
}
/*
* We have to wait one 32kHz cycle before disabling
* ForceBatCtrlCmpHigh since this needs to be written
* in a separate cycle
*/
udelay(32);
/* Disable 'force comparator' */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
FORCE_BAT_CTRL_CMP_HIGH, ~FORCE_BAT_CTRL_CMP_HIGH);
if (ret) {
dev_err(di->dev, "%s failed disabling force comp\n",
__func__);
goto disable_force_comp;
}
}
return ret;
/*
* We have to try unsetting FORCE_BAT_CTRL_CMP_HIGH one more time
* if we got an error above
*/
disable_curr_source:
if (is_ab8540(di->parent)) {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_60U_ENA | BAT_CTRL_120U_ENA,
~(BAT_CTRL_60U_ENA | BAT_CTRL_120U_ENA));
} else if (is_ab9540(di->parent) || is_ab8505(di->parent)) {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_16U_ENA | BAT_CTRL_18U_ENA,
~(BAT_CTRL_16U_ENA | BAT_CTRL_18U_ENA));
} else {
/* Write 0 to the curr bits */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA,
~(BAT_CTRL_7U_ENA | BAT_CTRL_20U_ENA));
}
if (ret) {
dev_err(di->dev, "%s failed disabling current source\n",
__func__);
return ret;
}
enable_pu_comp:
/* Enable Pull-Up and comparator */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA,
BAT_CTRL_PULL_UP_ENA | BAT_CTRL_CMP_ENA);
if (ret) {
dev_err(di->dev, "%s failed enabling PU and comp\n",
__func__);
return ret;
}
disable_force_comp:
/*
* We have to wait one 32kHz cycle before disabling
* ForceBatCtrlCmpHigh since this needs to be written
* in a separate cycle
*/
udelay(32);
/* Disable 'force comparator' */
ret = abx500_mask_and_set_register_interruptible(di->dev,
AB8500_CHARGER, AB8500_BAT_CTRL_CURRENT_SOURCE,
FORCE_BAT_CTRL_CMP_HIGH, ~FORCE_BAT_CTRL_CMP_HIGH);
if (ret) {
dev_err(di->dev, "%s failed disabling force comp\n",
__func__);
return ret;
}
return ret;
}
/**
* ab8500_btemp_get_batctrl_res() - get battery resistance
* @di: pointer to the ab8500_btemp structure
*
* This function returns the battery pack identification resistance.
* Returns value in Ohms.
*/
static int ab8500_btemp_get_batctrl_res(struct ab8500_btemp *di)
{
int ret;
int batctrl = 0;
int res;
int inst_curr;
int i;
/*
* BATCTRL current sources are included on AB8500 cut2.0
* and future versions
*/
ret = ab8500_btemp_curr_source_enable(di, true);
if (ret) {
dev_err(di->dev, "%s curr source enabled failed\n", __func__);
return ret;
}
if (!di->fg)
di->fg = ab8500_fg_get();
if (!di->fg) {
dev_err(di->dev, "No fg found\n");
return -EINVAL;
}
ret = ab8500_fg_inst_curr_start(di->fg);
if (ret) {
dev_err(di->dev, "Failed to start current measurement\n");
return ret;
}
do {
msleep(20);
} while (!ab8500_fg_inst_curr_started(di->fg));
i = 0;
do {
batctrl += ab8500_btemp_read_batctrl_voltage(di);
i++;
msleep(20);
} while (!ab8500_fg_inst_curr_done(di->fg));
batctrl /= i;
ret = ab8500_fg_inst_curr_finalize(di->fg, &inst_curr);
if (ret) {
dev_err(di->dev, "Failed to finalize current measurement\n");
return ret;
}
res = ab8500_btemp_batctrl_volt_to_res(di, batctrl, inst_curr);
ret = ab8500_btemp_curr_source_enable(di, false);
if (ret) {
dev_err(di->dev, "%s curr source disable failed\n", __func__);
return ret;
}
dev_dbg(di->dev, "%s batctrl: %d res: %d inst_curr: %d samples: %d\n",
__func__, batctrl, res, inst_curr, i);
return res;
}
/**
* ab8500_btemp_res_to_temp() - resistance to temperature
* @di: pointer to the ab8500_btemp structure
* @tbl: pointer to the resiatance to temperature table
* @tbl_size: size of the resistance to temperature table
* @res: resistance to calculate the temperature from
*
* This function returns the battery temperature in degrees Celcius
* based on the NTC resistance.
*/
static int ab8500_btemp_res_to_temp(struct ab8500_btemp *di,
const struct abx500_res_to_temp *tbl, int tbl_size, int res)
{
int i, temp;
/*
* Calculate the formula for the straight line
* Simple interpolation if we are within
* the resistance table limits, extrapolate
* if resistance is outside the limits.
*/
if (res > tbl[0].resist)
i = 0;
else if (res <= tbl[tbl_size - 1].resist)
i = tbl_size - 2;
else {
i = 0;
while (!(res <= tbl[i].resist &&
res > tbl[i + 1].resist))
i++;
}
temp = tbl[i].temp + ((tbl[i + 1].temp - tbl[i].temp) *
(res - tbl[i].resist)) / (tbl[i + 1].resist - tbl[i].resist);
return temp;
}
/**
* ab8500_btemp_measure_temp() - measure battery temperature
* @di: pointer to the ab8500_btemp structure
*
* Returns battery temperature (on success) else the previous temperature
*/
static int ab8500_btemp_measure_temp(struct ab8500_btemp *di)
{
int temp;
static int prev;
int rbat, rntc, vntc;
u8 id;
id = di->bm->batt_id;
if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL &&
id != BATTERY_UNKNOWN) {
rbat = ab8500_btemp_get_batctrl_res(di);
if (rbat < 0) {
dev_err(di->dev, "%s get batctrl res failed\n",
__func__);
/*
* Return out-of-range temperature so that
* charging is stopped
*/
return BTEMP_THERMAL_LOW_LIMIT;
}
temp = ab8500_btemp_res_to_temp(di,
di->bm->bat_type[id].r_to_t_tbl,
di->bm->bat_type[id].n_temp_tbl_elements, rbat);
} else {
vntc = ab8500_gpadc_convert(di->gpadc, BTEMP_BALL);
if (vntc < 0) {
dev_err(di->dev,
"%s gpadc conversion failed,"
" using previous value\n", __func__);
return prev;
}
/*
* The PCB NTC is sourced from VTVOUT via a 230kOhm
* resistor.
*/
rntc = 230000 * vntc / (VTVOUT_V - vntc);
temp = ab8500_btemp_res_to_temp(di,
di->bm->bat_type[id].r_to_t_tbl,
di->bm->bat_type[id].n_temp_tbl_elements, rntc);
prev = temp;
}
dev_dbg(di->dev, "Battery temperature is %d\n", temp);
return temp;
}
/**
* ab8500_btemp_id() - Identify the connected battery
* @di: pointer to the ab8500_btemp structure
*
* This function will try to identify the battery by reading the ID
* resistor. Some brands use a combined ID resistor with a NTC resistor to
* both be able to identify and to read the temperature of it.
*/
static int ab8500_btemp_id(struct ab8500_btemp *di)
{
int res;
u8 i;
if (is_ab8540(di->parent))
di->curr_source = BTEMP_BATCTRL_CURR_SRC_60UA;
else if (is_ab9540(di->parent) || is_ab8505(di->parent))
di->curr_source = BTEMP_BATCTRL_CURR_SRC_16UA;
else
di->curr_source = BTEMP_BATCTRL_CURR_SRC_7UA;
di->bm->batt_id = BATTERY_UNKNOWN;
res = ab8500_btemp_get_batctrl_res(di);
if (res < 0) {
dev_err(di->dev, "%s get batctrl res failed\n", __func__);
return -ENXIO;
}
/* BATTERY_UNKNOWN is defined on position 0, skip it! */
for (i = BATTERY_UNKNOWN + 1; i < di->bm->n_btypes; i++) {
if ((res <= di->bm->bat_type[i].resis_high) &&
(res >= di->bm->bat_type[i].resis_low)) {
dev_dbg(di->dev, "Battery detected on %s"
" low %d < res %d < high: %d"
" index: %d\n",
di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL ?
"BATCTRL" : "BATTEMP",
di->bm->bat_type[i].resis_low, res,
di->bm->bat_type[i].resis_high, i);
di->bm->batt_id = i;
break;
}
}
if (di->bm->batt_id == BATTERY_UNKNOWN) {
dev_warn(di->dev, "Battery identified as unknown"
", resistance %d Ohm\n", res);
return -ENXIO;
}
/*
* We only have to change current source if the
* detected type is Type 1.
*/
if (di->bm->adc_therm == ABx500_ADC_THERM_BATCTRL &&
di->bm->batt_id == 1) {
if (is_ab8540(di->parent)) {
dev_dbg(di->dev,
"Set BATCTRL current source to 60uA\n");
di->curr_source = BTEMP_BATCTRL_CURR_SRC_60UA;
} else if (is_ab9540(di->parent) || is_ab8505(di->parent)) {
dev_dbg(di->dev,
"Set BATCTRL current source to 16uA\n");
di->curr_source = BTEMP_BATCTRL_CURR_SRC_16UA;
} else {
dev_dbg(di->dev, "Set BATCTRL current source to 20uA\n");
di->curr_source = BTEMP_BATCTRL_CURR_SRC_20UA;
}
}
return di->bm->batt_id;
}
/**
* ab8500_btemp_periodic_work() - Measuring the temperature periodically
* @work: pointer to the work_struct structure
*
* Work function for measuring the temperature periodically
*/
static void ab8500_btemp_periodic_work(struct work_struct *work)
{
int interval;
int bat_temp;
struct ab8500_btemp *di = container_of(work,
struct ab8500_btemp, btemp_periodic_work.work);
if (!di->initialized) {
/* Identify the battery */
if (ab8500_btemp_id(di) < 0)
dev_warn(di->dev, "failed to identify the battery\n");
}
bat_temp = ab8500_btemp_measure_temp(di);
/*
* Filter battery temperature.
* Allow direct updates on temperature only if two samples result in
* same temperature. Else only allow 1 degree change from previous
* reported value in the direction of the new measurement.
*/
if ((bat_temp == di->prev_bat_temp) || !di->initialized) {
if ((di->bat_temp != di->prev_bat_temp) || !di->initialized) {
di->initialized = true;
di->bat_temp = bat_temp;
power_supply_changed(di->btemp_psy);
}
} else if (bat_temp < di->prev_bat_temp) {
di->bat_temp--;
power_supply_changed(di->btemp_psy);
} else if (bat_temp > di->prev_bat_temp) {
di->bat_temp++;
power_supply_changed(di->btemp_psy);
}
di->prev_bat_temp = bat_temp;
if (di->events.ac_conn || di->events.usb_conn)
interval = di->bm->temp_interval_chg;
else
interval = di->bm->temp_interval_nochg;
/* Schedule a new measurement */
queue_delayed_work(di->btemp_wq,
&di->btemp_periodic_work,
round_jiffies(interval * HZ));
}
/**
* ab8500_btemp_batctrlindb_handler() - battery removal detected
* @irq: interrupt number
* @_di: void pointer that has to address of ab8500_btemp
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_btemp_batctrlindb_handler(int irq, void *_di)
{
struct ab8500_btemp *di = _di;
dev_err(di->dev, "Battery removal detected!\n");
di->events.batt_rem = true;
power_supply_changed(di->btemp_psy);
return IRQ_HANDLED;
}
/**
* ab8500_btemp_templow_handler() - battery temp lower than 10 degrees
* @irq: interrupt number
* @_di: void pointer that has to address of ab8500_btemp
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_btemp_templow_handler(int irq, void *_di)
{
struct ab8500_btemp *di = _di;
if (is_ab8500_3p3_or_earlier(di->parent)) {
dev_dbg(di->dev, "Ignore false btemp low irq"
" for ABB cut 1.0, 1.1, 2.0 and 3.3\n");
} else {
dev_crit(di->dev, "Battery temperature lower than -10deg c\n");
di->events.btemp_low = true;
di->events.btemp_high = false;
di->events.btemp_medhigh = false;
di->events.btemp_lowmed = false;
power_supply_changed(di->btemp_psy);
}
return IRQ_HANDLED;
}
/**
* ab8500_btemp_temphigh_handler() - battery temp higher than max temp
* @irq: interrupt number
* @_di: void pointer that has to address of ab8500_btemp
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_btemp_temphigh_handler(int irq, void *_di)
{
struct ab8500_btemp *di = _di;
dev_crit(di->dev, "Battery temperature is higher than MAX temp\n");
di->events.btemp_high = true;
di->events.btemp_medhigh = false;
di->events.btemp_lowmed = false;
di->events.btemp_low = false;
power_supply_changed(di->btemp_psy);
return IRQ_HANDLED;
}
/**
* ab8500_btemp_lowmed_handler() - battery temp between low and medium
* @irq: interrupt number
* @_di: void pointer that has to address of ab8500_btemp
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_btemp_lowmed_handler(int irq, void *_di)
{
struct ab8500_btemp *di = _di;
dev_dbg(di->dev, "Battery temperature is between low and medium\n");
di->events.btemp_lowmed = true;
di->events.btemp_medhigh = false;
di->events.btemp_high = false;
di->events.btemp_low = false;
power_supply_changed(di->btemp_psy);
return IRQ_HANDLED;
}
/**
* ab8500_btemp_medhigh_handler() - battery temp between medium and high
* @irq: interrupt number
* @_di: void pointer that has to address of ab8500_btemp
*
* Returns IRQ status(IRQ_HANDLED)
*/
static irqreturn_t ab8500_btemp_medhigh_handler(int irq, void *_di)
{
struct ab8500_btemp *di = _di;
dev_dbg(di->dev, "Battery temperature is between medium and high\n");
di->events.btemp_medhigh = true;
di->events.btemp_lowmed = false;
di->events.btemp_high = false;
di->events.btemp_low = false;
power_supply_changed(di->btemp_psy);
return IRQ_HANDLED;
}
/**
* ab8500_btemp_periodic() - Periodic temperature measurements
* @di: pointer to the ab8500_btemp structure
* @enable: enable or disable periodic temperature measurements
*
* Starts of stops periodic temperature measurements. Periodic measurements
* should only be done when a charger is connected.
*/
static void ab8500_btemp_periodic(struct ab8500_btemp *di,
bool enable)
{
dev_dbg(di->dev, "Enable periodic temperature measurements: %d\n",
enable);
/*
* Make sure a new measurement is done directly by cancelling
* any pending work
*/
cancel_delayed_work_sync(&di->btemp_periodic_work);
if (enable)
queue_delayed_work(di->btemp_wq, &di->btemp_periodic_work, 0);
}
/**
* ab8500_btemp_get_temp() - get battery temperature
* @di: pointer to the ab8500_btemp structure
*
* Returns battery temperature
*/
int ab8500_btemp_get_temp(struct ab8500_btemp *di)
{
int temp = 0;
/*
* The BTEMP events are not reliabe on AB8500 cut3.3
* and prior versions
*/
if (is_ab8500_3p3_or_earlier(di->parent)) {
temp = di->bat_temp * 10;
} else {
if (di->events.btemp_low) {
if (temp > di->btemp_ranges.btemp_low_limit)
temp = di->btemp_ranges.btemp_low_limit * 10;
else
temp = di->bat_temp * 10;
} else if (di->events.btemp_high) {
if (temp < di->btemp_ranges.btemp_high_limit)
temp = di->btemp_ranges.btemp_high_limit * 10;
else
temp = di->bat_temp * 10;
} else if (di->events.btemp_lowmed) {
if (temp > di->btemp_ranges.btemp_med_limit)
temp = di->btemp_ranges.btemp_med_limit * 10;
else
temp = di->bat_temp * 10;
} else if (di->events.btemp_medhigh) {
if (temp < di->btemp_ranges.btemp_med_limit)
temp = di->btemp_ranges.btemp_med_limit * 10;
else
temp = di->bat_temp * 10;
} else
temp = di->bat_temp * 10;
}
return temp;
}
EXPORT_SYMBOL(ab8500_btemp_get_temp);
/**
* ab8500_btemp_get_batctrl_temp() - get the temperature
* @btemp: pointer to the btemp structure
*
* Returns the batctrl temperature in millidegrees
*/
int ab8500_btemp_get_batctrl_temp(struct ab8500_btemp *btemp)
{
return btemp->bat_temp * 1000;
}
EXPORT_SYMBOL(ab8500_btemp_get_batctrl_temp);
/**
* ab8500_btemp_get_property() - get the btemp properties
* @psy: pointer to the power_supply structure
* @psp: pointer to the power_supply_property structure
* @val: pointer to the power_supply_propval union
*
* This function gets called when an application tries to get the btemp
* properties by reading the sysfs files.
* online: presence of the battery
* present: presence of the battery
* technology: battery technology
* temp: battery temperature
* Returns error code in case of failure else 0(on success)
*/
static int ab8500_btemp_get_property(struct power_supply *psy,
enum power_supply_property psp,
union power_supply_propval *val)
{
struct ab8500_btemp *di = power_supply_get_drvdata(psy);
switch (psp) {
case POWER_SUPPLY_PROP_PRESENT:
case POWER_SUPPLY_PROP_ONLINE:
if (di->events.batt_rem)
val->intval = 0;
else
val->intval = 1;
break;
case POWER_SUPPLY_PROP_TECHNOLOGY:
val->intval = di->bm->bat_type[di->bm->batt_id].name;
break;
case POWER_SUPPLY_PROP_TEMP:
val->intval = ab8500_btemp_get_temp(di);
break;
default:
return -EINVAL;
}
return 0;
}
static int ab8500_btemp_get_ext_psy_data(struct device *dev, void *data)
{
struct power_supply *psy;
struct power_supply *ext;
struct ab8500_btemp *di;
union power_supply_propval ret;
int i, j;
bool psy_found = false;
psy = (struct power_supply *)data;
ext = dev_get_drvdata(dev);
di = power_supply_get_drvdata(psy);
/*
* For all psy where the name of your driver
* appears in any supplied_to
*/
for (i = 0; i < ext->num_supplicants; i++) {
if (!strcmp(ext->supplied_to[i], psy->desc->name))
psy_found = true;
}
if (!psy_found)
return 0;
/* Go through all properties for the psy */
for (j = 0; j < ext->desc->num_properties; j++) {
enum power_supply_property prop;
prop = ext->desc->properties[j];
if (power_supply_get_property(ext, prop, &ret))
continue;
switch (prop) {
case POWER_SUPPLY_PROP_PRESENT:
switch (ext->desc->type) {
case POWER_SUPPLY_TYPE_MAINS:
/* AC disconnected */
if (!ret.intval && di->events.ac_conn) {
di->events.ac_conn = false;
}
/* AC connected */
else if (ret.intval && !di->events.ac_conn) {
di->events.ac_conn = true;
if (!di->events.usb_conn)
ab8500_btemp_periodic(di, true);
}
break;
case POWER_SUPPLY_TYPE_USB:
/* USB disconnected */
if (!ret.intval && di->events.usb_conn) {
di->events.usb_conn = false;
}
/* USB connected */
else if (ret.intval && !di->events.usb_conn) {
di->events.usb_conn = true;
if (!di->events.ac_conn)
ab8500_btemp_periodic(di, true);
}
break;
default:
break;
}
break;
default:
break;
}
}
return 0;
}
/**
* ab8500_btemp_external_power_changed() - callback for power supply changes
* @psy: pointer to the structure power_supply
*
* This function is pointing to the function pointer external_power_changed
* of the structure power_supply.
* This function gets executed when there is a change in the external power
* supply to the btemp.
*/
static void ab8500_btemp_external_power_changed(struct power_supply *psy)
{
struct ab8500_btemp *di = power_supply_get_drvdata(psy);
class_for_each_device(power_supply_class, NULL,
di->btemp_psy, ab8500_btemp_get_ext_psy_data);
}
/* ab8500 btemp driver interrupts and their respective isr */
static struct ab8500_btemp_interrupts ab8500_btemp_irq[] = {
{"BAT_CTRL_INDB", ab8500_btemp_batctrlindb_handler},
{"BTEMP_LOW", ab8500_btemp_templow_handler},
{"BTEMP_HIGH", ab8500_btemp_temphigh_handler},
{"BTEMP_LOW_MEDIUM", ab8500_btemp_lowmed_handler},
{"BTEMP_MEDIUM_HIGH", ab8500_btemp_medhigh_handler},
};
#if defined(CONFIG_PM)
static int ab8500_btemp_resume(struct platform_device *pdev)
{
struct ab8500_btemp *di = platform_get_drvdata(pdev);
ab8500_btemp_periodic(di, true);
return 0;
}
static int ab8500_btemp_suspend(struct platform_device *pdev,
pm_message_t state)
{
struct ab8500_btemp *di = platform_get_drvdata(pdev);
ab8500_btemp_periodic(di, false);
return 0;
}
#else
#define ab8500_btemp_suspend NULL
#define ab8500_btemp_resume NULL
#endif
static int ab8500_btemp_remove(struct platform_device *pdev)
{
struct ab8500_btemp *di = platform_get_drvdata(pdev);
int i, irq;
/* Disable interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_btemp_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
free_irq(irq, di);
}
/* Delete the work queue */
destroy_workqueue(di->btemp_wq);
flush_scheduled_work();
power_supply_unregister(di->btemp_psy);
return 0;
}
static char *supply_interface[] = {
"ab8500_chargalg",
"ab8500_fg",
};
static const struct power_supply_desc ab8500_btemp_desc = {
.name = "ab8500_btemp",
.type = POWER_SUPPLY_TYPE_BATTERY,
.properties = ab8500_btemp_props,
.num_properties = ARRAY_SIZE(ab8500_btemp_props),
.get_property = ab8500_btemp_get_property,
.external_power_changed = ab8500_btemp_external_power_changed,
};
static int ab8500_btemp_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
struct abx500_bm_data *plat = pdev->dev.platform_data;
struct power_supply_config psy_cfg = {};
struct ab8500_btemp *di;
int irq, i, ret = 0;
u8 val;
di = devm_kzalloc(&pdev->dev, sizeof(*di), GFP_KERNEL);
if (!di) {
dev_err(&pdev->dev, "%s no mem for ab8500_btemp\n", __func__);
return -ENOMEM;
}
if (!plat) {
dev_err(&pdev->dev, "no battery management data supplied\n");
return -EINVAL;
}
di->bm = plat;
if (np) {
ret = ab8500_bm_of_probe(&pdev->dev, np, di->bm);
if (ret) {
dev_err(&pdev->dev, "failed to get battery information\n");
return ret;
}
}
/* get parent data */
di->dev = &pdev->dev;
di->parent = dev_get_drvdata(pdev->dev.parent);
di->gpadc = ab8500_gpadc_get("ab8500-gpadc.0");
di->initialized = false;
psy_cfg.supplied_to = supply_interface;
psy_cfg.num_supplicants = ARRAY_SIZE(supply_interface);
psy_cfg.drv_data = di;
/* Create a work queue for the btemp */
di->btemp_wq =
create_singlethread_workqueue("ab8500_btemp_wq");
if (di->btemp_wq == NULL) {
dev_err(di->dev, "failed to create work queue\n");
return -ENOMEM;
}
/* Init work for measuring temperature periodically */
INIT_DEFERRABLE_WORK(&di->btemp_periodic_work,
ab8500_btemp_periodic_work);
/* Set BTEMP thermal limits. Low and Med are fixed */
di->btemp_ranges.btemp_low_limit = BTEMP_THERMAL_LOW_LIMIT;
di->btemp_ranges.btemp_med_limit = BTEMP_THERMAL_MED_LIMIT;
ret = abx500_get_register_interruptible(di->dev, AB8500_CHARGER,
AB8500_BTEMP_HIGH_TH, &val);
if (ret < 0) {
dev_err(di->dev, "%s ab8500 read failed\n", __func__);
goto free_btemp_wq;
}
switch (val) {
case BTEMP_HIGH_TH_57_0:
case BTEMP_HIGH_TH_57_1:
di->btemp_ranges.btemp_high_limit =
BTEMP_THERMAL_HIGH_LIMIT_57;
break;
case BTEMP_HIGH_TH_52:
di->btemp_ranges.btemp_high_limit =
BTEMP_THERMAL_HIGH_LIMIT_52;
break;
case BTEMP_HIGH_TH_62:
di->btemp_ranges.btemp_high_limit =
BTEMP_THERMAL_HIGH_LIMIT_62;
break;
}
/* Register BTEMP power supply class */
di->btemp_psy = power_supply_register(di->dev, &ab8500_btemp_desc,
&psy_cfg);
if (IS_ERR(di->btemp_psy)) {
dev_err(di->dev, "failed to register BTEMP psy\n");
ret = PTR_ERR(di->btemp_psy);
goto free_btemp_wq;
}
/* Register interrupts */
for (i = 0; i < ARRAY_SIZE(ab8500_btemp_irq); i++) {
irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
ret = request_threaded_irq(irq, NULL, ab8500_btemp_irq[i].isr,
IRQF_SHARED | IRQF_NO_SUSPEND,
ab8500_btemp_irq[i].name, di);
if (ret) {
dev_err(di->dev, "failed to request %s IRQ %d: %d\n"
, ab8500_btemp_irq[i].name, irq, ret);
goto free_irq;
}
dev_dbg(di->dev, "Requested %s IRQ %d: %d\n",
ab8500_btemp_irq[i].name, irq, ret);
}
platform_set_drvdata(pdev, di);
/* Kick off periodic temperature measurements */
ab8500_btemp_periodic(di, true);
list_add_tail(&di->node, &ab8500_btemp_list);
return ret;
free_irq:
power_supply_unregister(di->btemp_psy);
/* We also have to free all successfully registered irqs */
for (i = i - 1; i >= 0; i--) {
irq = platform_get_irq_byname(pdev, ab8500_btemp_irq[i].name);
free_irq(irq, di);
}
free_btemp_wq:
destroy_workqueue(di->btemp_wq);
return ret;
}
static const struct of_device_id ab8500_btemp_match[] = {
{ .compatible = "stericsson,ab8500-btemp", },
{ },
};
static struct platform_driver ab8500_btemp_driver = {
.probe = ab8500_btemp_probe,
.remove = ab8500_btemp_remove,
.suspend = ab8500_btemp_suspend,
.resume = ab8500_btemp_resume,
.driver = {
.name = "ab8500-btemp",
.of_match_table = ab8500_btemp_match,
},
};
static int __init ab8500_btemp_init(void)
{
return platform_driver_register(&ab8500_btemp_driver);
}
static void __exit ab8500_btemp_exit(void)
{
platform_driver_unregister(&ab8500_btemp_driver);
}
device_initcall(ab8500_btemp_init);
module_exit(ab8500_btemp_exit);
MODULE_LICENSE("GPL v2");
MODULE_AUTHOR("Johan Palsson, Karl Komierowski, Arun R Murthy");
MODULE_ALIAS("platform:ab8500-btemp");
MODULE_DESCRIPTION("AB8500 battery temperature driver");
| gpl-2.0 |
lx324310/linux | drivers/infiniband/hw/usnic/usnic_debugfs.c | 1582 | 4099 | /*
* Copyright (c) 2013, Cisco Systems, Inc. All rights reserved.
*
* This program is free software; you may redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/debugfs.h>
#include <linux/module.h>
#include "usnic.h"
#include "usnic_log.h"
#include "usnic_debugfs.h"
#include "usnic_ib_qp_grp.h"
#include "usnic_transport.h"
static struct dentry *debugfs_root;
static struct dentry *flows_dentry;
static ssize_t usnic_debugfs_buildinfo_read(struct file *f, char __user *data,
size_t count, loff_t *ppos)
{
char buf[500];
int res;
if (*ppos > 0)
return 0;
res = scnprintf(buf, sizeof(buf),
"version: %s\n"
"build date: %s\n",
DRV_VERSION, DRV_RELDATE);
return simple_read_from_buffer(data, count, ppos, buf, res);
}
static const struct file_operations usnic_debugfs_buildinfo_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = usnic_debugfs_buildinfo_read
};
static ssize_t flowinfo_read(struct file *f, char __user *data,
size_t count, loff_t *ppos)
{
struct usnic_ib_qp_grp_flow *qp_flow;
int n;
int left;
char *ptr;
char buf[512];
qp_flow = f->private_data;
ptr = buf;
left = count;
if (*ppos > 0)
return 0;
spin_lock(&qp_flow->qp_grp->lock);
n = scnprintf(ptr, left,
"QP Grp ID: %d Transport: %s ",
qp_flow->qp_grp->grp_id,
usnic_transport_to_str(qp_flow->trans_type));
UPDATE_PTR_LEFT(n, ptr, left);
if (qp_flow->trans_type == USNIC_TRANSPORT_ROCE_CUSTOM) {
n = scnprintf(ptr, left, "Port_Num:%hu\n",
qp_flow->usnic_roce.port_num);
UPDATE_PTR_LEFT(n, ptr, left);
} else if (qp_flow->trans_type == USNIC_TRANSPORT_IPV4_UDP) {
n = usnic_transport_sock_to_str(ptr, left,
qp_flow->udp.sock);
UPDATE_PTR_LEFT(n, ptr, left);
n = scnprintf(ptr, left, "\n");
UPDATE_PTR_LEFT(n, ptr, left);
}
spin_unlock(&qp_flow->qp_grp->lock);
return simple_read_from_buffer(data, count, ppos, buf, ptr - buf);
}
static const struct file_operations flowinfo_ops = {
.owner = THIS_MODULE,
.open = simple_open,
.read = flowinfo_read,
};
void usnic_debugfs_init(void)
{
debugfs_root = debugfs_create_dir(DRV_NAME, NULL);
if (IS_ERR(debugfs_root)) {
usnic_err("Failed to create debugfs root dir, check if debugfs is enabled in kernel configuration\n");
goto out_clear_root;
}
flows_dentry = debugfs_create_dir("flows", debugfs_root);
if (IS_ERR_OR_NULL(flows_dentry)) {
usnic_err("Failed to create debugfs flow dir with err %ld\n",
PTR_ERR(flows_dentry));
goto out_free_root;
}
debugfs_create_file("build-info", S_IRUGO, debugfs_root,
NULL, &usnic_debugfs_buildinfo_ops);
return;
out_free_root:
debugfs_remove_recursive(debugfs_root);
out_clear_root:
debugfs_root = NULL;
}
void usnic_debugfs_exit(void)
{
if (!debugfs_root)
return;
debugfs_remove_recursive(debugfs_root);
debugfs_root = NULL;
}
void usnic_debugfs_flow_add(struct usnic_ib_qp_grp_flow *qp_flow)
{
if (IS_ERR_OR_NULL(flows_dentry))
return;
scnprintf(qp_flow->dentry_name, sizeof(qp_flow->dentry_name),
"%u", qp_flow->flow->flow_id);
qp_flow->dbgfs_dentry = debugfs_create_file(qp_flow->dentry_name,
S_IRUGO,
flows_dentry,
qp_flow,
&flowinfo_ops);
if (IS_ERR_OR_NULL(qp_flow->dbgfs_dentry)) {
usnic_err("Failed to create dbg fs entry for flow %u\n",
qp_flow->flow->flow_id);
}
}
void usnic_debugfs_flow_remove(struct usnic_ib_qp_grp_flow *qp_flow)
{
if (!IS_ERR_OR_NULL(qp_flow->dbgfs_dentry))
debugfs_remove(qp_flow->dbgfs_dentry);
}
| gpl-2.0 |
mdo-rom/platform_kernel_samsung_crespo | drivers/net/natsemi.c | 2350 | 95162 | /* natsemi.c: A Linux PCI Ethernet driver for the NatSemi DP8381x series. */
/*
Written/copyright 1999-2001 by Donald Becker.
Portions copyright (c) 2001,2002 Sun Microsystems (thockin@sun.com)
Portions copyright 2001,2002 Manfred Spraul (manfred@colorfullife.com)
Portions copyright 2004 Harald Welte <laforge@gnumonks.org>
This software may be used and distributed according to the terms of
the GNU General Public License (GPL), incorporated herein by reference.
Drivers based on or derived from this code fall under the GPL and must
retain the authorship, copyright and license notice. This file is not
a complete program and may only be used when the entire operating
system is licensed under the GPL. License for under other terms may be
available. Contact the original author for details.
The original author may be reached as becker@scyld.com, or at
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Support information and updates available at
http://www.scyld.com/network/netsemi.html
[link no longer provides useful info -jgarzik]
TODO:
* big endian support with CFG:BEM instead of cpu_to_le32
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/init.h>
#include <linux/spinlock.h>
#include <linux/ethtool.h>
#include <linux/delay.h>
#include <linux/rtnetlink.h>
#include <linux/mii.h>
#include <linux/crc32.h>
#include <linux/bitops.h>
#include <linux/prefetch.h>
#include <asm/processor.h> /* Processor type for cache alignment. */
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#define DRV_NAME "natsemi"
#define DRV_VERSION "2.1"
#define DRV_RELDATE "Sept 11, 2006"
#define RX_OFFSET 2
/* Updated to recommendations in pci-skeleton v2.03. */
/* The user-configurable values.
These may be modified when a driver module is loaded.*/
#define NATSEMI_DEF_MSG (NETIF_MSG_DRV | \
NETIF_MSG_LINK | \
NETIF_MSG_WOL | \
NETIF_MSG_RX_ERR | \
NETIF_MSG_TX_ERR)
static int debug = -1;
static int mtu;
/* Maximum number of multicast addresses to filter (vs. rx-all-multicast).
This chip uses a 512 element hash table based on the Ethernet CRC. */
static const int multicast_filter_limit = 100;
/* Set the copy breakpoint for the copy-only-tiny-frames scheme.
Setting to > 1518 effectively disables this feature. */
static int rx_copybreak;
static int dspcfg_workaround = 1;
/* Used to pass the media type, etc.
Both 'options[]' and 'full_duplex[]' should exist for driver
interoperability.
The media type is usually passed in 'options[]'.
*/
#define MAX_UNITS 8 /* More are supported, limit only on options */
static int options[MAX_UNITS];
static int full_duplex[MAX_UNITS];
/* Operational parameters that are set at compile time. */
/* Keep the ring sizes a power of two for compile efficiency.
The compiler will convert <unsigned>'%'<2^N> into a bit mask.
Making the Tx ring too large decreases the effectiveness of channel
bonding and packet priority.
There are no ill effects from too-large receive rings. */
#define TX_RING_SIZE 16
#define TX_QUEUE_LEN 10 /* Limit ring entries actually used, min 4. */
#define RX_RING_SIZE 32
/* Operational parameters that usually are not changed. */
/* Time in jiffies before concluding the transmitter is hung. */
#define TX_TIMEOUT (2*HZ)
#define NATSEMI_HW_TIMEOUT 400
#define NATSEMI_TIMER_FREQ 5*HZ
#define NATSEMI_PG0_NREGS 64
#define NATSEMI_RFDR_NREGS 8
#define NATSEMI_PG1_NREGS 4
#define NATSEMI_NREGS (NATSEMI_PG0_NREGS + NATSEMI_RFDR_NREGS + \
NATSEMI_PG1_NREGS)
#define NATSEMI_REGS_VER 1 /* v1 added RFDR registers */
#define NATSEMI_REGS_SIZE (NATSEMI_NREGS * sizeof(u32))
/* Buffer sizes:
* The nic writes 32-bit values, even if the upper bytes of
* a 32-bit value are beyond the end of the buffer.
*/
#define NATSEMI_HEADERS 22 /* 2*mac,type,vlan,crc */
#define NATSEMI_PADDING 16 /* 2 bytes should be sufficient */
#define NATSEMI_LONGPKT 1518 /* limit for normal packets */
#define NATSEMI_RX_LIMIT 2046 /* maximum supported by hardware */
/* These identify the driver base version and may not be removed. */
static const char version[] __devinitconst =
KERN_INFO DRV_NAME " dp8381x driver, version "
DRV_VERSION ", " DRV_RELDATE "\n"
" originally by Donald Becker <becker@scyld.com>\n"
" 2.4.x kernel port by Jeff Garzik, Tjeerd Mulder\n";
MODULE_AUTHOR("Donald Becker <becker@scyld.com>");
MODULE_DESCRIPTION("National Semiconductor DP8381x series PCI Ethernet driver");
MODULE_LICENSE("GPL");
module_param(mtu, int, 0);
module_param(debug, int, 0);
module_param(rx_copybreak, int, 0);
module_param(dspcfg_workaround, int, 0);
module_param_array(options, int, NULL, 0);
module_param_array(full_duplex, int, NULL, 0);
MODULE_PARM_DESC(mtu, "DP8381x MTU (all boards)");
MODULE_PARM_DESC(debug, "DP8381x default debug level");
MODULE_PARM_DESC(rx_copybreak,
"DP8381x copy breakpoint for copy-only-tiny-frames");
MODULE_PARM_DESC(dspcfg_workaround, "DP8381x: control DspCfg workaround");
MODULE_PARM_DESC(options,
"DP8381x: Bits 0-3: media type, bit 17: full duplex");
MODULE_PARM_DESC(full_duplex, "DP8381x full duplex setting(s) (1)");
/*
Theory of Operation
I. Board Compatibility
This driver is designed for National Semiconductor DP83815 PCI Ethernet NIC.
It also works with other chips in in the DP83810 series.
II. Board-specific settings
This driver requires the PCI interrupt line to be valid.
It honors the EEPROM-set values.
III. Driver operation
IIIa. Ring buffers
This driver uses two statically allocated fixed-size descriptor lists
formed into rings by a branch from the final descriptor to the beginning of
the list. The ring sizes are set at compile time by RX/TX_RING_SIZE.
The NatSemi design uses a 'next descriptor' pointer that the driver forms
into a list.
IIIb/c. Transmit/Receive Structure
This driver uses a zero-copy receive and transmit scheme.
The driver allocates full frame size skbuffs for the Rx ring buffers at
open() time and passes the skb->data field to the chip as receive data
buffers. When an incoming frame is less than RX_COPYBREAK bytes long,
a fresh skbuff is allocated and the frame is copied to the new skbuff.
When the incoming frame is larger, the skbuff is passed directly up the
protocol stack. Buffers consumed this way are replaced by newly allocated
skbuffs in a later phase of receives.
The RX_COPYBREAK value is chosen to trade-off the memory wasted by
using a full-sized skbuff for small frames vs. the copying costs of larger
frames. New boards are typically used in generously configured machines
and the underfilled buffers have negligible impact compared to the benefit of
a single allocation size, so the default value of zero results in never
copying packets. When copying is done, the cost is usually mitigated by using
a combined copy/checksum routine. Copying also preloads the cache, which is
most useful with small frames.
A subtle aspect of the operation is that unaligned buffers are not permitted
by the hardware. Thus the IP header at offset 14 in an ethernet frame isn't
longword aligned for further processing. On copies frames are put into the
skbuff at an offset of "+2", 16-byte aligning the IP header.
IIId. Synchronization
Most operations are synchronized on the np->lock irq spinlock, except the
receive and transmit paths which are synchronised using a combination of
hardware descriptor ownership, disabling interrupts and NAPI poll scheduling.
IVb. References
http://www.scyld.com/expert/100mbps.html
http://www.scyld.com/expert/NWay.html
Datasheet is available from:
http://www.national.com/pf/DP/DP83815.html
IVc. Errata
None characterised.
*/
/*
* Support for fibre connections on Am79C874:
* This phy needs a special setup when connected to a fibre cable.
* http://www.amd.com/files/connectivitysolutions/networking/archivednetworking/22235.pdf
*/
#define PHYID_AM79C874 0x0022561b
enum {
MII_MCTRL = 0x15, /* mode control register */
MII_FX_SEL = 0x0001, /* 100BASE-FX (fiber) */
MII_EN_SCRM = 0x0004, /* enable scrambler (tp) */
};
enum {
NATSEMI_FLAG_IGNORE_PHY = 0x1,
};
/* array of board data directly indexed by pci_tbl[x].driver_data */
static struct {
const char *name;
unsigned long flags;
unsigned int eeprom_size;
} natsemi_pci_info[] __devinitdata = {
{ "Aculab E1/T1 PMXc cPCI carrier card", NATSEMI_FLAG_IGNORE_PHY, 128 },
{ "NatSemi DP8381[56]", 0, 24 },
};
static DEFINE_PCI_DEVICE_TABLE(natsemi_pci_tbl) = {
{ PCI_VENDOR_ID_NS, 0x0020, 0x12d9, 0x000c, 0, 0, 0 },
{ PCI_VENDOR_ID_NS, 0x0020, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 1 },
{ } /* terminate list */
};
MODULE_DEVICE_TABLE(pci, natsemi_pci_tbl);
/* Offsets to the device registers.
Unlike software-only systems, device drivers interact with complex hardware.
It's not useful to define symbolic names for every register bit in the
device.
*/
enum register_offsets {
ChipCmd = 0x00,
ChipConfig = 0x04,
EECtrl = 0x08,
PCIBusCfg = 0x0C,
IntrStatus = 0x10,
IntrMask = 0x14,
IntrEnable = 0x18,
IntrHoldoff = 0x1C, /* DP83816 only */
TxRingPtr = 0x20,
TxConfig = 0x24,
RxRingPtr = 0x30,
RxConfig = 0x34,
ClkRun = 0x3C,
WOLCmd = 0x40,
PauseCmd = 0x44,
RxFilterAddr = 0x48,
RxFilterData = 0x4C,
BootRomAddr = 0x50,
BootRomData = 0x54,
SiliconRev = 0x58,
StatsCtrl = 0x5C,
StatsData = 0x60,
RxPktErrs = 0x60,
RxMissed = 0x68,
RxCRCErrs = 0x64,
BasicControl = 0x80,
BasicStatus = 0x84,
AnegAdv = 0x90,
AnegPeer = 0x94,
PhyStatus = 0xC0,
MIntrCtrl = 0xC4,
MIntrStatus = 0xC8,
PhyCtrl = 0xE4,
/* These are from the spec, around page 78... on a separate table.
* The meaning of these registers depend on the value of PGSEL. */
PGSEL = 0xCC,
PMDCSR = 0xE4,
TSTDAT = 0xFC,
DSPCFG = 0xF4,
SDCFG = 0xF8
};
/* the values for the 'magic' registers above (PGSEL=1) */
#define PMDCSR_VAL 0x189c /* enable preferred adaptation circuitry */
#define TSTDAT_VAL 0x0
#define DSPCFG_VAL 0x5040
#define SDCFG_VAL 0x008c /* set voltage thresholds for Signal Detect */
#define DSPCFG_LOCK 0x20 /* coefficient lock bit in DSPCFG */
#define DSPCFG_COEF 0x1000 /* see coefficient (in TSTDAT) bit in DSPCFG */
#define TSTDAT_FIXED 0xe8 /* magic number for bad coefficients */
/* misc PCI space registers */
enum pci_register_offsets {
PCIPM = 0x44,
};
enum ChipCmd_bits {
ChipReset = 0x100,
RxReset = 0x20,
TxReset = 0x10,
RxOff = 0x08,
RxOn = 0x04,
TxOff = 0x02,
TxOn = 0x01,
};
enum ChipConfig_bits {
CfgPhyDis = 0x200,
CfgPhyRst = 0x400,
CfgExtPhy = 0x1000,
CfgAnegEnable = 0x2000,
CfgAneg100 = 0x4000,
CfgAnegFull = 0x8000,
CfgAnegDone = 0x8000000,
CfgFullDuplex = 0x20000000,
CfgSpeed100 = 0x40000000,
CfgLink = 0x80000000,
};
enum EECtrl_bits {
EE_ShiftClk = 0x04,
EE_DataIn = 0x01,
EE_ChipSelect = 0x08,
EE_DataOut = 0x02,
MII_Data = 0x10,
MII_Write = 0x20,
MII_ShiftClk = 0x40,
};
enum PCIBusCfg_bits {
EepromReload = 0x4,
};
/* Bits in the interrupt status/mask registers. */
enum IntrStatus_bits {
IntrRxDone = 0x0001,
IntrRxIntr = 0x0002,
IntrRxErr = 0x0004,
IntrRxEarly = 0x0008,
IntrRxIdle = 0x0010,
IntrRxOverrun = 0x0020,
IntrTxDone = 0x0040,
IntrTxIntr = 0x0080,
IntrTxErr = 0x0100,
IntrTxIdle = 0x0200,
IntrTxUnderrun = 0x0400,
StatsMax = 0x0800,
SWInt = 0x1000,
WOLPkt = 0x2000,
LinkChange = 0x4000,
IntrHighBits = 0x8000,
RxStatusFIFOOver = 0x10000,
IntrPCIErr = 0xf00000,
RxResetDone = 0x1000000,
TxResetDone = 0x2000000,
IntrAbnormalSummary = 0xCD20,
};
/*
* Default Interrupts:
* Rx OK, Rx Packet Error, Rx Overrun,
* Tx OK, Tx Packet Error, Tx Underrun,
* MIB Service, Phy Interrupt, High Bits,
* Rx Status FIFO overrun,
* Received Target Abort, Received Master Abort,
* Signalled System Error, Received Parity Error
*/
#define DEFAULT_INTR 0x00f1cd65
enum TxConfig_bits {
TxDrthMask = 0x3f,
TxFlthMask = 0x3f00,
TxMxdmaMask = 0x700000,
TxMxdma_512 = 0x0,
TxMxdma_4 = 0x100000,
TxMxdma_8 = 0x200000,
TxMxdma_16 = 0x300000,
TxMxdma_32 = 0x400000,
TxMxdma_64 = 0x500000,
TxMxdma_128 = 0x600000,
TxMxdma_256 = 0x700000,
TxCollRetry = 0x800000,
TxAutoPad = 0x10000000,
TxMacLoop = 0x20000000,
TxHeartIgn = 0x40000000,
TxCarrierIgn = 0x80000000
};
/*
* Tx Configuration:
* - 256 byte DMA burst length
* - fill threshold 512 bytes (i.e. restart DMA when 512 bytes are free)
* - 64 bytes initial drain threshold (i.e. begin actual transmission
* when 64 byte are in the fifo)
* - on tx underruns, increase drain threshold by 64.
* - at most use a drain threshold of 1472 bytes: The sum of the fill
* threshold and the drain threshold must be less than 2016 bytes.
*
*/
#define TX_FLTH_VAL ((512/32) << 8)
#define TX_DRTH_VAL_START (64/32)
#define TX_DRTH_VAL_INC 2
#define TX_DRTH_VAL_LIMIT (1472/32)
enum RxConfig_bits {
RxDrthMask = 0x3e,
RxMxdmaMask = 0x700000,
RxMxdma_512 = 0x0,
RxMxdma_4 = 0x100000,
RxMxdma_8 = 0x200000,
RxMxdma_16 = 0x300000,
RxMxdma_32 = 0x400000,
RxMxdma_64 = 0x500000,
RxMxdma_128 = 0x600000,
RxMxdma_256 = 0x700000,
RxAcceptLong = 0x8000000,
RxAcceptTx = 0x10000000,
RxAcceptRunt = 0x40000000,
RxAcceptErr = 0x80000000
};
#define RX_DRTH_VAL (128/8)
enum ClkRun_bits {
PMEEnable = 0x100,
PMEStatus = 0x8000,
};
enum WolCmd_bits {
WakePhy = 0x1,
WakeUnicast = 0x2,
WakeMulticast = 0x4,
WakeBroadcast = 0x8,
WakeArp = 0x10,
WakePMatch0 = 0x20,
WakePMatch1 = 0x40,
WakePMatch2 = 0x80,
WakePMatch3 = 0x100,
WakeMagic = 0x200,
WakeMagicSecure = 0x400,
SecureHack = 0x100000,
WokePhy = 0x400000,
WokeUnicast = 0x800000,
WokeMulticast = 0x1000000,
WokeBroadcast = 0x2000000,
WokeArp = 0x4000000,
WokePMatch0 = 0x8000000,
WokePMatch1 = 0x10000000,
WokePMatch2 = 0x20000000,
WokePMatch3 = 0x40000000,
WokeMagic = 0x80000000,
WakeOptsSummary = 0x7ff
};
enum RxFilterAddr_bits {
RFCRAddressMask = 0x3ff,
AcceptMulticast = 0x00200000,
AcceptMyPhys = 0x08000000,
AcceptAllPhys = 0x10000000,
AcceptAllMulticast = 0x20000000,
AcceptBroadcast = 0x40000000,
RxFilterEnable = 0x80000000
};
enum StatsCtrl_bits {
StatsWarn = 0x1,
StatsFreeze = 0x2,
StatsClear = 0x4,
StatsStrobe = 0x8,
};
enum MIntrCtrl_bits {
MICRIntEn = 0x2,
};
enum PhyCtrl_bits {
PhyAddrMask = 0x1f,
};
#define PHY_ADDR_NONE 32
#define PHY_ADDR_INTERNAL 1
/* values we might find in the silicon revision register */
#define SRR_DP83815_C 0x0302
#define SRR_DP83815_D 0x0403
#define SRR_DP83816_A4 0x0504
#define SRR_DP83816_A5 0x0505
/* The Rx and Tx buffer descriptors. */
/* Note that using only 32 bit fields simplifies conversion to big-endian
architectures. */
struct netdev_desc {
__le32 next_desc;
__le32 cmd_status;
__le32 addr;
__le32 software_use;
};
/* Bits in network_desc.status */
enum desc_status_bits {
DescOwn=0x80000000, DescMore=0x40000000, DescIntr=0x20000000,
DescNoCRC=0x10000000, DescPktOK=0x08000000,
DescSizeMask=0xfff,
DescTxAbort=0x04000000, DescTxFIFO=0x02000000,
DescTxCarrier=0x01000000, DescTxDefer=0x00800000,
DescTxExcDefer=0x00400000, DescTxOOWCol=0x00200000,
DescTxExcColl=0x00100000, DescTxCollCount=0x000f0000,
DescRxAbort=0x04000000, DescRxOver=0x02000000,
DescRxDest=0x01800000, DescRxLong=0x00400000,
DescRxRunt=0x00200000, DescRxInvalid=0x00100000,
DescRxCRC=0x00080000, DescRxAlign=0x00040000,
DescRxLoop=0x00020000, DesRxColl=0x00010000,
};
struct netdev_private {
/* Descriptor rings first for alignment */
dma_addr_t ring_dma;
struct netdev_desc *rx_ring;
struct netdev_desc *tx_ring;
/* The addresses of receive-in-place skbuffs */
struct sk_buff *rx_skbuff[RX_RING_SIZE];
dma_addr_t rx_dma[RX_RING_SIZE];
/* address of a sent-in-place packet/buffer, for later free() */
struct sk_buff *tx_skbuff[TX_RING_SIZE];
dma_addr_t tx_dma[TX_RING_SIZE];
struct net_device *dev;
struct napi_struct napi;
/* Media monitoring timer */
struct timer_list timer;
/* Frequently used values: keep some adjacent for cache effect */
struct pci_dev *pci_dev;
struct netdev_desc *rx_head_desc;
/* Producer/consumer ring indices */
unsigned int cur_rx, dirty_rx;
unsigned int cur_tx, dirty_tx;
/* Based on MTU+slack. */
unsigned int rx_buf_sz;
int oom;
/* Interrupt status */
u32 intr_status;
/* Do not touch the nic registers */
int hands_off;
/* Don't pay attention to the reported link state. */
int ignore_phy;
/* external phy that is used: only valid if dev->if_port != PORT_TP */
int mii;
int phy_addr_external;
unsigned int full_duplex;
/* Rx filter */
u32 cur_rx_mode;
u32 rx_filter[16];
/* FIFO and PCI burst thresholds */
u32 tx_config, rx_config;
/* original contents of ClkRun register */
u32 SavedClkRun;
/* silicon revision */
u32 srr;
/* expected DSPCFG value */
u16 dspcfg;
int dspcfg_workaround;
/* parms saved in ethtool format */
u16 speed; /* The forced speed, 10Mb, 100Mb, gigabit */
u8 duplex; /* Duplex, half or full */
u8 autoneg; /* Autonegotiation enabled */
/* MII transceiver section */
u16 advertising;
unsigned int iosize;
spinlock_t lock;
u32 msg_enable;
/* EEPROM data */
int eeprom_size;
};
static void move_int_phy(struct net_device *dev, int addr);
static int eeprom_read(void __iomem *ioaddr, int location);
static int mdio_read(struct net_device *dev, int reg);
static void mdio_write(struct net_device *dev, int reg, u16 data);
static void init_phy_fixup(struct net_device *dev);
static int miiport_read(struct net_device *dev, int phy_id, int reg);
static void miiport_write(struct net_device *dev, int phy_id, int reg, u16 data);
static int find_mii(struct net_device *dev);
static void natsemi_reset(struct net_device *dev);
static void natsemi_reload_eeprom(struct net_device *dev);
static void natsemi_stop_rxtx(struct net_device *dev);
static int netdev_open(struct net_device *dev);
static void do_cable_magic(struct net_device *dev);
static void undo_cable_magic(struct net_device *dev);
static void check_link(struct net_device *dev);
static void netdev_timer(unsigned long data);
static void dump_ring(struct net_device *dev);
static void ns_tx_timeout(struct net_device *dev);
static int alloc_ring(struct net_device *dev);
static void refill_rx(struct net_device *dev);
static void init_ring(struct net_device *dev);
static void drain_tx(struct net_device *dev);
static void drain_ring(struct net_device *dev);
static void free_ring(struct net_device *dev);
static void reinit_ring(struct net_device *dev);
static void init_registers(struct net_device *dev);
static netdev_tx_t start_tx(struct sk_buff *skb, struct net_device *dev);
static irqreturn_t intr_handler(int irq, void *dev_instance);
static void netdev_error(struct net_device *dev, int intr_status);
static int natsemi_poll(struct napi_struct *napi, int budget);
static void netdev_rx(struct net_device *dev, int *work_done, int work_to_do);
static void netdev_tx_done(struct net_device *dev);
static int natsemi_change_mtu(struct net_device *dev, int new_mtu);
#ifdef CONFIG_NET_POLL_CONTROLLER
static void natsemi_poll_controller(struct net_device *dev);
#endif
static void __set_rx_mode(struct net_device *dev);
static void set_rx_mode(struct net_device *dev);
static void __get_stats(struct net_device *dev);
static struct net_device_stats *get_stats(struct net_device *dev);
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
static int netdev_set_wol(struct net_device *dev, u32 newval);
static int netdev_get_wol(struct net_device *dev, u32 *supported, u32 *cur);
static int netdev_set_sopass(struct net_device *dev, u8 *newval);
static int netdev_get_sopass(struct net_device *dev, u8 *data);
static int netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd);
static int netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd);
static void enable_wol_mode(struct net_device *dev, int enable_intr);
static int netdev_close(struct net_device *dev);
static int netdev_get_regs(struct net_device *dev, u8 *buf);
static int netdev_get_eeprom(struct net_device *dev, u8 *buf);
static const struct ethtool_ops ethtool_ops;
#define NATSEMI_ATTR(_name) \
static ssize_t natsemi_show_##_name(struct device *dev, \
struct device_attribute *attr, char *buf); \
static ssize_t natsemi_set_##_name(struct device *dev, \
struct device_attribute *attr, \
const char *buf, size_t count); \
static DEVICE_ATTR(_name, 0644, natsemi_show_##_name, natsemi_set_##_name)
#define NATSEMI_CREATE_FILE(_dev, _name) \
device_create_file(&_dev->dev, &dev_attr_##_name)
#define NATSEMI_REMOVE_FILE(_dev, _name) \
device_remove_file(&_dev->dev, &dev_attr_##_name)
NATSEMI_ATTR(dspcfg_workaround);
static ssize_t natsemi_show_dspcfg_workaround(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct netdev_private *np = netdev_priv(to_net_dev(dev));
return sprintf(buf, "%s\n", np->dspcfg_workaround ? "on" : "off");
}
static ssize_t natsemi_set_dspcfg_workaround(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct netdev_private *np = netdev_priv(to_net_dev(dev));
int new_setting;
unsigned long flags;
/* Find out the new setting */
if (!strncmp("on", buf, count - 1) || !strncmp("1", buf, count - 1))
new_setting = 1;
else if (!strncmp("off", buf, count - 1) ||
!strncmp("0", buf, count - 1))
new_setting = 0;
else
return count;
spin_lock_irqsave(&np->lock, flags);
np->dspcfg_workaround = new_setting;
spin_unlock_irqrestore(&np->lock, flags);
return count;
}
static inline void __iomem *ns_ioaddr(struct net_device *dev)
{
return (void __iomem *) dev->base_addr;
}
static inline void natsemi_irq_enable(struct net_device *dev)
{
writel(1, ns_ioaddr(dev) + IntrEnable);
readl(ns_ioaddr(dev) + IntrEnable);
}
static inline void natsemi_irq_disable(struct net_device *dev)
{
writel(0, ns_ioaddr(dev) + IntrEnable);
readl(ns_ioaddr(dev) + IntrEnable);
}
static void move_int_phy(struct net_device *dev, int addr)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
int target = 31;
/*
* The internal phy is visible on the external mii bus. Therefore we must
* move it away before we can send commands to an external phy.
* There are two addresses we must avoid:
* - the address on the external phy that is used for transmission.
* - the address that we want to access. User space can access phys
* on the mii bus with SIOCGMIIREG/SIOCSMIIREG, independent from the
* phy that is used for transmission.
*/
if (target == addr)
target--;
if (target == np->phy_addr_external)
target--;
writew(target, ioaddr + PhyCtrl);
readw(ioaddr + PhyCtrl);
udelay(1);
}
static void __devinit natsemi_init_media (struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
u32 tmp;
if (np->ignore_phy)
netif_carrier_on(dev);
else
netif_carrier_off(dev);
/* get the initial settings from hardware */
tmp = mdio_read(dev, MII_BMCR);
np->speed = (tmp & BMCR_SPEED100)? SPEED_100 : SPEED_10;
np->duplex = (tmp & BMCR_FULLDPLX)? DUPLEX_FULL : DUPLEX_HALF;
np->autoneg = (tmp & BMCR_ANENABLE)? AUTONEG_ENABLE: AUTONEG_DISABLE;
np->advertising= mdio_read(dev, MII_ADVERTISE);
if ((np->advertising & ADVERTISE_ALL) != ADVERTISE_ALL &&
netif_msg_probe(np)) {
printk(KERN_INFO "natsemi %s: Transceiver default autonegotiation %s "
"10%s %s duplex.\n",
pci_name(np->pci_dev),
(mdio_read(dev, MII_BMCR) & BMCR_ANENABLE)?
"enabled, advertise" : "disabled, force",
(np->advertising &
(ADVERTISE_100FULL|ADVERTISE_100HALF))?
"0" : "",
(np->advertising &
(ADVERTISE_100FULL|ADVERTISE_10FULL))?
"full" : "half");
}
if (netif_msg_probe(np))
printk(KERN_INFO
"natsemi %s: Transceiver status %#04x advertising %#04x.\n",
pci_name(np->pci_dev), mdio_read(dev, MII_BMSR),
np->advertising);
}
static const struct net_device_ops natsemi_netdev_ops = {
.ndo_open = netdev_open,
.ndo_stop = netdev_close,
.ndo_start_xmit = start_tx,
.ndo_get_stats = get_stats,
.ndo_set_multicast_list = set_rx_mode,
.ndo_change_mtu = natsemi_change_mtu,
.ndo_do_ioctl = netdev_ioctl,
.ndo_tx_timeout = ns_tx_timeout,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = natsemi_poll_controller,
#endif
};
static int __devinit natsemi_probe1 (struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *dev;
struct netdev_private *np;
int i, option, irq, chip_idx = ent->driver_data;
static int find_cnt = -1;
resource_size_t iostart;
unsigned long iosize;
void __iomem *ioaddr;
const int pcibar = 1; /* PCI base address register */
int prev_eedata;
u32 tmp;
/* when built into the kernel, we only print version if device is found */
#ifndef MODULE
static int printed_version;
if (!printed_version++)
printk(version);
#endif
i = pci_enable_device(pdev);
if (i) return i;
/* natsemi has a non-standard PM control register
* in PCI config space. Some boards apparently need
* to be brought to D0 in this manner.
*/
pci_read_config_dword(pdev, PCIPM, &tmp);
if (tmp & PCI_PM_CTRL_STATE_MASK) {
/* D0 state, disable PME assertion */
u32 newtmp = tmp & ~PCI_PM_CTRL_STATE_MASK;
pci_write_config_dword(pdev, PCIPM, newtmp);
}
find_cnt++;
iostart = pci_resource_start(pdev, pcibar);
iosize = pci_resource_len(pdev, pcibar);
irq = pdev->irq;
pci_set_master(pdev);
dev = alloc_etherdev(sizeof (struct netdev_private));
if (!dev)
return -ENOMEM;
SET_NETDEV_DEV(dev, &pdev->dev);
i = pci_request_regions(pdev, DRV_NAME);
if (i)
goto err_pci_request_regions;
ioaddr = ioremap(iostart, iosize);
if (!ioaddr) {
i = -ENOMEM;
goto err_ioremap;
}
/* Work around the dropped serial bit. */
prev_eedata = eeprom_read(ioaddr, 6);
for (i = 0; i < 3; i++) {
int eedata = eeprom_read(ioaddr, i + 7);
dev->dev_addr[i*2] = (eedata << 1) + (prev_eedata >> 15);
dev->dev_addr[i*2+1] = eedata >> 7;
prev_eedata = eedata;
}
/* Store MAC Address in perm_addr */
memcpy(dev->perm_addr, dev->dev_addr, ETH_ALEN);
dev->base_addr = (unsigned long __force) ioaddr;
dev->irq = irq;
np = netdev_priv(dev);
netif_napi_add(dev, &np->napi, natsemi_poll, 64);
np->dev = dev;
np->pci_dev = pdev;
pci_set_drvdata(pdev, dev);
np->iosize = iosize;
spin_lock_init(&np->lock);
np->msg_enable = (debug >= 0) ? (1<<debug)-1 : NATSEMI_DEF_MSG;
np->hands_off = 0;
np->intr_status = 0;
np->eeprom_size = natsemi_pci_info[chip_idx].eeprom_size;
if (natsemi_pci_info[chip_idx].flags & NATSEMI_FLAG_IGNORE_PHY)
np->ignore_phy = 1;
else
np->ignore_phy = 0;
np->dspcfg_workaround = dspcfg_workaround;
/* Initial port:
* - If configured to ignore the PHY set up for external.
* - If the nic was configured to use an external phy and if find_mii
* finds a phy: use external port, first phy that replies.
* - Otherwise: internal port.
* Note that the phy address for the internal phy doesn't matter:
* The address would be used to access a phy over the mii bus, but
* the internal phy is accessed through mapped registers.
*/
if (np->ignore_phy || readl(ioaddr + ChipConfig) & CfgExtPhy)
dev->if_port = PORT_MII;
else
dev->if_port = PORT_TP;
/* Reset the chip to erase previous misconfiguration. */
natsemi_reload_eeprom(dev);
natsemi_reset(dev);
if (dev->if_port != PORT_TP) {
np->phy_addr_external = find_mii(dev);
/* If we're ignoring the PHY it doesn't matter if we can't
* find one. */
if (!np->ignore_phy && np->phy_addr_external == PHY_ADDR_NONE) {
dev->if_port = PORT_TP;
np->phy_addr_external = PHY_ADDR_INTERNAL;
}
} else {
np->phy_addr_external = PHY_ADDR_INTERNAL;
}
option = find_cnt < MAX_UNITS ? options[find_cnt] : 0;
if (dev->mem_start)
option = dev->mem_start;
/* The lower four bits are the media type. */
if (option) {
if (option & 0x200)
np->full_duplex = 1;
if (option & 15)
printk(KERN_INFO
"natsemi %s: ignoring user supplied media type %d",
pci_name(np->pci_dev), option & 15);
}
if (find_cnt < MAX_UNITS && full_duplex[find_cnt])
np->full_duplex = 1;
dev->netdev_ops = &natsemi_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
SET_ETHTOOL_OPS(dev, ðtool_ops);
if (mtu)
dev->mtu = mtu;
natsemi_init_media(dev);
/* save the silicon revision for later querying */
np->srr = readl(ioaddr + SiliconRev);
if (netif_msg_hw(np))
printk(KERN_INFO "natsemi %s: silicon revision %#04x.\n",
pci_name(np->pci_dev), np->srr);
i = register_netdev(dev);
if (i)
goto err_register_netdev;
if (NATSEMI_CREATE_FILE(pdev, dspcfg_workaround))
goto err_create_file;
if (netif_msg_drv(np)) {
printk(KERN_INFO "natsemi %s: %s at %#08llx "
"(%s), %pM, IRQ %d",
dev->name, natsemi_pci_info[chip_idx].name,
(unsigned long long)iostart, pci_name(np->pci_dev),
dev->dev_addr, irq);
if (dev->if_port == PORT_TP)
printk(", port TP.\n");
else if (np->ignore_phy)
printk(", port MII, ignoring PHY\n");
else
printk(", port MII, phy ad %d.\n", np->phy_addr_external);
}
return 0;
err_create_file:
unregister_netdev(dev);
err_register_netdev:
iounmap(ioaddr);
err_ioremap:
pci_release_regions(pdev);
pci_set_drvdata(pdev, NULL);
err_pci_request_regions:
free_netdev(dev);
return i;
}
/* Read the EEPROM and MII Management Data I/O (MDIO) interfaces.
The EEPROM code is for the common 93c06/46 EEPROMs with 6 bit addresses. */
/* Delay between EEPROM clock transitions.
No extra delay is needed with 33Mhz PCI, but future 66Mhz access may need
a delay. Note that pre-2.0.34 kernels had a cache-alignment bug that
made udelay() unreliable.
The old method of using an ISA access as a delay, __SLOW_DOWN_IO__, is
deprecated.
*/
#define eeprom_delay(ee_addr) readl(ee_addr)
#define EE_Write0 (EE_ChipSelect)
#define EE_Write1 (EE_ChipSelect | EE_DataIn)
/* The EEPROM commands include the alway-set leading bit. */
enum EEPROM_Cmds {
EE_WriteCmd=(5 << 6), EE_ReadCmd=(6 << 6), EE_EraseCmd=(7 << 6),
};
static int eeprom_read(void __iomem *addr, int location)
{
int i;
int retval = 0;
void __iomem *ee_addr = addr + EECtrl;
int read_cmd = location | EE_ReadCmd;
writel(EE_Write0, ee_addr);
/* Shift the read command bits out. */
for (i = 10; i >= 0; i--) {
short dataval = (read_cmd & (1 << i)) ? EE_Write1 : EE_Write0;
writel(dataval, ee_addr);
eeprom_delay(ee_addr);
writel(dataval | EE_ShiftClk, ee_addr);
eeprom_delay(ee_addr);
}
writel(EE_ChipSelect, ee_addr);
eeprom_delay(ee_addr);
for (i = 0; i < 16; i++) {
writel(EE_ChipSelect | EE_ShiftClk, ee_addr);
eeprom_delay(ee_addr);
retval |= (readl(ee_addr) & EE_DataOut) ? 1 << i : 0;
writel(EE_ChipSelect, ee_addr);
eeprom_delay(ee_addr);
}
/* Terminate the EEPROM access. */
writel(EE_Write0, ee_addr);
writel(0, ee_addr);
return retval;
}
/* MII transceiver control section.
* The 83815 series has an internal transceiver, and we present the
* internal management registers as if they were MII connected.
* External Phy registers are referenced through the MII interface.
*/
/* clock transitions >= 20ns (25MHz)
* One readl should be good to PCI @ 100MHz
*/
#define mii_delay(ioaddr) readl(ioaddr + EECtrl)
static int mii_getbit (struct net_device *dev)
{
int data;
void __iomem *ioaddr = ns_ioaddr(dev);
writel(MII_ShiftClk, ioaddr + EECtrl);
data = readl(ioaddr + EECtrl);
writel(0, ioaddr + EECtrl);
mii_delay(ioaddr);
return (data & MII_Data)? 1 : 0;
}
static void mii_send_bits (struct net_device *dev, u32 data, int len)
{
u32 i;
void __iomem *ioaddr = ns_ioaddr(dev);
for (i = (1 << (len-1)); i; i >>= 1)
{
u32 mdio_val = MII_Write | ((data & i)? MII_Data : 0);
writel(mdio_val, ioaddr + EECtrl);
mii_delay(ioaddr);
writel(mdio_val | MII_ShiftClk, ioaddr + EECtrl);
mii_delay(ioaddr);
}
writel(0, ioaddr + EECtrl);
mii_delay(ioaddr);
}
static int miiport_read(struct net_device *dev, int phy_id, int reg)
{
u32 cmd;
int i;
u32 retval = 0;
/* Ensure sync */
mii_send_bits (dev, 0xffffffff, 32);
/* ST(2), OP(2), ADDR(5), REG#(5), TA(2), Data(16) total 32 bits */
/* ST,OP = 0110'b for read operation */
cmd = (0x06 << 10) | (phy_id << 5) | reg;
mii_send_bits (dev, cmd, 14);
/* Turnaround */
if (mii_getbit (dev))
return 0;
/* Read data */
for (i = 0; i < 16; i++) {
retval <<= 1;
retval |= mii_getbit (dev);
}
/* End cycle */
mii_getbit (dev);
return retval;
}
static void miiport_write(struct net_device *dev, int phy_id, int reg, u16 data)
{
u32 cmd;
/* Ensure sync */
mii_send_bits (dev, 0xffffffff, 32);
/* ST(2), OP(2), ADDR(5), REG#(5), TA(2), Data(16) total 32 bits */
/* ST,OP,AAAAA,RRRRR,TA = 0101xxxxxxxxxx10'b = 0x5002 for write */
cmd = (0x5002 << 16) | (phy_id << 23) | (reg << 18) | data;
mii_send_bits (dev, cmd, 32);
/* End cycle */
mii_getbit (dev);
}
static int mdio_read(struct net_device *dev, int reg)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
/* The 83815 series has two ports:
* - an internal transceiver
* - an external mii bus
*/
if (dev->if_port == PORT_TP)
return readw(ioaddr+BasicControl+(reg<<2));
else
return miiport_read(dev, np->phy_addr_external, reg);
}
static void mdio_write(struct net_device *dev, int reg, u16 data)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
/* The 83815 series has an internal transceiver; handle separately */
if (dev->if_port == PORT_TP)
writew(data, ioaddr+BasicControl+(reg<<2));
else
miiport_write(dev, np->phy_addr_external, reg, data);
}
static void init_phy_fixup(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
int i;
u32 cfg;
u16 tmp;
/* restore stuff lost when power was out */
tmp = mdio_read(dev, MII_BMCR);
if (np->autoneg == AUTONEG_ENABLE) {
/* renegotiate if something changed */
if ((tmp & BMCR_ANENABLE) == 0 ||
np->advertising != mdio_read(dev, MII_ADVERTISE))
{
/* turn on autonegotiation and force negotiation */
tmp |= (BMCR_ANENABLE | BMCR_ANRESTART);
mdio_write(dev, MII_ADVERTISE, np->advertising);
}
} else {
/* turn off auto negotiation, set speed and duplexity */
tmp &= ~(BMCR_ANENABLE | BMCR_SPEED100 | BMCR_FULLDPLX);
if (np->speed == SPEED_100)
tmp |= BMCR_SPEED100;
if (np->duplex == DUPLEX_FULL)
tmp |= BMCR_FULLDPLX;
/*
* Note: there is no good way to inform the link partner
* that our capabilities changed. The user has to unplug
* and replug the network cable after some changes, e.g.
* after switching from 10HD, autoneg off to 100 HD,
* autoneg off.
*/
}
mdio_write(dev, MII_BMCR, tmp);
readl(ioaddr + ChipConfig);
udelay(1);
/* find out what phy this is */
np->mii = (mdio_read(dev, MII_PHYSID1) << 16)
+ mdio_read(dev, MII_PHYSID2);
/* handle external phys here */
switch (np->mii) {
case PHYID_AM79C874:
/* phy specific configuration for fibre/tp operation */
tmp = mdio_read(dev, MII_MCTRL);
tmp &= ~(MII_FX_SEL | MII_EN_SCRM);
if (dev->if_port == PORT_FIBRE)
tmp |= MII_FX_SEL;
else
tmp |= MII_EN_SCRM;
mdio_write(dev, MII_MCTRL, tmp);
break;
default:
break;
}
cfg = readl(ioaddr + ChipConfig);
if (cfg & CfgExtPhy)
return;
/* On page 78 of the spec, they recommend some settings for "optimum
performance" to be done in sequence. These settings optimize some
of the 100Mbit autodetection circuitry. They say we only want to
do this for rev C of the chip, but engineers at NSC (Bradley
Kennedy) recommends always setting them. If you don't, you get
errors on some autonegotiations that make the device unusable.
It seems that the DSP needs a few usec to reinitialize after
the start of the phy. Just retry writing these values until they
stick.
*/
for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
int dspcfg;
writew(1, ioaddr + PGSEL);
writew(PMDCSR_VAL, ioaddr + PMDCSR);
writew(TSTDAT_VAL, ioaddr + TSTDAT);
np->dspcfg = (np->srr <= SRR_DP83815_C)?
DSPCFG_VAL : (DSPCFG_COEF | readw(ioaddr + DSPCFG));
writew(np->dspcfg, ioaddr + DSPCFG);
writew(SDCFG_VAL, ioaddr + SDCFG);
writew(0, ioaddr + PGSEL);
readl(ioaddr + ChipConfig);
udelay(10);
writew(1, ioaddr + PGSEL);
dspcfg = readw(ioaddr + DSPCFG);
writew(0, ioaddr + PGSEL);
if (np->dspcfg == dspcfg)
break;
}
if (netif_msg_link(np)) {
if (i==NATSEMI_HW_TIMEOUT) {
printk(KERN_INFO
"%s: DSPCFG mismatch after retrying for %d usec.\n",
dev->name, i*10);
} else {
printk(KERN_INFO
"%s: DSPCFG accepted after %d usec.\n",
dev->name, i*10);
}
}
/*
* Enable PHY Specific event based interrupts. Link state change
* and Auto-Negotiation Completion are among the affected.
* Read the intr status to clear it (needed for wake events).
*/
readw(ioaddr + MIntrStatus);
writew(MICRIntEn, ioaddr + MIntrCtrl);
}
static int switch_port_external(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
u32 cfg;
cfg = readl(ioaddr + ChipConfig);
if (cfg & CfgExtPhy)
return 0;
if (netif_msg_link(np)) {
printk(KERN_INFO "%s: switching to external transceiver.\n",
dev->name);
}
/* 1) switch back to external phy */
writel(cfg | (CfgExtPhy | CfgPhyDis), ioaddr + ChipConfig);
readl(ioaddr + ChipConfig);
udelay(1);
/* 2) reset the external phy: */
/* resetting the external PHY has been known to cause a hub supplying
* power over Ethernet to kill the power. We don't want to kill
* power to this computer, so we avoid resetting the phy.
*/
/* 3) reinit the phy fixup, it got lost during power down. */
move_int_phy(dev, np->phy_addr_external);
init_phy_fixup(dev);
return 1;
}
static int switch_port_internal(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
int i;
u32 cfg;
u16 bmcr;
cfg = readl(ioaddr + ChipConfig);
if (!(cfg &CfgExtPhy))
return 0;
if (netif_msg_link(np)) {
printk(KERN_INFO "%s: switching to internal transceiver.\n",
dev->name);
}
/* 1) switch back to internal phy: */
cfg = cfg & ~(CfgExtPhy | CfgPhyDis);
writel(cfg, ioaddr + ChipConfig);
readl(ioaddr + ChipConfig);
udelay(1);
/* 2) reset the internal phy: */
bmcr = readw(ioaddr+BasicControl+(MII_BMCR<<2));
writel(bmcr | BMCR_RESET, ioaddr+BasicControl+(MII_BMCR<<2));
readl(ioaddr + ChipConfig);
udelay(10);
for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
bmcr = readw(ioaddr+BasicControl+(MII_BMCR<<2));
if (!(bmcr & BMCR_RESET))
break;
udelay(10);
}
if (i==NATSEMI_HW_TIMEOUT && netif_msg_link(np)) {
printk(KERN_INFO
"%s: phy reset did not complete in %d usec.\n",
dev->name, i*10);
}
/* 3) reinit the phy fixup, it got lost during power down. */
init_phy_fixup(dev);
return 1;
}
/* Scan for a PHY on the external mii bus.
* There are two tricky points:
* - Do not scan while the internal phy is enabled. The internal phy will
* crash: e.g. reads from the DSPCFG register will return odd values and
* the nasty random phy reset code will reset the nic every few seconds.
* - The internal phy must be moved around, an external phy could
* have the same address as the internal phy.
*/
static int find_mii(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int tmp;
int i;
int did_switch;
/* Switch to external phy */
did_switch = switch_port_external(dev);
/* Scan the possible phy addresses:
*
* PHY address 0 means that the phy is in isolate mode. Not yet
* supported due to lack of test hardware. User space should
* handle it through ethtool.
*/
for (i = 1; i <= 31; i++) {
move_int_phy(dev, i);
tmp = miiport_read(dev, i, MII_BMSR);
if (tmp != 0xffff && tmp != 0x0000) {
/* found something! */
np->mii = (mdio_read(dev, MII_PHYSID1) << 16)
+ mdio_read(dev, MII_PHYSID2);
if (netif_msg_probe(np)) {
printk(KERN_INFO "natsemi %s: found external phy %08x at address %d.\n",
pci_name(np->pci_dev), np->mii, i);
}
break;
}
}
/* And switch back to internal phy: */
if (did_switch)
switch_port_internal(dev);
return i;
}
/* CFG bits [13:16] [18:23] */
#define CFG_RESET_SAVE 0xfde000
/* WCSR bits [0:4] [9:10] */
#define WCSR_RESET_SAVE 0x61f
/* RFCR bits [20] [22] [27:31] */
#define RFCR_RESET_SAVE 0xf8500000;
static void natsemi_reset(struct net_device *dev)
{
int i;
u32 cfg;
u32 wcsr;
u32 rfcr;
u16 pmatch[3];
u16 sopass[3];
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
/*
* Resetting the chip causes some registers to be lost.
* Natsemi suggests NOT reloading the EEPROM while live, so instead
* we save the state that would have been loaded from EEPROM
* on a normal power-up (see the spec EEPROM map). This assumes
* whoever calls this will follow up with init_registers() eventually.
*/
/* CFG */
cfg = readl(ioaddr + ChipConfig) & CFG_RESET_SAVE;
/* WCSR */
wcsr = readl(ioaddr + WOLCmd) & WCSR_RESET_SAVE;
/* RFCR */
rfcr = readl(ioaddr + RxFilterAddr) & RFCR_RESET_SAVE;
/* PMATCH */
for (i = 0; i < 3; i++) {
writel(i*2, ioaddr + RxFilterAddr);
pmatch[i] = readw(ioaddr + RxFilterData);
}
/* SOPAS */
for (i = 0; i < 3; i++) {
writel(0xa+(i*2), ioaddr + RxFilterAddr);
sopass[i] = readw(ioaddr + RxFilterData);
}
/* now whack the chip */
writel(ChipReset, ioaddr + ChipCmd);
for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
if (!(readl(ioaddr + ChipCmd) & ChipReset))
break;
udelay(5);
}
if (i==NATSEMI_HW_TIMEOUT) {
printk(KERN_WARNING "%s: reset did not complete in %d usec.\n",
dev->name, i*5);
} else if (netif_msg_hw(np)) {
printk(KERN_DEBUG "%s: reset completed in %d usec.\n",
dev->name, i*5);
}
/* restore CFG */
cfg |= readl(ioaddr + ChipConfig) & ~CFG_RESET_SAVE;
/* turn on external phy if it was selected */
if (dev->if_port == PORT_TP)
cfg &= ~(CfgExtPhy | CfgPhyDis);
else
cfg |= (CfgExtPhy | CfgPhyDis);
writel(cfg, ioaddr + ChipConfig);
/* restore WCSR */
wcsr |= readl(ioaddr + WOLCmd) & ~WCSR_RESET_SAVE;
writel(wcsr, ioaddr + WOLCmd);
/* read RFCR */
rfcr |= readl(ioaddr + RxFilterAddr) & ~RFCR_RESET_SAVE;
/* restore PMATCH */
for (i = 0; i < 3; i++) {
writel(i*2, ioaddr + RxFilterAddr);
writew(pmatch[i], ioaddr + RxFilterData);
}
for (i = 0; i < 3; i++) {
writel(0xa+(i*2), ioaddr + RxFilterAddr);
writew(sopass[i], ioaddr + RxFilterData);
}
/* restore RFCR */
writel(rfcr, ioaddr + RxFilterAddr);
}
static void reset_rx(struct net_device *dev)
{
int i;
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
np->intr_status &= ~RxResetDone;
writel(RxReset, ioaddr + ChipCmd);
for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
np->intr_status |= readl(ioaddr + IntrStatus);
if (np->intr_status & RxResetDone)
break;
udelay(15);
}
if (i==NATSEMI_HW_TIMEOUT) {
printk(KERN_WARNING "%s: RX reset did not complete in %d usec.\n",
dev->name, i*15);
} else if (netif_msg_hw(np)) {
printk(KERN_WARNING "%s: RX reset took %d usec.\n",
dev->name, i*15);
}
}
static void natsemi_reload_eeprom(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
int i;
writel(EepromReload, ioaddr + PCIBusCfg);
for (i=0;i<NATSEMI_HW_TIMEOUT;i++) {
udelay(50);
if (!(readl(ioaddr + PCIBusCfg) & EepromReload))
break;
}
if (i==NATSEMI_HW_TIMEOUT) {
printk(KERN_WARNING "natsemi %s: EEPROM did not reload in %d usec.\n",
pci_name(np->pci_dev), i*50);
} else if (netif_msg_hw(np)) {
printk(KERN_DEBUG "natsemi %s: EEPROM reloaded in %d usec.\n",
pci_name(np->pci_dev), i*50);
}
}
static void natsemi_stop_rxtx(struct net_device *dev)
{
void __iomem * ioaddr = ns_ioaddr(dev);
struct netdev_private *np = netdev_priv(dev);
int i;
writel(RxOff | TxOff, ioaddr + ChipCmd);
for(i=0;i< NATSEMI_HW_TIMEOUT;i++) {
if ((readl(ioaddr + ChipCmd) & (TxOn|RxOn)) == 0)
break;
udelay(5);
}
if (i==NATSEMI_HW_TIMEOUT) {
printk(KERN_WARNING "%s: Tx/Rx process did not stop in %d usec.\n",
dev->name, i*5);
} else if (netif_msg_hw(np)) {
printk(KERN_DEBUG "%s: Tx/Rx process stopped in %d usec.\n",
dev->name, i*5);
}
}
static int netdev_open(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
int i;
/* Reset the chip, just in case. */
natsemi_reset(dev);
i = request_irq(dev->irq, intr_handler, IRQF_SHARED, dev->name, dev);
if (i) return i;
if (netif_msg_ifup(np))
printk(KERN_DEBUG "%s: netdev_open() irq %d.\n",
dev->name, dev->irq);
i = alloc_ring(dev);
if (i < 0) {
free_irq(dev->irq, dev);
return i;
}
napi_enable(&np->napi);
init_ring(dev);
spin_lock_irq(&np->lock);
init_registers(dev);
/* now set the MAC address according to dev->dev_addr */
for (i = 0; i < 3; i++) {
u16 mac = (dev->dev_addr[2*i+1]<<8) + dev->dev_addr[2*i];
writel(i*2, ioaddr + RxFilterAddr);
writew(mac, ioaddr + RxFilterData);
}
writel(np->cur_rx_mode, ioaddr + RxFilterAddr);
spin_unlock_irq(&np->lock);
netif_start_queue(dev);
if (netif_msg_ifup(np))
printk(KERN_DEBUG "%s: Done netdev_open(), status: %#08x.\n",
dev->name, (int)readl(ioaddr + ChipCmd));
/* Set the timer to check for link beat. */
init_timer(&np->timer);
np->timer.expires = round_jiffies(jiffies + NATSEMI_TIMER_FREQ);
np->timer.data = (unsigned long)dev;
np->timer.function = netdev_timer; /* timer handler */
add_timer(&np->timer);
return 0;
}
static void do_cable_magic(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem *ioaddr = ns_ioaddr(dev);
if (dev->if_port != PORT_TP)
return;
if (np->srr >= SRR_DP83816_A5)
return;
/*
* 100 MBit links with short cables can trip an issue with the chip.
* The problem manifests as lots of CRC errors and/or flickering
* activity LED while idle. This process is based on instructions
* from engineers at National.
*/
if (readl(ioaddr + ChipConfig) & CfgSpeed100) {
u16 data;
writew(1, ioaddr + PGSEL);
/*
* coefficient visibility should already be enabled via
* DSPCFG | 0x1000
*/
data = readw(ioaddr + TSTDAT) & 0xff;
/*
* the value must be negative, and within certain values
* (these values all come from National)
*/
if (!(data & 0x80) || ((data >= 0xd8) && (data <= 0xff))) {
np = netdev_priv(dev);
/* the bug has been triggered - fix the coefficient */
writew(TSTDAT_FIXED, ioaddr + TSTDAT);
/* lock the value */
data = readw(ioaddr + DSPCFG);
np->dspcfg = data | DSPCFG_LOCK;
writew(np->dspcfg, ioaddr + DSPCFG);
}
writew(0, ioaddr + PGSEL);
}
}
static void undo_cable_magic(struct net_device *dev)
{
u16 data;
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
if (dev->if_port != PORT_TP)
return;
if (np->srr >= SRR_DP83816_A5)
return;
writew(1, ioaddr + PGSEL);
/* make sure the lock bit is clear */
data = readw(ioaddr + DSPCFG);
np->dspcfg = data & ~DSPCFG_LOCK;
writew(np->dspcfg, ioaddr + DSPCFG);
writew(0, ioaddr + PGSEL);
}
static void check_link(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
int duplex = np->duplex;
u16 bmsr;
/* If we are ignoring the PHY then don't try reading it. */
if (np->ignore_phy)
goto propagate_state;
/* The link status field is latched: it remains low after a temporary
* link failure until it's read. We need the current link status,
* thus read twice.
*/
mdio_read(dev, MII_BMSR);
bmsr = mdio_read(dev, MII_BMSR);
if (!(bmsr & BMSR_LSTATUS)) {
if (netif_carrier_ok(dev)) {
if (netif_msg_link(np))
printk(KERN_NOTICE "%s: link down.\n",
dev->name);
netif_carrier_off(dev);
undo_cable_magic(dev);
}
return;
}
if (!netif_carrier_ok(dev)) {
if (netif_msg_link(np))
printk(KERN_NOTICE "%s: link up.\n", dev->name);
netif_carrier_on(dev);
do_cable_magic(dev);
}
duplex = np->full_duplex;
if (!duplex) {
if (bmsr & BMSR_ANEGCOMPLETE) {
int tmp = mii_nway_result(
np->advertising & mdio_read(dev, MII_LPA));
if (tmp == LPA_100FULL || tmp == LPA_10FULL)
duplex = 1;
} else if (mdio_read(dev, MII_BMCR) & BMCR_FULLDPLX)
duplex = 1;
}
propagate_state:
/* if duplex is set then bit 28 must be set, too */
if (duplex ^ !!(np->rx_config & RxAcceptTx)) {
if (netif_msg_link(np))
printk(KERN_INFO
"%s: Setting %s-duplex based on negotiated "
"link capability.\n", dev->name,
duplex ? "full" : "half");
if (duplex) {
np->rx_config |= RxAcceptTx;
np->tx_config |= TxCarrierIgn | TxHeartIgn;
} else {
np->rx_config &= ~RxAcceptTx;
np->tx_config &= ~(TxCarrierIgn | TxHeartIgn);
}
writel(np->tx_config, ioaddr + TxConfig);
writel(np->rx_config, ioaddr + RxConfig);
}
}
static void init_registers(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
init_phy_fixup(dev);
/* clear any interrupts that are pending, such as wake events */
readl(ioaddr + IntrStatus);
writel(np->ring_dma, ioaddr + RxRingPtr);
writel(np->ring_dma + RX_RING_SIZE * sizeof(struct netdev_desc),
ioaddr + TxRingPtr);
/* Initialize other registers.
* Configure the PCI bus bursts and FIFO thresholds.
* Configure for standard, in-spec Ethernet.
* Start with half-duplex. check_link will update
* to the correct settings.
*/
/* DRTH: 2: start tx if 64 bytes are in the fifo
* FLTH: 0x10: refill with next packet if 512 bytes are free
* MXDMA: 0: up to 256 byte bursts.
* MXDMA must be <= FLTH
* ECRETRY=1
* ATP=1
*/
np->tx_config = TxAutoPad | TxCollRetry | TxMxdma_256 |
TX_FLTH_VAL | TX_DRTH_VAL_START;
writel(np->tx_config, ioaddr + TxConfig);
/* DRTH 0x10: start copying to memory if 128 bytes are in the fifo
* MXDMA 0: up to 256 byte bursts
*/
np->rx_config = RxMxdma_256 | RX_DRTH_VAL;
/* if receive ring now has bigger buffers than normal, enable jumbo */
if (np->rx_buf_sz > NATSEMI_LONGPKT)
np->rx_config |= RxAcceptLong;
writel(np->rx_config, ioaddr + RxConfig);
/* Disable PME:
* The PME bit is initialized from the EEPROM contents.
* PCI cards probably have PME disabled, but motherboard
* implementations may have PME set to enable WakeOnLan.
* With PME set the chip will scan incoming packets but
* nothing will be written to memory. */
np->SavedClkRun = readl(ioaddr + ClkRun);
writel(np->SavedClkRun & ~PMEEnable, ioaddr + ClkRun);
if (np->SavedClkRun & PMEStatus && netif_msg_wol(np)) {
printk(KERN_NOTICE "%s: Wake-up event %#08x\n",
dev->name, readl(ioaddr + WOLCmd));
}
check_link(dev);
__set_rx_mode(dev);
/* Enable interrupts by setting the interrupt mask. */
writel(DEFAULT_INTR, ioaddr + IntrMask);
natsemi_irq_enable(dev);
writel(RxOn | TxOn, ioaddr + ChipCmd);
writel(StatsClear, ioaddr + StatsCtrl); /* Clear Stats */
}
/*
* netdev_timer:
* Purpose:
* 1) check for link changes. Usually they are handled by the MII interrupt
* but it doesn't hurt to check twice.
* 2) check for sudden death of the NIC:
* It seems that a reference set for this chip went out with incorrect info,
* and there exist boards that aren't quite right. An unexpected voltage
* drop can cause the PHY to get itself in a weird state (basically reset).
* NOTE: this only seems to affect revC chips. The user can disable
* this check via dspcfg_workaround sysfs option.
* 3) check of death of the RX path due to OOM
*/
static void netdev_timer(unsigned long data)
{
struct net_device *dev = (struct net_device *)data;
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
int next_tick = NATSEMI_TIMER_FREQ;
if (netif_msg_timer(np)) {
/* DO NOT read the IntrStatus register,
* a read clears any pending interrupts.
*/
printk(KERN_DEBUG "%s: Media selection timer tick.\n",
dev->name);
}
if (dev->if_port == PORT_TP) {
u16 dspcfg;
spin_lock_irq(&np->lock);
/* check for a nasty random phy-reset - use dspcfg as a flag */
writew(1, ioaddr+PGSEL);
dspcfg = readw(ioaddr+DSPCFG);
writew(0, ioaddr+PGSEL);
if (np->dspcfg_workaround && dspcfg != np->dspcfg) {
if (!netif_queue_stopped(dev)) {
spin_unlock_irq(&np->lock);
if (netif_msg_drv(np))
printk(KERN_NOTICE "%s: possible phy reset: "
"re-initializing\n", dev->name);
disable_irq(dev->irq);
spin_lock_irq(&np->lock);
natsemi_stop_rxtx(dev);
dump_ring(dev);
reinit_ring(dev);
init_registers(dev);
spin_unlock_irq(&np->lock);
enable_irq(dev->irq);
} else {
/* hurry back */
next_tick = HZ;
spin_unlock_irq(&np->lock);
}
} else {
/* init_registers() calls check_link() for the above case */
check_link(dev);
spin_unlock_irq(&np->lock);
}
} else {
spin_lock_irq(&np->lock);
check_link(dev);
spin_unlock_irq(&np->lock);
}
if (np->oom) {
disable_irq(dev->irq);
np->oom = 0;
refill_rx(dev);
enable_irq(dev->irq);
if (!np->oom) {
writel(RxOn, ioaddr + ChipCmd);
} else {
next_tick = 1;
}
}
if (next_tick > 1)
mod_timer(&np->timer, round_jiffies(jiffies + next_tick));
else
mod_timer(&np->timer, jiffies + next_tick);
}
static void dump_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
if (netif_msg_pktdata(np)) {
int i;
printk(KERN_DEBUG " Tx ring at %p:\n", np->tx_ring);
for (i = 0; i < TX_RING_SIZE; i++) {
printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
i, np->tx_ring[i].next_desc,
np->tx_ring[i].cmd_status,
np->tx_ring[i].addr);
}
printk(KERN_DEBUG " Rx ring %p:\n", np->rx_ring);
for (i = 0; i < RX_RING_SIZE; i++) {
printk(KERN_DEBUG " #%d desc. %#08x %#08x %#08x.\n",
i, np->rx_ring[i].next_desc,
np->rx_ring[i].cmd_status,
np->rx_ring[i].addr);
}
}
}
static void ns_tx_timeout(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
disable_irq(dev->irq);
spin_lock_irq(&np->lock);
if (!np->hands_off) {
if (netif_msg_tx_err(np))
printk(KERN_WARNING
"%s: Transmit timed out, status %#08x,"
" resetting...\n",
dev->name, readl(ioaddr + IntrStatus));
dump_ring(dev);
natsemi_reset(dev);
reinit_ring(dev);
init_registers(dev);
} else {
printk(KERN_WARNING
"%s: tx_timeout while in hands_off state?\n",
dev->name);
}
spin_unlock_irq(&np->lock);
enable_irq(dev->irq);
dev->trans_start = jiffies; /* prevent tx timeout */
dev->stats.tx_errors++;
netif_wake_queue(dev);
}
static int alloc_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
np->rx_ring = pci_alloc_consistent(np->pci_dev,
sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
&np->ring_dma);
if (!np->rx_ring)
return -ENOMEM;
np->tx_ring = &np->rx_ring[RX_RING_SIZE];
return 0;
}
static void refill_rx(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
/* Refill the Rx ring buffers. */
for (; np->cur_rx - np->dirty_rx > 0; np->dirty_rx++) {
struct sk_buff *skb;
int entry = np->dirty_rx % RX_RING_SIZE;
if (np->rx_skbuff[entry] == NULL) {
unsigned int buflen = np->rx_buf_sz+NATSEMI_PADDING;
skb = dev_alloc_skb(buflen);
np->rx_skbuff[entry] = skb;
if (skb == NULL)
break; /* Better luck next round. */
skb->dev = dev; /* Mark as being used by this device. */
np->rx_dma[entry] = pci_map_single(np->pci_dev,
skb->data, buflen, PCI_DMA_FROMDEVICE);
np->rx_ring[entry].addr = cpu_to_le32(np->rx_dma[entry]);
}
np->rx_ring[entry].cmd_status = cpu_to_le32(np->rx_buf_sz);
}
if (np->cur_rx - np->dirty_rx == RX_RING_SIZE) {
if (netif_msg_rx_err(np))
printk(KERN_WARNING "%s: going OOM.\n", dev->name);
np->oom = 1;
}
}
static void set_bufsize(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
if (dev->mtu <= ETH_DATA_LEN)
np->rx_buf_sz = ETH_DATA_LEN + NATSEMI_HEADERS;
else
np->rx_buf_sz = dev->mtu + NATSEMI_HEADERS;
}
/* Initialize the Rx and Tx rings, along with various 'dev' bits. */
static void init_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int i;
/* 1) TX ring */
np->dirty_tx = np->cur_tx = 0;
for (i = 0; i < TX_RING_SIZE; i++) {
np->tx_skbuff[i] = NULL;
np->tx_ring[i].next_desc = cpu_to_le32(np->ring_dma
+sizeof(struct netdev_desc)
*((i+1)%TX_RING_SIZE+RX_RING_SIZE));
np->tx_ring[i].cmd_status = 0;
}
/* 2) RX ring */
np->dirty_rx = 0;
np->cur_rx = RX_RING_SIZE;
np->oom = 0;
set_bufsize(dev);
np->rx_head_desc = &np->rx_ring[0];
/* Please be careful before changing this loop - at least gcc-2.95.1
* miscompiles it otherwise.
*/
/* Initialize all Rx descriptors. */
for (i = 0; i < RX_RING_SIZE; i++) {
np->rx_ring[i].next_desc = cpu_to_le32(np->ring_dma
+sizeof(struct netdev_desc)
*((i+1)%RX_RING_SIZE));
np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
np->rx_skbuff[i] = NULL;
}
refill_rx(dev);
dump_ring(dev);
}
static void drain_tx(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int i;
for (i = 0; i < TX_RING_SIZE; i++) {
if (np->tx_skbuff[i]) {
pci_unmap_single(np->pci_dev,
np->tx_dma[i], np->tx_skbuff[i]->len,
PCI_DMA_TODEVICE);
dev_kfree_skb(np->tx_skbuff[i]);
dev->stats.tx_dropped++;
}
np->tx_skbuff[i] = NULL;
}
}
static void drain_rx(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
unsigned int buflen = np->rx_buf_sz;
int i;
/* Free all the skbuffs in the Rx queue. */
for (i = 0; i < RX_RING_SIZE; i++) {
np->rx_ring[i].cmd_status = 0;
np->rx_ring[i].addr = cpu_to_le32(0xBADF00D0); /* An invalid address. */
if (np->rx_skbuff[i]) {
pci_unmap_single(np->pci_dev, np->rx_dma[i],
buflen + NATSEMI_PADDING,
PCI_DMA_FROMDEVICE);
dev_kfree_skb(np->rx_skbuff[i]);
}
np->rx_skbuff[i] = NULL;
}
}
static void drain_ring(struct net_device *dev)
{
drain_rx(dev);
drain_tx(dev);
}
static void free_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
pci_free_consistent(np->pci_dev,
sizeof(struct netdev_desc) * (RX_RING_SIZE+TX_RING_SIZE),
np->rx_ring, np->ring_dma);
}
static void reinit_rx(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int i;
/* RX Ring */
np->dirty_rx = 0;
np->cur_rx = RX_RING_SIZE;
np->rx_head_desc = &np->rx_ring[0];
/* Initialize all Rx descriptors. */
for (i = 0; i < RX_RING_SIZE; i++)
np->rx_ring[i].cmd_status = cpu_to_le32(DescOwn);
refill_rx(dev);
}
static void reinit_ring(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
int i;
/* drain TX ring */
drain_tx(dev);
np->dirty_tx = np->cur_tx = 0;
for (i=0;i<TX_RING_SIZE;i++)
np->tx_ring[i].cmd_status = 0;
reinit_rx(dev);
}
static netdev_tx_t start_tx(struct sk_buff *skb, struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
unsigned entry;
unsigned long flags;
/* Note: Ordering is important here, set the field with the
"ownership" bit last, and only then increment cur_tx. */
/* Calculate the next Tx descriptor entry. */
entry = np->cur_tx % TX_RING_SIZE;
np->tx_skbuff[entry] = skb;
np->tx_dma[entry] = pci_map_single(np->pci_dev,
skb->data,skb->len, PCI_DMA_TODEVICE);
np->tx_ring[entry].addr = cpu_to_le32(np->tx_dma[entry]);
spin_lock_irqsave(&np->lock, flags);
if (!np->hands_off) {
np->tx_ring[entry].cmd_status = cpu_to_le32(DescOwn | skb->len);
/* StrongARM: Explicitly cache flush np->tx_ring and
* skb->data,skb->len. */
wmb();
np->cur_tx++;
if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1) {
netdev_tx_done(dev);
if (np->cur_tx - np->dirty_tx >= TX_QUEUE_LEN - 1)
netif_stop_queue(dev);
}
/* Wake the potentially-idle transmit channel. */
writel(TxOn, ioaddr + ChipCmd);
} else {
dev_kfree_skb_irq(skb);
dev->stats.tx_dropped++;
}
spin_unlock_irqrestore(&np->lock, flags);
if (netif_msg_tx_queued(np)) {
printk(KERN_DEBUG "%s: Transmit frame #%d queued in slot %d.\n",
dev->name, np->cur_tx, entry);
}
return NETDEV_TX_OK;
}
static void netdev_tx_done(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
for (; np->cur_tx - np->dirty_tx > 0; np->dirty_tx++) {
int entry = np->dirty_tx % TX_RING_SIZE;
if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescOwn))
break;
if (netif_msg_tx_done(np))
printk(KERN_DEBUG
"%s: tx frame #%d finished, status %#08x.\n",
dev->name, np->dirty_tx,
le32_to_cpu(np->tx_ring[entry].cmd_status));
if (np->tx_ring[entry].cmd_status & cpu_to_le32(DescPktOK)) {
dev->stats.tx_packets++;
dev->stats.tx_bytes += np->tx_skbuff[entry]->len;
} else { /* Various Tx errors */
int tx_status =
le32_to_cpu(np->tx_ring[entry].cmd_status);
if (tx_status & (DescTxAbort|DescTxExcColl))
dev->stats.tx_aborted_errors++;
if (tx_status & DescTxFIFO)
dev->stats.tx_fifo_errors++;
if (tx_status & DescTxCarrier)
dev->stats.tx_carrier_errors++;
if (tx_status & DescTxOOWCol)
dev->stats.tx_window_errors++;
dev->stats.tx_errors++;
}
pci_unmap_single(np->pci_dev,np->tx_dma[entry],
np->tx_skbuff[entry]->len,
PCI_DMA_TODEVICE);
/* Free the original skb. */
dev_kfree_skb_irq(np->tx_skbuff[entry]);
np->tx_skbuff[entry] = NULL;
}
if (netif_queue_stopped(dev) &&
np->cur_tx - np->dirty_tx < TX_QUEUE_LEN - 4) {
/* The ring is no longer full, wake queue. */
netif_wake_queue(dev);
}
}
/* The interrupt handler doesn't actually handle interrupts itself, it
* schedules a NAPI poll if there is anything to do. */
static irqreturn_t intr_handler(int irq, void *dev_instance)
{
struct net_device *dev = dev_instance;
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
/* Reading IntrStatus automatically acknowledges so don't do
* that while interrupts are disabled, (for example, while a
* poll is scheduled). */
if (np->hands_off || !readl(ioaddr + IntrEnable))
return IRQ_NONE;
np->intr_status = readl(ioaddr + IntrStatus);
if (!np->intr_status)
return IRQ_NONE;
if (netif_msg_intr(np))
printk(KERN_DEBUG
"%s: Interrupt, status %#08x, mask %#08x.\n",
dev->name, np->intr_status,
readl(ioaddr + IntrMask));
prefetch(&np->rx_skbuff[np->cur_rx % RX_RING_SIZE]);
if (napi_schedule_prep(&np->napi)) {
/* Disable interrupts and register for poll */
natsemi_irq_disable(dev);
__napi_schedule(&np->napi);
} else
printk(KERN_WARNING
"%s: Ignoring interrupt, status %#08x, mask %#08x.\n",
dev->name, np->intr_status,
readl(ioaddr + IntrMask));
return IRQ_HANDLED;
}
/* This is the NAPI poll routine. As well as the standard RX handling
* it also handles all other interrupts that the chip might raise.
*/
static int natsemi_poll(struct napi_struct *napi, int budget)
{
struct netdev_private *np = container_of(napi, struct netdev_private, napi);
struct net_device *dev = np->dev;
void __iomem * ioaddr = ns_ioaddr(dev);
int work_done = 0;
do {
if (netif_msg_intr(np))
printk(KERN_DEBUG
"%s: Poll, status %#08x, mask %#08x.\n",
dev->name, np->intr_status,
readl(ioaddr + IntrMask));
/* netdev_rx() may read IntrStatus again if the RX state
* machine falls over so do it first. */
if (np->intr_status &
(IntrRxDone | IntrRxIntr | RxStatusFIFOOver |
IntrRxErr | IntrRxOverrun)) {
netdev_rx(dev, &work_done, budget);
}
if (np->intr_status &
(IntrTxDone | IntrTxIntr | IntrTxIdle | IntrTxErr)) {
spin_lock(&np->lock);
netdev_tx_done(dev);
spin_unlock(&np->lock);
}
/* Abnormal error summary/uncommon events handlers. */
if (np->intr_status & IntrAbnormalSummary)
netdev_error(dev, np->intr_status);
if (work_done >= budget)
return work_done;
np->intr_status = readl(ioaddr + IntrStatus);
} while (np->intr_status);
napi_complete(napi);
/* Reenable interrupts providing nothing is trying to shut
* the chip down. */
spin_lock(&np->lock);
if (!np->hands_off)
natsemi_irq_enable(dev);
spin_unlock(&np->lock);
return work_done;
}
/* This routine is logically part of the interrupt handler, but separated
for clarity and better register allocation. */
static void netdev_rx(struct net_device *dev, int *work_done, int work_to_do)
{
struct netdev_private *np = netdev_priv(dev);
int entry = np->cur_rx % RX_RING_SIZE;
int boguscnt = np->dirty_rx + RX_RING_SIZE - np->cur_rx;
s32 desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
unsigned int buflen = np->rx_buf_sz;
void __iomem * ioaddr = ns_ioaddr(dev);
/* If the driver owns the next entry it's a new packet. Send it up. */
while (desc_status < 0) { /* e.g. & DescOwn */
int pkt_len;
if (netif_msg_rx_status(np))
printk(KERN_DEBUG
" netdev_rx() entry %d status was %#08x.\n",
entry, desc_status);
if (--boguscnt < 0)
break;
if (*work_done >= work_to_do)
break;
(*work_done)++;
pkt_len = (desc_status & DescSizeMask) - 4;
if ((desc_status&(DescMore|DescPktOK|DescRxLong)) != DescPktOK){
if (desc_status & DescMore) {
unsigned long flags;
if (netif_msg_rx_err(np))
printk(KERN_WARNING
"%s: Oversized(?) Ethernet "
"frame spanned multiple "
"buffers, entry %#08x "
"status %#08x.\n", dev->name,
np->cur_rx, desc_status);
dev->stats.rx_length_errors++;
/* The RX state machine has probably
* locked up beneath us. Follow the
* reset procedure documented in
* AN-1287. */
spin_lock_irqsave(&np->lock, flags);
reset_rx(dev);
reinit_rx(dev);
writel(np->ring_dma, ioaddr + RxRingPtr);
check_link(dev);
spin_unlock_irqrestore(&np->lock, flags);
/* We'll enable RX on exit from this
* function. */
break;
} else {
/* There was an error. */
dev->stats.rx_errors++;
if (desc_status & (DescRxAbort|DescRxOver))
dev->stats.rx_over_errors++;
if (desc_status & (DescRxLong|DescRxRunt))
dev->stats.rx_length_errors++;
if (desc_status & (DescRxInvalid|DescRxAlign))
dev->stats.rx_frame_errors++;
if (desc_status & DescRxCRC)
dev->stats.rx_crc_errors++;
}
} else if (pkt_len > np->rx_buf_sz) {
/* if this is the tail of a double buffer
* packet, we've already counted the error
* on the first part. Ignore the second half.
*/
} else {
struct sk_buff *skb;
/* Omit CRC size. */
/* Check if the packet is long enough to accept
* without copying to a minimally-sized skbuff. */
if (pkt_len < rx_copybreak &&
(skb = dev_alloc_skb(pkt_len + RX_OFFSET)) != NULL) {
/* 16 byte align the IP header */
skb_reserve(skb, RX_OFFSET);
pci_dma_sync_single_for_cpu(np->pci_dev,
np->rx_dma[entry],
buflen,
PCI_DMA_FROMDEVICE);
skb_copy_to_linear_data(skb,
np->rx_skbuff[entry]->data, pkt_len);
skb_put(skb, pkt_len);
pci_dma_sync_single_for_device(np->pci_dev,
np->rx_dma[entry],
buflen,
PCI_DMA_FROMDEVICE);
} else {
pci_unmap_single(np->pci_dev, np->rx_dma[entry],
buflen + NATSEMI_PADDING,
PCI_DMA_FROMDEVICE);
skb_put(skb = np->rx_skbuff[entry], pkt_len);
np->rx_skbuff[entry] = NULL;
}
skb->protocol = eth_type_trans(skb, dev);
netif_receive_skb(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
entry = (++np->cur_rx) % RX_RING_SIZE;
np->rx_head_desc = &np->rx_ring[entry];
desc_status = le32_to_cpu(np->rx_head_desc->cmd_status);
}
refill_rx(dev);
/* Restart Rx engine if stopped. */
if (np->oom)
mod_timer(&np->timer, jiffies + 1);
else
writel(RxOn, ioaddr + ChipCmd);
}
static void netdev_error(struct net_device *dev, int intr_status)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
spin_lock(&np->lock);
if (intr_status & LinkChange) {
u16 lpa = mdio_read(dev, MII_LPA);
if (mdio_read(dev, MII_BMCR) & BMCR_ANENABLE &&
netif_msg_link(np)) {
printk(KERN_INFO
"%s: Autonegotiation advertising"
" %#04x partner %#04x.\n", dev->name,
np->advertising, lpa);
}
/* read MII int status to clear the flag */
readw(ioaddr + MIntrStatus);
check_link(dev);
}
if (intr_status & StatsMax) {
__get_stats(dev);
}
if (intr_status & IntrTxUnderrun) {
if ((np->tx_config & TxDrthMask) < TX_DRTH_VAL_LIMIT) {
np->tx_config += TX_DRTH_VAL_INC;
if (netif_msg_tx_err(np))
printk(KERN_NOTICE
"%s: increased tx threshold, txcfg %#08x.\n",
dev->name, np->tx_config);
} else {
if (netif_msg_tx_err(np))
printk(KERN_NOTICE
"%s: tx underrun with maximum tx threshold, txcfg %#08x.\n",
dev->name, np->tx_config);
}
writel(np->tx_config, ioaddr + TxConfig);
}
if (intr_status & WOLPkt && netif_msg_wol(np)) {
int wol_status = readl(ioaddr + WOLCmd);
printk(KERN_NOTICE "%s: Link wake-up event %#08x\n",
dev->name, wol_status);
}
if (intr_status & RxStatusFIFOOver) {
if (netif_msg_rx_err(np) && netif_msg_intr(np)) {
printk(KERN_NOTICE "%s: Rx status FIFO overrun\n",
dev->name);
}
dev->stats.rx_fifo_errors++;
dev->stats.rx_errors++;
}
/* Hmmmmm, it's not clear how to recover from PCI faults. */
if (intr_status & IntrPCIErr) {
printk(KERN_NOTICE "%s: PCI error %#08x\n", dev->name,
intr_status & IntrPCIErr);
dev->stats.tx_fifo_errors++;
dev->stats.tx_errors++;
dev->stats.rx_fifo_errors++;
dev->stats.rx_errors++;
}
spin_unlock(&np->lock);
}
static void __get_stats(struct net_device *dev)
{
void __iomem * ioaddr = ns_ioaddr(dev);
/* The chip only need report frame silently dropped. */
dev->stats.rx_crc_errors += readl(ioaddr + RxCRCErrs);
dev->stats.rx_missed_errors += readl(ioaddr + RxMissed);
}
static struct net_device_stats *get_stats(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
/* The chip only need report frame silently dropped. */
spin_lock_irq(&np->lock);
if (netif_running(dev) && !np->hands_off)
__get_stats(dev);
spin_unlock_irq(&np->lock);
return &dev->stats;
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void natsemi_poll_controller(struct net_device *dev)
{
disable_irq(dev->irq);
intr_handler(dev->irq, dev);
enable_irq(dev->irq);
}
#endif
#define HASH_TABLE 0x200
static void __set_rx_mode(struct net_device *dev)
{
void __iomem * ioaddr = ns_ioaddr(dev);
struct netdev_private *np = netdev_priv(dev);
u8 mc_filter[64]; /* Multicast hash filter */
u32 rx_mode;
if (dev->flags & IFF_PROMISC) { /* Set promiscuous. */
rx_mode = RxFilterEnable | AcceptBroadcast
| AcceptAllMulticast | AcceptAllPhys | AcceptMyPhys;
} else if ((netdev_mc_count(dev) > multicast_filter_limit) ||
(dev->flags & IFF_ALLMULTI)) {
rx_mode = RxFilterEnable | AcceptBroadcast
| AcceptAllMulticast | AcceptMyPhys;
} else {
struct netdev_hw_addr *ha;
int i;
memset(mc_filter, 0, sizeof(mc_filter));
netdev_for_each_mc_addr(ha, dev) {
int b = (ether_crc(ETH_ALEN, ha->addr) >> 23) & 0x1ff;
mc_filter[b/8] |= (1 << (b & 0x07));
}
rx_mode = RxFilterEnable | AcceptBroadcast
| AcceptMulticast | AcceptMyPhys;
for (i = 0; i < 64; i += 2) {
writel(HASH_TABLE + i, ioaddr + RxFilterAddr);
writel((mc_filter[i + 1] << 8) + mc_filter[i],
ioaddr + RxFilterData);
}
}
writel(rx_mode, ioaddr + RxFilterAddr);
np->cur_rx_mode = rx_mode;
}
static int natsemi_change_mtu(struct net_device *dev, int new_mtu)
{
if (new_mtu < 64 || new_mtu > NATSEMI_RX_LIMIT-NATSEMI_HEADERS)
return -EINVAL;
dev->mtu = new_mtu;
/* synchronized against open : rtnl_lock() held by caller */
if (netif_running(dev)) {
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
disable_irq(dev->irq);
spin_lock(&np->lock);
/* stop engines */
natsemi_stop_rxtx(dev);
/* drain rx queue */
drain_rx(dev);
/* change buffers */
set_bufsize(dev);
reinit_rx(dev);
writel(np->ring_dma, ioaddr + RxRingPtr);
/* restart engines */
writel(RxOn | TxOn, ioaddr + ChipCmd);
spin_unlock(&np->lock);
enable_irq(dev->irq);
}
return 0;
}
static void set_rx_mode(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
spin_lock_irq(&np->lock);
if (!np->hands_off)
__set_rx_mode(dev);
spin_unlock_irq(&np->lock);
}
static void get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct netdev_private *np = netdev_priv(dev);
strncpy(info->driver, DRV_NAME, ETHTOOL_BUSINFO_LEN);
strncpy(info->version, DRV_VERSION, ETHTOOL_BUSINFO_LEN);
strncpy(info->bus_info, pci_name(np->pci_dev), ETHTOOL_BUSINFO_LEN);
}
static int get_regs_len(struct net_device *dev)
{
return NATSEMI_REGS_SIZE;
}
static int get_eeprom_len(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
return np->eeprom_size;
}
static int get_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
spin_lock_irq(&np->lock);
netdev_get_ecmd(dev, ecmd);
spin_unlock_irq(&np->lock);
return 0;
}
static int set_settings(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
int res;
spin_lock_irq(&np->lock);
res = netdev_set_ecmd(dev, ecmd);
spin_unlock_irq(&np->lock);
return res;
}
static void get_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct netdev_private *np = netdev_priv(dev);
spin_lock_irq(&np->lock);
netdev_get_wol(dev, &wol->supported, &wol->wolopts);
netdev_get_sopass(dev, wol->sopass);
spin_unlock_irq(&np->lock);
}
static int set_wol(struct net_device *dev, struct ethtool_wolinfo *wol)
{
struct netdev_private *np = netdev_priv(dev);
int res;
spin_lock_irq(&np->lock);
netdev_set_wol(dev, wol->wolopts);
res = netdev_set_sopass(dev, wol->sopass);
spin_unlock_irq(&np->lock);
return res;
}
static void get_regs(struct net_device *dev, struct ethtool_regs *regs, void *buf)
{
struct netdev_private *np = netdev_priv(dev);
regs->version = NATSEMI_REGS_VER;
spin_lock_irq(&np->lock);
netdev_get_regs(dev, buf);
spin_unlock_irq(&np->lock);
}
static u32 get_msglevel(struct net_device *dev)
{
struct netdev_private *np = netdev_priv(dev);
return np->msg_enable;
}
static void set_msglevel(struct net_device *dev, u32 val)
{
struct netdev_private *np = netdev_priv(dev);
np->msg_enable = val;
}
static int nway_reset(struct net_device *dev)
{
int tmp;
int r = -EINVAL;
/* if autoneg is off, it's an error */
tmp = mdio_read(dev, MII_BMCR);
if (tmp & BMCR_ANENABLE) {
tmp |= (BMCR_ANRESTART);
mdio_write(dev, MII_BMCR, tmp);
r = 0;
}
return r;
}
static u32 get_link(struct net_device *dev)
{
/* LSTATUS is latched low until a read - so read twice */
mdio_read(dev, MII_BMSR);
return (mdio_read(dev, MII_BMSR)&BMSR_LSTATUS) ? 1:0;
}
static int get_eeprom(struct net_device *dev, struct ethtool_eeprom *eeprom, u8 *data)
{
struct netdev_private *np = netdev_priv(dev);
u8 *eebuf;
int res;
eebuf = kmalloc(np->eeprom_size, GFP_KERNEL);
if (!eebuf)
return -ENOMEM;
eeprom->magic = PCI_VENDOR_ID_NS | (PCI_DEVICE_ID_NS_83815<<16);
spin_lock_irq(&np->lock);
res = netdev_get_eeprom(dev, eebuf);
spin_unlock_irq(&np->lock);
if (!res)
memcpy(data, eebuf+eeprom->offset, eeprom->len);
kfree(eebuf);
return res;
}
static const struct ethtool_ops ethtool_ops = {
.get_drvinfo = get_drvinfo,
.get_regs_len = get_regs_len,
.get_eeprom_len = get_eeprom_len,
.get_settings = get_settings,
.set_settings = set_settings,
.get_wol = get_wol,
.set_wol = set_wol,
.get_regs = get_regs,
.get_msglevel = get_msglevel,
.set_msglevel = set_msglevel,
.nway_reset = nway_reset,
.get_link = get_link,
.get_eeprom = get_eeprom,
};
static int netdev_set_wol(struct net_device *dev, u32 newval)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
u32 data = readl(ioaddr + WOLCmd) & ~WakeOptsSummary;
/* translate to bitmasks this chip understands */
if (newval & WAKE_PHY)
data |= WakePhy;
if (newval & WAKE_UCAST)
data |= WakeUnicast;
if (newval & WAKE_MCAST)
data |= WakeMulticast;
if (newval & WAKE_BCAST)
data |= WakeBroadcast;
if (newval & WAKE_ARP)
data |= WakeArp;
if (newval & WAKE_MAGIC)
data |= WakeMagic;
if (np->srr >= SRR_DP83815_D) {
if (newval & WAKE_MAGICSECURE) {
data |= WakeMagicSecure;
}
}
writel(data, ioaddr + WOLCmd);
return 0;
}
static int netdev_get_wol(struct net_device *dev, u32 *supported, u32 *cur)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
u32 regval = readl(ioaddr + WOLCmd);
*supported = (WAKE_PHY | WAKE_UCAST | WAKE_MCAST | WAKE_BCAST
| WAKE_ARP | WAKE_MAGIC);
if (np->srr >= SRR_DP83815_D) {
/* SOPASS works on revD and higher */
*supported |= WAKE_MAGICSECURE;
}
*cur = 0;
/* translate from chip bitmasks */
if (regval & WakePhy)
*cur |= WAKE_PHY;
if (regval & WakeUnicast)
*cur |= WAKE_UCAST;
if (regval & WakeMulticast)
*cur |= WAKE_MCAST;
if (regval & WakeBroadcast)
*cur |= WAKE_BCAST;
if (regval & WakeArp)
*cur |= WAKE_ARP;
if (regval & WakeMagic)
*cur |= WAKE_MAGIC;
if (regval & WakeMagicSecure) {
/* this can be on in revC, but it's broken */
*cur |= WAKE_MAGICSECURE;
}
return 0;
}
static int netdev_set_sopass(struct net_device *dev, u8 *newval)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
u16 *sval = (u16 *)newval;
u32 addr;
if (np->srr < SRR_DP83815_D) {
return 0;
}
/* enable writing to these registers by disabling the RX filter */
addr = readl(ioaddr + RxFilterAddr) & ~RFCRAddressMask;
addr &= ~RxFilterEnable;
writel(addr, ioaddr + RxFilterAddr);
/* write the three words to (undocumented) RFCR vals 0xa, 0xc, 0xe */
writel(addr | 0xa, ioaddr + RxFilterAddr);
writew(sval[0], ioaddr + RxFilterData);
writel(addr | 0xc, ioaddr + RxFilterAddr);
writew(sval[1], ioaddr + RxFilterData);
writel(addr | 0xe, ioaddr + RxFilterAddr);
writew(sval[2], ioaddr + RxFilterData);
/* re-enable the RX filter */
writel(addr | RxFilterEnable, ioaddr + RxFilterAddr);
return 0;
}
static int netdev_get_sopass(struct net_device *dev, u8 *data)
{
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
u16 *sval = (u16 *)data;
u32 addr;
if (np->srr < SRR_DP83815_D) {
sval[0] = sval[1] = sval[2] = 0;
return 0;
}
/* read the three words from (undocumented) RFCR vals 0xa, 0xc, 0xe */
addr = readl(ioaddr + RxFilterAddr) & ~RFCRAddressMask;
writel(addr | 0xa, ioaddr + RxFilterAddr);
sval[0] = readw(ioaddr + RxFilterData);
writel(addr | 0xc, ioaddr + RxFilterAddr);
sval[1] = readw(ioaddr + RxFilterData);
writel(addr | 0xe, ioaddr + RxFilterAddr);
sval[2] = readw(ioaddr + RxFilterData);
writel(addr, ioaddr + RxFilterAddr);
return 0;
}
static int netdev_get_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
u32 tmp;
ecmd->port = dev->if_port;
ethtool_cmd_speed_set(ecmd, np->speed);
ecmd->duplex = np->duplex;
ecmd->autoneg = np->autoneg;
ecmd->advertising = 0;
if (np->advertising & ADVERTISE_10HALF)
ecmd->advertising |= ADVERTISED_10baseT_Half;
if (np->advertising & ADVERTISE_10FULL)
ecmd->advertising |= ADVERTISED_10baseT_Full;
if (np->advertising & ADVERTISE_100HALF)
ecmd->advertising |= ADVERTISED_100baseT_Half;
if (np->advertising & ADVERTISE_100FULL)
ecmd->advertising |= ADVERTISED_100baseT_Full;
ecmd->supported = (SUPPORTED_Autoneg |
SUPPORTED_10baseT_Half | SUPPORTED_10baseT_Full |
SUPPORTED_100baseT_Half | SUPPORTED_100baseT_Full |
SUPPORTED_TP | SUPPORTED_MII | SUPPORTED_FIBRE);
ecmd->phy_address = np->phy_addr_external;
/*
* We intentionally report the phy address of the external
* phy, even if the internal phy is used. This is necessary
* to work around a deficiency of the ethtool interface:
* It's only possible to query the settings of the active
* port. Therefore
* # ethtool -s ethX port mii
* actually sends an ioctl to switch to port mii with the
* settings that are used for the current active port.
* If we would report a different phy address in this
* command, then
* # ethtool -s ethX port tp;ethtool -s ethX port mii
* would unintentionally change the phy address.
*
* Fortunately the phy address doesn't matter with the
* internal phy...
*/
/* set information based on active port type */
switch (ecmd->port) {
default:
case PORT_TP:
ecmd->advertising |= ADVERTISED_TP;
ecmd->transceiver = XCVR_INTERNAL;
break;
case PORT_MII:
ecmd->advertising |= ADVERTISED_MII;
ecmd->transceiver = XCVR_EXTERNAL;
break;
case PORT_FIBRE:
ecmd->advertising |= ADVERTISED_FIBRE;
ecmd->transceiver = XCVR_EXTERNAL;
break;
}
/* if autonegotiation is on, try to return the active speed/duplex */
if (ecmd->autoneg == AUTONEG_ENABLE) {
ecmd->advertising |= ADVERTISED_Autoneg;
tmp = mii_nway_result(
np->advertising & mdio_read(dev, MII_LPA));
if (tmp == LPA_100FULL || tmp == LPA_100HALF)
ethtool_cmd_speed_set(ecmd, SPEED_100);
else
ethtool_cmd_speed_set(ecmd, SPEED_10);
if (tmp == LPA_100FULL || tmp == LPA_10FULL)
ecmd->duplex = DUPLEX_FULL;
else
ecmd->duplex = DUPLEX_HALF;
}
/* ignore maxtxpkt, maxrxpkt for now */
return 0;
}
static int netdev_set_ecmd(struct net_device *dev, struct ethtool_cmd *ecmd)
{
struct netdev_private *np = netdev_priv(dev);
if (ecmd->port != PORT_TP && ecmd->port != PORT_MII && ecmd->port != PORT_FIBRE)
return -EINVAL;
if (ecmd->transceiver != XCVR_INTERNAL && ecmd->transceiver != XCVR_EXTERNAL)
return -EINVAL;
if (ecmd->autoneg == AUTONEG_ENABLE) {
if ((ecmd->advertising & (ADVERTISED_10baseT_Half |
ADVERTISED_10baseT_Full |
ADVERTISED_100baseT_Half |
ADVERTISED_100baseT_Full)) == 0) {
return -EINVAL;
}
} else if (ecmd->autoneg == AUTONEG_DISABLE) {
u32 speed = ethtool_cmd_speed(ecmd);
if (speed != SPEED_10 && speed != SPEED_100)
return -EINVAL;
if (ecmd->duplex != DUPLEX_HALF && ecmd->duplex != DUPLEX_FULL)
return -EINVAL;
} else {
return -EINVAL;
}
/*
* If we're ignoring the PHY then autoneg and the internal
* transciever are really not going to work so don't let the
* user select them.
*/
if (np->ignore_phy && (ecmd->autoneg == AUTONEG_ENABLE ||
ecmd->port == PORT_TP))
return -EINVAL;
/*
* maxtxpkt, maxrxpkt: ignored for now.
*
* transceiver:
* PORT_TP is always XCVR_INTERNAL, PORT_MII and PORT_FIBRE are always
* XCVR_EXTERNAL. The implementation thus ignores ecmd->transceiver and
* selects based on ecmd->port.
*
* Actually PORT_FIBRE is nearly identical to PORT_MII: it's for fibre
* phys that are connected to the mii bus. It's used to apply fibre
* specific updates.
*/
/* WHEW! now lets bang some bits */
/* save the parms */
dev->if_port = ecmd->port;
np->autoneg = ecmd->autoneg;
np->phy_addr_external = ecmd->phy_address & PhyAddrMask;
if (np->autoneg == AUTONEG_ENABLE) {
/* advertise only what has been requested */
np->advertising &= ~(ADVERTISE_ALL | ADVERTISE_100BASE4);
if (ecmd->advertising & ADVERTISED_10baseT_Half)
np->advertising |= ADVERTISE_10HALF;
if (ecmd->advertising & ADVERTISED_10baseT_Full)
np->advertising |= ADVERTISE_10FULL;
if (ecmd->advertising & ADVERTISED_100baseT_Half)
np->advertising |= ADVERTISE_100HALF;
if (ecmd->advertising & ADVERTISED_100baseT_Full)
np->advertising |= ADVERTISE_100FULL;
} else {
np->speed = ethtool_cmd_speed(ecmd);
np->duplex = ecmd->duplex;
/* user overriding the initial full duplex parm? */
if (np->duplex == DUPLEX_HALF)
np->full_duplex = 0;
}
/* get the right phy enabled */
if (ecmd->port == PORT_TP)
switch_port_internal(dev);
else
switch_port_external(dev);
/* set parms and see how this affected our link status */
init_phy_fixup(dev);
check_link(dev);
return 0;
}
static int netdev_get_regs(struct net_device *dev, u8 *buf)
{
int i;
int j;
u32 rfcr;
u32 *rbuf = (u32 *)buf;
void __iomem * ioaddr = ns_ioaddr(dev);
/* read non-mii page 0 of registers */
for (i = 0; i < NATSEMI_PG0_NREGS/2; i++) {
rbuf[i] = readl(ioaddr + i*4);
}
/* read current mii registers */
for (i = NATSEMI_PG0_NREGS/2; i < NATSEMI_PG0_NREGS; i++)
rbuf[i] = mdio_read(dev, i & 0x1f);
/* read only the 'magic' registers from page 1 */
writew(1, ioaddr + PGSEL);
rbuf[i++] = readw(ioaddr + PMDCSR);
rbuf[i++] = readw(ioaddr + TSTDAT);
rbuf[i++] = readw(ioaddr + DSPCFG);
rbuf[i++] = readw(ioaddr + SDCFG);
writew(0, ioaddr + PGSEL);
/* read RFCR indexed registers */
rfcr = readl(ioaddr + RxFilterAddr);
for (j = 0; j < NATSEMI_RFDR_NREGS; j++) {
writel(j*2, ioaddr + RxFilterAddr);
rbuf[i++] = readw(ioaddr + RxFilterData);
}
writel(rfcr, ioaddr + RxFilterAddr);
/* the interrupt status is clear-on-read - see if we missed any */
if (rbuf[4] & rbuf[5]) {
printk(KERN_WARNING
"%s: shoot, we dropped an interrupt (%#08x)\n",
dev->name, rbuf[4] & rbuf[5]);
}
return 0;
}
#define SWAP_BITS(x) ( (((x) & 0x0001) << 15) | (((x) & 0x0002) << 13) \
| (((x) & 0x0004) << 11) | (((x) & 0x0008) << 9) \
| (((x) & 0x0010) << 7) | (((x) & 0x0020) << 5) \
| (((x) & 0x0040) << 3) | (((x) & 0x0080) << 1) \
| (((x) & 0x0100) >> 1) | (((x) & 0x0200) >> 3) \
| (((x) & 0x0400) >> 5) | (((x) & 0x0800) >> 7) \
| (((x) & 0x1000) >> 9) | (((x) & 0x2000) >> 11) \
| (((x) & 0x4000) >> 13) | (((x) & 0x8000) >> 15) )
static int netdev_get_eeprom(struct net_device *dev, u8 *buf)
{
int i;
u16 *ebuf = (u16 *)buf;
void __iomem * ioaddr = ns_ioaddr(dev);
struct netdev_private *np = netdev_priv(dev);
/* eeprom_read reads 16 bits, and indexes by 16 bits */
for (i = 0; i < np->eeprom_size/2; i++) {
ebuf[i] = eeprom_read(ioaddr, i);
/* The EEPROM itself stores data bit-swapped, but eeprom_read
* reads it back "sanely". So we swap it back here in order to
* present it to userland as it is stored. */
ebuf[i] = SWAP_BITS(ebuf[i]);
}
return 0;
}
static int netdev_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
struct mii_ioctl_data *data = if_mii(rq);
struct netdev_private *np = netdev_priv(dev);
switch(cmd) {
case SIOCGMIIPHY: /* Get address of MII PHY in use. */
data->phy_id = np->phy_addr_external;
/* Fall Through */
case SIOCGMIIREG: /* Read MII PHY register. */
/* The phy_id is not enough to uniquely identify
* the intended target. Therefore the command is sent to
* the given mii on the current port.
*/
if (dev->if_port == PORT_TP) {
if ((data->phy_id & 0x1f) == np->phy_addr_external)
data->val_out = mdio_read(dev,
data->reg_num & 0x1f);
else
data->val_out = 0;
} else {
move_int_phy(dev, data->phy_id & 0x1f);
data->val_out = miiport_read(dev, data->phy_id & 0x1f,
data->reg_num & 0x1f);
}
return 0;
case SIOCSMIIREG: /* Write MII PHY register. */
if (dev->if_port == PORT_TP) {
if ((data->phy_id & 0x1f) == np->phy_addr_external) {
if ((data->reg_num & 0x1f) == MII_ADVERTISE)
np->advertising = data->val_in;
mdio_write(dev, data->reg_num & 0x1f,
data->val_in);
}
} else {
if ((data->phy_id & 0x1f) == np->phy_addr_external) {
if ((data->reg_num & 0x1f) == MII_ADVERTISE)
np->advertising = data->val_in;
}
move_int_phy(dev, data->phy_id & 0x1f);
miiport_write(dev, data->phy_id & 0x1f,
data->reg_num & 0x1f,
data->val_in);
}
return 0;
default:
return -EOPNOTSUPP;
}
}
static void enable_wol_mode(struct net_device *dev, int enable_intr)
{
void __iomem * ioaddr = ns_ioaddr(dev);
struct netdev_private *np = netdev_priv(dev);
if (netif_msg_wol(np))
printk(KERN_INFO "%s: remaining active for wake-on-lan\n",
dev->name);
/* For WOL we must restart the rx process in silent mode.
* Write NULL to the RxRingPtr. Only possible if
* rx process is stopped
*/
writel(0, ioaddr + RxRingPtr);
/* read WoL status to clear */
readl(ioaddr + WOLCmd);
/* PME on, clear status */
writel(np->SavedClkRun | PMEEnable | PMEStatus, ioaddr + ClkRun);
/* and restart the rx process */
writel(RxOn, ioaddr + ChipCmd);
if (enable_intr) {
/* enable the WOL interrupt.
* Could be used to send a netlink message.
*/
writel(WOLPkt | LinkChange, ioaddr + IntrMask);
natsemi_irq_enable(dev);
}
}
static int netdev_close(struct net_device *dev)
{
void __iomem * ioaddr = ns_ioaddr(dev);
struct netdev_private *np = netdev_priv(dev);
if (netif_msg_ifdown(np))
printk(KERN_DEBUG
"%s: Shutting down ethercard, status was %#04x.\n",
dev->name, (int)readl(ioaddr + ChipCmd));
if (netif_msg_pktdata(np))
printk(KERN_DEBUG
"%s: Queue pointers were Tx %d / %d, Rx %d / %d.\n",
dev->name, np->cur_tx, np->dirty_tx,
np->cur_rx, np->dirty_rx);
napi_disable(&np->napi);
/*
* FIXME: what if someone tries to close a device
* that is suspended?
* Should we reenable the nic to switch to
* the final WOL settings?
*/
del_timer_sync(&np->timer);
disable_irq(dev->irq);
spin_lock_irq(&np->lock);
natsemi_irq_disable(dev);
np->hands_off = 1;
spin_unlock_irq(&np->lock);
enable_irq(dev->irq);
free_irq(dev->irq, dev);
/* Interrupt disabled, interrupt handler released,
* queue stopped, timer deleted, rtnl_lock held
* All async codepaths that access the driver are disabled.
*/
spin_lock_irq(&np->lock);
np->hands_off = 0;
readl(ioaddr + IntrMask);
readw(ioaddr + MIntrStatus);
/* Freeze Stats */
writel(StatsFreeze, ioaddr + StatsCtrl);
/* Stop the chip's Tx and Rx processes. */
natsemi_stop_rxtx(dev);
__get_stats(dev);
spin_unlock_irq(&np->lock);
/* clear the carrier last - an interrupt could reenable it otherwise */
netif_carrier_off(dev);
netif_stop_queue(dev);
dump_ring(dev);
drain_ring(dev);
free_ring(dev);
{
u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
if (wol) {
/* restart the NIC in WOL mode.
* The nic must be stopped for this.
*/
enable_wol_mode(dev, 0);
} else {
/* Restore PME enable bit unmolested */
writel(np->SavedClkRun, ioaddr + ClkRun);
}
}
return 0;
}
static void __devexit natsemi_remove1 (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata(pdev);
void __iomem * ioaddr = ns_ioaddr(dev);
NATSEMI_REMOVE_FILE(pdev, dspcfg_workaround);
unregister_netdev (dev);
pci_release_regions (pdev);
iounmap(ioaddr);
free_netdev (dev);
pci_set_drvdata(pdev, NULL);
}
#ifdef CONFIG_PM
/*
* The ns83815 chip doesn't have explicit RxStop bits.
* Kicking the Rx or Tx process for a new packet reenables the Rx process
* of the nic, thus this function must be very careful:
*
* suspend/resume synchronization:
* entry points:
* netdev_open, netdev_close, netdev_ioctl, set_rx_mode, intr_handler,
* start_tx, ns_tx_timeout
*
* No function accesses the hardware without checking np->hands_off.
* the check occurs under spin_lock_irq(&np->lock);
* exceptions:
* * netdev_ioctl: noncritical access.
* * netdev_open: cannot happen due to the device_detach
* * netdev_close: doesn't hurt.
* * netdev_timer: timer stopped by natsemi_suspend.
* * intr_handler: doesn't acquire the spinlock. suspend calls
* disable_irq() to enforce synchronization.
* * natsemi_poll: checks before reenabling interrupts. suspend
* sets hands_off, disables interrupts and then waits with
* napi_disable().
*
* Interrupts must be disabled, otherwise hands_off can cause irq storms.
*/
static int natsemi_suspend (struct pci_dev *pdev, pm_message_t state)
{
struct net_device *dev = pci_get_drvdata (pdev);
struct netdev_private *np = netdev_priv(dev);
void __iomem * ioaddr = ns_ioaddr(dev);
rtnl_lock();
if (netif_running (dev)) {
del_timer_sync(&np->timer);
disable_irq(dev->irq);
spin_lock_irq(&np->lock);
natsemi_irq_disable(dev);
np->hands_off = 1;
natsemi_stop_rxtx(dev);
netif_stop_queue(dev);
spin_unlock_irq(&np->lock);
enable_irq(dev->irq);
napi_disable(&np->napi);
/* Update the error counts. */
__get_stats(dev);
/* pci_power_off(pdev, -1); */
drain_ring(dev);
{
u32 wol = readl(ioaddr + WOLCmd) & WakeOptsSummary;
/* Restore PME enable bit */
if (wol) {
/* restart the NIC in WOL mode.
* The nic must be stopped for this.
* FIXME: use the WOL interrupt
*/
enable_wol_mode(dev, 0);
} else {
/* Restore PME enable bit unmolested */
writel(np->SavedClkRun, ioaddr + ClkRun);
}
}
}
netif_device_detach(dev);
rtnl_unlock();
return 0;
}
static int natsemi_resume (struct pci_dev *pdev)
{
struct net_device *dev = pci_get_drvdata (pdev);
struct netdev_private *np = netdev_priv(dev);
int ret = 0;
rtnl_lock();
if (netif_device_present(dev))
goto out;
if (netif_running(dev)) {
BUG_ON(!np->hands_off);
ret = pci_enable_device(pdev);
if (ret < 0) {
dev_err(&pdev->dev,
"pci_enable_device() failed: %d\n", ret);
goto out;
}
/* pci_power_on(pdev); */
napi_enable(&np->napi);
natsemi_reset(dev);
init_ring(dev);
disable_irq(dev->irq);
spin_lock_irq(&np->lock);
np->hands_off = 0;
init_registers(dev);
netif_device_attach(dev);
spin_unlock_irq(&np->lock);
enable_irq(dev->irq);
mod_timer(&np->timer, round_jiffies(jiffies + 1*HZ));
}
netif_device_attach(dev);
out:
rtnl_unlock();
return ret;
}
#endif /* CONFIG_PM */
static struct pci_driver natsemi_driver = {
.name = DRV_NAME,
.id_table = natsemi_pci_tbl,
.probe = natsemi_probe1,
.remove = __devexit_p(natsemi_remove1),
#ifdef CONFIG_PM
.suspend = natsemi_suspend,
.resume = natsemi_resume,
#endif
};
static int __init natsemi_init_mod (void)
{
/* when a module, this is printed whether or not devices are found in probe */
#ifdef MODULE
printk(version);
#endif
return pci_register_driver(&natsemi_driver);
}
static void __exit natsemi_exit_mod (void)
{
pci_unregister_driver (&natsemi_driver);
}
module_init(natsemi_init_mod);
module_exit(natsemi_exit_mod);
| gpl-2.0 |
EdwinMoq/android_kernel_lge_omap4-common | arch/mips/lantiq/xway/gpio.c | 2606 | 5144 | /*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* Copyright (C) 2010 John Crispin <blogic@openwrt.org>
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/ioport.h>
#include <linux/io.h>
#include <lantiq_soc.h>
#define LTQ_GPIO_OUT 0x00
#define LTQ_GPIO_IN 0x04
#define LTQ_GPIO_DIR 0x08
#define LTQ_GPIO_ALTSEL0 0x0C
#define LTQ_GPIO_ALTSEL1 0x10
#define LTQ_GPIO_OD 0x14
#define PINS_PER_PORT 16
#define MAX_PORTS 3
#define ltq_gpio_getbit(m, r, p) (!!(ltq_r32(m + r) & (1 << p)))
#define ltq_gpio_setbit(m, r, p) ltq_w32_mask(0, (1 << p), m + r)
#define ltq_gpio_clearbit(m, r, p) ltq_w32_mask((1 << p), 0, m + r)
struct ltq_gpio {
void __iomem *membase;
struct gpio_chip chip;
};
static struct ltq_gpio ltq_gpio_port[MAX_PORTS];
int gpio_to_irq(unsigned int gpio)
{
return -EINVAL;
}
EXPORT_SYMBOL(gpio_to_irq);
int irq_to_gpio(unsigned int gpio)
{
return -EINVAL;
}
EXPORT_SYMBOL(irq_to_gpio);
int ltq_gpio_request(unsigned int pin, unsigned int alt0,
unsigned int alt1, unsigned int dir, const char *name)
{
int id = 0;
if (pin >= (MAX_PORTS * PINS_PER_PORT))
return -EINVAL;
if (gpio_request(pin, name)) {
pr_err("failed to setup lantiq gpio: %s\n", name);
return -EBUSY;
}
if (dir)
gpio_direction_output(pin, 1);
else
gpio_direction_input(pin);
while (pin >= PINS_PER_PORT) {
pin -= PINS_PER_PORT;
id++;
}
if (alt0)
ltq_gpio_setbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL0, pin);
else
ltq_gpio_clearbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL0, pin);
if (alt1)
ltq_gpio_setbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL1, pin);
else
ltq_gpio_clearbit(ltq_gpio_port[id].membase,
LTQ_GPIO_ALTSEL1, pin);
return 0;
}
EXPORT_SYMBOL(ltq_gpio_request);
static void ltq_gpio_set(struct gpio_chip *chip, unsigned int offset, int value)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
if (value)
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_OUT, offset);
else
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_OUT, offset);
}
static int ltq_gpio_get(struct gpio_chip *chip, unsigned int offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
return ltq_gpio_getbit(ltq_gpio->membase, LTQ_GPIO_IN, offset);
}
static int ltq_gpio_direction_input(struct gpio_chip *chip, unsigned int offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_OD, offset);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_DIR, offset);
return 0;
}
static int ltq_gpio_direction_output(struct gpio_chip *chip,
unsigned int offset, int value)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_OD, offset);
ltq_gpio_setbit(ltq_gpio->membase, LTQ_GPIO_DIR, offset);
ltq_gpio_set(chip, offset, value);
return 0;
}
static int ltq_gpio_req(struct gpio_chip *chip, unsigned offset)
{
struct ltq_gpio *ltq_gpio = container_of(chip, struct ltq_gpio, chip);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_ALTSEL0, offset);
ltq_gpio_clearbit(ltq_gpio->membase, LTQ_GPIO_ALTSEL1, offset);
return 0;
}
static int ltq_gpio_probe(struct platform_device *pdev)
{
struct resource *res;
if (pdev->id >= MAX_PORTS) {
dev_err(&pdev->dev, "invalid gpio port %d\n",
pdev->id);
return -EINVAL;
}
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
dev_err(&pdev->dev, "failed to get memory for gpio port %d\n",
pdev->id);
return -ENOENT;
}
res = devm_request_mem_region(&pdev->dev, res->start,
resource_size(res), dev_name(&pdev->dev));
if (!res) {
dev_err(&pdev->dev,
"failed to request memory for gpio port %d\n",
pdev->id);
return -EBUSY;
}
ltq_gpio_port[pdev->id].membase = devm_ioremap_nocache(&pdev->dev,
res->start, resource_size(res));
if (!ltq_gpio_port[pdev->id].membase) {
dev_err(&pdev->dev, "failed to remap memory for gpio port %d\n",
pdev->id);
return -ENOMEM;
}
ltq_gpio_port[pdev->id].chip.label = "ltq_gpio";
ltq_gpio_port[pdev->id].chip.direction_input = ltq_gpio_direction_input;
ltq_gpio_port[pdev->id].chip.direction_output =
ltq_gpio_direction_output;
ltq_gpio_port[pdev->id].chip.get = ltq_gpio_get;
ltq_gpio_port[pdev->id].chip.set = ltq_gpio_set;
ltq_gpio_port[pdev->id].chip.request = ltq_gpio_req;
ltq_gpio_port[pdev->id].chip.base = PINS_PER_PORT * pdev->id;
ltq_gpio_port[pdev->id].chip.ngpio = PINS_PER_PORT;
platform_set_drvdata(pdev, <q_gpio_port[pdev->id]);
return gpiochip_add(<q_gpio_port[pdev->id].chip);
}
static struct platform_driver
ltq_gpio_driver = {
.probe = ltq_gpio_probe,
.driver = {
.name = "ltq_gpio",
.owner = THIS_MODULE,
},
};
int __init ltq_gpio_init(void)
{
int ret = platform_driver_register(<q_gpio_driver);
if (ret)
pr_info("ltq_gpio : Error registering platfom driver!");
return ret;
}
postcore_initcall(ltq_gpio_init);
| gpl-2.0 |
TeamExodus/kernel_cyanogen_msm8916 | drivers/media/usb/pvrusb2/pvrusb2-devattr.c | 3374 | 17404 | /*
*
*
* Copyright (C) 2007 Mike Isely <isely@pobox.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
This source file should encompass ALL per-device type information for the
driver. To define a new device, add elements to the pvr2_device_table and
pvr2_device_desc structures.
*/
#include "pvrusb2-devattr.h"
#include <linux/usb.h>
#include <linux/module.h>
/* This is needed in order to pull in tuner type ids... */
#include <linux/i2c.h>
#include <media/tuner.h>
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
#include "pvrusb2-hdw-internal.h"
#include "lgdt330x.h"
#include "s5h1409.h"
#include "s5h1411.h"
#include "tda10048.h"
#include "tda18271.h"
#include "tda8290.h"
#include "tuner-simple.h"
#endif
/*------------------------------------------------------------------------*/
/* Hauppauge PVR-USB2 Model 29xxx */
static const struct pvr2_device_client_desc pvr2_cli_29xxx[] = {
{ .module_id = PVR2_CLIENT_ID_SAA7115 },
{ .module_id = PVR2_CLIENT_ID_MSP3400 },
{ .module_id = PVR2_CLIENT_ID_TUNER },
{ .module_id = PVR2_CLIENT_ID_DEMOD },
};
#define PVR2_FIRMWARE_29xxx "v4l-pvrusb2-29xxx-01.fw"
static const char *pvr2_fw1_names_29xxx[] = {
PVR2_FIRMWARE_29xxx,
};
static const struct pvr2_device_desc pvr2_device_29xxx = {
.description = "WinTV PVR USB2 Model 29xxx",
.shortname = "29xxx",
.client_table.lst = pvr2_cli_29xxx,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_29xxx),
.fx2_firmware.lst = pvr2_fw1_names_29xxx,
.fx2_firmware.cnt = ARRAY_SIZE(pvr2_fw1_names_29xxx),
.flag_has_hauppauge_rom = !0,
.flag_has_analogtuner = !0,
.flag_has_fmradio = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_HAUPPAUGE,
.led_scheme = PVR2_LED_SCHEME_HAUPPAUGE,
.ir_scheme = PVR2_IR_SCHEME_29XXX,
};
/*------------------------------------------------------------------------*/
/* Hauppauge PVR-USB2 Model 24xxx */
static const struct pvr2_device_client_desc pvr2_cli_24xxx[] = {
{ .module_id = PVR2_CLIENT_ID_CX25840 },
{ .module_id = PVR2_CLIENT_ID_TUNER },
{ .module_id = PVR2_CLIENT_ID_WM8775 },
{ .module_id = PVR2_CLIENT_ID_DEMOD },
};
#define PVR2_FIRMWARE_24xxx "v4l-pvrusb2-24xxx-01.fw"
static const char *pvr2_fw1_names_24xxx[] = {
PVR2_FIRMWARE_24xxx,
};
static const struct pvr2_device_desc pvr2_device_24xxx = {
.description = "WinTV PVR USB2 Model 24xxx",
.shortname = "24xxx",
.client_table.lst = pvr2_cli_24xxx,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_24xxx),
.fx2_firmware.lst = pvr2_fw1_names_24xxx,
.fx2_firmware.cnt = ARRAY_SIZE(pvr2_fw1_names_24xxx),
.flag_has_cx25840 = !0,
.flag_has_wm8775 = !0,
.flag_has_hauppauge_rom = !0,
.flag_has_analogtuner = !0,
.flag_has_fmradio = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_HAUPPAUGE,
.led_scheme = PVR2_LED_SCHEME_HAUPPAUGE,
.ir_scheme = PVR2_IR_SCHEME_24XXX,
};
/*------------------------------------------------------------------------*/
/* GOTVIEW USB2.0 DVD2 */
static const struct pvr2_device_client_desc pvr2_cli_gotview_2[] = {
{ .module_id = PVR2_CLIENT_ID_CX25840 },
{ .module_id = PVR2_CLIENT_ID_TUNER },
{ .module_id = PVR2_CLIENT_ID_DEMOD },
};
static const struct pvr2_device_desc pvr2_device_gotview_2 = {
.description = "Gotview USB 2.0 DVD 2",
.shortname = "gv2",
.client_table.lst = pvr2_cli_gotview_2,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_gotview_2),
.flag_has_cx25840 = !0,
.default_tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.flag_has_analogtuner = !0,
.flag_has_fmradio = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_GOTVIEW,
};
/*------------------------------------------------------------------------*/
/* GOTVIEW USB2.0 DVD Deluxe */
/* (same module list as gotview_2) */
static const struct pvr2_device_desc pvr2_device_gotview_2d = {
.description = "Gotview USB 2.0 DVD Deluxe",
.shortname = "gv2d",
.client_table.lst = pvr2_cli_gotview_2,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_gotview_2),
.flag_has_cx25840 = !0,
.default_tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_GOTVIEW,
};
/*------------------------------------------------------------------------*/
/* Terratec Grabster AV400 */
static const struct pvr2_device_client_desc pvr2_cli_av400[] = {
{ .module_id = PVR2_CLIENT_ID_CX25840 },
};
static const struct pvr2_device_desc pvr2_device_av400 = {
.description = "Terratec Grabster AV400",
.shortname = "av400",
.flag_is_experimental = 1,
.client_table.lst = pvr2_cli_av400,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_av400),
.flag_has_cx25840 = !0,
.flag_has_analogtuner = 0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_AV400,
};
/*------------------------------------------------------------------------*/
/* OnAir Creator */
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
static struct lgdt330x_config pvr2_lgdt3303_config = {
.demod_address = 0x0e,
.demod_chip = LGDT3303,
.clock_polarity_flip = 1,
};
static int pvr2_lgdt3303_attach(struct pvr2_dvb_adapter *adap)
{
adap->fe = dvb_attach(lgdt330x_attach, &pvr2_lgdt3303_config,
&adap->channel.hdw->i2c_adap);
if (adap->fe)
return 0;
return -EIO;
}
static int pvr2_lgh06xf_attach(struct pvr2_dvb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe,
&adap->channel.hdw->i2c_adap, 0x61,
TUNER_LG_TDVS_H06XF);
return 0;
}
static const struct pvr2_dvb_props pvr2_onair_creator_fe_props = {
.frontend_attach = pvr2_lgdt3303_attach,
.tuner_attach = pvr2_lgh06xf_attach,
};
#endif
static const struct pvr2_device_client_desc pvr2_cli_onair_creator[] = {
{ .module_id = PVR2_CLIENT_ID_SAA7115 },
{ .module_id = PVR2_CLIENT_ID_CS53L32A },
{ .module_id = PVR2_CLIENT_ID_TUNER },
};
static const struct pvr2_device_desc pvr2_device_onair_creator = {
.description = "OnAir Creator Hybrid USB tuner",
.shortname = "oac",
.client_table.lst = pvr2_cli_onair_creator,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_onair_creator),
.default_tuner_type = TUNER_LG_TDVS_H06XF,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.flag_digital_requires_cx23416 = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_ONAIR,
.digital_control_scheme = PVR2_DIGITAL_SCHEME_ONAIR,
.default_std_mask = V4L2_STD_NTSC_M,
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
.dvb_props = &pvr2_onair_creator_fe_props,
#endif
};
/*------------------------------------------------------------------------*/
/* OnAir USB 2.0 */
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
static struct lgdt330x_config pvr2_lgdt3302_config = {
.demod_address = 0x0e,
.demod_chip = LGDT3302,
};
static int pvr2_lgdt3302_attach(struct pvr2_dvb_adapter *adap)
{
adap->fe = dvb_attach(lgdt330x_attach, &pvr2_lgdt3302_config,
&adap->channel.hdw->i2c_adap);
if (adap->fe)
return 0;
return -EIO;
}
static int pvr2_fcv1236d_attach(struct pvr2_dvb_adapter *adap)
{
dvb_attach(simple_tuner_attach, adap->fe,
&adap->channel.hdw->i2c_adap, 0x61,
TUNER_PHILIPS_FCV1236D);
return 0;
}
static const struct pvr2_dvb_props pvr2_onair_usb2_fe_props = {
.frontend_attach = pvr2_lgdt3302_attach,
.tuner_attach = pvr2_fcv1236d_attach,
};
#endif
static const struct pvr2_device_client_desc pvr2_cli_onair_usb2[] = {
{ .module_id = PVR2_CLIENT_ID_SAA7115 },
{ .module_id = PVR2_CLIENT_ID_CS53L32A },
{ .module_id = PVR2_CLIENT_ID_TUNER },
};
static const struct pvr2_device_desc pvr2_device_onair_usb2 = {
.description = "OnAir USB2 Hybrid USB tuner",
.shortname = "oa2",
.client_table.lst = pvr2_cli_onair_usb2,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_onair_usb2),
.default_tuner_type = TUNER_PHILIPS_FCV1236D,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.flag_digital_requires_cx23416 = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_ONAIR,
.digital_control_scheme = PVR2_DIGITAL_SCHEME_ONAIR,
.default_std_mask = V4L2_STD_NTSC_M,
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
.dvb_props = &pvr2_onair_usb2_fe_props,
#endif
};
/*------------------------------------------------------------------------*/
/* Hauppauge PVR-USB2 Model 73xxx */
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
static struct tda10048_config hauppauge_tda10048_config = {
.demod_address = 0x10 >> 1,
.output_mode = TDA10048_PARALLEL_OUTPUT,
.fwbulkwritelen = TDA10048_BULKWRITE_50,
.inversion = TDA10048_INVERSION_ON,
.dtv6_if_freq_khz = TDA10048_IF_3300,
.dtv7_if_freq_khz = TDA10048_IF_3800,
.dtv8_if_freq_khz = TDA10048_IF_4300,
.clk_freq_khz = TDA10048_CLK_16000,
.disable_gate_access = 1,
};
static struct tda829x_config tda829x_no_probe = {
.probe_tuner = TDA829X_DONT_PROBE,
};
static struct tda18271_std_map hauppauge_tda18271_dvbt_std_map = {
.dvbt_6 = { .if_freq = 3300, .agc_mode = 3, .std = 4,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_7 = { .if_freq = 3800, .agc_mode = 3, .std = 5,
.if_lvl = 1, .rfagc_top = 0x37, },
.dvbt_8 = { .if_freq = 4300, .agc_mode = 3, .std = 6,
.if_lvl = 1, .rfagc_top = 0x37, },
};
static struct tda18271_config hauppauge_tda18271_dvb_config = {
.std_map = &hauppauge_tda18271_dvbt_std_map,
.gate = TDA18271_GATE_ANALOG,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
static int pvr2_tda10048_attach(struct pvr2_dvb_adapter *adap)
{
adap->fe = dvb_attach(tda10048_attach, &hauppauge_tda10048_config,
&adap->channel.hdw->i2c_adap);
if (adap->fe)
return 0;
return -EIO;
}
static int pvr2_73xxx_tda18271_8295_attach(struct pvr2_dvb_adapter *adap)
{
dvb_attach(tda829x_attach, adap->fe,
&adap->channel.hdw->i2c_adap, 0x42,
&tda829x_no_probe);
dvb_attach(tda18271_attach, adap->fe, 0x60,
&adap->channel.hdw->i2c_adap,
&hauppauge_tda18271_dvb_config);
return 0;
}
static const struct pvr2_dvb_props pvr2_73xxx_dvb_props = {
.frontend_attach = pvr2_tda10048_attach,
.tuner_attach = pvr2_73xxx_tda18271_8295_attach,
};
#endif
static const struct pvr2_device_client_desc pvr2_cli_73xxx[] = {
{ .module_id = PVR2_CLIENT_ID_CX25840 },
{ .module_id = PVR2_CLIENT_ID_TUNER,
.i2c_address_list = "\x42"},
};
#define PVR2_FIRMWARE_73xxx "v4l-pvrusb2-73xxx-01.fw"
static const char *pvr2_fw1_names_73xxx[] = {
PVR2_FIRMWARE_73xxx,
};
static const struct pvr2_device_desc pvr2_device_73xxx = {
.description = "WinTV HVR-1900 Model 73xxx",
.shortname = "73xxx",
.client_table.lst = pvr2_cli_73xxx,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_73xxx),
.fx2_firmware.lst = pvr2_fw1_names_73xxx,
.fx2_firmware.cnt = ARRAY_SIZE(pvr2_fw1_names_73xxx),
.flag_has_cx25840 = !0,
.flag_has_hauppauge_rom = !0,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.flag_fx2_16kb = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_HAUPPAUGE,
.digital_control_scheme = PVR2_DIGITAL_SCHEME_HAUPPAUGE,
.led_scheme = PVR2_LED_SCHEME_HAUPPAUGE,
.ir_scheme = PVR2_IR_SCHEME_ZILOG,
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
.dvb_props = &pvr2_73xxx_dvb_props,
#endif
};
/*------------------------------------------------------------------------*/
/* Hauppauge PVR-USB2 Model 75xxx */
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
static struct s5h1409_config pvr2_s5h1409_config = {
.demod_address = 0x32 >> 1,
.output_mode = S5H1409_PARALLEL_OUTPUT,
.gpio = S5H1409_GPIO_OFF,
.qam_if = 4000,
.inversion = S5H1409_INVERSION_ON,
.status_mode = S5H1409_DEMODLOCKING,
};
static struct s5h1411_config pvr2_s5h1411_config = {
.output_mode = S5H1411_PARALLEL_OUTPUT,
.gpio = S5H1411_GPIO_OFF,
.vsb_if = S5H1411_IF_44000,
.qam_if = S5H1411_IF_4000,
.inversion = S5H1411_INVERSION_ON,
.status_mode = S5H1411_DEMODLOCKING,
};
static struct tda18271_std_map hauppauge_tda18271_std_map = {
.atsc_6 = { .if_freq = 5380, .agc_mode = 3, .std = 3,
.if_lvl = 6, .rfagc_top = 0x37, },
.qam_6 = { .if_freq = 4000, .agc_mode = 3, .std = 0,
.if_lvl = 6, .rfagc_top = 0x37, },
};
static struct tda18271_config hauppauge_tda18271_config = {
.std_map = &hauppauge_tda18271_std_map,
.gate = TDA18271_GATE_ANALOG,
.output_opt = TDA18271_OUTPUT_LT_OFF,
};
static int pvr2_s5h1409_attach(struct pvr2_dvb_adapter *adap)
{
adap->fe = dvb_attach(s5h1409_attach, &pvr2_s5h1409_config,
&adap->channel.hdw->i2c_adap);
if (adap->fe)
return 0;
return -EIO;
}
static int pvr2_s5h1411_attach(struct pvr2_dvb_adapter *adap)
{
adap->fe = dvb_attach(s5h1411_attach, &pvr2_s5h1411_config,
&adap->channel.hdw->i2c_adap);
if (adap->fe)
return 0;
return -EIO;
}
static int pvr2_tda18271_8295_attach(struct pvr2_dvb_adapter *adap)
{
dvb_attach(tda829x_attach, adap->fe,
&adap->channel.hdw->i2c_adap, 0x42,
&tda829x_no_probe);
dvb_attach(tda18271_attach, adap->fe, 0x60,
&adap->channel.hdw->i2c_adap,
&hauppauge_tda18271_config);
return 0;
}
static const struct pvr2_dvb_props pvr2_750xx_dvb_props = {
.frontend_attach = pvr2_s5h1409_attach,
.tuner_attach = pvr2_tda18271_8295_attach,
};
static const struct pvr2_dvb_props pvr2_751xx_dvb_props = {
.frontend_attach = pvr2_s5h1411_attach,
.tuner_attach = pvr2_tda18271_8295_attach,
};
#endif
#define PVR2_FIRMWARE_75xxx "v4l-pvrusb2-73xxx-01.fw"
static const char *pvr2_fw1_names_75xxx[] = {
PVR2_FIRMWARE_75xxx,
};
static const struct pvr2_device_desc pvr2_device_750xx = {
.description = "WinTV HVR-1950 Model 750xx",
.shortname = "750xx",
.client_table.lst = pvr2_cli_73xxx,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_73xxx),
.fx2_firmware.lst = pvr2_fw1_names_75xxx,
.fx2_firmware.cnt = ARRAY_SIZE(pvr2_fw1_names_75xxx),
.flag_has_cx25840 = !0,
.flag_has_hauppauge_rom = !0,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.flag_fx2_16kb = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_HAUPPAUGE,
.digital_control_scheme = PVR2_DIGITAL_SCHEME_HAUPPAUGE,
.default_std_mask = V4L2_STD_NTSC_M,
.led_scheme = PVR2_LED_SCHEME_HAUPPAUGE,
.ir_scheme = PVR2_IR_SCHEME_ZILOG,
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
.dvb_props = &pvr2_750xx_dvb_props,
#endif
};
static const struct pvr2_device_desc pvr2_device_751xx = {
.description = "WinTV HVR-1950 Model 751xx",
.shortname = "751xx",
.client_table.lst = pvr2_cli_73xxx,
.client_table.cnt = ARRAY_SIZE(pvr2_cli_73xxx),
.fx2_firmware.lst = pvr2_fw1_names_75xxx,
.fx2_firmware.cnt = ARRAY_SIZE(pvr2_fw1_names_75xxx),
.flag_has_cx25840 = !0,
.flag_has_hauppauge_rom = !0,
.flag_has_analogtuner = !0,
.flag_has_composite = !0,
.flag_has_svideo = !0,
.flag_fx2_16kb = !0,
.signal_routing_scheme = PVR2_ROUTING_SCHEME_HAUPPAUGE,
.digital_control_scheme = PVR2_DIGITAL_SCHEME_HAUPPAUGE,
.default_std_mask = V4L2_STD_NTSC_M,
.led_scheme = PVR2_LED_SCHEME_HAUPPAUGE,
.ir_scheme = PVR2_IR_SCHEME_ZILOG,
#ifdef CONFIG_VIDEO_PVRUSB2_DVB
.dvb_props = &pvr2_751xx_dvb_props,
#endif
};
/*------------------------------------------------------------------------*/
struct usb_device_id pvr2_device_table[] = {
{ USB_DEVICE(0x2040, 0x2900),
.driver_info = (kernel_ulong_t)&pvr2_device_29xxx},
{ USB_DEVICE(0x2040, 0x2950), /* Logically identical to 2900 */
.driver_info = (kernel_ulong_t)&pvr2_device_29xxx},
{ USB_DEVICE(0x2040, 0x2400),
.driver_info = (kernel_ulong_t)&pvr2_device_24xxx},
{ USB_DEVICE(0x1164, 0x0622),
.driver_info = (kernel_ulong_t)&pvr2_device_gotview_2},
{ USB_DEVICE(0x1164, 0x0602),
.driver_info = (kernel_ulong_t)&pvr2_device_gotview_2d},
{ USB_DEVICE(0x11ba, 0x1003),
.driver_info = (kernel_ulong_t)&pvr2_device_onair_creator},
{ USB_DEVICE(0x11ba, 0x1001),
.driver_info = (kernel_ulong_t)&pvr2_device_onair_usb2},
{ USB_DEVICE(0x2040, 0x7300),
.driver_info = (kernel_ulong_t)&pvr2_device_73xxx},
{ USB_DEVICE(0x2040, 0x7500),
.driver_info = (kernel_ulong_t)&pvr2_device_750xx},
{ USB_DEVICE(0x2040, 0x7501),
.driver_info = (kernel_ulong_t)&pvr2_device_751xx},
{ USB_DEVICE(0x0ccd, 0x0039),
.driver_info = (kernel_ulong_t)&pvr2_device_av400},
{ }
};
MODULE_DEVICE_TABLE(usb, pvr2_device_table);
MODULE_FIRMWARE(PVR2_FIRMWARE_29xxx);
MODULE_FIRMWARE(PVR2_FIRMWARE_24xxx);
MODULE_FIRMWARE(PVR2_FIRMWARE_73xxx);
MODULE_FIRMWARE(PVR2_FIRMWARE_75xxx);
/*
Stuff for Emacs to see, in order to encourage consistent editing style:
*** Local Variables: ***
*** mode: c ***
*** fill-column: 75 ***
*** tab-width: 8 ***
*** c-basic-offset: 8 ***
*** End: ***
*/
| gpl-2.0 |
elkay/LK_DNA_2 | drivers/md/dm-delay.c | 3886 | 8648 | /*
* Copyright (C) 2005-2007 Red Hat GmbH
*
* A target that delays reads and/or writes and can send
* them to different devices.
*
* This file is released under the GPL.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/bio.h>
#include <linux/slab.h>
#include <linux/device-mapper.h>
#define DM_MSG_PREFIX "delay"
struct delay_c {
struct timer_list delay_timer;
struct mutex timer_lock;
struct work_struct flush_expired_bios;
struct list_head delayed_bios;
atomic_t may_delay;
mempool_t *delayed_pool;
struct dm_dev *dev_read;
sector_t start_read;
unsigned read_delay;
unsigned reads;
struct dm_dev *dev_write;
sector_t start_write;
unsigned write_delay;
unsigned writes;
};
struct dm_delay_info {
struct delay_c *context;
struct list_head list;
struct bio *bio;
unsigned long expires;
};
static DEFINE_MUTEX(delayed_bios_lock);
static struct workqueue_struct *kdelayd_wq;
static struct kmem_cache *delayed_cache;
static void handle_delayed_timer(unsigned long data)
{
struct delay_c *dc = (struct delay_c *)data;
queue_work(kdelayd_wq, &dc->flush_expired_bios);
}
static void queue_timeout(struct delay_c *dc, unsigned long expires)
{
mutex_lock(&dc->timer_lock);
if (!timer_pending(&dc->delay_timer) || expires < dc->delay_timer.expires)
mod_timer(&dc->delay_timer, expires);
mutex_unlock(&dc->timer_lock);
}
static void flush_bios(struct bio *bio)
{
struct bio *n;
while (bio) {
n = bio->bi_next;
bio->bi_next = NULL;
generic_make_request(bio);
bio = n;
}
}
static struct bio *flush_delayed_bios(struct delay_c *dc, int flush_all)
{
struct dm_delay_info *delayed, *next;
unsigned long next_expires = 0;
int start_timer = 0;
struct bio_list flush_bios = { };
mutex_lock(&delayed_bios_lock);
list_for_each_entry_safe(delayed, next, &dc->delayed_bios, list) {
if (flush_all || time_after_eq(jiffies, delayed->expires)) {
list_del(&delayed->list);
bio_list_add(&flush_bios, delayed->bio);
if ((bio_data_dir(delayed->bio) == WRITE))
delayed->context->writes--;
else
delayed->context->reads--;
mempool_free(delayed, dc->delayed_pool);
continue;
}
if (!start_timer) {
start_timer = 1;
next_expires = delayed->expires;
} else
next_expires = min(next_expires, delayed->expires);
}
mutex_unlock(&delayed_bios_lock);
if (start_timer)
queue_timeout(dc, next_expires);
return bio_list_get(&flush_bios);
}
static void flush_expired_bios(struct work_struct *work)
{
struct delay_c *dc;
dc = container_of(work, struct delay_c, flush_expired_bios);
flush_bios(flush_delayed_bios(dc, 0));
}
/*
* Mapping parameters:
* <device> <offset> <delay> [<write_device> <write_offset> <write_delay>]
*
* With separate write parameters, the first set is only used for reads.
* Delays are specified in milliseconds.
*/
static int delay_ctr(struct dm_target *ti, unsigned int argc, char **argv)
{
struct delay_c *dc;
unsigned long long tmpll;
char dummy;
if (argc != 3 && argc != 6) {
ti->error = "requires exactly 3 or 6 arguments";
return -EINVAL;
}
dc = kmalloc(sizeof(*dc), GFP_KERNEL);
if (!dc) {
ti->error = "Cannot allocate context";
return -ENOMEM;
}
dc->reads = dc->writes = 0;
if (sscanf(argv[1], "%llu%c", &tmpll, &dummy) != 1) {
ti->error = "Invalid device sector";
goto bad;
}
dc->start_read = tmpll;
if (sscanf(argv[2], "%u%c", &dc->read_delay, &dummy) != 1) {
ti->error = "Invalid delay";
goto bad;
}
if (dm_get_device(ti, argv[0], dm_table_get_mode(ti->table),
&dc->dev_read)) {
ti->error = "Device lookup failed";
goto bad;
}
dc->dev_write = NULL;
if (argc == 3)
goto out;
if (sscanf(argv[4], "%llu%c", &tmpll, &dummy) != 1) {
ti->error = "Invalid write device sector";
goto bad_dev_read;
}
dc->start_write = tmpll;
if (sscanf(argv[5], "%u%c", &dc->write_delay, &dummy) != 1) {
ti->error = "Invalid write delay";
goto bad_dev_read;
}
if (dm_get_device(ti, argv[3], dm_table_get_mode(ti->table),
&dc->dev_write)) {
ti->error = "Write device lookup failed";
goto bad_dev_read;
}
out:
dc->delayed_pool = mempool_create_slab_pool(128, delayed_cache);
if (!dc->delayed_pool) {
DMERR("Couldn't create delayed bio pool.");
goto bad_dev_write;
}
setup_timer(&dc->delay_timer, handle_delayed_timer, (unsigned long)dc);
INIT_WORK(&dc->flush_expired_bios, flush_expired_bios);
INIT_LIST_HEAD(&dc->delayed_bios);
mutex_init(&dc->timer_lock);
atomic_set(&dc->may_delay, 1);
ti->num_flush_requests = 1;
ti->num_discard_requests = 1;
ti->private = dc;
return 0;
bad_dev_write:
if (dc->dev_write)
dm_put_device(ti, dc->dev_write);
bad_dev_read:
dm_put_device(ti, dc->dev_read);
bad:
kfree(dc);
return -EINVAL;
}
static void delay_dtr(struct dm_target *ti)
{
struct delay_c *dc = ti->private;
flush_workqueue(kdelayd_wq);
dm_put_device(ti, dc->dev_read);
if (dc->dev_write)
dm_put_device(ti, dc->dev_write);
mempool_destroy(dc->delayed_pool);
kfree(dc);
}
static int delay_bio(struct delay_c *dc, int delay, struct bio *bio)
{
struct dm_delay_info *delayed;
unsigned long expires = 0;
if (!delay || !atomic_read(&dc->may_delay))
return 1;
delayed = mempool_alloc(dc->delayed_pool, GFP_NOIO);
delayed->context = dc;
delayed->bio = bio;
delayed->expires = expires = jiffies + (delay * HZ / 1000);
mutex_lock(&delayed_bios_lock);
if (bio_data_dir(bio) == WRITE)
dc->writes++;
else
dc->reads++;
list_add_tail(&delayed->list, &dc->delayed_bios);
mutex_unlock(&delayed_bios_lock);
queue_timeout(dc, expires);
return 0;
}
static void delay_presuspend(struct dm_target *ti)
{
struct delay_c *dc = ti->private;
atomic_set(&dc->may_delay, 0);
del_timer_sync(&dc->delay_timer);
flush_bios(flush_delayed_bios(dc, 1));
}
static void delay_resume(struct dm_target *ti)
{
struct delay_c *dc = ti->private;
atomic_set(&dc->may_delay, 1);
}
static int delay_map(struct dm_target *ti, struct bio *bio,
union map_info *map_context)
{
struct delay_c *dc = ti->private;
if ((bio_data_dir(bio) == WRITE) && (dc->dev_write)) {
bio->bi_bdev = dc->dev_write->bdev;
if (bio_sectors(bio))
bio->bi_sector = dc->start_write +
dm_target_offset(ti, bio->bi_sector);
return delay_bio(dc, dc->write_delay, bio);
}
bio->bi_bdev = dc->dev_read->bdev;
bio->bi_sector = dc->start_read + dm_target_offset(ti, bio->bi_sector);
return delay_bio(dc, dc->read_delay, bio);
}
static int delay_status(struct dm_target *ti, status_type_t type,
char *result, unsigned maxlen)
{
struct delay_c *dc = ti->private;
int sz = 0;
switch (type) {
case STATUSTYPE_INFO:
DMEMIT("%u %u", dc->reads, dc->writes);
break;
case STATUSTYPE_TABLE:
DMEMIT("%s %llu %u", dc->dev_read->name,
(unsigned long long) dc->start_read,
dc->read_delay);
if (dc->dev_write)
DMEMIT(" %s %llu %u", dc->dev_write->name,
(unsigned long long) dc->start_write,
dc->write_delay);
break;
}
return 0;
}
static int delay_iterate_devices(struct dm_target *ti,
iterate_devices_callout_fn fn, void *data)
{
struct delay_c *dc = ti->private;
int ret = 0;
ret = fn(ti, dc->dev_read, dc->start_read, ti->len, data);
if (ret)
goto out;
if (dc->dev_write)
ret = fn(ti, dc->dev_write, dc->start_write, ti->len, data);
out:
return ret;
}
static struct target_type delay_target = {
.name = "delay",
.version = {1, 1, 0},
.module = THIS_MODULE,
.ctr = delay_ctr,
.dtr = delay_dtr,
.map = delay_map,
.presuspend = delay_presuspend,
.resume = delay_resume,
.status = delay_status,
.iterate_devices = delay_iterate_devices,
};
static int __init dm_delay_init(void)
{
int r = -ENOMEM;
kdelayd_wq = alloc_workqueue("kdelayd", WQ_MEM_RECLAIM, 0);
if (!kdelayd_wq) {
DMERR("Couldn't start kdelayd");
goto bad_queue;
}
delayed_cache = KMEM_CACHE(dm_delay_info, 0);
if (!delayed_cache) {
DMERR("Couldn't create delayed bio cache.");
goto bad_memcache;
}
r = dm_register_target(&delay_target);
if (r < 0) {
DMERR("register failed %d", r);
goto bad_register;
}
return 0;
bad_register:
kmem_cache_destroy(delayed_cache);
bad_memcache:
destroy_workqueue(kdelayd_wq);
bad_queue:
return r;
}
static void __exit dm_delay_exit(void)
{
dm_unregister_target(&delay_target);
kmem_cache_destroy(delayed_cache);
destroy_workqueue(kdelayd_wq);
}
/* Module hooks */
module_init(dm_delay_init);
module_exit(dm_delay_exit);
MODULE_DESCRIPTION(DM_NAME " delay target");
MODULE_AUTHOR("Heinz Mauelshagen <mauelshagen@redhat.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
jxxhwy/NewWorld_f160_JB_kernel | drivers/pcmcia/yenta_socket.c | 4398 | 40340 | /*
* Regular cardbus driver ("yenta_socket")
*
* (C) Copyright 1999, 2000 Linus Torvalds
*
* Changelog:
* Aug 2002: Manfred Spraul <manfred@colorfullife.com>
* Dynamically adjust the size of the bridge resource
*
* May 2003: Dominik Brodowski <linux@brodo.de>
* Merge pci_socket.c and yenta.c into one file
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/workqueue.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <pcmcia/ss.h>
#include "yenta_socket.h"
#include "i82365.h"
static bool disable_clkrun;
module_param(disable_clkrun, bool, 0444);
MODULE_PARM_DESC(disable_clkrun, "If PC card doesn't function properly, please try this option");
static bool isa_probe = 1;
module_param(isa_probe, bool, 0444);
MODULE_PARM_DESC(isa_probe, "If set ISA interrupts are probed (default). Set to N to disable probing");
static bool pwr_irqs_off;
module_param(pwr_irqs_off, bool, 0644);
MODULE_PARM_DESC(pwr_irqs_off, "Force IRQs off during power-on of slot. Use only when seeing IRQ storms!");
static char o2_speedup[] = "default";
module_param_string(o2_speedup, o2_speedup, sizeof(o2_speedup), 0444);
MODULE_PARM_DESC(o2_speedup, "Use prefetch/burst for O2-bridges: 'on', 'off' "
"or 'default' (uses recommended behaviour for the detected bridge)");
/*
* Only probe "regular" interrupts, don't
* touch dangerous spots like the mouse irq,
* because there are mice that apparently
* get really confused if they get fondled
* too intimately.
*
* Default to 11, 10, 9, 7, 6, 5, 4, 3.
*/
static u32 isa_interrupts = 0x0ef8;
#define debug(x, s, args...) dev_dbg(&s->dev->dev, x, ##args)
/* Don't ask.. */
#define to_cycles(ns) ((ns)/120)
#define to_ns(cycles) ((cycles)*120)
/*
* yenta PCI irq probing.
* currently only used in the TI/EnE initialization code
*/
#ifdef CONFIG_YENTA_TI
static int yenta_probe_cb_irq(struct yenta_socket *socket);
static unsigned int yenta_probe_irq(struct yenta_socket *socket,
u32 isa_irq_mask);
#endif
static unsigned int override_bios;
module_param(override_bios, uint, 0000);
MODULE_PARM_DESC(override_bios, "yenta ignore bios resource allocation");
/*
* Generate easy-to-use ways of reading a cardbus sockets
* regular memory space ("cb_xxx"), configuration space
* ("config_xxx") and compatibility space ("exca_xxxx")
*/
static inline u32 cb_readl(struct yenta_socket *socket, unsigned reg)
{
u32 val = readl(socket->base + reg);
debug("%04x %08x\n", socket, reg, val);
return val;
}
static inline void cb_writel(struct yenta_socket *socket, unsigned reg, u32 val)
{
debug("%04x %08x\n", socket, reg, val);
writel(val, socket->base + reg);
readl(socket->base + reg); /* avoid problems with PCI write posting */
}
static inline u8 config_readb(struct yenta_socket *socket, unsigned offset)
{
u8 val;
pci_read_config_byte(socket->dev, offset, &val);
debug("%04x %02x\n", socket, offset, val);
return val;
}
static inline u16 config_readw(struct yenta_socket *socket, unsigned offset)
{
u16 val;
pci_read_config_word(socket->dev, offset, &val);
debug("%04x %04x\n", socket, offset, val);
return val;
}
static inline u32 config_readl(struct yenta_socket *socket, unsigned offset)
{
u32 val;
pci_read_config_dword(socket->dev, offset, &val);
debug("%04x %08x\n", socket, offset, val);
return val;
}
static inline void config_writeb(struct yenta_socket *socket, unsigned offset, u8 val)
{
debug("%04x %02x\n", socket, offset, val);
pci_write_config_byte(socket->dev, offset, val);
}
static inline void config_writew(struct yenta_socket *socket, unsigned offset, u16 val)
{
debug("%04x %04x\n", socket, offset, val);
pci_write_config_word(socket->dev, offset, val);
}
static inline void config_writel(struct yenta_socket *socket, unsigned offset, u32 val)
{
debug("%04x %08x\n", socket, offset, val);
pci_write_config_dword(socket->dev, offset, val);
}
static inline u8 exca_readb(struct yenta_socket *socket, unsigned reg)
{
u8 val = readb(socket->base + 0x800 + reg);
debug("%04x %02x\n", socket, reg, val);
return val;
}
static inline u8 exca_readw(struct yenta_socket *socket, unsigned reg)
{
u16 val;
val = readb(socket->base + 0x800 + reg);
val |= readb(socket->base + 0x800 + reg + 1) << 8;
debug("%04x %04x\n", socket, reg, val);
return val;
}
static inline void exca_writeb(struct yenta_socket *socket, unsigned reg, u8 val)
{
debug("%04x %02x\n", socket, reg, val);
writeb(val, socket->base + 0x800 + reg);
readb(socket->base + 0x800 + reg); /* PCI write posting... */
}
static void exca_writew(struct yenta_socket *socket, unsigned reg, u16 val)
{
debug("%04x %04x\n", socket, reg, val);
writeb(val, socket->base + 0x800 + reg);
writeb(val >> 8, socket->base + 0x800 + reg + 1);
/* PCI write posting... */
readb(socket->base + 0x800 + reg);
readb(socket->base + 0x800 + reg + 1);
}
static ssize_t show_yenta_registers(struct device *yentadev, struct device_attribute *attr, char *buf)
{
struct pci_dev *dev = to_pci_dev(yentadev);
struct yenta_socket *socket = pci_get_drvdata(dev);
int offset = 0, i;
offset = snprintf(buf, PAGE_SIZE, "CB registers:");
for (i = 0; i < 0x24; i += 4) {
unsigned val;
if (!(i & 15))
offset += snprintf(buf + offset, PAGE_SIZE - offset, "\n%02x:", i);
val = cb_readl(socket, i);
offset += snprintf(buf + offset, PAGE_SIZE - offset, " %08x", val);
}
offset += snprintf(buf + offset, PAGE_SIZE - offset, "\n\nExCA registers:");
for (i = 0; i < 0x45; i++) {
unsigned char val;
if (!(i & 7)) {
if (i & 8) {
memcpy(buf + offset, " -", 2);
offset += 2;
} else
offset += snprintf(buf + offset, PAGE_SIZE - offset, "\n%02x:", i);
}
val = exca_readb(socket, i);
offset += snprintf(buf + offset, PAGE_SIZE - offset, " %02x", val);
}
buf[offset++] = '\n';
return offset;
}
static DEVICE_ATTR(yenta_registers, S_IRUSR, show_yenta_registers, NULL);
/*
* Ugh, mixed-mode cardbus and 16-bit pccard state: things depend
* on what kind of card is inserted..
*/
static int yenta_get_status(struct pcmcia_socket *sock, unsigned int *value)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
unsigned int val;
u32 state = cb_readl(socket, CB_SOCKET_STATE);
val = (state & CB_3VCARD) ? SS_3VCARD : 0;
val |= (state & CB_XVCARD) ? SS_XVCARD : 0;
val |= (state & (CB_5VCARD | CB_3VCARD | CB_XVCARD | CB_YVCARD)) ? 0 : SS_PENDING;
val |= (state & (CB_CDETECT1 | CB_CDETECT2)) ? SS_PENDING : 0;
if (state & CB_CBCARD) {
val |= SS_CARDBUS;
val |= (state & CB_CARDSTS) ? SS_STSCHG : 0;
val |= (state & (CB_CDETECT1 | CB_CDETECT2)) ? 0 : SS_DETECT;
val |= (state & CB_PWRCYCLE) ? SS_POWERON | SS_READY : 0;
} else if (state & CB_16BITCARD) {
u8 status = exca_readb(socket, I365_STATUS);
val |= ((status & I365_CS_DETECT) == I365_CS_DETECT) ? SS_DETECT : 0;
if (exca_readb(socket, I365_INTCTL) & I365_PC_IOCARD) {
val |= (status & I365_CS_STSCHG) ? 0 : SS_STSCHG;
} else {
val |= (status & I365_CS_BVD1) ? 0 : SS_BATDEAD;
val |= (status & I365_CS_BVD2) ? 0 : SS_BATWARN;
}
val |= (status & I365_CS_WRPROT) ? SS_WRPROT : 0;
val |= (status & I365_CS_READY) ? SS_READY : 0;
val |= (status & I365_CS_POWERON) ? SS_POWERON : 0;
}
*value = val;
return 0;
}
static void yenta_set_power(struct yenta_socket *socket, socket_state_t *state)
{
/* some birdges require to use the ExCA registers to power 16bit cards */
if (!(cb_readl(socket, CB_SOCKET_STATE) & CB_CBCARD) &&
(socket->flags & YENTA_16BIT_POWER_EXCA)) {
u8 reg, old;
reg = old = exca_readb(socket, I365_POWER);
reg &= ~(I365_VCC_MASK | I365_VPP1_MASK | I365_VPP2_MASK);
/* i82365SL-DF style */
if (socket->flags & YENTA_16BIT_POWER_DF) {
switch (state->Vcc) {
case 33:
reg |= I365_VCC_3V;
break;
case 50:
reg |= I365_VCC_5V;
break;
default:
reg = 0;
break;
}
switch (state->Vpp) {
case 33:
case 50:
reg |= I365_VPP1_5V;
break;
case 120:
reg |= I365_VPP1_12V;
break;
}
} else {
/* i82365SL-B style */
switch (state->Vcc) {
case 50:
reg |= I365_VCC_5V;
break;
default:
reg = 0;
break;
}
switch (state->Vpp) {
case 50:
reg |= I365_VPP1_5V | I365_VPP2_5V;
break;
case 120:
reg |= I365_VPP1_12V | I365_VPP2_12V;
break;
}
}
if (reg != old)
exca_writeb(socket, I365_POWER, reg);
} else {
u32 reg = 0; /* CB_SC_STPCLK? */
switch (state->Vcc) {
case 33:
reg = CB_SC_VCC_3V;
break;
case 50:
reg = CB_SC_VCC_5V;
break;
default:
reg = 0;
break;
}
switch (state->Vpp) {
case 33:
reg |= CB_SC_VPP_3V;
break;
case 50:
reg |= CB_SC_VPP_5V;
break;
case 120:
reg |= CB_SC_VPP_12V;
break;
}
if (reg != cb_readl(socket, CB_SOCKET_CONTROL))
cb_writel(socket, CB_SOCKET_CONTROL, reg);
}
}
static int yenta_set_socket(struct pcmcia_socket *sock, socket_state_t *state)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
u16 bridge;
/* if powering down: do it immediately */
if (state->Vcc == 0)
yenta_set_power(socket, state);
socket->io_irq = state->io_irq;
bridge = config_readw(socket, CB_BRIDGE_CONTROL) & ~(CB_BRIDGE_CRST | CB_BRIDGE_INTR);
if (cb_readl(socket, CB_SOCKET_STATE) & CB_CBCARD) {
u8 intr;
bridge |= (state->flags & SS_RESET) ? CB_BRIDGE_CRST : 0;
/* ISA interrupt control? */
intr = exca_readb(socket, I365_INTCTL);
intr = (intr & ~0xf);
if (!socket->dev->irq) {
intr |= socket->cb_irq ? socket->cb_irq : state->io_irq;
bridge |= CB_BRIDGE_INTR;
}
exca_writeb(socket, I365_INTCTL, intr);
} else {
u8 reg;
reg = exca_readb(socket, I365_INTCTL) & (I365_RING_ENA | I365_INTR_ENA);
reg |= (state->flags & SS_RESET) ? 0 : I365_PC_RESET;
reg |= (state->flags & SS_IOCARD) ? I365_PC_IOCARD : 0;
if (state->io_irq != socket->dev->irq) {
reg |= state->io_irq;
bridge |= CB_BRIDGE_INTR;
}
exca_writeb(socket, I365_INTCTL, reg);
reg = exca_readb(socket, I365_POWER) & (I365_VCC_MASK|I365_VPP1_MASK);
reg |= I365_PWR_NORESET;
if (state->flags & SS_PWR_AUTO)
reg |= I365_PWR_AUTO;
if (state->flags & SS_OUTPUT_ENA)
reg |= I365_PWR_OUT;
if (exca_readb(socket, I365_POWER) != reg)
exca_writeb(socket, I365_POWER, reg);
/* CSC interrupt: no ISA irq for CSC */
reg = exca_readb(socket, I365_CSCINT);
reg &= I365_CSC_IRQ_MASK;
reg |= I365_CSC_DETECT;
if (state->flags & SS_IOCARD) {
if (state->csc_mask & SS_STSCHG)
reg |= I365_CSC_STSCHG;
} else {
if (state->csc_mask & SS_BATDEAD)
reg |= I365_CSC_BVD1;
if (state->csc_mask & SS_BATWARN)
reg |= I365_CSC_BVD2;
if (state->csc_mask & SS_READY)
reg |= I365_CSC_READY;
}
exca_writeb(socket, I365_CSCINT, reg);
exca_readb(socket, I365_CSC);
if (sock->zoom_video)
sock->zoom_video(sock, state->flags & SS_ZVCARD);
}
config_writew(socket, CB_BRIDGE_CONTROL, bridge);
/* Socket event mask: get card insert/remove events.. */
cb_writel(socket, CB_SOCKET_EVENT, -1);
cb_writel(socket, CB_SOCKET_MASK, CB_CDMASK);
/* if powering up: do it as the last step when the socket is configured */
if (state->Vcc != 0)
yenta_set_power(socket, state);
return 0;
}
static int yenta_set_io_map(struct pcmcia_socket *sock, struct pccard_io_map *io)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
int map;
unsigned char ioctl, addr, enable;
map = io->map;
if (map > 1)
return -EINVAL;
enable = I365_ENA_IO(map);
addr = exca_readb(socket, I365_ADDRWIN);
/* Disable the window before changing it.. */
if (addr & enable) {
addr &= ~enable;
exca_writeb(socket, I365_ADDRWIN, addr);
}
exca_writew(socket, I365_IO(map)+I365_W_START, io->start);
exca_writew(socket, I365_IO(map)+I365_W_STOP, io->stop);
ioctl = exca_readb(socket, I365_IOCTL) & ~I365_IOCTL_MASK(map);
if (io->flags & MAP_0WS)
ioctl |= I365_IOCTL_0WS(map);
if (io->flags & MAP_16BIT)
ioctl |= I365_IOCTL_16BIT(map);
if (io->flags & MAP_AUTOSZ)
ioctl |= I365_IOCTL_IOCS16(map);
exca_writeb(socket, I365_IOCTL, ioctl);
if (io->flags & MAP_ACTIVE)
exca_writeb(socket, I365_ADDRWIN, addr | enable);
return 0;
}
static int yenta_set_mem_map(struct pcmcia_socket *sock, struct pccard_mem_map *mem)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
struct pci_bus_region region;
int map;
unsigned char addr, enable;
unsigned int start, stop, card_start;
unsigned short word;
pcibios_resource_to_bus(socket->dev, ®ion, mem->res);
map = mem->map;
start = region.start;
stop = region.end;
card_start = mem->card_start;
if (map > 4 || start > stop || ((start ^ stop) >> 24) ||
(card_start >> 26) || mem->speed > 1000)
return -EINVAL;
enable = I365_ENA_MEM(map);
addr = exca_readb(socket, I365_ADDRWIN);
if (addr & enable) {
addr &= ~enable;
exca_writeb(socket, I365_ADDRWIN, addr);
}
exca_writeb(socket, CB_MEM_PAGE(map), start >> 24);
word = (start >> 12) & 0x0fff;
if (mem->flags & MAP_16BIT)
word |= I365_MEM_16BIT;
if (mem->flags & MAP_0WS)
word |= I365_MEM_0WS;
exca_writew(socket, I365_MEM(map) + I365_W_START, word);
word = (stop >> 12) & 0x0fff;
switch (to_cycles(mem->speed)) {
case 0:
break;
case 1:
word |= I365_MEM_WS0;
break;
case 2:
word |= I365_MEM_WS1;
break;
default:
word |= I365_MEM_WS1 | I365_MEM_WS0;
break;
}
exca_writew(socket, I365_MEM(map) + I365_W_STOP, word);
word = ((card_start - start) >> 12) & 0x3fff;
if (mem->flags & MAP_WRPROT)
word |= I365_MEM_WRPROT;
if (mem->flags & MAP_ATTRIB)
word |= I365_MEM_REG;
exca_writew(socket, I365_MEM(map) + I365_W_OFF, word);
if (mem->flags & MAP_ACTIVE)
exca_writeb(socket, I365_ADDRWIN, addr | enable);
return 0;
}
static irqreturn_t yenta_interrupt(int irq, void *dev_id)
{
unsigned int events;
struct yenta_socket *socket = (struct yenta_socket *) dev_id;
u8 csc;
u32 cb_event;
/* Clear interrupt status for the event */
cb_event = cb_readl(socket, CB_SOCKET_EVENT);
cb_writel(socket, CB_SOCKET_EVENT, cb_event);
csc = exca_readb(socket, I365_CSC);
if (!(cb_event || csc))
return IRQ_NONE;
events = (cb_event & (CB_CD1EVENT | CB_CD2EVENT)) ? SS_DETECT : 0 ;
events |= (csc & I365_CSC_DETECT) ? SS_DETECT : 0;
if (exca_readb(socket, I365_INTCTL) & I365_PC_IOCARD) {
events |= (csc & I365_CSC_STSCHG) ? SS_STSCHG : 0;
} else {
events |= (csc & I365_CSC_BVD1) ? SS_BATDEAD : 0;
events |= (csc & I365_CSC_BVD2) ? SS_BATWARN : 0;
events |= (csc & I365_CSC_READY) ? SS_READY : 0;
}
if (events)
pcmcia_parse_events(&socket->socket, events);
return IRQ_HANDLED;
}
static void yenta_interrupt_wrapper(unsigned long data)
{
struct yenta_socket *socket = (struct yenta_socket *) data;
yenta_interrupt(0, (void *)socket);
socket->poll_timer.expires = jiffies + HZ;
add_timer(&socket->poll_timer);
}
static void yenta_clear_maps(struct yenta_socket *socket)
{
int i;
struct resource res = { .start = 0, .end = 0x0fff };
pccard_io_map io = { 0, 0, 0, 0, 1 };
pccard_mem_map mem = { .res = &res, };
yenta_set_socket(&socket->socket, &dead_socket);
for (i = 0; i < 2; i++) {
io.map = i;
yenta_set_io_map(&socket->socket, &io);
}
for (i = 0; i < 5; i++) {
mem.map = i;
yenta_set_mem_map(&socket->socket, &mem);
}
}
/* redoes voltage interrogation if required */
static void yenta_interrogate(struct yenta_socket *socket)
{
u32 state;
state = cb_readl(socket, CB_SOCKET_STATE);
if (!(state & (CB_5VCARD | CB_3VCARD | CB_XVCARD | CB_YVCARD)) ||
(state & (CB_CDETECT1 | CB_CDETECT2 | CB_NOTACARD | CB_BADVCCREQ)) ||
((state & (CB_16BITCARD | CB_CBCARD)) == (CB_16BITCARD | CB_CBCARD)))
cb_writel(socket, CB_SOCKET_FORCE, CB_CVSTEST);
}
/* Called at resume and initialization events */
static int yenta_sock_init(struct pcmcia_socket *sock)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
exca_writeb(socket, I365_GBLCTL, 0x00);
exca_writeb(socket, I365_GENCTL, 0x00);
/* Redo card voltage interrogation */
yenta_interrogate(socket);
yenta_clear_maps(socket);
if (socket->type && socket->type->sock_init)
socket->type->sock_init(socket);
/* Re-enable CSC interrupts */
cb_writel(socket, CB_SOCKET_MASK, CB_CDMASK);
return 0;
}
static int yenta_sock_suspend(struct pcmcia_socket *sock)
{
struct yenta_socket *socket = container_of(sock, struct yenta_socket, socket);
/* Disable CSC interrupts */
cb_writel(socket, CB_SOCKET_MASK, 0x0);
return 0;
}
/*
* Use an adaptive allocation for the memory resource,
* sometimes the memory behind pci bridges is limited:
* 1/8 of the size of the io window of the parent.
* max 4 MB, min 16 kB. We try very hard to not get below
* the "ACC" values, though.
*/
#define BRIDGE_MEM_MAX (4*1024*1024)
#define BRIDGE_MEM_ACC (128*1024)
#define BRIDGE_MEM_MIN (16*1024)
#define BRIDGE_IO_MAX 512
#define BRIDGE_IO_ACC 256
#define BRIDGE_IO_MIN 32
#ifndef PCIBIOS_MIN_CARDBUS_IO
#define PCIBIOS_MIN_CARDBUS_IO PCIBIOS_MIN_IO
#endif
static int yenta_search_one_res(struct resource *root, struct resource *res,
u32 min)
{
u32 align, size, start, end;
if (res->flags & IORESOURCE_IO) {
align = 1024;
size = BRIDGE_IO_MAX;
start = PCIBIOS_MIN_CARDBUS_IO;
end = ~0U;
} else {
unsigned long avail = root->end - root->start;
int i;
size = BRIDGE_MEM_MAX;
if (size > avail/8) {
size = (avail+1)/8;
/* round size down to next power of 2 */
i = 0;
while ((size /= 2) != 0)
i++;
size = 1 << i;
}
if (size < min)
size = min;
align = size;
start = PCIBIOS_MIN_MEM;
end = ~0U;
}
do {
if (allocate_resource(root, res, size, start, end, align,
NULL, NULL) == 0) {
return 1;
}
size = size/2;
align = size;
} while (size >= min);
return 0;
}
static int yenta_search_res(struct yenta_socket *socket, struct resource *res,
u32 min)
{
struct resource *root;
int i;
pci_bus_for_each_resource(socket->dev->bus, root, i) {
if (!root)
continue;
if ((res->flags ^ root->flags) &
(IORESOURCE_IO | IORESOURCE_MEM | IORESOURCE_PREFETCH))
continue; /* Wrong type */
if (yenta_search_one_res(root, res, min))
return 1;
}
return 0;
}
static int yenta_allocate_res(struct yenta_socket *socket, int nr, unsigned type, int addr_start, int addr_end)
{
struct pci_dev *dev = socket->dev;
struct resource *res;
struct pci_bus_region region;
unsigned mask;
res = dev->resource + PCI_BRIDGE_RESOURCES + nr;
/* Already allocated? */
if (res->parent)
return 0;
/* The granularity of the memory limit is 4kB, on IO it's 4 bytes */
mask = ~0xfff;
if (type & IORESOURCE_IO)
mask = ~3;
res->name = dev->subordinate->name;
res->flags = type;
region.start = config_readl(socket, addr_start) & mask;
region.end = config_readl(socket, addr_end) | ~mask;
if (region.start && region.end > region.start && !override_bios) {
pcibios_bus_to_resource(dev, res, ®ion);
if (pci_claim_resource(dev, PCI_BRIDGE_RESOURCES + nr) == 0)
return 0;
dev_printk(KERN_INFO, &dev->dev,
"Preassigned resource %d busy or not available, "
"reconfiguring...\n",
nr);
}
if (type & IORESOURCE_IO) {
if ((yenta_search_res(socket, res, BRIDGE_IO_MAX)) ||
(yenta_search_res(socket, res, BRIDGE_IO_ACC)) ||
(yenta_search_res(socket, res, BRIDGE_IO_MIN)))
return 1;
} else {
if (type & IORESOURCE_PREFETCH) {
if ((yenta_search_res(socket, res, BRIDGE_MEM_MAX)) ||
(yenta_search_res(socket, res, BRIDGE_MEM_ACC)) ||
(yenta_search_res(socket, res, BRIDGE_MEM_MIN)))
return 1;
/* Approximating prefetchable by non-prefetchable */
res->flags = IORESOURCE_MEM;
}
if ((yenta_search_res(socket, res, BRIDGE_MEM_MAX)) ||
(yenta_search_res(socket, res, BRIDGE_MEM_ACC)) ||
(yenta_search_res(socket, res, BRIDGE_MEM_MIN)))
return 1;
}
dev_printk(KERN_INFO, &dev->dev,
"no resource of type %x available, trying to continue...\n",
type);
res->start = res->end = res->flags = 0;
return 0;
}
/*
* Allocate the bridge mappings for the device..
*/
static void yenta_allocate_resources(struct yenta_socket *socket)
{
int program = 0;
program += yenta_allocate_res(socket, 0, IORESOURCE_IO,
PCI_CB_IO_BASE_0, PCI_CB_IO_LIMIT_0);
program += yenta_allocate_res(socket, 1, IORESOURCE_IO,
PCI_CB_IO_BASE_1, PCI_CB_IO_LIMIT_1);
program += yenta_allocate_res(socket, 2, IORESOURCE_MEM|IORESOURCE_PREFETCH,
PCI_CB_MEMORY_BASE_0, PCI_CB_MEMORY_LIMIT_0);
program += yenta_allocate_res(socket, 3, IORESOURCE_MEM,
PCI_CB_MEMORY_BASE_1, PCI_CB_MEMORY_LIMIT_1);
if (program)
pci_setup_cardbus(socket->dev->subordinate);
}
/*
* Free the bridge mappings for the device..
*/
static void yenta_free_resources(struct yenta_socket *socket)
{
int i;
for (i = 0; i < 4; i++) {
struct resource *res;
res = socket->dev->resource + PCI_BRIDGE_RESOURCES + i;
if (res->start != 0 && res->end != 0)
release_resource(res);
res->start = res->end = res->flags = 0;
}
}
/*
* Close it down - release our resources and go home..
*/
static void __devexit yenta_close(struct pci_dev *dev)
{
struct yenta_socket *sock = pci_get_drvdata(dev);
/* Remove the register attributes */
device_remove_file(&dev->dev, &dev_attr_yenta_registers);
/* we don't want a dying socket registered */
pcmcia_unregister_socket(&sock->socket);
/* Disable all events so we don't die in an IRQ storm */
cb_writel(sock, CB_SOCKET_MASK, 0x0);
exca_writeb(sock, I365_CSCINT, 0);
if (sock->cb_irq)
free_irq(sock->cb_irq, sock);
else
del_timer_sync(&sock->poll_timer);
if (sock->base)
iounmap(sock->base);
yenta_free_resources(sock);
pci_release_regions(dev);
pci_disable_device(dev);
pci_set_drvdata(dev, NULL);
}
static struct pccard_operations yenta_socket_operations = {
.init = yenta_sock_init,
.suspend = yenta_sock_suspend,
.get_status = yenta_get_status,
.set_socket = yenta_set_socket,
.set_io_map = yenta_set_io_map,
.set_mem_map = yenta_set_mem_map,
};
#ifdef CONFIG_YENTA_TI
#include "ti113x.h"
#endif
#ifdef CONFIG_YENTA_RICOH
#include "ricoh.h"
#endif
#ifdef CONFIG_YENTA_TOSHIBA
#include "topic.h"
#endif
#ifdef CONFIG_YENTA_O2
#include "o2micro.h"
#endif
enum {
CARDBUS_TYPE_DEFAULT = -1,
CARDBUS_TYPE_TI,
CARDBUS_TYPE_TI113X,
CARDBUS_TYPE_TI12XX,
CARDBUS_TYPE_TI1250,
CARDBUS_TYPE_RICOH,
CARDBUS_TYPE_TOPIC95,
CARDBUS_TYPE_TOPIC97,
CARDBUS_TYPE_O2MICRO,
CARDBUS_TYPE_ENE,
};
/*
* Different cardbus controllers have slightly different
* initialization sequences etc details. List them here..
*/
static struct cardbus_type cardbus_type[] = {
#ifdef CONFIG_YENTA_TI
[CARDBUS_TYPE_TI] = {
.override = ti_override,
.save_state = ti_save_state,
.restore_state = ti_restore_state,
.sock_init = ti_init,
},
[CARDBUS_TYPE_TI113X] = {
.override = ti113x_override,
.save_state = ti_save_state,
.restore_state = ti_restore_state,
.sock_init = ti_init,
},
[CARDBUS_TYPE_TI12XX] = {
.override = ti12xx_override,
.save_state = ti_save_state,
.restore_state = ti_restore_state,
.sock_init = ti_init,
},
[CARDBUS_TYPE_TI1250] = {
.override = ti1250_override,
.save_state = ti_save_state,
.restore_state = ti_restore_state,
.sock_init = ti_init,
},
[CARDBUS_TYPE_ENE] = {
.override = ene_override,
.save_state = ti_save_state,
.restore_state = ti_restore_state,
.sock_init = ti_init,
},
#endif
#ifdef CONFIG_YENTA_RICOH
[CARDBUS_TYPE_RICOH] = {
.override = ricoh_override,
.save_state = ricoh_save_state,
.restore_state = ricoh_restore_state,
},
#endif
#ifdef CONFIG_YENTA_TOSHIBA
[CARDBUS_TYPE_TOPIC95] = {
.override = topic95_override,
},
[CARDBUS_TYPE_TOPIC97] = {
.override = topic97_override,
},
#endif
#ifdef CONFIG_YENTA_O2
[CARDBUS_TYPE_O2MICRO] = {
.override = o2micro_override,
.restore_state = o2micro_restore_state,
},
#endif
};
static unsigned int yenta_probe_irq(struct yenta_socket *socket, u32 isa_irq_mask)
{
int i;
unsigned long val;
u32 mask;
u8 reg;
/*
* Probe for usable interrupts using the force
* register to generate bogus card status events.
*/
cb_writel(socket, CB_SOCKET_EVENT, -1);
cb_writel(socket, CB_SOCKET_MASK, CB_CSTSMASK);
reg = exca_readb(socket, I365_CSCINT);
exca_writeb(socket, I365_CSCINT, 0);
val = probe_irq_on() & isa_irq_mask;
for (i = 1; i < 16; i++) {
if (!((val >> i) & 1))
continue;
exca_writeb(socket, I365_CSCINT, I365_CSC_STSCHG | (i << 4));
cb_writel(socket, CB_SOCKET_FORCE, CB_FCARDSTS);
udelay(100);
cb_writel(socket, CB_SOCKET_EVENT, -1);
}
cb_writel(socket, CB_SOCKET_MASK, 0);
exca_writeb(socket, I365_CSCINT, reg);
mask = probe_irq_mask(val) & 0xffff;
return mask;
}
/*
* yenta PCI irq probing.
* currently only used in the TI/EnE initialization code
*/
#ifdef CONFIG_YENTA_TI
/* interrupt handler, only used during probing */
static irqreturn_t yenta_probe_handler(int irq, void *dev_id)
{
struct yenta_socket *socket = (struct yenta_socket *) dev_id;
u8 csc;
u32 cb_event;
/* Clear interrupt status for the event */
cb_event = cb_readl(socket, CB_SOCKET_EVENT);
cb_writel(socket, CB_SOCKET_EVENT, -1);
csc = exca_readb(socket, I365_CSC);
if (cb_event || csc) {
socket->probe_status = 1;
return IRQ_HANDLED;
}
return IRQ_NONE;
}
/* probes the PCI interrupt, use only on override functions */
static int yenta_probe_cb_irq(struct yenta_socket *socket)
{
u8 reg = 0;
if (!socket->cb_irq)
return -1;
socket->probe_status = 0;
if (request_irq(socket->cb_irq, yenta_probe_handler, IRQF_SHARED, "yenta", socket)) {
dev_printk(KERN_WARNING, &socket->dev->dev,
"request_irq() in yenta_probe_cb_irq() failed!\n");
return -1;
}
/* generate interrupt, wait */
if (!socket->dev->irq)
reg = exca_readb(socket, I365_CSCINT);
exca_writeb(socket, I365_CSCINT, reg | I365_CSC_STSCHG);
cb_writel(socket, CB_SOCKET_EVENT, -1);
cb_writel(socket, CB_SOCKET_MASK, CB_CSTSMASK);
cb_writel(socket, CB_SOCKET_FORCE, CB_FCARDSTS);
msleep(100);
/* disable interrupts */
cb_writel(socket, CB_SOCKET_MASK, 0);
exca_writeb(socket, I365_CSCINT, reg);
cb_writel(socket, CB_SOCKET_EVENT, -1);
exca_readb(socket, I365_CSC);
free_irq(socket->cb_irq, socket);
return (int) socket->probe_status;
}
#endif /* CONFIG_YENTA_TI */
/*
* Set static data that doesn't need re-initializing..
*/
static void yenta_get_socket_capabilities(struct yenta_socket *socket, u32 isa_irq_mask)
{
socket->socket.pci_irq = socket->cb_irq;
if (isa_probe)
socket->socket.irq_mask = yenta_probe_irq(socket, isa_irq_mask);
else
socket->socket.irq_mask = 0;
dev_printk(KERN_INFO, &socket->dev->dev,
"ISA IRQ mask 0x%04x, PCI irq %d\n",
socket->socket.irq_mask, socket->cb_irq);
}
/*
* Initialize the standard cardbus registers
*/
static void yenta_config_init(struct yenta_socket *socket)
{
u16 bridge;
struct pci_dev *dev = socket->dev;
struct pci_bus_region region;
pcibios_resource_to_bus(socket->dev, ®ion, &dev->resource[0]);
config_writel(socket, CB_LEGACY_MODE_BASE, 0);
config_writel(socket, PCI_BASE_ADDRESS_0, region.start);
config_writew(socket, PCI_COMMAND,
PCI_COMMAND_IO |
PCI_COMMAND_MEMORY |
PCI_COMMAND_MASTER |
PCI_COMMAND_WAIT);
/* MAGIC NUMBERS! Fixme */
config_writeb(socket, PCI_CACHE_LINE_SIZE, L1_CACHE_BYTES / 4);
config_writeb(socket, PCI_LATENCY_TIMER, 168);
config_writel(socket, PCI_PRIMARY_BUS,
(176 << 24) | /* sec. latency timer */
(dev->subordinate->subordinate << 16) | /* subordinate bus */
(dev->subordinate->secondary << 8) | /* secondary bus */
dev->subordinate->primary); /* primary bus */
/*
* Set up the bridging state:
* - enable write posting.
* - memory window 0 prefetchable, window 1 non-prefetchable
* - PCI interrupts enabled if a PCI interrupt exists..
*/
bridge = config_readw(socket, CB_BRIDGE_CONTROL);
bridge &= ~(CB_BRIDGE_CRST | CB_BRIDGE_PREFETCH1 | CB_BRIDGE_ISAEN | CB_BRIDGE_VGAEN);
bridge |= CB_BRIDGE_PREFETCH0 | CB_BRIDGE_POSTEN;
config_writew(socket, CB_BRIDGE_CONTROL, bridge);
}
/**
* yenta_fixup_parent_bridge - Fix subordinate bus# of the parent bridge
* @cardbus_bridge: The PCI bus which the CardBus bridge bridges to
*
* Checks if devices on the bus which the CardBus bridge bridges to would be
* invisible during PCI scans because of a misconfigured subordinate number
* of the parent brige - some BIOSes seem to be too lazy to set it right.
* Does the fixup carefully by checking how far it can go without conflicts.
* See http://bugzilla.kernel.org/show_bug.cgi?id=2944 for more information.
*/
static void yenta_fixup_parent_bridge(struct pci_bus *cardbus_bridge)
{
struct list_head *tmp;
unsigned char upper_limit;
/*
* We only check and fix the parent bridge: All systems which need
* this fixup that have been reviewed are laptops and the only bridge
* which needed fixing was the parent bridge of the CardBus bridge:
*/
struct pci_bus *bridge_to_fix = cardbus_bridge->parent;
/* Check bus numbers are already set up correctly: */
if (bridge_to_fix->subordinate >= cardbus_bridge->subordinate)
return; /* The subordinate number is ok, nothing to do */
if (!bridge_to_fix->parent)
return; /* Root bridges are ok */
/* stay within the limits of the bus range of the parent: */
upper_limit = bridge_to_fix->parent->subordinate;
/* check the bus ranges of all silbling bridges to prevent overlap */
list_for_each(tmp, &bridge_to_fix->parent->children) {
struct pci_bus *silbling = pci_bus_b(tmp);
/*
* If the silbling has a higher secondary bus number
* and it's secondary is equal or smaller than our
* current upper limit, set the new upper limit to
* the bus number below the silbling's range:
*/
if (silbling->secondary > bridge_to_fix->subordinate
&& silbling->secondary <= upper_limit)
upper_limit = silbling->secondary - 1;
}
/* Show that the wanted subordinate number is not possible: */
if (cardbus_bridge->subordinate > upper_limit)
dev_printk(KERN_WARNING, &cardbus_bridge->dev,
"Upper limit for fixing this "
"bridge's parent bridge: #%02x\n", upper_limit);
/* If we have room to increase the bridge's subordinate number, */
if (bridge_to_fix->subordinate < upper_limit) {
/* use the highest number of the hidden bus, within limits */
unsigned char subordinate_to_assign =
min(cardbus_bridge->subordinate, upper_limit);
dev_printk(KERN_INFO, &bridge_to_fix->dev,
"Raising subordinate bus# of parent "
"bus (#%02x) from #%02x to #%02x\n",
bridge_to_fix->number,
bridge_to_fix->subordinate, subordinate_to_assign);
/* Save the new subordinate in the bus struct of the bridge */
bridge_to_fix->subordinate = subordinate_to_assign;
/* and update the PCI config space with the new subordinate */
pci_write_config_byte(bridge_to_fix->self,
PCI_SUBORDINATE_BUS, bridge_to_fix->subordinate);
}
}
/*
* Initialize a cardbus controller. Make sure we have a usable
* interrupt, and that we can map the cardbus area. Fill in the
* socket information structure..
*/
static int __devinit yenta_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
struct yenta_socket *socket;
int ret;
/*
* If we failed to assign proper bus numbers for this cardbus
* controller during PCI probe, its subordinate pci_bus is NULL.
* Bail out if so.
*/
if (!dev->subordinate) {
dev_printk(KERN_ERR, &dev->dev, "no bus associated! "
"(try 'pci=assign-busses')\n");
return -ENODEV;
}
socket = kzalloc(sizeof(struct yenta_socket), GFP_KERNEL);
if (!socket)
return -ENOMEM;
/* prepare pcmcia_socket */
socket->socket.ops = ¥ta_socket_operations;
socket->socket.resource_ops = &pccard_nonstatic_ops;
socket->socket.dev.parent = &dev->dev;
socket->socket.driver_data = socket;
socket->socket.owner = THIS_MODULE;
socket->socket.features = SS_CAP_PAGE_REGS | SS_CAP_PCCARD;
socket->socket.map_size = 0x1000;
socket->socket.cb_dev = dev;
/* prepare struct yenta_socket */
socket->dev = dev;
pci_set_drvdata(dev, socket);
/*
* Do some basic sanity checking..
*/
if (pci_enable_device(dev)) {
ret = -EBUSY;
goto free;
}
ret = pci_request_regions(dev, "yenta_socket");
if (ret)
goto disable;
if (!pci_resource_start(dev, 0)) {
dev_printk(KERN_ERR, &dev->dev, "No cardbus resource!\n");
ret = -ENODEV;
goto release;
}
/*
* Ok, start setup.. Map the cardbus registers,
* and request the IRQ.
*/
socket->base = ioremap(pci_resource_start(dev, 0), 0x1000);
if (!socket->base) {
ret = -ENOMEM;
goto release;
}
/*
* report the subsystem vendor and device for help debugging
* the irq stuff...
*/
dev_printk(KERN_INFO, &dev->dev, "CardBus bridge found [%04x:%04x]\n",
dev->subsystem_vendor, dev->subsystem_device);
yenta_config_init(socket);
/* Disable all events */
cb_writel(socket, CB_SOCKET_MASK, 0x0);
/* Set up the bridge regions.. */
yenta_allocate_resources(socket);
socket->cb_irq = dev->irq;
/* Do we have special options for the device? */
if (id->driver_data != CARDBUS_TYPE_DEFAULT &&
id->driver_data < ARRAY_SIZE(cardbus_type)) {
socket->type = &cardbus_type[id->driver_data];
ret = socket->type->override(socket);
if (ret < 0)
goto unmap;
}
/* We must finish initialization here */
if (!socket->cb_irq || request_irq(socket->cb_irq, yenta_interrupt, IRQF_SHARED, "yenta", socket)) {
/* No IRQ or request_irq failed. Poll */
socket->cb_irq = 0; /* But zero is a valid IRQ number. */
init_timer(&socket->poll_timer);
socket->poll_timer.function = yenta_interrupt_wrapper;
socket->poll_timer.data = (unsigned long)socket;
socket->poll_timer.expires = jiffies + HZ;
add_timer(&socket->poll_timer);
dev_printk(KERN_INFO, &dev->dev,
"no PCI IRQ, CardBus support disabled for this "
"socket.\n");
dev_printk(KERN_INFO, &dev->dev,
"check your BIOS CardBus, BIOS IRQ or ACPI "
"settings.\n");
} else {
socket->socket.features |= SS_CAP_CARDBUS;
}
/* Figure out what the dang thing can do for the PCMCIA layer... */
yenta_interrogate(socket);
yenta_get_socket_capabilities(socket, isa_interrupts);
dev_printk(KERN_INFO, &dev->dev,
"Socket status: %08x\n", cb_readl(socket, CB_SOCKET_STATE));
yenta_fixup_parent_bridge(dev->subordinate);
/* Register it with the pcmcia layer.. */
ret = pcmcia_register_socket(&socket->socket);
if (ret == 0) {
/* Add the yenta register attributes */
ret = device_create_file(&dev->dev, &dev_attr_yenta_registers);
if (ret == 0)
goto out;
/* error path... */
pcmcia_unregister_socket(&socket->socket);
}
unmap:
iounmap(socket->base);
release:
pci_release_regions(dev);
disable:
pci_disable_device(dev);
free:
kfree(socket);
out:
return ret;
}
#ifdef CONFIG_PM
static int yenta_dev_suspend_noirq(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct yenta_socket *socket = pci_get_drvdata(pdev);
if (!socket)
return 0;
if (socket->type && socket->type->save_state)
socket->type->save_state(socket);
pci_save_state(pdev);
pci_read_config_dword(pdev, 16*4, &socket->saved_state[0]);
pci_read_config_dword(pdev, 17*4, &socket->saved_state[1]);
pci_disable_device(pdev);
return 0;
}
static int yenta_dev_resume_noirq(struct device *dev)
{
struct pci_dev *pdev = to_pci_dev(dev);
struct yenta_socket *socket = pci_get_drvdata(pdev);
int ret;
if (!socket)
return 0;
pci_write_config_dword(pdev, 16*4, socket->saved_state[0]);
pci_write_config_dword(pdev, 17*4, socket->saved_state[1]);
ret = pci_enable_device(pdev);
if (ret)
return ret;
pci_set_master(pdev);
if (socket->type && socket->type->restore_state)
socket->type->restore_state(socket);
return 0;
}
static const struct dev_pm_ops yenta_pm_ops = {
.suspend_noirq = yenta_dev_suspend_noirq,
.resume_noirq = yenta_dev_resume_noirq,
.freeze_noirq = yenta_dev_suspend_noirq,
.thaw_noirq = yenta_dev_resume_noirq,
.poweroff_noirq = yenta_dev_suspend_noirq,
.restore_noirq = yenta_dev_resume_noirq,
};
#define YENTA_PM_OPS (¥ta_pm_ops)
#else
#define YENTA_PM_OPS NULL
#endif
#define CB_ID(vend, dev, type) \
{ \
.vendor = vend, \
.device = dev, \
.subvendor = PCI_ANY_ID, \
.subdevice = PCI_ANY_ID, \
.class = PCI_CLASS_BRIDGE_CARDBUS << 8, \
.class_mask = ~0, \
.driver_data = CARDBUS_TYPE_##type, \
}
static DEFINE_PCI_DEVICE_TABLE(yenta_table) = {
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1031, TI),
/*
* TBD: Check if these TI variants can use more
* advanced overrides instead. (I can't get the
* data sheets for these devices. --rmk)
*/
#ifdef CONFIG_YENTA_TI
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1210, TI),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1130, TI113X),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1131, TI113X),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1211, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1220, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1221, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1225, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1251A, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1251B, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1420, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1450, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1451A, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1510, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1520, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1620, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_4410, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_4450, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_4451, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_4510, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_4520, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1250, TI1250),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_1410, TI1250),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_XX21_XX11, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_X515, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_XX12, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_X420, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_X620, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_7410, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_7510, TI12XX),
CB_ID(PCI_VENDOR_ID_TI, PCI_DEVICE_ID_TI_7610, TI12XX),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_710, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_712, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_720, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_722, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_1211, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_1225, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_1410, ENE),
CB_ID(PCI_VENDOR_ID_ENE, PCI_DEVICE_ID_ENE_1420, ENE),
#endif /* CONFIG_YENTA_TI */
#ifdef CONFIG_YENTA_RICOH
CB_ID(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C465, RICOH),
CB_ID(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C466, RICOH),
CB_ID(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C475, RICOH),
CB_ID(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C476, RICOH),
CB_ID(PCI_VENDOR_ID_RICOH, PCI_DEVICE_ID_RICOH_RL5C478, RICOH),
#endif
#ifdef CONFIG_YENTA_TOSHIBA
CB_ID(PCI_VENDOR_ID_TOSHIBA, PCI_DEVICE_ID_TOSHIBA_TOPIC95, TOPIC95),
CB_ID(PCI_VENDOR_ID_TOSHIBA, PCI_DEVICE_ID_TOSHIBA_TOPIC97, TOPIC97),
CB_ID(PCI_VENDOR_ID_TOSHIBA, PCI_DEVICE_ID_TOSHIBA_TOPIC100, TOPIC97),
#endif
#ifdef CONFIG_YENTA_O2
CB_ID(PCI_VENDOR_ID_O2, PCI_ANY_ID, O2MICRO),
#endif
/* match any cardbus bridge */
CB_ID(PCI_ANY_ID, PCI_ANY_ID, DEFAULT),
{ /* all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, yenta_table);
static struct pci_driver yenta_cardbus_driver = {
.name = "yenta_cardbus",
.id_table = yenta_table,
.probe = yenta_probe,
.remove = __devexit_p(yenta_close),
.driver.pm = YENTA_PM_OPS,
};
static int __init yenta_socket_init(void)
{
return pci_register_driver(¥ta_cardbus_driver);
}
static void __exit yenta_socket_exit(void)
{
pci_unregister_driver(¥ta_cardbus_driver);
}
module_init(yenta_socket_init);
module_exit(yenta_socket_exit);
MODULE_LICENSE("GPL");
| gpl-2.0 |
SimpleAOSP-Kernel/kernel_mako | tools/perf/util/config.c | 4910 | 9894 | /*
* config.c
*
* Helper functions for parsing config items.
* Originally copied from GIT source.
*
* Copyright (C) Linus Torvalds, 2005
* Copyright (C) Johannes Schindelin, 2005
*
*/
#include "util.h"
#include "cache.h"
#include "exec_cmd.h"
#define MAXNAME (256)
#define DEBUG_CACHE_DIR ".debug"
char buildid_dir[MAXPATHLEN]; /* root dir for buildid, binary cache */
static FILE *config_file;
static const char *config_file_name;
static int config_linenr;
static int config_file_eof;
static const char *config_exclusive_filename;
static int get_next_char(void)
{
int c;
FILE *f;
c = '\n';
if ((f = config_file) != NULL) {
c = fgetc(f);
if (c == '\r') {
/* DOS like systems */
c = fgetc(f);
if (c != '\n') {
ungetc(c, f);
c = '\r';
}
}
if (c == '\n')
config_linenr++;
if (c == EOF) {
config_file_eof = 1;
c = '\n';
}
}
return c;
}
static char *parse_value(void)
{
static char value[1024];
int quote = 0, comment = 0, space = 0;
size_t len = 0;
for (;;) {
int c = get_next_char();
if (len >= sizeof(value) - 1)
return NULL;
if (c == '\n') {
if (quote)
return NULL;
value[len] = 0;
return value;
}
if (comment)
continue;
if (isspace(c) && !quote) {
space = 1;
continue;
}
if (!quote) {
if (c == ';' || c == '#') {
comment = 1;
continue;
}
}
if (space) {
if (len)
value[len++] = ' ';
space = 0;
}
if (c == '\\') {
c = get_next_char();
switch (c) {
case '\n':
continue;
case 't':
c = '\t';
break;
case 'b':
c = '\b';
break;
case 'n':
c = '\n';
break;
/* Some characters escape as themselves */
case '\\': case '"':
break;
/* Reject unknown escape sequences */
default:
return NULL;
}
value[len++] = c;
continue;
}
if (c == '"') {
quote = 1-quote;
continue;
}
value[len++] = c;
}
}
static inline int iskeychar(int c)
{
return isalnum(c) || c == '-';
}
static int get_value(config_fn_t fn, void *data, char *name, unsigned int len)
{
int c;
char *value;
/* Get the full name */
for (;;) {
c = get_next_char();
if (config_file_eof)
break;
if (!iskeychar(c))
break;
name[len++] = c;
if (len >= MAXNAME)
return -1;
}
name[len] = 0;
while (c == ' ' || c == '\t')
c = get_next_char();
value = NULL;
if (c != '\n') {
if (c != '=')
return -1;
value = parse_value();
if (!value)
return -1;
}
return fn(name, value, data);
}
static int get_extended_base_var(char *name, int baselen, int c)
{
do {
if (c == '\n')
return -1;
c = get_next_char();
} while (isspace(c));
/* We require the format to be '[base "extension"]' */
if (c != '"')
return -1;
name[baselen++] = '.';
for (;;) {
int ch = get_next_char();
if (ch == '\n')
return -1;
if (ch == '"')
break;
if (ch == '\\') {
ch = get_next_char();
if (ch == '\n')
return -1;
}
name[baselen++] = ch;
if (baselen > MAXNAME / 2)
return -1;
}
/* Final ']' */
if (get_next_char() != ']')
return -1;
return baselen;
}
static int get_base_var(char *name)
{
int baselen = 0;
for (;;) {
int c = get_next_char();
if (config_file_eof)
return -1;
if (c == ']')
return baselen;
if (isspace(c))
return get_extended_base_var(name, baselen, c);
if (!iskeychar(c) && c != '.')
return -1;
if (baselen > MAXNAME / 2)
return -1;
name[baselen++] = tolower(c);
}
}
static int perf_parse_file(config_fn_t fn, void *data)
{
int comment = 0;
int baselen = 0;
static char var[MAXNAME];
/* U+FEFF Byte Order Mark in UTF8 */
static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf";
const unsigned char *bomptr = utf8_bom;
for (;;) {
int c = get_next_char();
if (bomptr && *bomptr) {
/* We are at the file beginning; skip UTF8-encoded BOM
* if present. Sane editors won't put this in on their
* own, but e.g. Windows Notepad will do it happily. */
if ((unsigned char) c == *bomptr) {
bomptr++;
continue;
} else {
/* Do not tolerate partial BOM. */
if (bomptr != utf8_bom)
break;
/* No BOM at file beginning. Cool. */
bomptr = NULL;
}
}
if (c == '\n') {
if (config_file_eof)
return 0;
comment = 0;
continue;
}
if (comment || isspace(c))
continue;
if (c == '#' || c == ';') {
comment = 1;
continue;
}
if (c == '[') {
baselen = get_base_var(var);
if (baselen <= 0)
break;
var[baselen++] = '.';
var[baselen] = 0;
continue;
}
if (!isalpha(c))
break;
var[baselen] = tolower(c);
if (get_value(fn, data, var, baselen+1) < 0)
break;
}
die("bad config file line %d in %s", config_linenr, config_file_name);
}
static int parse_unit_factor(const char *end, unsigned long *val)
{
if (!*end)
return 1;
else if (!strcasecmp(end, "k")) {
*val *= 1024;
return 1;
}
else if (!strcasecmp(end, "m")) {
*val *= 1024 * 1024;
return 1;
}
else if (!strcasecmp(end, "g")) {
*val *= 1024 * 1024 * 1024;
return 1;
}
return 0;
}
static int perf_parse_long(const char *value, long *ret)
{
if (value && *value) {
char *end;
long val = strtol(value, &end, 0);
unsigned long factor = 1;
if (!parse_unit_factor(end, &factor))
return 0;
*ret = val * factor;
return 1;
}
return 0;
}
static void die_bad_config(const char *name)
{
if (config_file_name)
die("bad config value for '%s' in %s", name, config_file_name);
die("bad config value for '%s'", name);
}
int perf_config_int(const char *name, const char *value)
{
long ret = 0;
if (!perf_parse_long(value, &ret))
die_bad_config(name);
return ret;
}
static int perf_config_bool_or_int(const char *name, const char *value, int *is_bool)
{
*is_bool = 1;
if (!value)
return 1;
if (!*value)
return 0;
if (!strcasecmp(value, "true") || !strcasecmp(value, "yes") || !strcasecmp(value, "on"))
return 1;
if (!strcasecmp(value, "false") || !strcasecmp(value, "no") || !strcasecmp(value, "off"))
return 0;
*is_bool = 0;
return perf_config_int(name, value);
}
int perf_config_bool(const char *name, const char *value)
{
int discard;
return !!perf_config_bool_or_int(name, value, &discard);
}
const char *perf_config_dirname(const char *name, const char *value)
{
if (!name)
return NULL;
return value;
}
static int perf_default_core_config(const char *var __used, const char *value __used)
{
/* Add other config variables here. */
return 0;
}
int perf_default_config(const char *var, const char *value, void *dummy __used)
{
if (!prefixcmp(var, "core."))
return perf_default_core_config(var, value);
/* Add other config variables here. */
return 0;
}
static int perf_config_from_file(config_fn_t fn, const char *filename, void *data)
{
int ret;
FILE *f = fopen(filename, "r");
ret = -1;
if (f) {
config_file = f;
config_file_name = filename;
config_linenr = 1;
config_file_eof = 0;
ret = perf_parse_file(fn, data);
fclose(f);
config_file_name = NULL;
}
return ret;
}
static const char *perf_etc_perfconfig(void)
{
static const char *system_wide;
if (!system_wide)
system_wide = system_path(ETC_PERFCONFIG);
return system_wide;
}
static int perf_env_bool(const char *k, int def)
{
const char *v = getenv(k);
return v ? perf_config_bool(k, v) : def;
}
static int perf_config_system(void)
{
return !perf_env_bool("PERF_CONFIG_NOSYSTEM", 0);
}
static int perf_config_global(void)
{
return !perf_env_bool("PERF_CONFIG_NOGLOBAL", 0);
}
int perf_config(config_fn_t fn, void *data)
{
int ret = 0, found = 0;
const char *home = NULL;
/* Setting $PERF_CONFIG makes perf read _only_ the given config file. */
if (config_exclusive_filename)
return perf_config_from_file(fn, config_exclusive_filename, data);
if (perf_config_system() && !access(perf_etc_perfconfig(), R_OK)) {
ret += perf_config_from_file(fn, perf_etc_perfconfig(),
data);
found += 1;
}
home = getenv("HOME");
if (perf_config_global() && home) {
char *user_config = strdup(mkpath("%s/.perfconfig", home));
struct stat st;
if (user_config == NULL) {
warning("Not enough memory to process %s/.perfconfig, "
"ignoring it.", home);
goto out;
}
if (stat(user_config, &st) < 0)
goto out_free;
if (st.st_uid && (st.st_uid != geteuid())) {
warning("File %s not owned by current user or root, "
"ignoring it.", user_config);
goto out_free;
}
if (!st.st_size)
goto out_free;
ret += perf_config_from_file(fn, user_config, data);
found += 1;
out_free:
free(user_config);
}
out:
if (found == 0)
return -1;
return ret;
}
/*
* Call this to report error for your variable that should not
* get a boolean value (i.e. "[my] var" means "true").
*/
int config_error_nonbool(const char *var)
{
return error("Missing value for '%s'", var);
}
struct buildid_dir_config {
char *dir;
};
static int buildid_dir_command_config(const char *var, const char *value,
void *data)
{
struct buildid_dir_config *c = data;
const char *v;
/* same dir for all commands */
if (!prefixcmp(var, "buildid.") && !strcmp(var + 8, "dir")) {
v = perf_config_dirname(var, value);
if (!v)
return -1;
strncpy(c->dir, v, MAXPATHLEN-1);
c->dir[MAXPATHLEN-1] = '\0';
}
return 0;
}
static void check_buildid_dir_config(void)
{
struct buildid_dir_config c;
c.dir = buildid_dir;
perf_config(buildid_dir_command_config, &c);
}
void set_buildid_dir(void)
{
buildid_dir[0] = '\0';
/* try config file */
check_buildid_dir_config();
/* default to $HOME/.debug */
if (buildid_dir[0] == '\0') {
char *v = getenv("HOME");
if (v) {
snprintf(buildid_dir, MAXPATHLEN-1, "%s/%s",
v, DEBUG_CACHE_DIR);
} else {
strncpy(buildid_dir, DEBUG_CACHE_DIR, MAXPATHLEN-1);
}
buildid_dir[MAXPATHLEN-1] = '\0';
}
/* for communicating with external commands */
setenv("PERF_BUILDID_DIR", buildid_dir, 1);
}
| gpl-2.0 |
hunter3k/android_kernel_lge_d315 | drivers/w1/masters/w1-gpio.c | 4910 | 3335 | /*
* w1-gpio - GPIO w1 bus master driver
*
* Copyright (C) 2007 Ville Syrjala <syrjala@sci.fi>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/w1-gpio.h>
#include <linux/gpio.h>
#include "../w1.h"
#include "../w1_int.h"
static void w1_gpio_write_bit_dir(void *data, u8 bit)
{
struct w1_gpio_platform_data *pdata = data;
if (bit)
gpio_direction_input(pdata->pin);
else
gpio_direction_output(pdata->pin, 0);
}
static void w1_gpio_write_bit_val(void *data, u8 bit)
{
struct w1_gpio_platform_data *pdata = data;
gpio_set_value(pdata->pin, bit);
}
static u8 w1_gpio_read_bit(void *data)
{
struct w1_gpio_platform_data *pdata = data;
return gpio_get_value(pdata->pin) ? 1 : 0;
}
static int __init w1_gpio_probe(struct platform_device *pdev)
{
struct w1_bus_master *master;
struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
int err;
if (!pdata)
return -ENXIO;
master = kzalloc(sizeof(struct w1_bus_master), GFP_KERNEL);
if (!master)
return -ENOMEM;
err = gpio_request(pdata->pin, "w1");
if (err)
goto free_master;
master->data = pdata;
master->read_bit = w1_gpio_read_bit;
if (pdata->is_open_drain) {
gpio_direction_output(pdata->pin, 1);
master->write_bit = w1_gpio_write_bit_val;
} else {
gpio_direction_input(pdata->pin);
master->write_bit = w1_gpio_write_bit_dir;
}
err = w1_add_master_device(master);
if (err)
goto free_gpio;
if (pdata->enable_external_pullup)
pdata->enable_external_pullup(1);
platform_set_drvdata(pdev, master);
return 0;
free_gpio:
gpio_free(pdata->pin);
free_master:
kfree(master);
return err;
}
static int __exit w1_gpio_remove(struct platform_device *pdev)
{
struct w1_bus_master *master = platform_get_drvdata(pdev);
struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
if (pdata->enable_external_pullup)
pdata->enable_external_pullup(0);
w1_remove_master_device(master);
gpio_free(pdata->pin);
kfree(master);
return 0;
}
#ifdef CONFIG_PM
static int w1_gpio_suspend(struct platform_device *pdev, pm_message_t state)
{
struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
if (pdata->enable_external_pullup)
pdata->enable_external_pullup(0);
return 0;
}
static int w1_gpio_resume(struct platform_device *pdev)
{
struct w1_gpio_platform_data *pdata = pdev->dev.platform_data;
if (pdata->enable_external_pullup)
pdata->enable_external_pullup(1);
return 0;
}
#else
#define w1_gpio_suspend NULL
#define w1_gpio_resume NULL
#endif
static struct platform_driver w1_gpio_driver = {
.driver = {
.name = "w1-gpio",
.owner = THIS_MODULE,
},
.remove = __exit_p(w1_gpio_remove),
.suspend = w1_gpio_suspend,
.resume = w1_gpio_resume,
};
static int __init w1_gpio_init(void)
{
return platform_driver_probe(&w1_gpio_driver, w1_gpio_probe);
}
static void __exit w1_gpio_exit(void)
{
platform_driver_unregister(&w1_gpio_driver);
}
module_init(w1_gpio_init);
module_exit(w1_gpio_exit);
MODULE_DESCRIPTION("GPIO w1 bus master driver");
MODULE_AUTHOR("Ville Syrjala <syrjala@sci.fi>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
ShivangDave/android_kernel_sony_msm7x27a-Mesona | arch/arm/plat-mxc/devices/platform-mxc-ehci.c | 5166 | 2658 | /*
* Copyright (C) 2010 Pengutronix
* Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 2 as published by the
* Free Software Foundation.
*/
#include <linux/dma-mapping.h>
#include <mach/hardware.h>
#include <mach/devices-common.h>
#define imx_mxc_ehci_data_entry_single(soc, _id, hs) \
{ \
.id = _id, \
.iobase = soc ## _USB_ ## hs ## _BASE_ADDR, \
.irq = soc ## _INT_USB_ ## hs, \
}
#ifdef CONFIG_SOC_IMX25
const struct imx_mxc_ehci_data imx25_mxc_ehci_otg_data __initconst =
imx_mxc_ehci_data_entry_single(MX25, 0, OTG);
const struct imx_mxc_ehci_data imx25_mxc_ehci_hs_data __initconst =
imx_mxc_ehci_data_entry_single(MX25, 1, HS);
#endif /* ifdef CONFIG_SOC_IMX25 */
#ifdef CONFIG_SOC_IMX27
const struct imx_mxc_ehci_data imx27_mxc_ehci_otg_data __initconst =
imx_mxc_ehci_data_entry_single(MX27, 0, OTG);
const struct imx_mxc_ehci_data imx27_mxc_ehci_hs_data[] __initconst = {
imx_mxc_ehci_data_entry_single(MX27, 1, HS1),
imx_mxc_ehci_data_entry_single(MX27, 2, HS2),
};
#endif /* ifdef CONFIG_SOC_IMX27 */
#ifdef CONFIG_SOC_IMX31
const struct imx_mxc_ehci_data imx31_mxc_ehci_otg_data __initconst =
imx_mxc_ehci_data_entry_single(MX31, 0, OTG);
const struct imx_mxc_ehci_data imx31_mxc_ehci_hs_data[] __initconst = {
imx_mxc_ehci_data_entry_single(MX31, 1, HS1),
imx_mxc_ehci_data_entry_single(MX31, 2, HS2),
};
#endif /* ifdef CONFIG_SOC_IMX31 */
#ifdef CONFIG_SOC_IMX35
const struct imx_mxc_ehci_data imx35_mxc_ehci_otg_data __initconst =
imx_mxc_ehci_data_entry_single(MX35, 0, OTG);
const struct imx_mxc_ehci_data imx35_mxc_ehci_hs_data __initconst =
imx_mxc_ehci_data_entry_single(MX35, 1, HS);
#endif /* ifdef CONFIG_SOC_IMX35 */
#ifdef CONFIG_SOC_IMX51
const struct imx_mxc_ehci_data imx51_mxc_ehci_otg_data __initconst =
imx_mxc_ehci_data_entry_single(MX51, 0, OTG);
const struct imx_mxc_ehci_data imx51_mxc_ehci_hs_data[] __initconst = {
imx_mxc_ehci_data_entry_single(MX51, 1, HS1),
imx_mxc_ehci_data_entry_single(MX51, 2, HS2),
};
#endif /* ifdef CONFIG_SOC_IMX51 */
struct platform_device *__init imx_add_mxc_ehci(
const struct imx_mxc_ehci_data *data,
const struct mxc_usbh_platform_data *pdata)
{
struct resource res[] = {
{
.start = data->iobase,
.end = data->iobase + SZ_512 - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irq,
.end = data->irq,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device_dmamask("mxc-ehci", data->id,
res, ARRAY_SIZE(res),
pdata, sizeof(*pdata), DMA_BIT_MASK(32));
}
| gpl-2.0 |
jrior001/android_kernel_oneplus_msm8974 | arch/arm/mach-ixp4xx/wg302v2-pci.c | 5422 | 1482 | /*
* arch/arch/mach-ixp4xx/wg302v2-pci.c
*
* PCI setup routines for the Netgear WG302 v2 and WAG302 v2
*
* Copyright (C) 2007 Imre Kaloz <kaloz@openwrt.org>
*
* based on coyote-pci.c:
* Copyright (C) 2002 Jungo Software Technologies.
* Copyright (C) 2003 MontaVista Software, Inc.
*
* Maintainer: Imre Kaloz <kaloz@openwrt.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/irq.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <asm/mach/pci.h>
void __init wg302v2_pci_preinit(void)
{
irq_set_irq_type(IRQ_IXP4XX_GPIO8, IRQ_TYPE_LEVEL_LOW);
irq_set_irq_type(IRQ_IXP4XX_GPIO9, IRQ_TYPE_LEVEL_LOW);
ixp4xx_pci_preinit();
}
static int __init wg302v2_map_irq(const struct pci_dev *dev, u8 slot, u8 pin)
{
if (slot == 1)
return IRQ_IXP4XX_GPIO8;
else if (slot == 2)
return IRQ_IXP4XX_GPIO9;
else return -1;
}
struct hw_pci wg302v2_pci __initdata = {
.nr_controllers = 1,
.preinit = wg302v2_pci_preinit,
.swizzle = pci_std_swizzle,
.setup = ixp4xx_setup,
.scan = ixp4xx_scan_bus,
.map_irq = wg302v2_map_irq,
};
int __init wg302v2_pci_init(void)
{
if (machine_is_wg302v2())
pci_common_init(&wg302v2_pci);
return 0;
}
subsys_initcall(wg302v2_pci_init);
| gpl-2.0 |
TEAM-RAZOR-DEVICES/android_kernel_lge_awifi | drivers/media/radio/wl128x/fmdrv_tx.c | 7982 | 9306 | /*
* FM Driver for Connectivity chip of Texas Instruments.
* This sub-module of FM driver implements FM TX functionality.
*
* Copyright (C) 2011 Texas Instruments
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/delay.h>
#include "fmdrv.h"
#include "fmdrv_common.h"
#include "fmdrv_tx.h"
int fm_tx_set_stereo_mono(struct fmdev *fmdev, u16 mode)
{
u16 payload;
int ret;
if (fmdev->tx_data.aud_mode == mode)
return 0;
fmdbg("stereo mode: %d\n", mode);
/* Set Stereo/Mono mode */
payload = (1 - mode);
ret = fmc_send_cmd(fmdev, MONO_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
fmdev->tx_data.aud_mode = mode;
return ret;
}
static int set_rds_text(struct fmdev *fmdev, u8 *rds_text)
{
u16 payload;
int ret;
ret = fmc_send_cmd(fmdev, RDS_DATA_SET, REG_WR, rds_text,
strlen(rds_text), NULL, NULL);
if (ret < 0)
return ret;
/* Scroll mode */
payload = (u16)0x1;
ret = fmc_send_cmd(fmdev, DISPLAY_MODE, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
return 0;
}
static int set_rds_data_mode(struct fmdev *fmdev, u8 mode)
{
u16 payload;
int ret;
/* Setting unique PI TODO: how unique? */
payload = (u16)0xcafe;
ret = fmc_send_cmd(fmdev, PI_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* Set decoder id */
payload = (u16)0xa;
ret = fmc_send_cmd(fmdev, DI_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* TODO: RDS_MODE_GET? */
return 0;
}
static int set_rds_len(struct fmdev *fmdev, u8 type, u16 len)
{
u16 payload;
int ret;
len |= type << 8;
payload = len;
ret = fmc_send_cmd(fmdev, RDS_CONFIG_DATA_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* TODO: LENGTH_GET? */
return 0;
}
int fm_tx_set_rds_mode(struct fmdev *fmdev, u8 rds_en_dis)
{
u16 payload;
int ret;
u8 rds_text[] = "Zoom2\n";
fmdbg("rds_en_dis:%d(E:%d, D:%d)\n", rds_en_dis,
FM_RDS_ENABLE, FM_RDS_DISABLE);
if (rds_en_dis == FM_RDS_ENABLE) {
/* Set RDS length */
set_rds_len(fmdev, 0, strlen(rds_text));
/* Set RDS text */
set_rds_text(fmdev, rds_text);
/* Set RDS mode */
set_rds_data_mode(fmdev, 0x0);
}
/* Send command to enable RDS */
if (rds_en_dis == FM_RDS_ENABLE)
payload = 0x01;
else
payload = 0x00;
ret = fmc_send_cmd(fmdev, RDS_DATA_ENB, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
if (rds_en_dis == FM_RDS_ENABLE) {
/* Set RDS length */
set_rds_len(fmdev, 0, strlen(rds_text));
/* Set RDS text */
set_rds_text(fmdev, rds_text);
}
fmdev->tx_data.rds.flag = rds_en_dis;
return 0;
}
int fm_tx_set_radio_text(struct fmdev *fmdev, u8 *rds_text, u8 rds_type)
{
u16 payload;
int ret;
if (fmdev->curr_fmmode != FM_MODE_TX)
return -EPERM;
fm_tx_set_rds_mode(fmdev, 0);
/* Set RDS length */
set_rds_len(fmdev, rds_type, strlen(rds_text));
/* Set RDS text */
set_rds_text(fmdev, rds_text);
/* Set RDS mode */
set_rds_data_mode(fmdev, 0x0);
payload = 1;
ret = fmc_send_cmd(fmdev, RDS_DATA_ENB, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
return 0;
}
int fm_tx_set_af(struct fmdev *fmdev, u32 af)
{
u16 payload;
int ret;
if (fmdev->curr_fmmode != FM_MODE_TX)
return -EPERM;
fmdbg("AF: %d\n", af);
af = (af - 87500) / 100;
payload = (u16)af;
ret = fmc_send_cmd(fmdev, TA_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
return 0;
}
int fm_tx_set_region(struct fmdev *fmdev, u8 region)
{
u16 payload;
int ret;
if (region != FM_BAND_EUROPE_US && region != FM_BAND_JAPAN) {
fmerr("Invalid band\n");
return -EINVAL;
}
/* Send command to set the band */
payload = (u16)region;
ret = fmc_send_cmd(fmdev, TX_BAND_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
return 0;
}
int fm_tx_set_mute_mode(struct fmdev *fmdev, u8 mute_mode_toset)
{
u16 payload;
int ret;
fmdbg("tx: mute mode %d\n", mute_mode_toset);
payload = mute_mode_toset;
ret = fmc_send_cmd(fmdev, MUTE, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
return 0;
}
/* Set TX Audio I/O */
static int set_audio_io(struct fmdev *fmdev)
{
struct fmtx_data *tx = &fmdev->tx_data;
u16 payload;
int ret;
/* Set Audio I/O Enable */
payload = tx->audio_io;
ret = fmc_send_cmd(fmdev, AUDIO_IO_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* TODO: is audio set? */
return 0;
}
/* Start TX Transmission */
static int enable_xmit(struct fmdev *fmdev, u8 new_xmit_state)
{
struct fmtx_data *tx = &fmdev->tx_data;
unsigned long timeleft;
u16 payload;
int ret;
/* Enable POWER_ENB interrupts */
payload = FM_POW_ENB_EVENT;
ret = fmc_send_cmd(fmdev, INT_MASK_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* Set Power Enable */
payload = new_xmit_state;
ret = fmc_send_cmd(fmdev, POWER_ENB_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* Wait for Power Enabled */
init_completion(&fmdev->maintask_comp);
timeleft = wait_for_completion_timeout(&fmdev->maintask_comp,
FM_DRV_TX_TIMEOUT);
if (!timeleft) {
fmerr("Timeout(%d sec),didn't get tune ended interrupt\n",
jiffies_to_msecs(FM_DRV_TX_TIMEOUT) / 1000);
return -ETIMEDOUT;
}
set_bit(FM_CORE_TX_XMITING, &fmdev->flag);
tx->xmit_state = new_xmit_state;
return 0;
}
/* Set TX power level */
int fm_tx_set_pwr_lvl(struct fmdev *fmdev, u8 new_pwr_lvl)
{
u16 payload;
struct fmtx_data *tx = &fmdev->tx_data;
int ret;
if (fmdev->curr_fmmode != FM_MODE_TX)
return -EPERM;
fmdbg("tx: pwr_level_to_set %ld\n", (long int)new_pwr_lvl);
/* If the core isn't ready update global variable */
if (!test_bit(FM_CORE_READY, &fmdev->flag)) {
tx->pwr_lvl = new_pwr_lvl;
return 0;
}
/* Set power level: Application will specify power level value in
* units of dB/uV, whereas range and step are specific to FM chip.
* For TI's WL chips, convert application specified power level value
* to chip specific value by subtracting 122 from it. Refer to TI FM
* data sheet for details.
* */
payload = (FM_PWR_LVL_HIGH - new_pwr_lvl);
ret = fmc_send_cmd(fmdev, POWER_LEV_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
/* TODO: is the power level set? */
tx->pwr_lvl = new_pwr_lvl;
return 0;
}
/*
* Sets FM TX pre-emphasis filter value (OFF, 50us, or 75us)
* Convert V4L2 specified filter values to chip specific filter values.
*/
int fm_tx_set_preemph_filter(struct fmdev *fmdev, u32 preemphasis)
{
struct fmtx_data *tx = &fmdev->tx_data;
u16 payload;
int ret;
if (fmdev->curr_fmmode != FM_MODE_TX)
return -EPERM;
switch (preemphasis) {
case V4L2_PREEMPHASIS_DISABLED:
payload = FM_TX_PREEMPH_OFF;
break;
case V4L2_PREEMPHASIS_50_uS:
payload = FM_TX_PREEMPH_50US;
break;
case V4L2_PREEMPHASIS_75_uS:
payload = FM_TX_PREEMPH_75US;
break;
}
ret = fmc_send_cmd(fmdev, PREMPH_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
tx->preemph = payload;
return ret;
}
/* Get the TX tuning capacitor value.*/
int fm_tx_get_tune_cap_val(struct fmdev *fmdev)
{
u16 curr_val;
u32 resp_len;
int ret;
if (fmdev->curr_fmmode != FM_MODE_TX)
return -EPERM;
ret = fmc_send_cmd(fmdev, READ_FMANT_TUNE_VALUE, REG_RD,
NULL, sizeof(curr_val), &curr_val, &resp_len);
if (ret < 0)
return ret;
curr_val = be16_to_cpu(curr_val);
return curr_val;
}
/* Set TX Frequency */
int fm_tx_set_freq(struct fmdev *fmdev, u32 freq_to_set)
{
struct fmtx_data *tx = &fmdev->tx_data;
u16 payload, chanl_index;
int ret;
if (test_bit(FM_CORE_TX_XMITING, &fmdev->flag)) {
enable_xmit(fmdev, 0);
clear_bit(FM_CORE_TX_XMITING, &fmdev->flag);
}
/* Enable FR, BL interrupts */
payload = (FM_FR_EVENT | FM_BL_EVENT);
ret = fmc_send_cmd(fmdev, INT_MASK_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
tx->tx_frq = (unsigned long)freq_to_set;
fmdbg("tx: freq_to_set %ld\n", (long int)tx->tx_frq);
chanl_index = freq_to_set / 10;
/* Set current tuner channel */
payload = chanl_index;
ret = fmc_send_cmd(fmdev, CHANL_SET, REG_WR, &payload,
sizeof(payload), NULL, NULL);
if (ret < 0)
return ret;
fm_tx_set_pwr_lvl(fmdev, tx->pwr_lvl);
fm_tx_set_preemph_filter(fmdev, tx->preemph);
tx->audio_io = 0x01; /* I2S */
set_audio_io(fmdev);
enable_xmit(fmdev, 0x01); /* Enable transmission */
tx->aud_mode = FM_STEREO_MODE;
tx->rds.flag = FM_RDS_DISABLE;
return 0;
}
| gpl-2.0 |
CheckYourScreen/Arsenic.Kernel | net/netfilter/xt_osf.c | 7982 | 10051 | /*
* Copyright (c) 2003+ Evgeniy Polyakov <zbr@ioremap.net>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/if.h>
#include <linux/inetdevice.h>
#include <linux/ip.h>
#include <linux/list.h>
#include <linux/rculist.h>
#include <linux/skbuff.h>
#include <linux/slab.h>
#include <linux/tcp.h>
#include <net/ip.h>
#include <net/tcp.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/x_tables.h>
#include <net/netfilter/nf_log.h>
#include <linux/netfilter/xt_osf.h>
struct xt_osf_finger {
struct rcu_head rcu_head;
struct list_head finger_entry;
struct xt_osf_user_finger finger;
};
enum osf_fmatch_states {
/* Packet does not match the fingerprint */
FMATCH_WRONG = 0,
/* Packet matches the fingerprint */
FMATCH_OK,
/* Options do not match the fingerprint, but header does */
FMATCH_OPT_WRONG,
};
/*
* Indexed by dont-fragment bit.
* It is the only constant value in the fingerprint.
*/
static struct list_head xt_osf_fingers[2];
static const struct nla_policy xt_osf_policy[OSF_ATTR_MAX + 1] = {
[OSF_ATTR_FINGER] = { .len = sizeof(struct xt_osf_user_finger) },
};
static int xt_osf_add_callback(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const osf_attrs[])
{
struct xt_osf_user_finger *f;
struct xt_osf_finger *kf = NULL, *sf;
int err = 0;
if (!osf_attrs[OSF_ATTR_FINGER])
return -EINVAL;
if (!(nlh->nlmsg_flags & NLM_F_CREATE))
return -EINVAL;
f = nla_data(osf_attrs[OSF_ATTR_FINGER]);
kf = kmalloc(sizeof(struct xt_osf_finger), GFP_KERNEL);
if (!kf)
return -ENOMEM;
memcpy(&kf->finger, f, sizeof(struct xt_osf_user_finger));
list_for_each_entry(sf, &xt_osf_fingers[!!f->df], finger_entry) {
if (memcmp(&sf->finger, f, sizeof(struct xt_osf_user_finger)))
continue;
kfree(kf);
kf = NULL;
if (nlh->nlmsg_flags & NLM_F_EXCL)
err = -EEXIST;
break;
}
/*
* We are protected by nfnl mutex.
*/
if (kf)
list_add_tail_rcu(&kf->finger_entry, &xt_osf_fingers[!!f->df]);
return err;
}
static int xt_osf_remove_callback(struct sock *ctnl, struct sk_buff *skb,
const struct nlmsghdr *nlh,
const struct nlattr * const osf_attrs[])
{
struct xt_osf_user_finger *f;
struct xt_osf_finger *sf;
int err = -ENOENT;
if (!osf_attrs[OSF_ATTR_FINGER])
return -EINVAL;
f = nla_data(osf_attrs[OSF_ATTR_FINGER]);
list_for_each_entry(sf, &xt_osf_fingers[!!f->df], finger_entry) {
if (memcmp(&sf->finger, f, sizeof(struct xt_osf_user_finger)))
continue;
/*
* We are protected by nfnl mutex.
*/
list_del_rcu(&sf->finger_entry);
kfree_rcu(sf, rcu_head);
err = 0;
break;
}
return err;
}
static const struct nfnl_callback xt_osf_nfnetlink_callbacks[OSF_MSG_MAX] = {
[OSF_MSG_ADD] = {
.call = xt_osf_add_callback,
.attr_count = OSF_ATTR_MAX,
.policy = xt_osf_policy,
},
[OSF_MSG_REMOVE] = {
.call = xt_osf_remove_callback,
.attr_count = OSF_ATTR_MAX,
.policy = xt_osf_policy,
},
};
static const struct nfnetlink_subsystem xt_osf_nfnetlink = {
.name = "osf",
.subsys_id = NFNL_SUBSYS_OSF,
.cb_count = OSF_MSG_MAX,
.cb = xt_osf_nfnetlink_callbacks,
};
static inline int xt_osf_ttl(const struct sk_buff *skb, const struct xt_osf_info *info,
unsigned char f_ttl)
{
const struct iphdr *ip = ip_hdr(skb);
if (info->flags & XT_OSF_TTL) {
if (info->ttl == XT_OSF_TTL_TRUE)
return ip->ttl == f_ttl;
if (info->ttl == XT_OSF_TTL_NOCHECK)
return 1;
else if (ip->ttl <= f_ttl)
return 1;
else {
struct in_device *in_dev = __in_dev_get_rcu(skb->dev);
int ret = 0;
for_ifa(in_dev) {
if (inet_ifa_match(ip->saddr, ifa)) {
ret = (ip->ttl == f_ttl);
break;
}
}
endfor_ifa(in_dev);
return ret;
}
}
return ip->ttl == f_ttl;
}
static bool
xt_osf_match_packet(const struct sk_buff *skb, struct xt_action_param *p)
{
const struct xt_osf_info *info = p->matchinfo;
const struct iphdr *ip = ip_hdr(skb);
const struct tcphdr *tcp;
struct tcphdr _tcph;
int fmatch = FMATCH_WRONG, fcount = 0;
unsigned int optsize = 0, check_WSS = 0;
u16 window, totlen, mss = 0;
bool df;
const unsigned char *optp = NULL, *_optp = NULL;
unsigned char opts[MAX_IPOPTLEN];
const struct xt_osf_finger *kf;
const struct xt_osf_user_finger *f;
if (!info)
return false;
tcp = skb_header_pointer(skb, ip_hdrlen(skb), sizeof(struct tcphdr), &_tcph);
if (!tcp)
return false;
if (!tcp->syn)
return false;
totlen = ntohs(ip->tot_len);
df = ntohs(ip->frag_off) & IP_DF;
window = ntohs(tcp->window);
if (tcp->doff * 4 > sizeof(struct tcphdr)) {
optsize = tcp->doff * 4 - sizeof(struct tcphdr);
_optp = optp = skb_header_pointer(skb, ip_hdrlen(skb) +
sizeof(struct tcphdr), optsize, opts);
}
rcu_read_lock();
list_for_each_entry_rcu(kf, &xt_osf_fingers[df], finger_entry) {
f = &kf->finger;
if (!(info->flags & XT_OSF_LOG) && strcmp(info->genre, f->genre))
continue;
optp = _optp;
fmatch = FMATCH_WRONG;
if (totlen == f->ss && xt_osf_ttl(skb, info, f->ttl)) {
int foptsize, optnum;
/*
* Should not happen if userspace parser was written correctly.
*/
if (f->wss.wc >= OSF_WSS_MAX)
continue;
/* Check options */
foptsize = 0;
for (optnum = 0; optnum < f->opt_num; ++optnum)
foptsize += f->opt[optnum].length;
if (foptsize > MAX_IPOPTLEN ||
optsize > MAX_IPOPTLEN ||
optsize != foptsize)
continue;
check_WSS = f->wss.wc;
for (optnum = 0; optnum < f->opt_num; ++optnum) {
if (f->opt[optnum].kind == (*optp)) {
__u32 len = f->opt[optnum].length;
const __u8 *optend = optp + len;
int loop_cont = 0;
fmatch = FMATCH_OK;
switch (*optp) {
case OSFOPT_MSS:
mss = optp[3];
mss <<= 8;
mss |= optp[2];
mss = ntohs(mss);
break;
case OSFOPT_TS:
loop_cont = 1;
break;
}
optp = optend;
} else
fmatch = FMATCH_OPT_WRONG;
if (fmatch != FMATCH_OK)
break;
}
if (fmatch != FMATCH_OPT_WRONG) {
fmatch = FMATCH_WRONG;
switch (check_WSS) {
case OSF_WSS_PLAIN:
if (f->wss.val == 0 || window == f->wss.val)
fmatch = FMATCH_OK;
break;
case OSF_WSS_MSS:
/*
* Some smart modems decrease mangle MSS to
* SMART_MSS_2, so we check standard, decreased
* and the one provided in the fingerprint MSS
* values.
*/
#define SMART_MSS_1 1460
#define SMART_MSS_2 1448
if (window == f->wss.val * mss ||
window == f->wss.val * SMART_MSS_1 ||
window == f->wss.val * SMART_MSS_2)
fmatch = FMATCH_OK;
break;
case OSF_WSS_MTU:
if (window == f->wss.val * (mss + 40) ||
window == f->wss.val * (SMART_MSS_1 + 40) ||
window == f->wss.val * (SMART_MSS_2 + 40))
fmatch = FMATCH_OK;
break;
case OSF_WSS_MODULO:
if ((window % f->wss.val) == 0)
fmatch = FMATCH_OK;
break;
}
}
if (fmatch != FMATCH_OK)
continue;
fcount++;
if (info->flags & XT_OSF_LOG)
nf_log_packet(p->family, p->hooknum, skb,
p->in, p->out, NULL,
"%s [%s:%s] : %pI4:%d -> %pI4:%d hops=%d\n",
f->genre, f->version, f->subtype,
&ip->saddr, ntohs(tcp->source),
&ip->daddr, ntohs(tcp->dest),
f->ttl - ip->ttl);
if ((info->flags & XT_OSF_LOG) &&
info->loglevel == XT_OSF_LOGLEVEL_FIRST)
break;
}
}
rcu_read_unlock();
if (!fcount && (info->flags & XT_OSF_LOG))
nf_log_packet(p->family, p->hooknum, skb, p->in, p->out, NULL,
"Remote OS is not known: %pI4:%u -> %pI4:%u\n",
&ip->saddr, ntohs(tcp->source),
&ip->daddr, ntohs(tcp->dest));
if (fcount)
fmatch = FMATCH_OK;
return fmatch == FMATCH_OK;
}
static struct xt_match xt_osf_match = {
.name = "osf",
.revision = 0,
.family = NFPROTO_IPV4,
.proto = IPPROTO_TCP,
.hooks = (1 << NF_INET_LOCAL_IN) |
(1 << NF_INET_PRE_ROUTING) |
(1 << NF_INET_FORWARD),
.match = xt_osf_match_packet,
.matchsize = sizeof(struct xt_osf_info),
.me = THIS_MODULE,
};
static int __init xt_osf_init(void)
{
int err = -EINVAL;
int i;
for (i=0; i<ARRAY_SIZE(xt_osf_fingers); ++i)
INIT_LIST_HEAD(&xt_osf_fingers[i]);
err = nfnetlink_subsys_register(&xt_osf_nfnetlink);
if (err < 0) {
pr_err("Failed to register OSF nsfnetlink helper (%d)\n", err);
goto err_out_exit;
}
err = xt_register_match(&xt_osf_match);
if (err) {
pr_err("Failed to register OS fingerprint "
"matching module (%d)\n", err);
goto err_out_remove;
}
return 0;
err_out_remove:
nfnetlink_subsys_unregister(&xt_osf_nfnetlink);
err_out_exit:
return err;
}
static void __exit xt_osf_fini(void)
{
struct xt_osf_finger *f;
int i;
nfnetlink_subsys_unregister(&xt_osf_nfnetlink);
xt_unregister_match(&xt_osf_match);
rcu_read_lock();
for (i=0; i<ARRAY_SIZE(xt_osf_fingers); ++i) {
list_for_each_entry_rcu(f, &xt_osf_fingers[i], finger_entry) {
list_del_rcu(&f->finger_entry);
kfree_rcu(f, rcu_head);
}
}
rcu_read_unlock();
rcu_barrier();
}
module_init(xt_osf_init);
module_exit(xt_osf_fini);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Evgeniy Polyakov <zbr@ioremap.net>");
MODULE_DESCRIPTION("Passive OS fingerprint matching.");
MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_OSF);
| gpl-2.0 |
k2wl/kernel-gt-i9082-stock-based | drivers/message/fusion/mptctl.c | 7982 | 88566 | /*
* linux/drivers/message/fusion/mptctl.c
* mpt Ioctl driver.
* For use with LSI PCI chip/adapters
* running LSI Fusion MPT (Message Passing Technology) firmware.
*
* Copyright (c) 1999-2008 LSI Corporation
* (mailto:DL-MPTFusionLinux@lsi.com)
*
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
NO WARRANTY
THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
solely responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to
the risks and costs of program errors, damage to or loss of data,
programs or equipment, and unavailability or interruption of operations.
DISCLAIMER OF LIABILITY
NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/delay.h> /* for mdelay */
#include <linux/miscdevice.h>
#include <linux/mutex.h>
#include <linux/compat.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_cmnd.h>
#include <scsi/scsi_device.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#define COPYRIGHT "Copyright (c) 1999-2008 LSI Corporation"
#define MODULEAUTHOR "LSI Corporation"
#include "mptbase.h"
#include "mptctl.h"
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#define my_NAME "Fusion MPT misc device (ioctl) driver"
#define my_VERSION MPT_LINUX_VERSION_COMMON
#define MYNAM "mptctl"
MODULE_AUTHOR(MODULEAUTHOR);
MODULE_DESCRIPTION(my_NAME);
MODULE_LICENSE("GPL");
MODULE_VERSION(my_VERSION);
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static DEFINE_MUTEX(mpctl_mutex);
static u8 mptctl_id = MPT_MAX_PROTOCOL_DRIVERS;
static u8 mptctl_taskmgmt_id = MPT_MAX_PROTOCOL_DRIVERS;
static DECLARE_WAIT_QUEUE_HEAD ( mptctl_wait );
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
struct buflist {
u8 *kptr;
int len;
};
/*
* Function prototypes. Called from OS entry point mptctl_ioctl.
* arg contents specific to function.
*/
static int mptctl_fw_download(unsigned long arg);
static int mptctl_getiocinfo(unsigned long arg, unsigned int cmd);
static int mptctl_gettargetinfo(unsigned long arg);
static int mptctl_readtest(unsigned long arg);
static int mptctl_mpt_command(unsigned long arg);
static int mptctl_eventquery(unsigned long arg);
static int mptctl_eventenable(unsigned long arg);
static int mptctl_eventreport(unsigned long arg);
static int mptctl_replace_fw(unsigned long arg);
static int mptctl_do_reset(unsigned long arg);
static int mptctl_hp_hostinfo(unsigned long arg, unsigned int cmd);
static int mptctl_hp_targetinfo(unsigned long arg);
static int mptctl_probe(struct pci_dev *, const struct pci_device_id *);
static void mptctl_remove(struct pci_dev *);
#ifdef CONFIG_COMPAT
static long compat_mpctl_ioctl(struct file *f, unsigned cmd, unsigned long arg);
#endif
/*
* Private function calls.
*/
static int mptctl_do_mpt_command(struct mpt_ioctl_command karg, void __user *mfPtr);
static int mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen);
static MptSge_t *kbuf_alloc_2_sgl(int bytes, u32 dir, int sge_offset, int *frags,
struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc);
static void kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma,
struct buflist *buflist, MPT_ADAPTER *ioc);
/*
* Reset Handler cleanup function
*/
static int mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase);
/*
* Event Handler function
*/
static int mptctl_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply);
static struct fasync_struct *async_queue=NULL;
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* Scatter gather list (SGL) sizes and limits...
*/
//#define MAX_SCSI_FRAGS 9
#define MAX_FRAGS_SPILL1 9
#define MAX_FRAGS_SPILL2 15
#define FRAGS_PER_BUCKET (MAX_FRAGS_SPILL2 + 1)
//#define MAX_CHAIN_FRAGS 64
//#define MAX_CHAIN_FRAGS (15+15+15+16)
#define MAX_CHAIN_FRAGS (4 * MAX_FRAGS_SPILL2 + 1)
// Define max sg LIST bytes ( == (#frags + #chains) * 8 bytes each)
// Works out to: 592d bytes! (9+1)*8 + 4*(15+1)*8
// ^----------------- 80 + 512
#define MAX_SGL_BYTES ((MAX_FRAGS_SPILL1 + 1 + (4 * FRAGS_PER_BUCKET)) * 8)
/* linux only seems to ever give 128kB MAX contiguous (GFP_USER) mem bytes */
#define MAX_KMALLOC_SZ (128*1024)
#define MPT_IOCTL_DEFAULT_TIMEOUT 10 /* Default timeout value (seconds) */
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/**
* mptctl_syscall_down - Down the MPT adapter syscall semaphore.
* @ioc: Pointer to MPT adapter
* @nonblock: boolean, non-zero if O_NONBLOCK is set
*
* All of the ioctl commands can potentially sleep, which is illegal
* with a spinlock held, thus we perform mutual exclusion here.
*
* Returns negative errno on error, or zero for success.
*/
static inline int
mptctl_syscall_down(MPT_ADAPTER *ioc, int nonblock)
{
int rc = 0;
if (nonblock) {
if (!mutex_trylock(&ioc->ioctl_cmds.mutex))
rc = -EAGAIN;
} else {
if (mutex_lock_interruptible(&ioc->ioctl_cmds.mutex))
rc = -ERESTARTSYS;
}
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* This is the callback for any message we have posted. The message itself
* will be returned to the message pool when we return from the IRQ
*
* This runs in irq context so be short and sweet.
*/
static int
mptctl_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *req, MPT_FRAME_HDR *reply)
{
char *sense_data;
int req_index;
int sz;
if (!req)
return 0;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "completing mpi function "
"(0x%02X), req=%p, reply=%p\n", ioc->name, req->u.hdr.Function,
req, reply));
/*
* Handling continuation of the same reply. Processing the first
* reply, and eating the other replys that come later.
*/
if (ioc->ioctl_cmds.msg_context != req->u.hdr.MsgContext)
goto out_continuation;
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
if (!reply)
goto out;
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_RF_VALID;
sz = min(ioc->reply_sz, 4*reply->u.reply.MsgLength);
memcpy(ioc->ioctl_cmds.reply, reply, sz);
if (reply->u.reply.IOCStatus || reply->u.reply.IOCLogInfo)
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"iocstatus (0x%04X), loginfo (0x%08X)\n", ioc->name,
le16_to_cpu(reply->u.reply.IOCStatus),
le32_to_cpu(reply->u.reply.IOCLogInfo)));
if ((req->u.hdr.Function == MPI_FUNCTION_SCSI_IO_REQUEST) ||
(req->u.hdr.Function ==
MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)) {
if (reply->u.sreply.SCSIStatus || reply->u.sreply.SCSIState)
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"scsi_status (0x%02x), scsi_state (0x%02x), "
"tag = (0x%04x), transfer_count (0x%08x)\n", ioc->name,
reply->u.sreply.SCSIStatus,
reply->u.sreply.SCSIState,
le16_to_cpu(reply->u.sreply.TaskTag),
le32_to_cpu(reply->u.sreply.TransferCount)));
if (reply->u.sreply.SCSIState &
MPI_SCSI_STATE_AUTOSENSE_VALID) {
sz = req->u.scsireq.SenseBufferLength;
req_index =
le16_to_cpu(req->u.frame.hwhdr.msgctxu.fld.req_idx);
sense_data = ((u8 *)ioc->sense_buf_pool +
(req_index * MPT_SENSE_BUFFER_ALLOC));
memcpy(ioc->ioctl_cmds.sense, sense_data, sz);
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_SENSE_VALID;
}
}
out:
/* We are done, issue wake up
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_PENDING) {
if (req->u.hdr.Function == MPI_FUNCTION_SCSI_TASK_MGMT) {
mpt_clear_taskmgmt_in_progress_flag(ioc);
ioc->ioctl_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->ioctl_cmds.done);
if (ioc->bus_type == SAS)
ioc->schedule_target_reset(ioc);
} else {
ioc->ioctl_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->ioctl_cmds.done);
}
}
out_continuation:
if (reply && (reply->u.reply.MsgFlags &
MPI_MSGFLAGS_CONTINUATION_REPLY))
return 0;
return 1;
}
static int
mptctl_taskmgmt_reply(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *mr)
{
if (!mf)
return 0;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt completed (mf=%p, mr=%p)\n",
ioc->name, mf, mr));
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_COMMAND_GOOD;
if (!mr)
goto out;
ioc->taskmgmt_cmds.status |= MPT_MGMT_STATUS_RF_VALID;
memcpy(ioc->taskmgmt_cmds.reply, mr,
min(MPT_DEFAULT_FRAME_SIZE, 4 * mr->u.reply.MsgLength));
out:
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_PENDING) {
mpt_clear_taskmgmt_in_progress_flag(ioc);
ioc->taskmgmt_cmds.status &= ~MPT_MGMT_STATUS_PENDING;
complete(&ioc->taskmgmt_cmds.done);
if (ioc->bus_type == SAS)
ioc->schedule_target_reset(ioc);
return 1;
}
return 0;
}
static int
mptctl_do_taskmgmt(MPT_ADAPTER *ioc, u8 tm_type, u8 bus_id, u8 target_id)
{
MPT_FRAME_HDR *mf;
SCSITaskMgmt_t *pScsiTm;
SCSITaskMgmtReply_t *pScsiTmReply;
int ii;
int retval;
unsigned long timeout;
unsigned long time_count;
u16 iocstatus;
mutex_lock(&ioc->taskmgmt_cmds.mutex);
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) {
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
return -EPERM;
}
retval = 0;
mf = mpt_get_msg_frame(mptctl_taskmgmt_id, ioc);
if (mf == NULL) {
dtmprintk(ioc,
printk(MYIOC_s_WARN_FMT "TaskMgmt, no msg frames!!\n",
ioc->name));
mpt_clear_taskmgmt_in_progress_flag(ioc);
retval = -ENOMEM;
goto tm_done;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "TaskMgmt request (mf=%p)\n",
ioc->name, mf));
pScsiTm = (SCSITaskMgmt_t *) mf;
memset(pScsiTm, 0, sizeof(SCSITaskMgmt_t));
pScsiTm->Function = MPI_FUNCTION_SCSI_TASK_MGMT;
pScsiTm->TaskType = tm_type;
if ((tm_type == MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS) &&
(ioc->bus_type == FC))
pScsiTm->MsgFlags =
MPI_SCSITASKMGMT_MSGFLAGS_LIPRESET_RESET_OPTION;
pScsiTm->TargetID = target_id;
pScsiTm->Bus = bus_id;
pScsiTm->ChainOffset = 0;
pScsiTm->Reserved = 0;
pScsiTm->Reserved1 = 0;
pScsiTm->TaskMsgContext = 0;
for (ii= 0; ii < 8; ii++)
pScsiTm->LUN[ii] = 0;
for (ii=0; ii < 7; ii++)
pScsiTm->Reserved2[ii] = 0;
switch (ioc->bus_type) {
case FC:
timeout = 40;
break;
case SAS:
timeout = 30;
break;
case SPI:
default:
timeout = 10;
break;
}
dtmprintk(ioc,
printk(MYIOC_s_DEBUG_FMT "TaskMgmt type=%d timeout=%ld\n",
ioc->name, tm_type, timeout));
INITIALIZE_MGMT_STATUS(ioc->taskmgmt_cmds.status)
time_count = jiffies;
if ((ioc->facts.IOCCapabilities & MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q) &&
(ioc->facts.MsgVersion >= MPI_VERSION_01_05))
mpt_put_msg_frame_hi_pri(mptctl_taskmgmt_id, ioc, mf);
else {
retval = mpt_send_handshake_request(mptctl_taskmgmt_id, ioc,
sizeof(SCSITaskMgmt_t), (u32 *)pScsiTm, CAN_SLEEP);
if (retval != 0) {
dfailprintk(ioc,
printk(MYIOC_s_ERR_FMT
"TaskMgmt send_handshake FAILED!"
" (ioc %p, mf %p, rc=%d) \n", ioc->name,
ioc, mf, retval));
mpt_free_msg_frame(ioc, mf);
mpt_clear_taskmgmt_in_progress_flag(ioc);
goto tm_done;
}
}
/* Now wait for the command to complete */
ii = wait_for_completion_timeout(&ioc->taskmgmt_cmds.done, timeout*HZ);
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
mpt_free_msg_frame(ioc, mf);
mpt_clear_taskmgmt_in_progress_flag(ioc);
if (ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET)
retval = 0;
else
retval = -1; /* return failure */
goto tm_done;
}
if (!(ioc->taskmgmt_cmds.status & MPT_MGMT_STATUS_RF_VALID)) {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
retval = -1; /* return failure */
goto tm_done;
}
pScsiTmReply = (SCSITaskMgmtReply_t *) ioc->taskmgmt_cmds.reply;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt fw_channel = %d, fw_id = %d, task_type=0x%02X, "
"iocstatus=0x%04X\n\tloginfo=0x%08X, response_code=0x%02X, "
"term_cmnds=%d\n", ioc->name, pScsiTmReply->Bus,
pScsiTmReply->TargetID, tm_type,
le16_to_cpu(pScsiTmReply->IOCStatus),
le32_to_cpu(pScsiTmReply->IOCLogInfo),
pScsiTmReply->ResponseCode,
le32_to_cpu(pScsiTmReply->TerminationCount)));
iocstatus = le16_to_cpu(pScsiTmReply->IOCStatus) & MPI_IOCSTATUS_MASK;
if (iocstatus == MPI_IOCSTATUS_SCSI_TASK_TERMINATED ||
iocstatus == MPI_IOCSTATUS_SCSI_IOC_TERMINATED ||
iocstatus == MPI_IOCSTATUS_SUCCESS)
retval = 0;
else {
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"TaskMgmt failed\n", ioc->name));
retval = -1; /* return failure */
}
tm_done:
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
CLEAR_MGMT_STATUS(ioc->taskmgmt_cmds.status)
return retval;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* mptctl_timeout_expired
*
* Expecting an interrupt, however timed out.
*
*/
static void
mptctl_timeout_expired(MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf)
{
unsigned long flags;
int ret_val = -1;
SCSIIORequest_t *scsi_req = (SCSIIORequest_t *) mf;
u8 function = mf->u.hdr.Function;
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT ": %s\n",
ioc->name, __func__));
if (mpt_fwfault_debug)
mpt_halt_firmware(ioc);
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
CLEAR_MGMT_PENDING_STATUS(ioc->ioctl_cmds.status)
mpt_free_msg_frame(ioc, mf);
return;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
CLEAR_MGMT_PENDING_STATUS(ioc->ioctl_cmds.status)
if (ioc->bus_type == SAS) {
if (function == MPI_FUNCTION_SCSI_IO_REQUEST)
ret_val = mptctl_do_taskmgmt(ioc,
MPI_SCSITASKMGMT_TASKTYPE_TARGET_RESET,
scsi_req->Bus, scsi_req->TargetID);
else if (function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH)
ret_val = mptctl_do_taskmgmt(ioc,
MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
scsi_req->Bus, 0);
if (!ret_val)
return;
} else {
if ((function == MPI_FUNCTION_SCSI_IO_REQUEST) ||
(function == MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH))
ret_val = mptctl_do_taskmgmt(ioc,
MPI_SCSITASKMGMT_TASKTYPE_RESET_BUS,
scsi_req->Bus, 0);
if (!ret_val)
return;
}
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Calling Reset! \n",
ioc->name));
mpt_Soft_Hard_ResetHandler(ioc, CAN_SLEEP);
mpt_free_msg_frame(ioc, mf);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* mptctl_ioc_reset
*
* Clean-up functionality. Used only if there has been a
* reload of the FW due.
*
*/
static int
mptctl_ioc_reset(MPT_ADAPTER *ioc, int reset_phase)
{
switch(reset_phase) {
case MPT_IOC_SETUP_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_SETUP_RESET\n", ioc->name, __func__));
break;
case MPT_IOC_PRE_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_PRE_RESET\n", ioc->name, __func__));
break;
case MPT_IOC_POST_RESET:
dtmprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"%s: MPT_IOC_POST_RESET\n", ioc->name, __func__));
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_PENDING) {
ioc->ioctl_cmds.status |= MPT_MGMT_STATUS_DID_IOCRESET;
complete(&ioc->ioctl_cmds.done);
}
break;
default:
break;
}
return 1;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* ASYNC Event Notification Support */
static int
mptctl_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply)
{
u8 event;
event = le32_to_cpu(pEvReply->Event) & 0xFF;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "%s() called\n",
ioc->name, __func__));
if(async_queue == NULL)
return 1;
/* Raise SIGIO for persistent events.
* TODO - this define is not in MPI spec yet,
* but they plan to set it to 0x21
*/
if (event == 0x21 ) {
ioc->aen_event_read_flag=1;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "Raised SIGIO to application\n",
ioc->name));
devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
kill_fasync(&async_queue, SIGIO, POLL_IN);
return 1;
}
/* This flag is set after SIGIO was raised, and
* remains set until the application has read
* the event log via ioctl=MPTEVENTREPORT
*/
if(ioc->aen_event_read_flag)
return 1;
/* Signal only for the events that are
* requested for by the application
*/
if (ioc->events && (ioc->eventTypes & ( 1 << event))) {
ioc->aen_event_read_flag=1;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
devtverboseprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"Raised SIGIO to application\n", ioc->name));
kill_fasync(&async_queue, SIGIO, POLL_IN);
}
return 1;
}
static int
mptctl_release(struct inode *inode, struct file *filep)
{
fasync_helper(-1, filep, 0, &async_queue);
return 0;
}
static int
mptctl_fasync(int fd, struct file *filep, int mode)
{
MPT_ADAPTER *ioc;
int ret;
mutex_lock(&mpctl_mutex);
list_for_each_entry(ioc, &ioc_list, list)
ioc->aen_event_read_flag=0;
ret = fasync_helper(fd, filep, mode, &async_queue);
mutex_unlock(&mpctl_mutex);
return ret;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* MPT ioctl handler
* cmd - specify the particular IOCTL command to be issued
* arg - data specific to the command. Must not be null.
*/
static long
__mptctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
mpt_ioctl_header __user *uhdr = (void __user *) arg;
mpt_ioctl_header khdr;
int iocnum;
unsigned iocnumX;
int nonblock = (file->f_flags & O_NONBLOCK);
int ret;
MPT_ADAPTER *iocp = NULL;
if (copy_from_user(&khdr, uhdr, sizeof(khdr))) {
printk(KERN_ERR MYNAM "%s::mptctl_ioctl() @%d - "
"Unable to copy mpt_ioctl_header data @ %p\n",
__FILE__, __LINE__, uhdr);
return -EFAULT;
}
ret = -ENXIO; /* (-6) No such device or address */
/* Verify intended MPT adapter - set iocnum and the adapter
* pointer (iocp)
*/
iocnumX = khdr.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL))
return -ENODEV;
if (!iocp->active) {
printk(KERN_DEBUG MYNAM "%s::mptctl_ioctl() @%d - Controller disabled.\n",
__FILE__, __LINE__);
return -EFAULT;
}
/* Handle those commands that are just returning
* information stored in the driver.
* These commands should never time out and are unaffected
* by TM and FW reloads.
*/
if ((cmd & ~IOCSIZE_MASK) == (MPTIOCINFO & ~IOCSIZE_MASK)) {
return mptctl_getiocinfo(arg, _IOC_SIZE(cmd));
} else if (cmd == MPTTARGETINFO) {
return mptctl_gettargetinfo(arg);
} else if (cmd == MPTTEST) {
return mptctl_readtest(arg);
} else if (cmd == MPTEVENTQUERY) {
return mptctl_eventquery(arg);
} else if (cmd == MPTEVENTENABLE) {
return mptctl_eventenable(arg);
} else if (cmd == MPTEVENTREPORT) {
return mptctl_eventreport(arg);
} else if (cmd == MPTFWREPLACE) {
return mptctl_replace_fw(arg);
}
/* All of these commands require an interrupt or
* are unknown/illegal.
*/
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
if (cmd == MPTFWDOWNLOAD)
ret = mptctl_fw_download(arg);
else if (cmd == MPTCOMMAND)
ret = mptctl_mpt_command(arg);
else if (cmd == MPTHARDRESET)
ret = mptctl_do_reset(arg);
else if ((cmd & ~IOCSIZE_MASK) == (HP_GETHOSTINFO & ~IOCSIZE_MASK))
ret = mptctl_hp_hostinfo(arg, _IOC_SIZE(cmd));
else if (cmd == HP_GETTARGETINFO)
ret = mptctl_hp_targetinfo(arg);
else
ret = -EINVAL;
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static long
mptctl_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long ret;
mutex_lock(&mpctl_mutex);
ret = __mptctl_ioctl(file, cmd, arg);
mutex_unlock(&mpctl_mutex);
return ret;
}
static int mptctl_do_reset(unsigned long arg)
{
struct mpt_ioctl_diag_reset __user *urinfo = (void __user *) arg;
struct mpt_ioctl_diag_reset krinfo;
MPT_ADAPTER *iocp;
if (copy_from_user(&krinfo, urinfo, sizeof(struct mpt_ioctl_diag_reset))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_reset - "
"Unable to copy mpt_ioctl_diag_reset struct @ %p\n",
__FILE__, __LINE__, urinfo);
return -EFAULT;
}
if (mpt_verify_adapter(krinfo.hdr.iocnum, &iocp) < 0) {
printk(KERN_DEBUG MYNAM "%s@%d::mptctl_do_reset - ioc%d not found!\n",
__FILE__, __LINE__, krinfo.hdr.iocnum);
return -ENODEV; /* (-6) No such device or address */
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "mptctl_do_reset called.\n",
iocp->name));
if (mpt_HardResetHandler(iocp, CAN_SLEEP) != 0) {
printk (MYIOC_s_ERR_FMT "%s@%d::mptctl_do_reset - reset failed.\n",
iocp->name, __FILE__, __LINE__);
return -1;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* MPT FW download function. Cast the arg into the mpt_fw_xfer structure.
* This structure contains: iocnum, firmware length (bytes),
* pointer to user space memory where the fw image is stored.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENXIO if no such device
* -EAGAIN if resource problem
* -ENOMEM if no memory for SGE
* -EMLINK if too many chain buffers required
* -EBADRQC if adapter does not support FW download
* -EBUSY if adapter is busy
* -ENOMSG if FW upload returned bad status
*/
static int
mptctl_fw_download(unsigned long arg)
{
struct mpt_fw_xfer __user *ufwdl = (void __user *) arg;
struct mpt_fw_xfer kfwdl;
if (copy_from_user(&kfwdl, ufwdl, sizeof(struct mpt_fw_xfer))) {
printk(KERN_ERR MYNAM "%s@%d::_ioctl_fwdl - "
"Unable to copy mpt_fw_xfer struct @ %p\n",
__FILE__, __LINE__, ufwdl);
return -EFAULT;
}
return mptctl_do_fw_download(kfwdl.iocnum, kfwdl.bufp, kfwdl.fwlen);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* FW Download engine.
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENXIO if no such device
* -EAGAIN if resource problem
* -ENOMEM if no memory for SGE
* -EMLINK if too many chain buffers required
* -EBADRQC if adapter does not support FW download
* -EBUSY if adapter is busy
* -ENOMSG if FW upload returned bad status
*/
static int
mptctl_do_fw_download(int ioc, char __user *ufwbuf, size_t fwlen)
{
FWDownload_t *dlmsg;
MPT_FRAME_HDR *mf;
MPT_ADAPTER *iocp;
FWDownloadTCSGE_t *ptsge;
MptSge_t *sgl, *sgIn;
char *sgOut;
struct buflist *buflist;
struct buflist *bl;
dma_addr_t sgl_dma;
int ret;
int numfrags = 0;
int maxfrags;
int n = 0;
u32 sgdir;
u32 nib;
int fw_bytes_copied = 0;
int i;
int sge_offset = 0;
u16 iocstat;
pFWDownloadReply_t ReplyMsg = NULL;
unsigned long timeleft;
if (mpt_verify_adapter(ioc, &iocp) < 0) {
printk(KERN_DEBUG MYNAM "ioctl_fwdl - ioc%d not found!\n",
ioc);
return -ENODEV; /* (-6) No such device or address */
} else {
/* Valid device. Get a message frame and construct the FW download message.
*/
if ((mf = mpt_get_msg_frame(mptctl_id, iocp)) == NULL)
return -EAGAIN;
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT
"mptctl_do_fwdl called. mptctl_id = %xh.\n", iocp->name, mptctl_id));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.bufp = %p\n",
iocp->name, ufwbuf));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.fwlen = %d\n",
iocp->name, (int)fwlen));
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: kfwdl.ioc = %04xh\n",
iocp->name, ioc));
dlmsg = (FWDownload_t*) mf;
ptsge = (FWDownloadTCSGE_t *) &dlmsg->SGL;
sgOut = (char *) (ptsge + 1);
/*
* Construct f/w download request
*/
dlmsg->ImageType = MPI_FW_DOWNLOAD_ITYPE_FW;
dlmsg->Reserved = 0;
dlmsg->ChainOffset = 0;
dlmsg->Function = MPI_FUNCTION_FW_DOWNLOAD;
dlmsg->Reserved1[0] = dlmsg->Reserved1[1] = dlmsg->Reserved1[2] = 0;
if (iocp->facts.MsgVersion >= MPI_VERSION_01_05)
dlmsg->MsgFlags = MPI_FW_DOWNLOAD_MSGFLGS_LAST_SEGMENT;
else
dlmsg->MsgFlags = 0;
/* Set up the Transaction SGE.
*/
ptsge->Reserved = 0;
ptsge->ContextSize = 0;
ptsge->DetailsLength = 12;
ptsge->Flags = MPI_SGE_FLAGS_TRANSACTION_ELEMENT;
ptsge->Reserved_0100_Checksum = 0;
ptsge->ImageOffset = 0;
ptsge->ImageSize = cpu_to_le32(fwlen);
/* Add the SGL
*/
/*
* Need to kmalloc area(s) for holding firmware image bytes.
* But we need to do it piece meal, using a proper
* scatter gather list (with 128kB MAX hunks).
*
* A practical limit here might be # of sg hunks that fit into
* a single IOC request frame; 12 or 8 (see below), so:
* For FC9xx: 12 x 128kB == 1.5 mB (max)
* For C1030: 8 x 128kB == 1 mB (max)
* We could support chaining, but things get ugly(ier:)
*
* Set the sge_offset to the start of the sgl (bytes).
*/
sgdir = 0x04000000; /* IOC will READ from sys mem */
sge_offset = sizeof(MPIHeader_t) + sizeof(FWDownloadTCSGE_t);
if ((sgl = kbuf_alloc_2_sgl(fwlen, sgdir, sge_offset,
&numfrags, &buflist, &sgl_dma, iocp)) == NULL)
return -ENOMEM;
/*
* We should only need SGL with 2 simple_32bit entries (up to 256 kB)
* for FC9xx f/w image, but calculate max number of sge hunks
* we can fit into a request frame, and limit ourselves to that.
* (currently no chain support)
* maxfrags = (Request Size - FWdownload Size ) / Size of 32 bit SGE
* Request maxfrags
* 128 12
* 96 8
* 64 4
*/
maxfrags = (iocp->req_sz - sizeof(MPIHeader_t) -
sizeof(FWDownloadTCSGE_t))
/ iocp->SGE_size;
if (numfrags > maxfrags) {
ret = -EMLINK;
goto fwdl_out;
}
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "DbG: sgl buffer = %p, sgfrags = %d\n",
iocp->name, sgl, numfrags));
/*
* Parse SG list, copying sgl itself,
* plus f/w image hunks from user space as we go...
*/
ret = -EFAULT;
sgIn = sgl;
bl = buflist;
for (i=0; i < numfrags; i++) {
/* Get the SGE type: 0 - TCSGE, 3 - Chain, 1 - Simple SGE
* Skip everything but Simple. If simple, copy from
* user space into kernel space.
* Note: we should not have anything but Simple as
* Chain SGE are illegal.
*/
nib = (sgIn->FlagsLength & 0x30000000) >> 28;
if (nib == 0 || nib == 3) {
;
} else if (sgIn->Address) {
iocp->add_sge(sgOut, sgIn->FlagsLength, sgIn->Address);
n++;
if (copy_from_user(bl->kptr, ufwbuf+fw_bytes_copied, bl->len)) {
printk(MYIOC_s_ERR_FMT "%s@%d::_ioctl_fwdl - "
"Unable to copy f/w buffer hunk#%d @ %p\n",
iocp->name, __FILE__, __LINE__, n, ufwbuf);
goto fwdl_out;
}
fw_bytes_copied += bl->len;
}
sgIn++;
bl++;
sgOut += iocp->SGE_size;
}
DBG_DUMP_FW_DOWNLOAD(iocp, (u32 *)mf, numfrags);
/*
* Finally, perform firmware download.
*/
ReplyMsg = NULL;
SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, dlmsg->MsgContext);
INITIALIZE_MGMT_STATUS(iocp->ioctl_cmds.status)
mpt_put_msg_frame(mptctl_id, iocp, mf);
/* Now wait for the command to complete */
retry_wait:
timeleft = wait_for_completion_timeout(&iocp->ioctl_cmds.done, HZ*60);
if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
ret = -ETIME;
printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__);
if (iocp->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
mpt_free_msg_frame(iocp, mf);
goto fwdl_out;
}
if (!timeleft) {
printk(MYIOC_s_WARN_FMT
"FW download timeout, doorbell=0x%08x\n",
iocp->name, mpt_GetIocState(iocp, 0));
mptctl_timeout_expired(iocp, mf);
} else
goto retry_wait;
goto fwdl_out;
}
if (!(iocp->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)) {
printk(MYIOC_s_WARN_FMT "%s: failed\n", iocp->name, __func__);
mpt_free_msg_frame(iocp, mf);
ret = -ENODATA;
goto fwdl_out;
}
if (sgl)
kfree_sgl(sgl, sgl_dma, buflist, iocp);
ReplyMsg = (pFWDownloadReply_t)iocp->ioctl_cmds.reply;
iocstat = le16_to_cpu(ReplyMsg->IOCStatus) & MPI_IOCSTATUS_MASK;
if (iocstat == MPI_IOCSTATUS_SUCCESS) {
printk(MYIOC_s_INFO_FMT "F/W update successful!\n", iocp->name);
return 0;
} else if (iocstat == MPI_IOCSTATUS_INVALID_FUNCTION) {
printk(MYIOC_s_WARN_FMT "Hmmm... F/W download not supported!?!\n",
iocp->name);
printk(MYIOC_s_WARN_FMT "(time to go bang on somebodies door)\n",
iocp->name);
return -EBADRQC;
} else if (iocstat == MPI_IOCSTATUS_BUSY) {
printk(MYIOC_s_WARN_FMT "IOC_BUSY!\n", iocp->name);
printk(MYIOC_s_WARN_FMT "(try again later?)\n", iocp->name);
return -EBUSY;
} else {
printk(MYIOC_s_WARN_FMT "ioctl_fwdl() returned [bad] status = %04xh\n",
iocp->name, iocstat);
printk(MYIOC_s_WARN_FMT "(bad VooDoo)\n", iocp->name);
return -ENOMSG;
}
return 0;
fwdl_out:
CLEAR_MGMT_STATUS(iocp->ioctl_cmds.status);
SET_MGMT_MSG_CONTEXT(iocp->ioctl_cmds.msg_context, 0);
kfree_sgl(sgl, sgl_dma, buflist, iocp);
return ret;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* SGE Allocation routine
*
* Inputs: bytes - number of bytes to be transferred
* sgdir - data direction
* sge_offset - offset (in bytes) from the start of the request
* frame to the first SGE
* ioc - pointer to the mptadapter
* Outputs: frags - number of scatter gather elements
* blp - point to the buflist pointer
* sglbuf_dma - pointer to the (dma) sgl
* Returns: Null if failes
* pointer to the (virtual) sgl if successful.
*/
static MptSge_t *
kbuf_alloc_2_sgl(int bytes, u32 sgdir, int sge_offset, int *frags,
struct buflist **blp, dma_addr_t *sglbuf_dma, MPT_ADAPTER *ioc)
{
MptSge_t *sglbuf = NULL; /* pointer to array of SGE */
/* and chain buffers */
struct buflist *buflist = NULL; /* kernel routine */
MptSge_t *sgl;
int numfrags = 0;
int fragcnt = 0;
int alloc_sz = min(bytes,MAX_KMALLOC_SZ); // avoid kernel warning msg!
int bytes_allocd = 0;
int this_alloc;
dma_addr_t pa; // phys addr
int i, buflist_ent;
int sg_spill = MAX_FRAGS_SPILL1;
int dir;
/* initialization */
*frags = 0;
*blp = NULL;
/* Allocate and initialize an array of kernel
* structures for the SG elements.
*/
i = MAX_SGL_BYTES / 8;
buflist = kzalloc(i, GFP_USER);
if (!buflist)
return NULL;
buflist_ent = 0;
/* Allocate a single block of memory to store the sg elements and
* the chain buffers. The calling routine is responsible for
* copying the data in this array into the correct place in the
* request and chain buffers.
*/
sglbuf = pci_alloc_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf_dma);
if (sglbuf == NULL)
goto free_and_fail;
if (sgdir & 0x04000000)
dir = PCI_DMA_TODEVICE;
else
dir = PCI_DMA_FROMDEVICE;
/* At start:
* sgl = sglbuf = point to beginning of sg buffer
* buflist_ent = 0 = first kernel structure
* sg_spill = number of SGE that can be written before the first
* chain element.
*
*/
sgl = sglbuf;
sg_spill = ((ioc->req_sz - sge_offset)/ioc->SGE_size) - 1;
while (bytes_allocd < bytes) {
this_alloc = min(alloc_sz, bytes-bytes_allocd);
buflist[buflist_ent].len = this_alloc;
buflist[buflist_ent].kptr = pci_alloc_consistent(ioc->pcidev,
this_alloc,
&pa);
if (buflist[buflist_ent].kptr == NULL) {
alloc_sz = alloc_sz / 2;
if (alloc_sz == 0) {
printk(MYIOC_s_WARN_FMT "-SG: No can do - "
"not enough memory! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "-SG: (freeing %d frags)\n",
ioc->name, numfrags);
goto free_and_fail;
}
continue;
} else {
dma_addr_t dma_addr;
bytes_allocd += this_alloc;
sgl->FlagsLength = (0x10000000|sgdir|this_alloc);
dma_addr = pci_map_single(ioc->pcidev,
buflist[buflist_ent].kptr, this_alloc, dir);
sgl->Address = dma_addr;
fragcnt++;
numfrags++;
sgl++;
buflist_ent++;
}
if (bytes_allocd >= bytes)
break;
/* Need to chain? */
if (fragcnt == sg_spill) {
printk(MYIOC_s_WARN_FMT
"-SG: No can do - " "Chain required! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "(freeing %d frags)\n", ioc->name, numfrags);
goto free_and_fail;
}
/* overflow check... */
if (numfrags*8 > MAX_SGL_BYTES){
/* GRRRRR... */
printk(MYIOC_s_WARN_FMT "-SG: No can do - "
"too many SG frags! :-(\n", ioc->name);
printk(MYIOC_s_WARN_FMT "-SG: (freeing %d frags)\n",
ioc->name, numfrags);
goto free_and_fail;
}
}
/* Last sge fixup: set LE+eol+eob bits */
sgl[-1].FlagsLength |= 0xC1000000;
*frags = numfrags;
*blp = buflist;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: kbuf_alloc_2_sgl() - "
"%d SG frags generated!\n", ioc->name, numfrags));
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: kbuf_alloc_2_sgl() - "
"last (big) alloc_sz=%d\n", ioc->name, alloc_sz));
return sglbuf;
free_and_fail:
if (sglbuf != NULL) {
for (i = 0; i < numfrags; i++) {
dma_addr_t dma_addr;
u8 *kptr;
int len;
if ((sglbuf[i].FlagsLength >> 24) == 0x30)
continue;
dma_addr = sglbuf[i].Address;
kptr = buflist[i].kptr;
len = buflist[i].len;
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
}
pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sglbuf, *sglbuf_dma);
}
kfree(buflist);
return NULL;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* Routine to free the SGL elements.
*/
static void
kfree_sgl(MptSge_t *sgl, dma_addr_t sgl_dma, struct buflist *buflist, MPT_ADAPTER *ioc)
{
MptSge_t *sg = sgl;
struct buflist *bl = buflist;
u32 nib;
int dir;
int n = 0;
if (sg->FlagsLength & 0x04000000)
dir = PCI_DMA_TODEVICE;
else
dir = PCI_DMA_FROMDEVICE;
nib = (sg->FlagsLength & 0xF0000000) >> 28;
while (! (nib & 0x4)) { /* eob */
/* skip ignore/chain. */
if (nib == 0 || nib == 3) {
;
} else if (sg->Address) {
dma_addr_t dma_addr;
void *kptr;
int len;
dma_addr = sg->Address;
kptr = bl->kptr;
len = bl->len;
pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
n++;
}
sg++;
bl++;
nib = (le32_to_cpu(sg->FlagsLength) & 0xF0000000) >> 28;
}
/* we're at eob! */
if (sg->Address) {
dma_addr_t dma_addr;
void *kptr;
int len;
dma_addr = sg->Address;
kptr = bl->kptr;
len = bl->len;
pci_unmap_single(ioc->pcidev, dma_addr, len, dir);
pci_free_consistent(ioc->pcidev, len, kptr, dma_addr);
n++;
}
pci_free_consistent(ioc->pcidev, MAX_SGL_BYTES, sgl, sgl_dma);
kfree(buflist);
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "-SG: Free'd 1 SGL buf + %d kbufs!\n",
ioc->name, n));
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_getiocinfo - Query the host adapter for IOC information.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_getiocinfo (unsigned long arg, unsigned int data_size)
{
struct mpt_ioctl_iocinfo __user *uarg = (void __user *) arg;
struct mpt_ioctl_iocinfo *karg;
MPT_ADAPTER *ioc;
struct pci_dev *pdev;
int iocnum;
unsigned int port;
int cim_rev;
u8 revision;
struct scsi_device *sdev;
VirtDevice *vdevice;
/* Add of PCI INFO results in unaligned access for
* IA64 and Sparc. Reset long to int. Return no PCI
* data for obsolete format.
*/
if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev0))
cim_rev = 0;
else if (data_size == sizeof(struct mpt_ioctl_iocinfo_rev1))
cim_rev = 1;
else if (data_size == sizeof(struct mpt_ioctl_iocinfo))
cim_rev = 2;
else if (data_size == (sizeof(struct mpt_ioctl_iocinfo_rev0)+12))
cim_rev = 0; /* obsolete */
else
return -EFAULT;
karg = kmalloc(data_size, GFP_KERNEL);
if (karg == NULL) {
printk(KERN_ERR MYNAM "%s::mpt_ioctl_iocinfo() @%d - no memory available!\n",
__FILE__, __LINE__);
return -ENOMEM;
}
if (copy_from_user(karg, uarg, data_size)) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_getiocinfo - "
"Unable to read in mpt_ioctl_iocinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
kfree(karg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg->hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_getiocinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
kfree(karg);
return -ENODEV;
}
/* Verify the data transfer size is correct. */
if (karg->hdr.maxDataSize != data_size) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - "
"Structure size mismatch. Command not completed.\n",
ioc->name, __FILE__, __LINE__);
kfree(karg);
return -EFAULT;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_getiocinfo called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
if (ioc->bus_type == SAS)
karg->adapterType = MPT_IOCTL_INTERFACE_SAS;
else if (ioc->bus_type == FC)
karg->adapterType = MPT_IOCTL_INTERFACE_FC;
else
karg->adapterType = MPT_IOCTL_INTERFACE_SCSI;
if (karg->hdr.port > 1) {
kfree(karg);
return -EINVAL;
}
port = karg->hdr.port;
karg->port = port;
pdev = (struct pci_dev *) ioc->pcidev;
karg->pciId = pdev->device;
pci_read_config_byte(pdev, PCI_CLASS_REVISION, &revision);
karg->hwRev = revision;
karg->subSystemDevice = pdev->subsystem_device;
karg->subSystemVendor = pdev->subsystem_vendor;
if (cim_rev == 1) {
/* Get the PCI bus, device, and function numbers for the IOC
*/
karg->pciInfo.u.bits.busNumber = pdev->bus->number;
karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
} else if (cim_rev == 2) {
/* Get the PCI bus, device, function and segment ID numbers
for the IOC */
karg->pciInfo.u.bits.busNumber = pdev->bus->number;
karg->pciInfo.u.bits.deviceNumber = PCI_SLOT( pdev->devfn );
karg->pciInfo.u.bits.functionNumber = PCI_FUNC( pdev->devfn );
karg->pciInfo.segmentID = pci_domain_nr(pdev->bus);
}
/* Get number of devices
*/
karg->numDevices = 0;
if (ioc->sh) {
shost_for_each_device(sdev, ioc->sh) {
vdevice = sdev->hostdata;
if (vdevice == NULL || vdevice->vtarget == NULL)
continue;
if (vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT)
continue;
karg->numDevices++;
}
}
/* Set the BIOS and FW Version
*/
karg->FWVersion = ioc->facts.FWVersion.Word;
karg->BIOSVersion = ioc->biosVersion;
/* Set the Version Strings.
*/
strncpy (karg->driverVersion, MPT_LINUX_PACKAGE_NAME, MPT_IOCTL_VERSION_LENGTH);
karg->driverVersion[MPT_IOCTL_VERSION_LENGTH-1]='\0';
karg->busChangeEvent = 0;
karg->hostId = ioc->pfacts[port].PortSCSIID;
karg->rsvd[0] = karg->rsvd[1] = 0;
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, karg, data_size)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_getiocinfo - "
"Unable to write out mpt_ioctl_iocinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
kfree(karg);
return -EFAULT;
}
kfree(karg);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_gettargetinfo - Query the host adapter for target information.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_gettargetinfo (unsigned long arg)
{
struct mpt_ioctl_targetinfo __user *uarg = (void __user *) arg;
struct mpt_ioctl_targetinfo karg;
MPT_ADAPTER *ioc;
VirtDevice *vdevice;
char *pmem;
int *pdata;
int iocnum;
int numDevices = 0;
int lun;
int maxWordsLeft;
int numBytes;
u8 port;
struct scsi_device *sdev;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_targetinfo))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_gettargetinfo - "
"Unable to read in mpt_ioctl_targetinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_gettargetinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_gettargetinfo called.\n",
ioc->name));
/* Get the port number and set the maximum number of bytes
* in the returned structure.
* Ignore the port setting.
*/
numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
maxWordsLeft = numBytes/sizeof(int);
port = karg.hdr.port;
if (maxWordsLeft <= 0) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n",
ioc->name, __FILE__, __LINE__);
return -ENOMEM;
}
/* Fill in the data and return the structure to the calling
* program
*/
/* struct mpt_ioctl_targetinfo does not contain sufficient space
* for the target structures so when the IOCTL is called, there is
* not sufficient stack space for the structure. Allocate memory,
* populate the memory, copy back to the user, then free memory.
* targetInfo format:
* bits 31-24: reserved
* 23-16: LUN
* 15- 8: Bus Number
* 7- 0: Target ID
*/
pmem = kzalloc(numBytes, GFP_KERNEL);
if (!pmem) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo() - no memory available!\n",
ioc->name, __FILE__, __LINE__);
return -ENOMEM;
}
pdata = (int *) pmem;
/* Get number of devices
*/
if (ioc->sh){
shost_for_each_device(sdev, ioc->sh) {
if (!maxWordsLeft)
continue;
vdevice = sdev->hostdata;
if (vdevice == NULL || vdevice->vtarget == NULL)
continue;
if (vdevice->vtarget->tflags &
MPT_TARGET_FLAGS_RAID_COMPONENT)
continue;
lun = (vdevice->vtarget->raidVolume) ? 0x80 : vdevice->lun;
*pdata = (((u8)lun << 16) + (vdevice->vtarget->channel << 8) +
(vdevice->vtarget->id ));
pdata++;
numDevices++;
--maxWordsLeft;
}
}
karg.numDevices = numDevices;
/* Copy part of the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg,
sizeof(struct mpt_ioctl_targetinfo))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
kfree(pmem);
return -EFAULT;
}
/* Copy the remaining data from kernel memory to user memory
*/
if (copy_to_user(uarg->targetInfo, pmem, numBytes)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_gettargetinfo - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, pdata);
kfree(pmem);
return -EFAULT;
}
kfree(pmem);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* MPT IOCTL Test function.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_readtest (unsigned long arg)
{
struct mpt_ioctl_test __user *uarg = (void __user *) arg;
struct mpt_ioctl_test karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_test))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_readtest - "
"Unable to read in mpt_ioctl_test struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_readtest() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_readtest called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
#ifdef MFCNT
karg.chip_type = ioc->mfcnt;
#else
karg.chip_type = ioc->pcidev->device;
#endif
strncpy (karg.name, ioc->name, MPT_MAX_NAME);
karg.name[MPT_MAX_NAME-1]='\0';
strncpy (karg.product, ioc->prod_name, MPT_PRODUCT_LENGTH);
karg.product[MPT_PRODUCT_LENGTH-1]='\0';
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_test))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_readtest - "
"Unable to write out mpt_ioctl_test struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_eventquery - Query the host adapter for the event types
* that are being logged.
* @arg: User space argument
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
*/
static int
mptctl_eventquery (unsigned long arg)
{
struct mpt_ioctl_eventquery __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventquery karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventquery))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventquery - "
"Unable to read in mpt_ioctl_eventquery struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventquery() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventquery called.\n",
ioc->name));
karg.eventEntries = MPTCTL_EVENT_LOG_SIZE;
karg.eventTypes = ioc->eventTypes;
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(struct mpt_ioctl_eventquery))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventquery - "
"Unable to write out mpt_ioctl_eventquery struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_eventenable (unsigned long arg)
{
struct mpt_ioctl_eventenable __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventenable karg;
MPT_ADAPTER *ioc;
int iocnum;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventenable))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventenable - "
"Unable to read in mpt_ioctl_eventenable struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventenable() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventenable called.\n",
ioc->name));
if (ioc->events == NULL) {
/* Have not yet allocated memory - do so now.
*/
int sz = MPTCTL_EVENT_LOG_SIZE * sizeof(MPT_IOCTL_EVENTS);
ioc->events = kzalloc(sz, GFP_KERNEL);
if (!ioc->events) {
printk(MYIOC_s_ERR_FMT
": ERROR - Insufficient memory to add adapter!\n",
ioc->name);
return -ENOMEM;
}
ioc->alloc_total += sz;
ioc->eventContext = 0;
}
/* Update the IOC event logging flag.
*/
ioc->eventTypes = karg.eventTypes;
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_eventreport (unsigned long arg)
{
struct mpt_ioctl_eventreport __user *uarg = (void __user *) arg;
struct mpt_ioctl_eventreport karg;
MPT_ADAPTER *ioc;
int iocnum;
int numBytes, maxEvents, max;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_eventreport))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_eventreport - "
"Unable to read in mpt_ioctl_eventreport struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_eventreport() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_eventreport called.\n",
ioc->name));
numBytes = karg.hdr.maxDataSize - sizeof(mpt_ioctl_header);
maxEvents = numBytes/sizeof(MPT_IOCTL_EVENTS);
max = MPTCTL_EVENT_LOG_SIZE < maxEvents ? MPTCTL_EVENT_LOG_SIZE : maxEvents;
/* If fewer than 1 event is requested, there must have
* been some type of error.
*/
if ((max < 1) || !ioc->events)
return -ENODATA;
/* reset this flag so SIGIO can restart */
ioc->aen_event_read_flag=0;
/* Copy the data from kernel memory to user memory
*/
numBytes = max * sizeof(MPT_IOCTL_EVENTS);
if (copy_to_user(uarg->eventData, ioc->events, numBytes)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_eventreport - "
"Unable to write out mpt_ioctl_eventreport struct @ %p\n",
ioc->name, __FILE__, __LINE__, ioc->events);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int
mptctl_replace_fw (unsigned long arg)
{
struct mpt_ioctl_replace_fw __user *uarg = (void __user *) arg;
struct mpt_ioctl_replace_fw karg;
MPT_ADAPTER *ioc;
int iocnum;
int newFwSize;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_replace_fw))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_replace_fw - "
"Unable to read in mpt_ioctl_replace_fw struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_replace_fw() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_replace_fw called.\n",
ioc->name));
/* If caching FW, Free the old FW image
*/
if (ioc->cached_fw == NULL)
return 0;
mpt_free_fw_memory(ioc);
/* Allocate memory for the new FW image
*/
newFwSize = karg.newImageSize;
if (newFwSize & 0x01)
newFwSize += 1;
if (newFwSize & 0x02)
newFwSize += 2;
mpt_alloc_fw_memory(ioc, newFwSize);
if (ioc->cached_fw == NULL)
return -ENOMEM;
/* Copy the data from user memory to kernel space
*/
if (copy_from_user(ioc->cached_fw, uarg->newImage, newFwSize)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_replace_fw - "
"Unable to read in mpt_ioctl_replace_fw image "
"@ %p\n", ioc->name, __FILE__, __LINE__, uarg);
mpt_free_fw_memory(ioc);
return -EFAULT;
}
/* Update IOCFactsReply
*/
ioc->facts.FWImageSize = newFwSize;
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* MPT IOCTL MPTCOMMAND function.
* Cast the arg into the mpt_ioctl_mpt_command structure.
*
* Outputs: None.
* Return: 0 if successful
* -EBUSY if previous command timeout and IOC reset is not complete.
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_mpt_command (unsigned long arg)
{
struct mpt_ioctl_command __user *uarg = (void __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *ioc;
int iocnum;
int rc;
if (copy_from_user(&karg, uarg, sizeof(struct mpt_ioctl_command))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_mpt_command - "
"Unable to read in mpt_ioctl_command struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_mpt_command() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
rc = mptctl_do_mpt_command (karg, &uarg->MF);
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Worker routine for the IOCTL MPTCOMMAND and MPTCOMMAND32 (sparc) commands.
*
* Outputs: None.
* Return: 0 if successful
* -EBUSY if previous command timeout and IOC reset is not complete.
* -EFAULT if data unavailable
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
* -EPERM if SCSI I/O and target is untagged
*/
static int
mptctl_do_mpt_command (struct mpt_ioctl_command karg, void __user *mfPtr)
{
MPT_ADAPTER *ioc;
MPT_FRAME_HDR *mf = NULL;
MPIHeader_t *hdr;
char *psge;
struct buflist bufIn; /* data In buffer */
struct buflist bufOut; /* data Out buffer */
dma_addr_t dma_addr_in;
dma_addr_t dma_addr_out;
int sgSize = 0; /* Num SG elements */
int iocnum, flagsLength;
int sz, rc = 0;
int msgContext;
u16 req_idx;
ulong timeout;
unsigned long timeleft;
struct scsi_device *sdev;
unsigned long flags;
u8 function;
/* bufIn and bufOut are used for user to kernel space transfers
*/
bufIn.kptr = bufOut.kptr = NULL;
bufIn.len = bufOut.len = 0;
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_do_mpt_command() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
spin_lock_irqsave(&ioc->taskmgmt_lock, flags);
if (ioc->ioc_reset_in_progress) {
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
printk(KERN_ERR MYNAM "%s@%d::mptctl_do_mpt_command - "
"Busy with diagnostic reset\n", __FILE__, __LINE__);
return -EBUSY;
}
spin_unlock_irqrestore(&ioc->taskmgmt_lock, flags);
/* Verify that the final request frame will not be too large.
*/
sz = karg.dataSgeOffset * 4;
if (karg.dataInSize > 0)
sz += ioc->SGE_size;
if (karg.dataOutSize > 0)
sz += ioc->SGE_size;
if (sz > ioc->req_sz) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Request frame too large (%d) maximum (%d)\n",
ioc->name, __FILE__, __LINE__, sz, ioc->req_sz);
return -EFAULT;
}
/* Get a free request frame and save the message context.
*/
if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL)
return -EAGAIN;
hdr = (MPIHeader_t *) mf;
msgContext = le32_to_cpu(hdr->MsgContext);
req_idx = le16_to_cpu(mf->u.frame.hwhdr.msgctxu.fld.req_idx);
/* Copy the request frame
* Reset the saved message context.
* Request frame in user space
*/
if (copy_from_user(mf, mfPtr, karg.dataSgeOffset * 4)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to read MF from mpt_ioctl_command struct @ %p\n",
ioc->name, __FILE__, __LINE__, mfPtr);
function = -1;
rc = -EFAULT;
goto done_free_mem;
}
hdr->MsgContext = cpu_to_le32(msgContext);
function = hdr->Function;
/* Verify that this request is allowed.
*/
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "sending mpi function (0x%02X), req=%p\n",
ioc->name, hdr->Function, mf));
switch (function) {
case MPI_FUNCTION_IOC_FACTS:
case MPI_FUNCTION_PORT_FACTS:
karg.dataOutSize = karg.dataInSize = 0;
break;
case MPI_FUNCTION_CONFIG:
{
Config_t *config_frame;
config_frame = (Config_t *)mf;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "\ttype=0x%02x ext_type=0x%02x "
"number=0x%02x action=0x%02x\n", ioc->name,
config_frame->Header.PageType,
config_frame->ExtPageType,
config_frame->Header.PageNumber,
config_frame->Action));
break;
}
case MPI_FUNCTION_FC_COMMON_TRANSPORT_SEND:
case MPI_FUNCTION_FC_EX_LINK_SRVC_SEND:
case MPI_FUNCTION_FW_UPLOAD:
case MPI_FUNCTION_SCSI_ENCLOSURE_PROCESSOR:
case MPI_FUNCTION_FW_DOWNLOAD:
case MPI_FUNCTION_FC_PRIMITIVE_SEND:
case MPI_FUNCTION_TOOLBOX:
case MPI_FUNCTION_SAS_IO_UNIT_CONTROL:
break;
case MPI_FUNCTION_SCSI_IO_REQUEST:
if (ioc->sh) {
SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
int qtag = MPI_SCSIIO_CONTROL_UNTAGGED;
int scsidir = 0;
int dataSize;
u32 id;
id = (ioc->devices_per_bus == 0) ? 256 : ioc->devices_per_bus;
if (pScsiReq->TargetID > id) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Target ID out of bounds. \n",
ioc->name, __FILE__, __LINE__);
rc = -ENODEV;
goto done_free_mem;
}
if (pScsiReq->Bus >= ioc->number_of_buses) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Target Bus out of bounds. \n",
ioc->name, __FILE__, __LINE__);
rc = -ENODEV;
goto done_free_mem;
}
pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH;
pScsiReq->MsgFlags |= mpt_msg_flags(ioc);
/* verify that app has not requested
* more sense data than driver
* can provide, if so, reset this parameter
* set the sense buffer pointer low address
* update the control field to specify Q type
*/
if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
else
pScsiReq->SenseBufferLength = karg.maxSenseBytes;
pScsiReq->SenseBufferLowAddr =
cpu_to_le32(ioc->sense_buf_low_dma
+ (req_idx * MPT_SENSE_BUFFER_ALLOC));
shost_for_each_device(sdev, ioc->sh) {
struct scsi_target *starget = scsi_target(sdev);
VirtTarget *vtarget = starget->hostdata;
if (vtarget == NULL)
continue;
if ((pScsiReq->TargetID == vtarget->id) &&
(pScsiReq->Bus == vtarget->channel) &&
(vtarget->tflags & MPT_TARGET_FLAGS_Q_YES))
qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
}
/* Have the IOCTL driver set the direction based
* on the dataOutSize (ordering issue with Sparc).
*/
if (karg.dataOutSize > 0) {
scsidir = MPI_SCSIIO_CONTROL_WRITE;
dataSize = karg.dataOutSize;
} else {
scsidir = MPI_SCSIIO_CONTROL_READ;
dataSize = karg.dataInSize;
}
pScsiReq->Control = cpu_to_le32(scsidir | qtag);
pScsiReq->DataLength = cpu_to_le32(dataSize);
} else {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_SMP_PASSTHROUGH:
/* Check mf->PassthruFlags to determine if
* transfer is ImmediateMode or not.
* Immediate mode returns data in the ReplyFrame.
* Else, we are sending request and response data
* in two SGLs at the end of the mf.
*/
break;
case MPI_FUNCTION_SATA_PASSTHROUGH:
if (!ioc->sh) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_RAID_ACTION:
/* Just add a SGE
*/
break;
case MPI_FUNCTION_RAID_SCSI_IO_PASSTHROUGH:
if (ioc->sh) {
SCSIIORequest_t *pScsiReq = (SCSIIORequest_t *) mf;
int qtag = MPI_SCSIIO_CONTROL_SIMPLEQ;
int scsidir = MPI_SCSIIO_CONTROL_READ;
int dataSize;
pScsiReq->MsgFlags &= ~MPI_SCSIIO_MSGFLGS_SENSE_WIDTH;
pScsiReq->MsgFlags |= mpt_msg_flags(ioc);
/* verify that app has not requested
* more sense data than driver
* can provide, if so, reset this parameter
* set the sense buffer pointer low address
* update the control field to specify Q type
*/
if (karg.maxSenseBytes > MPT_SENSE_BUFFER_SIZE)
pScsiReq->SenseBufferLength = MPT_SENSE_BUFFER_SIZE;
else
pScsiReq->SenseBufferLength = karg.maxSenseBytes;
pScsiReq->SenseBufferLowAddr =
cpu_to_le32(ioc->sense_buf_low_dma
+ (req_idx * MPT_SENSE_BUFFER_ALLOC));
/* All commands to physical devices are tagged
*/
/* Have the IOCTL driver set the direction based
* on the dataOutSize (ordering issue with Sparc).
*/
if (karg.dataOutSize > 0) {
scsidir = MPI_SCSIIO_CONTROL_WRITE;
dataSize = karg.dataOutSize;
} else {
scsidir = MPI_SCSIIO_CONTROL_READ;
dataSize = karg.dataInSize;
}
pScsiReq->Control = cpu_to_le32(scsidir | qtag);
pScsiReq->DataLength = cpu_to_le32(dataSize);
} else {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"SCSI driver is not loaded. \n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
break;
case MPI_FUNCTION_SCSI_TASK_MGMT:
{
SCSITaskMgmt_t *pScsiTm;
pScsiTm = (SCSITaskMgmt_t *)mf;
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT
"\tTaskType=0x%x MsgFlags=0x%x "
"TaskMsgContext=0x%x id=%d channel=%d\n",
ioc->name, pScsiTm->TaskType, le32_to_cpu
(pScsiTm->TaskMsgContext), pScsiTm->MsgFlags,
pScsiTm->TargetID, pScsiTm->Bus));
break;
}
case MPI_FUNCTION_IOC_INIT:
{
IOCInit_t *pInit = (IOCInit_t *) mf;
u32 high_addr, sense_high;
/* Verify that all entries in the IOC INIT match
* existing setup (and in LE format).
*/
if (sizeof(dma_addr_t) == sizeof(u64)) {
high_addr = cpu_to_le32((u32)((u64)ioc->req_frames_dma >> 32));
sense_high= cpu_to_le32((u32)((u64)ioc->sense_buf_pool_dma >> 32));
} else {
high_addr = 0;
sense_high= 0;
}
if ((pInit->Flags != 0) || (pInit->MaxDevices != ioc->facts.MaxDevices) ||
(pInit->MaxBuses != ioc->facts.MaxBuses) ||
(pInit->ReplyFrameSize != cpu_to_le16(ioc->reply_sz)) ||
(pInit->HostMfaHighAddr != high_addr) ||
(pInit->SenseBufferHighAddr != sense_high)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"IOC_INIT issued with 1 or more incorrect parameters. Rejected.\n",
ioc->name, __FILE__, __LINE__);
rc = -EFAULT;
goto done_free_mem;
}
}
break;
default:
/*
* MPI_FUNCTION_PORT_ENABLE
* MPI_FUNCTION_TARGET_CMD_BUFFER_POST
* MPI_FUNCTION_TARGET_ASSIST
* MPI_FUNCTION_TARGET_STATUS_SEND
* MPI_FUNCTION_TARGET_MODE_ABORT
* MPI_FUNCTION_IOC_MESSAGE_UNIT_RESET
* MPI_FUNCTION_IO_UNIT_RESET
* MPI_FUNCTION_HANDSHAKE
* MPI_FUNCTION_REPLY_FRAME_REMOVAL
* MPI_FUNCTION_EVENT_NOTIFICATION
* (driver handles event notification)
* MPI_FUNCTION_EVENT_ACK
*/
/* What to do with these??? CHECK ME!!!
MPI_FUNCTION_FC_LINK_SRVC_BUF_POST
MPI_FUNCTION_FC_LINK_SRVC_RSP
MPI_FUNCTION_FC_ABORT
MPI_FUNCTION_LAN_SEND
MPI_FUNCTION_LAN_RECEIVE
MPI_FUNCTION_LAN_RESET
*/
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Illegal request (function 0x%x) \n",
ioc->name, __FILE__, __LINE__, hdr->Function);
rc = -EFAULT;
goto done_free_mem;
}
/* Add the SGL ( at most one data in SGE and one data out SGE )
* In the case of two SGE's - the data out (write) will always
* preceede the data in (read) SGE. psgList is used to free the
* allocated memory.
*/
psge = (char *) (((int *) mf) + karg.dataSgeOffset);
flagsLength = 0;
if (karg.dataOutSize > 0)
sgSize ++;
if (karg.dataInSize > 0)
sgSize ++;
if (sgSize > 0) {
/* Set up the dataOut memory allocation */
if (karg.dataOutSize > 0) {
if (karg.dataInSize > 0) {
flagsLength = ( MPI_SGE_FLAGS_SIMPLE_ELEMENT |
MPI_SGE_FLAGS_END_OF_BUFFER |
MPI_SGE_FLAGS_DIRECTION)
<< MPI_SGE_FLAGS_SHIFT;
} else {
flagsLength = MPT_SGE_FLAGS_SSIMPLE_WRITE;
}
flagsLength |= karg.dataOutSize;
bufOut.len = karg.dataOutSize;
bufOut.kptr = pci_alloc_consistent(
ioc->pcidev, bufOut.len, &dma_addr_out);
if (bufOut.kptr == NULL) {
rc = -ENOMEM;
goto done_free_mem;
} else {
/* Set up this SGE.
* Copy to MF and to sglbuf
*/
ioc->add_sge(psge, flagsLength, dma_addr_out);
psge += ioc->SGE_size;
/* Copy user data to kernel space.
*/
if (copy_from_user(bufOut.kptr,
karg.dataOutBufPtr,
bufOut.len)) {
printk(MYIOC_s_ERR_FMT
"%s@%d::mptctl_do_mpt_command - Unable "
"to read user data "
"struct @ %p\n",
ioc->name, __FILE__, __LINE__,karg.dataOutBufPtr);
rc = -EFAULT;
goto done_free_mem;
}
}
}
if (karg.dataInSize > 0) {
flagsLength = MPT_SGE_FLAGS_SSIMPLE_READ;
flagsLength |= karg.dataInSize;
bufIn.len = karg.dataInSize;
bufIn.kptr = pci_alloc_consistent(ioc->pcidev,
bufIn.len, &dma_addr_in);
if (bufIn.kptr == NULL) {
rc = -ENOMEM;
goto done_free_mem;
} else {
/* Set up this SGE
* Copy to MF and to sglbuf
*/
ioc->add_sge(psge, flagsLength, dma_addr_in);
}
}
} else {
/* Add a NULL SGE
*/
ioc->add_sge(psge, flagsLength, (dma_addr_t) -1);
}
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, hdr->MsgContext);
INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status)
if (hdr->Function == MPI_FUNCTION_SCSI_TASK_MGMT) {
mutex_lock(&ioc->taskmgmt_cmds.mutex);
if (mpt_set_taskmgmt_in_progress_flag(ioc) != 0) {
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
DBG_DUMP_TM_REQUEST_FRAME(ioc, (u32 *)mf);
if ((ioc->facts.IOCCapabilities & MPI_IOCFACTS_CAPABILITY_HIGH_PRI_Q) &&
(ioc->facts.MsgVersion >= MPI_VERSION_01_05))
mpt_put_msg_frame_hi_pri(mptctl_id, ioc, mf);
else {
rc =mpt_send_handshake_request(mptctl_id, ioc,
sizeof(SCSITaskMgmt_t), (u32*)mf, CAN_SLEEP);
if (rc != 0) {
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT
"send_handshake FAILED! (ioc %p, mf %p)\n",
ioc->name, ioc, mf));
mpt_clear_taskmgmt_in_progress_flag(ioc);
rc = -ENODATA;
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
}
} else
mpt_put_msg_frame(mptctl_id, ioc, mf);
/* Now wait for the command to complete */
timeout = (karg.timeout > 0) ? karg.timeout : MPT_IOCTL_DEFAULT_TIMEOUT;
retry_wait:
timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done,
HZ*timeout);
if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
rc = -ETIME;
dfailprintk(ioc, printk(MYIOC_s_ERR_FMT "%s: TIMED OUT!\n",
ioc->name, __func__));
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
goto done_free_mem;
}
if (!timeleft) {
printk(MYIOC_s_WARN_FMT
"mpt cmd timeout, doorbell=0x%08x"
" function=0x%x\n",
ioc->name, mpt_GetIocState(ioc, 0), function);
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
mptctl_timeout_expired(ioc, mf);
mf = NULL;
} else
goto retry_wait;
goto done_free_mem;
}
if (function == MPI_FUNCTION_SCSI_TASK_MGMT)
mutex_unlock(&ioc->taskmgmt_cmds.mutex);
mf = NULL;
/* If a valid reply frame, copy to the user.
* Offset 2: reply length in U32's
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID) {
if (karg.maxReplyBytes < ioc->reply_sz) {
sz = min(karg.maxReplyBytes,
4*ioc->ioctl_cmds.reply[2]);
} else {
sz = min(ioc->reply_sz, 4*ioc->ioctl_cmds.reply[2]);
}
if (sz > 0) {
if (copy_to_user(karg.replyFrameBufPtr,
ioc->ioctl_cmds.reply, sz)){
printk(MYIOC_s_ERR_FMT
"%s@%d::mptctl_do_mpt_command - "
"Unable to write out reply frame %p\n",
ioc->name, __FILE__, __LINE__, karg.replyFrameBufPtr);
rc = -ENODATA;
goto done_free_mem;
}
}
}
/* If valid sense data, copy to user.
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_SENSE_VALID) {
sz = min(karg.maxSenseBytes, MPT_SENSE_BUFFER_SIZE);
if (sz > 0) {
if (copy_to_user(karg.senseDataPtr,
ioc->ioctl_cmds.sense, sz)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to write sense data to user %p\n",
ioc->name, __FILE__, __LINE__,
karg.senseDataPtr);
rc = -ENODATA;
goto done_free_mem;
}
}
}
/* If the overall status is _GOOD and data in, copy data
* to user.
*/
if ((ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD) &&
(karg.dataInSize > 0) && (bufIn.kptr)) {
if (copy_to_user(karg.dataInBufPtr,
bufIn.kptr, karg.dataInSize)) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_do_mpt_command - "
"Unable to write data to user %p\n",
ioc->name, __FILE__, __LINE__,
karg.dataInBufPtr);
rc = -ENODATA;
}
}
done_free_mem:
CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status)
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0);
/* Free the allocated memory.
*/
if (bufOut.kptr != NULL) {
pci_free_consistent(ioc->pcidev,
bufOut.len, (void *) bufOut.kptr, dma_addr_out);
}
if (bufIn.kptr != NULL) {
pci_free_consistent(ioc->pcidev,
bufIn.len, (void *) bufIn.kptr, dma_addr_in);
}
/* mf is null if command issued successfully
* otherwise, failure occurred after mf acquired.
*/
if (mf)
mpt_free_msg_frame(ioc, mf);
return rc;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Prototype Routine for the HOST INFO command.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -EBUSY if previous command timeout and IOC reset is not complete.
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_hp_hostinfo(unsigned long arg, unsigned int data_size)
{
hp_host_info_t __user *uarg = (void __user *) arg;
MPT_ADAPTER *ioc;
struct pci_dev *pdev;
char *pbuf=NULL;
dma_addr_t buf_dma;
hp_host_info_t karg;
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
int iocnum;
int rc, cim_rev;
ToolboxIstwiReadWriteRequest_t *IstwiRWRequest;
MPT_FRAME_HDR *mf = NULL;
MPIHeader_t *mpi_hdr;
unsigned long timeleft;
int retval;
/* Reset long to int. Should affect IA64 and SPARC only
*/
if (data_size == sizeof(hp_host_info_t))
cim_rev = 1;
else if (data_size == sizeof(hp_host_info_rev0_t))
cim_rev = 0; /* obsolete */
else
return -EFAULT;
if (copy_from_user(&karg, uarg, sizeof(hp_host_info_t))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_hp_host_info - "
"Unable to read in hp_host_info struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_hp_hostinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT ": mptctl_hp_hostinfo called.\n",
ioc->name));
/* Fill in the data and return the structure to the calling
* program
*/
pdev = (struct pci_dev *) ioc->pcidev;
karg.vendor = pdev->vendor;
karg.device = pdev->device;
karg.subsystem_id = pdev->subsystem_device;
karg.subsystem_vendor = pdev->subsystem_vendor;
karg.devfn = pdev->devfn;
karg.bus = pdev->bus->number;
/* Save the SCSI host no. if
* SCSI driver loaded
*/
if (ioc->sh != NULL)
karg.host_no = ioc->sh->host_no;
else
karg.host_no = -1;
/* Reformat the fw_version into a string
*/
karg.fw_version[0] = ioc->facts.FWVersion.Struct.Major >= 10 ?
((ioc->facts.FWVersion.Struct.Major / 10) + '0') : '0';
karg.fw_version[1] = (ioc->facts.FWVersion.Struct.Major % 10 ) + '0';
karg.fw_version[2] = '.';
karg.fw_version[3] = ioc->facts.FWVersion.Struct.Minor >= 10 ?
((ioc->facts.FWVersion.Struct.Minor / 10) + '0') : '0';
karg.fw_version[4] = (ioc->facts.FWVersion.Struct.Minor % 10 ) + '0';
karg.fw_version[5] = '.';
karg.fw_version[6] = ioc->facts.FWVersion.Struct.Unit >= 10 ?
((ioc->facts.FWVersion.Struct.Unit / 10) + '0') : '0';
karg.fw_version[7] = (ioc->facts.FWVersion.Struct.Unit % 10 ) + '0';
karg.fw_version[8] = '.';
karg.fw_version[9] = ioc->facts.FWVersion.Struct.Dev >= 10 ?
((ioc->facts.FWVersion.Struct.Dev / 10) + '0') : '0';
karg.fw_version[10] = (ioc->facts.FWVersion.Struct.Dev % 10 ) + '0';
karg.fw_version[11] = '\0';
/* Issue a config request to get the device serial number
*/
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_MANUFACTURING;
cfg.cfghdr.hdr = &hdr;
cfg.physAddr = -1;
cfg.pageAddr = 0;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0; /* read */
cfg.timeout = 10;
strncpy(karg.serial_number, " ", 24);
if (mpt_config(ioc, &cfg) == 0) {
if (cfg.cfghdr.hdr->PageLength > 0) {
/* Issue the second config page request */
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
pbuf = pci_alloc_consistent(ioc->pcidev, hdr.PageLength * 4, &buf_dma);
if (pbuf) {
cfg.physAddr = buf_dma;
if (mpt_config(ioc, &cfg) == 0) {
ManufacturingPage0_t *pdata = (ManufacturingPage0_t *) pbuf;
if (strlen(pdata->BoardTracerNumber) > 1) {
strncpy(karg.serial_number, pdata->BoardTracerNumber, 24);
karg.serial_number[24-1]='\0';
}
}
pci_free_consistent(ioc->pcidev, hdr.PageLength * 4, pbuf, buf_dma);
pbuf = NULL;
}
}
}
rc = mpt_GetIocState(ioc, 1);
switch (rc) {
case MPI_IOC_STATE_OPERATIONAL:
karg.ioc_status = HP_STATUS_OK;
break;
case MPI_IOC_STATE_FAULT:
karg.ioc_status = HP_STATUS_FAILED;
break;
case MPI_IOC_STATE_RESET:
case MPI_IOC_STATE_READY:
default:
karg.ioc_status = HP_STATUS_OTHER;
break;
}
karg.base_io_addr = pci_resource_start(pdev, 0);
if ((ioc->bus_type == SAS) || (ioc->bus_type == FC))
karg.bus_phys_width = HP_BUS_WIDTH_UNK;
else
karg.bus_phys_width = HP_BUS_WIDTH_16;
karg.hard_resets = 0;
karg.soft_resets = 0;
karg.timeouts = 0;
if (ioc->sh != NULL) {
MPT_SCSI_HOST *hd = shost_priv(ioc->sh);
if (hd && (cim_rev == 1)) {
karg.hard_resets = ioc->hard_resets;
karg.soft_resets = ioc->soft_resets;
karg.timeouts = ioc->timeouts;
}
}
/*
* Gather ISTWI(Industry Standard Two Wire Interface) Data
*/
if ((mf = mpt_get_msg_frame(mptctl_id, ioc)) == NULL) {
dfailprintk(ioc, printk(MYIOC_s_WARN_FMT
"%s, no msg frames!!\n", ioc->name, __func__));
goto out;
}
IstwiRWRequest = (ToolboxIstwiReadWriteRequest_t *)mf;
mpi_hdr = (MPIHeader_t *) mf;
memset(IstwiRWRequest,0,sizeof(ToolboxIstwiReadWriteRequest_t));
IstwiRWRequest->Function = MPI_FUNCTION_TOOLBOX;
IstwiRWRequest->Tool = MPI_TOOLBOX_ISTWI_READ_WRITE_TOOL;
IstwiRWRequest->MsgContext = mpi_hdr->MsgContext;
IstwiRWRequest->Flags = MPI_TB_ISTWI_FLAGS_READ;
IstwiRWRequest->NumAddressBytes = 0x01;
IstwiRWRequest->DataLength = cpu_to_le16(0x04);
if (pdev->devfn & 1)
IstwiRWRequest->DeviceAddr = 0xB2;
else
IstwiRWRequest->DeviceAddr = 0xB0;
pbuf = pci_alloc_consistent(ioc->pcidev, 4, &buf_dma);
if (!pbuf)
goto out;
ioc->add_sge((char *)&IstwiRWRequest->SGL,
(MPT_SGE_FLAGS_SSIMPLE_READ|4), buf_dma);
retval = 0;
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context,
IstwiRWRequest->MsgContext);
INITIALIZE_MGMT_STATUS(ioc->ioctl_cmds.status)
mpt_put_msg_frame(mptctl_id, ioc, mf);
retry_wait:
timeleft = wait_for_completion_timeout(&ioc->ioctl_cmds.done,
HZ*MPT_IOCTL_DEFAULT_TIMEOUT);
if (!(ioc->ioctl_cmds.status & MPT_MGMT_STATUS_COMMAND_GOOD)) {
retval = -ETIME;
printk(MYIOC_s_WARN_FMT "%s: failed\n", ioc->name, __func__);
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_DID_IOCRESET) {
mpt_free_msg_frame(ioc, mf);
goto out;
}
if (!timeleft) {
printk(MYIOC_s_WARN_FMT
"HOST INFO command timeout, doorbell=0x%08x\n",
ioc->name, mpt_GetIocState(ioc, 0));
mptctl_timeout_expired(ioc, mf);
} else
goto retry_wait;
goto out;
}
/*
*ISTWI Data Definition
* pbuf[0] = FW_VERSION = 0x4
* pbuf[1] = Bay Count = 6 or 4 or 2, depending on
* the config, you should be seeing one out of these three values
* pbuf[2] = Drive Installed Map = bit pattern depend on which
* bays have drives in them
* pbuf[3] = Checksum (0x100 = (byte0 + byte2 + byte3)
*/
if (ioc->ioctl_cmds.status & MPT_MGMT_STATUS_RF_VALID)
karg.rsvd = *(u32 *)pbuf;
out:
CLEAR_MGMT_STATUS(ioc->ioctl_cmds.status)
SET_MGMT_MSG_CONTEXT(ioc->ioctl_cmds.msg_context, 0);
if (pbuf)
pci_free_consistent(ioc->pcidev, 4, pbuf, buf_dma);
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(hp_host_info_t))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_hpgethostinfo - "
"Unable to write out hp_host_info @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/* Prototype Routine for the TARGET INFO command.
*
* Outputs: None.
* Return: 0 if successful
* -EFAULT if data unavailable
* -EBUSY if previous command timeout and IOC reset is not complete.
* -ENODEV if no such device/adapter
* -ETIME if timer expires
* -ENOMEM if memory allocation error
*/
static int
mptctl_hp_targetinfo(unsigned long arg)
{
hp_target_info_t __user *uarg = (void __user *) arg;
SCSIDevicePage0_t *pg0_alloc;
SCSIDevicePage3_t *pg3_alloc;
MPT_ADAPTER *ioc;
MPT_SCSI_HOST *hd = NULL;
hp_target_info_t karg;
int iocnum;
int data_sz;
dma_addr_t page_dma;
CONFIGPARMS cfg;
ConfigPageHeader_t hdr;
int tmp, np, rc = 0;
if (copy_from_user(&karg, uarg, sizeof(hp_target_info_t))) {
printk(KERN_ERR MYNAM "%s@%d::mptctl_hp_targetinfo - "
"Unable to read in hp_host_targetinfo struct @ %p\n",
__FILE__, __LINE__, uarg);
return -EFAULT;
}
if (((iocnum = mpt_verify_adapter(karg.hdr.iocnum, &ioc)) < 0) ||
(ioc == NULL)) {
printk(KERN_DEBUG MYNAM "%s::mptctl_hp_targetinfo() @%d - ioc%d not found!\n",
__FILE__, __LINE__, iocnum);
return -ENODEV;
}
dctlprintk(ioc, printk(MYIOC_s_DEBUG_FMT "mptctl_hp_targetinfo called.\n",
ioc->name));
/* There is nothing to do for FCP parts.
*/
if ((ioc->bus_type == SAS) || (ioc->bus_type == FC))
return 0;
if ((ioc->spi_data.sdp0length == 0) || (ioc->sh == NULL))
return 0;
if (ioc->sh->host_no != karg.hdr.host)
return -ENODEV;
/* Get the data transfer speeds
*/
data_sz = ioc->spi_data.sdp0length * 4;
pg0_alloc = (SCSIDevicePage0_t *) pci_alloc_consistent(ioc->pcidev, data_sz, &page_dma);
if (pg0_alloc) {
hdr.PageVersion = ioc->spi_data.sdp0version;
hdr.PageLength = data_sz;
hdr.PageNumber = 0;
hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
cfg.dir = 0;
cfg.timeout = 0;
cfg.physAddr = page_dma;
cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
np = le32_to_cpu(pg0_alloc->NegotiatedParameters);
karg.negotiated_width = np & MPI_SCSIDEVPAGE0_NP_WIDE ?
HP_BUS_WIDTH_16 : HP_BUS_WIDTH_8;
if (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_OFFSET_MASK) {
tmp = (np & MPI_SCSIDEVPAGE0_NP_NEG_SYNC_PERIOD_MASK) >> 8;
if (tmp < 0x09)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA320;
else if (tmp <= 0x09)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA160;
else if (tmp <= 0x0A)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA2;
else if (tmp <= 0x0C)
karg.negotiated_speed = HP_DEV_SPEED_ULTRA;
else if (tmp <= 0x25)
karg.negotiated_speed = HP_DEV_SPEED_FAST;
else
karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
} else
karg.negotiated_speed = HP_DEV_SPEED_ASYNC;
}
pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg0_alloc, page_dma);
}
/* Set defaults
*/
karg.message_rejects = -1;
karg.phase_errors = -1;
karg.parity_errors = -1;
karg.select_timeouts = -1;
/* Get the target error parameters
*/
hdr.PageVersion = 0;
hdr.PageLength = 0;
hdr.PageNumber = 3;
hdr.PageType = MPI_CONFIG_PAGETYPE_SCSI_DEVICE;
cfg.cfghdr.hdr = &hdr;
cfg.action = MPI_CONFIG_ACTION_PAGE_HEADER;
cfg.dir = 0;
cfg.timeout = 0;
cfg.physAddr = -1;
if ((mpt_config(ioc, &cfg) == 0) && (cfg.cfghdr.hdr->PageLength > 0)) {
/* Issue the second config page request */
cfg.action = MPI_CONFIG_ACTION_PAGE_READ_CURRENT;
data_sz = (int) cfg.cfghdr.hdr->PageLength * 4;
pg3_alloc = (SCSIDevicePage3_t *) pci_alloc_consistent(
ioc->pcidev, data_sz, &page_dma);
if (pg3_alloc) {
cfg.physAddr = page_dma;
cfg.pageAddr = (karg.hdr.channel << 8) | karg.hdr.id;
if ((rc = mpt_config(ioc, &cfg)) == 0) {
karg.message_rejects = (u32) le16_to_cpu(pg3_alloc->MsgRejectCount);
karg.phase_errors = (u32) le16_to_cpu(pg3_alloc->PhaseErrorCount);
karg.parity_errors = (u32) le16_to_cpu(pg3_alloc->ParityErrorCount);
}
pci_free_consistent(ioc->pcidev, data_sz, (u8 *) pg3_alloc, page_dma);
}
}
hd = shost_priv(ioc->sh);
if (hd != NULL)
karg.select_timeouts = hd->sel_timeout[karg.hdr.id];
/* Copy the data from kernel memory to user memory
*/
if (copy_to_user((char __user *)arg, &karg, sizeof(hp_target_info_t))) {
printk(MYIOC_s_ERR_FMT "%s@%d::mptctl_hp_target_info - "
"Unable to write out mpt_ioctl_targetinfo struct @ %p\n",
ioc->name, __FILE__, __LINE__, uarg);
return -EFAULT;
}
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static const struct file_operations mptctl_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.fasync = mptctl_fasync,
.unlocked_ioctl = mptctl_ioctl,
.release = mptctl_release,
#ifdef CONFIG_COMPAT
.compat_ioctl = compat_mpctl_ioctl,
#endif
};
static struct miscdevice mptctl_miscdev = {
MPT_MINOR,
MYNAM,
&mptctl_fops
};
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
#ifdef CONFIG_COMPAT
static int
compat_mptfwxfer_ioctl(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_fw_xfer32 kfw32;
struct mpt_fw_xfer kfw;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&kfw32, (char __user *)arg, sizeof(kfw32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = kfw32.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mptfwxfer_ioctl @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mptfwxfer_ioctl() called\n",
iocp->name));
kfw.iocnum = iocnum;
kfw.fwlen = kfw32.fwlen;
kfw.bufp = compat_ptr(kfw32.bufp);
ret = mptctl_do_fw_download(kfw.iocnum, kfw.bufp, kfw.fwlen);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static int
compat_mpt_command(struct file *filp, unsigned int cmd,
unsigned long arg)
{
struct mpt_ioctl_command32 karg32;
struct mpt_ioctl_command32 __user *uarg = (struct mpt_ioctl_command32 __user *) arg;
struct mpt_ioctl_command karg;
MPT_ADAPTER *iocp = NULL;
int iocnum, iocnumX;
int nonblock = (filp->f_flags & O_NONBLOCK);
int ret;
if (copy_from_user(&karg32, (char __user *)arg, sizeof(karg32)))
return -EFAULT;
/* Verify intended MPT adapter */
iocnumX = karg32.hdr.iocnum & 0xFF;
if (((iocnum = mpt_verify_adapter(iocnumX, &iocp)) < 0) ||
(iocp == NULL)) {
printk(KERN_DEBUG MYNAM "::compat_mpt_command @%d - ioc%d not found!\n",
__LINE__, iocnumX);
return -ENODEV;
}
if ((ret = mptctl_syscall_down(iocp, nonblock)) != 0)
return ret;
dctlprintk(iocp, printk(MYIOC_s_DEBUG_FMT "compat_mpt_command() called\n",
iocp->name));
/* Copy data to karg */
karg.hdr.iocnum = karg32.hdr.iocnum;
karg.hdr.port = karg32.hdr.port;
karg.timeout = karg32.timeout;
karg.maxReplyBytes = karg32.maxReplyBytes;
karg.dataInSize = karg32.dataInSize;
karg.dataOutSize = karg32.dataOutSize;
karg.maxSenseBytes = karg32.maxSenseBytes;
karg.dataSgeOffset = karg32.dataSgeOffset;
karg.replyFrameBufPtr = (char __user *)(unsigned long)karg32.replyFrameBufPtr;
karg.dataInBufPtr = (char __user *)(unsigned long)karg32.dataInBufPtr;
karg.dataOutBufPtr = (char __user *)(unsigned long)karg32.dataOutBufPtr;
karg.senseDataPtr = (char __user *)(unsigned long)karg32.senseDataPtr;
/* Pass new structure to do_mpt_command
*/
ret = mptctl_do_mpt_command (karg, &uarg->MF);
mutex_unlock(&iocp->ioctl_cmds.mutex);
return ret;
}
static long compat_mpctl_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
{
long ret;
mutex_lock(&mpctl_mutex);
switch (cmd) {
case MPTIOCINFO:
case MPTIOCINFO1:
case MPTIOCINFO2:
case MPTTARGETINFO:
case MPTEVENTQUERY:
case MPTEVENTENABLE:
case MPTEVENTREPORT:
case MPTHARDRESET:
case HP_GETHOSTINFO:
case HP_GETTARGETINFO:
case MPTTEST:
ret = __mptctl_ioctl(f, cmd, arg);
break;
case MPTCOMMAND32:
ret = compat_mpt_command(f, cmd, arg);
break;
case MPTFWDOWNLOAD32:
ret = compat_mptfwxfer_ioctl(f, cmd, arg);
break;
default:
ret = -ENOIOCTLCMD;
break;
}
mutex_unlock(&mpctl_mutex);
return ret;
}
#endif
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_probe - Installs ioctl devices per bus.
* @pdev: Pointer to pci_dev structure
*
* Returns 0 for success, non-zero for failure.
*
*/
static int
mptctl_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
MPT_ADAPTER *ioc = pci_get_drvdata(pdev);
mutex_init(&ioc->ioctl_cmds.mutex);
init_completion(&ioc->ioctl_cmds.done);
return 0;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
/*
* mptctl_remove - Removed ioctl devices
* @pdev: Pointer to pci_dev structure
*
*
*/
static void
mptctl_remove(struct pci_dev *pdev)
{
}
static struct mpt_pci_driver mptctl_driver = {
.probe = mptctl_probe,
.remove = mptctl_remove,
};
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static int __init mptctl_init(void)
{
int err;
int where = 1;
show_mptmod_ver(my_NAME, my_VERSION);
mpt_device_driver_register(&mptctl_driver, MPTCTL_DRIVER);
/* Register this device */
err = misc_register(&mptctl_miscdev);
if (err < 0) {
printk(KERN_ERR MYNAM ": Can't register misc device [minor=%d].\n", MPT_MINOR);
goto out_fail;
}
printk(KERN_INFO MYNAM ": Registered with Fusion MPT base driver\n");
printk(KERN_INFO MYNAM ": /dev/%s @ (major,minor=%d,%d)\n",
mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
/*
* Install our handler
*/
++where;
mptctl_id = mpt_register(mptctl_reply, MPTCTL_DRIVER,
"mptctl_reply");
if (!mptctl_id || mptctl_id >= MPT_MAX_PROTOCOL_DRIVERS) {
printk(KERN_ERR MYNAM ": ERROR: Failed to register with Fusion MPT base driver\n");
misc_deregister(&mptctl_miscdev);
err = -EBUSY;
goto out_fail;
}
mptctl_taskmgmt_id = mpt_register(mptctl_taskmgmt_reply, MPTCTL_DRIVER,
"mptctl_taskmgmt_reply");
if (!mptctl_taskmgmt_id || mptctl_taskmgmt_id >= MPT_MAX_PROTOCOL_DRIVERS) {
printk(KERN_ERR MYNAM ": ERROR: Failed to register with Fusion MPT base driver\n");
mpt_deregister(mptctl_id);
misc_deregister(&mptctl_miscdev);
err = -EBUSY;
goto out_fail;
}
mpt_reset_register(mptctl_id, mptctl_ioc_reset);
mpt_event_register(mptctl_id, mptctl_event_process);
return 0;
out_fail:
mpt_device_driver_deregister(MPTCTL_DRIVER);
return err;
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
static void mptctl_exit(void)
{
misc_deregister(&mptctl_miscdev);
printk(KERN_INFO MYNAM ": Deregistered /dev/%s @ (major,minor=%d,%d)\n",
mptctl_miscdev.name, MISC_MAJOR, mptctl_miscdev.minor);
/* De-register event handler from base module */
mpt_event_deregister(mptctl_id);
/* De-register reset handler from base module */
mpt_reset_deregister(mptctl_id);
/* De-register callback handler from base module */
mpt_deregister(mptctl_taskmgmt_id);
mpt_deregister(mptctl_id);
mpt_device_driver_deregister(MPTCTL_DRIVER);
}
/*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
module_init(mptctl_init);
module_exit(mptctl_exit);
| gpl-2.0 |
Insswer/kernel_imx | drivers/gpu/drm/drm_dp_i2c_helper.c | 9262 | 5420 | /*
* Copyright © 2009 Keith Packard
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that copyright
* notice and this permission notice appear in supporting documentation, and
* that the name of the copyright holders not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no representations
* about the suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/sched.h>
#include <linux/i2c.h>
#include "drm_dp_helper.h"
#include "drmP.h"
/* Run a single AUX_CH I2C transaction, writing/reading data as necessary */
static int
i2c_algo_dp_aux_transaction(struct i2c_adapter *adapter, int mode,
uint8_t write_byte, uint8_t *read_byte)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
int ret;
ret = (*algo_data->aux_ch)(adapter, mode,
write_byte, read_byte);
return ret;
}
/*
* I2C over AUX CH
*/
/*
* Send the address. If the I2C link is running, this 'restarts'
* the connection with the new address, this is used for doing
* a write followed by a read (as needed for DDC)
*/
static int
i2c_algo_dp_aux_address(struct i2c_adapter *adapter, u16 address, bool reading)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
int mode = MODE_I2C_START;
int ret;
if (reading)
mode |= MODE_I2C_READ;
else
mode |= MODE_I2C_WRITE;
algo_data->address = address;
algo_data->running = true;
ret = i2c_algo_dp_aux_transaction(adapter, mode, 0, NULL);
return ret;
}
/*
* Stop the I2C transaction. This closes out the link, sending
* a bare address packet with the MOT bit turned off
*/
static void
i2c_algo_dp_aux_stop(struct i2c_adapter *adapter, bool reading)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
int mode = MODE_I2C_STOP;
if (reading)
mode |= MODE_I2C_READ;
else
mode |= MODE_I2C_WRITE;
if (algo_data->running) {
(void) i2c_algo_dp_aux_transaction(adapter, mode, 0, NULL);
algo_data->running = false;
}
}
/*
* Write a single byte to the current I2C address, the
* the I2C link must be running or this returns -EIO
*/
static int
i2c_algo_dp_aux_put_byte(struct i2c_adapter *adapter, u8 byte)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
int ret;
if (!algo_data->running)
return -EIO;
ret = i2c_algo_dp_aux_transaction(adapter, MODE_I2C_WRITE, byte, NULL);
return ret;
}
/*
* Read a single byte from the current I2C address, the
* I2C link must be running or this returns -EIO
*/
static int
i2c_algo_dp_aux_get_byte(struct i2c_adapter *adapter, u8 *byte_ret)
{
struct i2c_algo_dp_aux_data *algo_data = adapter->algo_data;
int ret;
if (!algo_data->running)
return -EIO;
ret = i2c_algo_dp_aux_transaction(adapter, MODE_I2C_READ, 0, byte_ret);
return ret;
}
static int
i2c_algo_dp_aux_xfer(struct i2c_adapter *adapter,
struct i2c_msg *msgs,
int num)
{
int ret = 0;
bool reading = false;
int m;
int b;
for (m = 0; m < num; m++) {
u16 len = msgs[m].len;
u8 *buf = msgs[m].buf;
reading = (msgs[m].flags & I2C_M_RD) != 0;
ret = i2c_algo_dp_aux_address(adapter, msgs[m].addr, reading);
if (ret < 0)
break;
if (reading) {
for (b = 0; b < len; b++) {
ret = i2c_algo_dp_aux_get_byte(adapter, &buf[b]);
if (ret < 0)
break;
}
} else {
for (b = 0; b < len; b++) {
ret = i2c_algo_dp_aux_put_byte(adapter, buf[b]);
if (ret < 0)
break;
}
}
if (ret < 0)
break;
}
if (ret >= 0)
ret = num;
i2c_algo_dp_aux_stop(adapter, reading);
DRM_DEBUG_KMS("dp_aux_xfer return %d\n", ret);
return ret;
}
static u32
i2c_algo_dp_aux_functionality(struct i2c_adapter *adapter)
{
return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
I2C_FUNC_SMBUS_READ_BLOCK_DATA |
I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
I2C_FUNC_10BIT_ADDR;
}
static const struct i2c_algorithm i2c_dp_aux_algo = {
.master_xfer = i2c_algo_dp_aux_xfer,
.functionality = i2c_algo_dp_aux_functionality,
};
static void
i2c_dp_aux_reset_bus(struct i2c_adapter *adapter)
{
(void) i2c_algo_dp_aux_address(adapter, 0, false);
(void) i2c_algo_dp_aux_stop(adapter, false);
}
static int
i2c_dp_aux_prepare_bus(struct i2c_adapter *adapter)
{
adapter->algo = &i2c_dp_aux_algo;
adapter->retries = 3;
i2c_dp_aux_reset_bus(adapter);
return 0;
}
int
i2c_dp_aux_add_bus(struct i2c_adapter *adapter)
{
int error;
error = i2c_dp_aux_prepare_bus(adapter);
if (error)
return error;
error = i2c_add_adapter(adapter);
return error;
}
EXPORT_SYMBOL(i2c_dp_aux_add_bus);
| gpl-2.0 |
omnirom/android_kernel_google_msm | drivers/net/wireless/rtlwifi/rtl8192se/led.c | 9518 | 4150 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "reg.h"
#include "led.h"
static void _rtl92se_init_led(struct ieee80211_hw *hw,
struct rtl_led *pled, enum rtl_led_pin ledpin)
{
pled->hw = hw;
pled->ledpin = ledpin;
pled->ledon = false;
}
void rtl92se_init_sw_leds(struct ieee80211_hw *hw)
{
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
_rtl92se_init_led(hw, &(pcipriv->ledctl.sw_led0), LED_PIN_LED0);
_rtl92se_init_led(hw, &(pcipriv->ledctl.sw_led1), LED_PIN_LED1);
}
void rtl92se_sw_led_on(struct ieee80211_hw *hw, struct rtl_led *pled)
{
u8 ledcfg;
struct rtl_priv *rtlpriv = rtl_priv(hw);
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n",
LEDCFG, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, LEDCFG);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
rtl_write_byte(rtlpriv, LEDCFG, ledcfg & 0xf0);
break;
case LED_PIN_LED1:
rtl_write_byte(rtlpriv, LEDCFG, ledcfg & 0x0f);
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
pled->ledon = true;
}
void rtl92se_sw_led_off(struct ieee80211_hw *hw, struct rtl_led *pled)
{
struct rtl_priv *rtlpriv;
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
u8 ledcfg;
rtlpriv = rtl_priv(hw);
if (!rtlpriv || rtlpriv->max_fw_size)
return;
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n",
LEDCFG, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, LEDCFG);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
ledcfg &= 0xf0;
if (pcipriv->ledctl.led_opendrain)
rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(1)));
else
rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(3)));
break;
case LED_PIN_LED1:
ledcfg &= 0x0f;
rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(3)));
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
pled->ledon = false;
}
static void _rtl92se_sw_led_control(struct ieee80211_hw *hw,
enum led_ctl_mode ledaction)
{
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_led *pLed0 = &(pcipriv->ledctl.sw_led0);
switch (ledaction) {
case LED_CTL_POWER_ON:
case LED_CTL_LINK:
case LED_CTL_NO_LINK:
rtl92se_sw_led_on(hw, pLed0);
break;
case LED_CTL_POWER_OFF:
rtl92se_sw_led_off(hw, pLed0);
break;
default:
break;
}
}
void rtl92se_led_control(struct ieee80211_hw *hw, enum led_ctl_mode ledaction)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
if ((ppsc->rfoff_reason > RF_CHANGE_BY_PS) &&
(ledaction == LED_CTL_TX ||
ledaction == LED_CTL_RX ||
ledaction == LED_CTL_SITE_SURVEY ||
ledaction == LED_CTL_LINK ||
ledaction == LED_CTL_NO_LINK ||
ledaction == LED_CTL_START_TO_LINK ||
ledaction == LED_CTL_POWER_ON)) {
return;
}
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "ledaction %d\n", ledaction);
_rtl92se_sw_led_control(hw, ledaction);
}
| gpl-2.0 |
ricardon/omap-audio | fs/efs/file.c | 12846 | 1190 | /*
* file.c
*
* Copyright (c) 1999 Al Smith
*
* Portions derived from work (c) 1995,1996 Christian Vogelgsang.
*/
#include <linux/buffer_head.h>
#include "efs.h"
int efs_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create)
{
int error = -EROFS;
long phys;
if (create)
return error;
if (iblock >= inode->i_blocks) {
#ifdef DEBUG
/*
* i have no idea why this happens as often as it does
*/
printk(KERN_WARNING "EFS: bmap(): block %d >= %ld (filesize %ld)\n",
block,
inode->i_blocks,
inode->i_size);
#endif
return 0;
}
phys = efs_map_block(inode, iblock);
if (phys)
map_bh(bh_result, inode->i_sb, phys);
return 0;
}
int efs_bmap(struct inode *inode, efs_block_t block) {
if (block < 0) {
printk(KERN_WARNING "EFS: bmap(): block < 0\n");
return 0;
}
/* are we about to read past the end of a file ? */
if (!(block < inode->i_blocks)) {
#ifdef DEBUG
/*
* i have no idea why this happens as often as it does
*/
printk(KERN_WARNING "EFS: bmap(): block %d >= %ld (filesize %ld)\n",
block,
inode->i_blocks,
inode->i_size);
#endif
return 0;
}
return efs_map_block(inode, block);
}
| gpl-2.0 |
alexbevi/scummvm | engines/sword2/sprite.cpp | 47 | 23398 | /* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* Additional copyright for this file:
* Copyright (C) 1994-1998 Revolution Software Ltd.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "common/endian.h"
#include "sword2/sword2.h"
#include "sword2/defs.h"
#include "sword2/screen.h"
namespace Sword2 {
/**
* This function takes a sprite and creates a mirror image of it.
* @param dst destination buffer
* @param src source buffer
* @param w width of the sprite
* @param h height of the sprite
*/
void Screen::mirrorSprite(byte *dst, byte *src, int16 w, int16 h) {
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
*dst++ = *(src + w - x - 1);
}
src += w;
}
}
/**
* This function takes a compressed frame of a sprite with up to 256 colors
* and decompresses it.
* @param dst destination buffer
* @param src source buffer
* @param decompSize the expected size of the decompressed sprite
*/
int32 Screen::decompressRLE256(byte *dst, byte *src, int32 decompSize) {
// PARAMETERS:
// source points to the start of the sprite data for input
// decompSize gives size of decompressed data in bytes
// dest points to start of destination buffer for decompressed
// data
byte headerByte; // block header byte
byte *endDest = dst + decompSize; // pointer to byte after end of decomp buffer
int32 rv;
while (1) {
// FLAT block
// read FLAT block header & increment 'scan' to first pixel
// of block
headerByte = *src++;
// if this isn't a zero-length block
if (headerByte) {
if (dst + headerByte > endDest) {
rv = 1;
break;
}
// set the next 'headerByte' pixels to the next color
// at 'source'
memset(dst, *src, headerByte);
// increment destination pointer to just after this
// block
dst += headerByte;
// increment source pointer to just after this color
src++;
// if we've decompressed all of the data
if (dst == endDest) {
rv = 0; // return "OK"
break;
}
}
// RAW block
// read RAW block header & increment 'scan' to first pixel of
// block
headerByte = *src++;
// if this isn't a zero-length block
if (headerByte) {
if (dst + headerByte > endDest) {
rv = 1;
break;
}
// copy the next 'headerByte' pixels from source to
// destination
memcpy(dst, src, headerByte);
// increment destination pointer to just after this
// block
dst += headerByte;
// increment source pointer to just after this block
src += headerByte;
// if we've decompressed all of the data
if (dst == endDest) {
rv = 0; // return "OK"
break;
}
}
}
return rv;
}
/**
* Unwinds a run of 16-color data into 256-color palette data.
*/
void Screen::unwindRaw16(byte *dst, byte *src, uint16 blockSize, byte *colTable) {
// for each pair of pixels
while (blockSize > 1) {
if (Sword2Engine::isPsx()) {
// 1st color = number in table at position given by upper
// nibble of source byte
*dst++ = colTable[(*src) & 0x0f];
// 2nd color = number in table at position given by lower
// nibble of source byte
*dst++ = colTable[(*src) >> 4];
} else {
*dst++ = colTable[(*src) >> 4];
*dst++ = colTable[(*src) & 0x0f];
}
// point to next source byte
src++;
// decrement count of how many pixels left to read
blockSize -= 2;
}
// if there's a final odd pixel
if (blockSize) {
// color = number in table at position given by upper nibble
// of source byte
*dst++ = colTable[(*src) >> 4];
}
}
/**
* This function takes a compressed frame of a sprite (with up to 16 colors)
* and decompresses it.
* @param dst destination buffer
* @param src source buffer
* @param decompSize the expected size of the uncompressed sprite
* @param colTable mapping from the 16 encoded colors to the current palette
*/
int32 Screen::decompressRLE16(byte *dst, byte *src, int32 decompSize, byte *colTable) {
byte headerByte; // block header byte
byte *endDest = dst + decompSize; // pointer to byte after end of decomp buffer
int32 rv;
while (1) {
// FLAT block
// read FLAT block header & increment 'scan' to first pixel
// of block
headerByte = *src++;
// if this isn't a zero-length block
if (headerByte) {
if (dst + headerByte > endDest) {
rv = 1;
break;
}
// set the next 'headerByte' pixels to the next
// color at 'source'
memset(dst, *src, headerByte);
// increment destination pointer to just after this
// block
dst += headerByte;
// increment source pointer to just after this color
src++;
// if we've decompressed all of the data
if (dst == endDest) {
rv = 0; // return "OK"
break;
}
}
// RAW block
// read RAW block header & increment 'scan' to first pixel of
// block
headerByte = *src++;
// if this isn't a zero-length block
if (headerByte) {
if (dst + headerByte > endDest) {
rv = 1;
break;
}
// copy the next 'headerByte' pixels from source to
// destination (NB. 2 pixels per byte)
unwindRaw16(dst, src, headerByte, colTable);
// increment destination pointer to just after this
// block
dst += headerByte;
// increment source pointer to just after this block
// (NB. headerByte gives pixels, so /2 for bytes)
src += (headerByte + 1) / 2;
// if we've decompressed all of the data
if (dst >= endDest) {
rv = 0; // return "OK"
break;
}
}
}
return rv;
}
/**
* This function takes a compressed HIF image and decompresses it.
* Used for PSX version sprites.
* @param dst destination buffer
* @param src source buffer
* @param skipData if pointer != NULL, value of pointed var
* is set to number of bytes composing the compressed data.
*/
uint32 Screen::decompressHIF(byte *src, byte *dst, uint32 *skipData) {
uint32 decompSize = 0;
uint32 readByte = 0;
for (;;) { // Main loop
byte control_byte = *src++;
readByte++;
uint32 byte_count = 0;
while (byte_count < 8) {
if (control_byte & 0x80) {
uint16 info_word = READ_BE_UINT16(src); // Read the info word
src += 2;
readByte += 2;
if (info_word == 0xFFFF) { // Got 0xFFFF code, finished.
if (skipData != NULL) *(skipData) = readByte;
return decompSize;
}
int32 repeat_count = (info_word >> 12) + 2; // How many time data needs to be refetched
while (repeat_count >= 0) {
uint16 refetchData = (info_word & 0xFFF) + 1;
if (refetchData > decompSize) return 0; // We have a problem here...
uint8 *old_data_src = dst - refetchData;
*dst++ = *old_data_src;
decompSize++;
repeat_count--;
}
} else {
*dst++ = *src++;
readByte++;
decompSize++;
}
byte_count++;
control_byte <<= 1; // Shifting left the control code one bit
}
}
}
// Double line image to keep aspect ratio.
// Used in PSX version.
void Screen::resizePsxSprite(byte *dst, byte *src, uint16 destW, uint16 destH) {
for (int i = 0; i < destH / 2; i++) {
memcpy(dst + i * destW * 2, src + i * destW, destW);
memcpy(dst + i * destW * 2 + destW, src + i * destW, destW);
}
}
// Sprites wider than 254px in PSX version are divided
// into slices, this recomposes the image.
void Screen::recomposePsxSprite(SpriteInfo *s) {
if (!s)
return;
uint16 noStripes = (s->w / 254) + ((s->w % 254) ? 1 : 0);
uint16 lastStripeSize = (s->w % 254) ? s->w % 254 : 254;
byte *buffer = (byte *)malloc(s->w * s->h / 2);
memset(buffer, 0, s->w * s->h / 2);
for (int idx = 0; idx < noStripes; idx++) {
uint16 stripeSize = (idx == noStripes - 1) ? lastStripeSize : 254;
for (int line = 0; line < s->h / 2; line++) {
memcpy(buffer + idx * 254 + line * s->w, s->data, stripeSize);
s->data += stripeSize;
}
}
s->data = buffer;
}
// Recomposes sprites wider than 254 pixels but also
// compressed with HIF.
// Used in PSX version.
void Screen::recomposeCompPsxSprite(SpriteInfo *s) {
if (!s)
return;
uint16 noStripes = (s->w / 254) + ((s->w % 254) ? 1 : 0);
uint16 lastStripeSize = (s->w % 254) ? s->w % 254 : 254;
byte *buffer = (byte *)malloc(s->w * s->h / 2);
byte *stripeBuffer = (byte *)malloc(254 * s->h);
memset(buffer, 0, s->w * s->h / 2);
uint32 skipData = 0;
uint32 compBytes = 0;
for (int idx = 0; idx < noStripes; idx++) {
uint16 stripeSize = (idx == noStripes - 1) ? lastStripeSize : 254;
decompressHIF((s->data) + skipData, stripeBuffer, &compBytes);
skipData += compBytes;
for (int line = 0; line < s->h / 2; line++) {
memcpy(buffer + idx * 254 + line * s->w, stripeBuffer + line * stripeSize, stripeSize);
}
}
free(stripeBuffer);
s->data = buffer;
}
/**
* Creates a sprite surface. Sprite surfaces are used by the in-game dialogs
* and for displaying cutscene subtitles, which makes them much easier to draw
* than standard sprites.
* @param s information about how to decode the sprite
* @param sprite the buffer that will be created to store the surface
* @return RD_OK, or an error code
*/
int32 Screen::createSurface(SpriteInfo *s, byte **sprite) {
*sprite = (byte *)malloc(s->w * s->h);
if (!*sprite)
return RDERR_OUTOFMEMORY;
// Surfaces are either uncompressed or RLE256-compressed. No need to
// test for anything else.
if (s->type & RDSPR_NOCOMPRESSION) {
memcpy(*sprite, s->data, s->w * s->h);
} else if (decompressRLE256(*sprite, s->data, s->w * s->h)) {
free(*sprite);
return RDERR_DECOMPRESSION;
}
return RD_OK;
}
/**
* Draws the sprite surface created earlier.
* @param s information about how to place the sprite
* @param surface pointer to the surface created earlier
* @param clipRect the clipping rectangle
*/
void Screen::drawSurface(SpriteInfo *s, byte *surface, Common::Rect *clipRect) {
Common::Rect rd, rs;
uint16 x, y;
byte *src, *dst;
rs.left = 0;
rs.right = s->w;
rs.top = 0;
rs.bottom = s->h;
rd.left = s->x;
rd.right = rd.left + rs.right;
rd.top = s->y;
rd.bottom = rd.top + rs.bottom;
Common::Rect defClipRect(0, 0, _screenWide, _screenDeep);
if (!clipRect) {
clipRect = &defClipRect;
}
if (clipRect->left > rd.left) {
rs.left += (clipRect->left - rd.left);
rd.left = clipRect->left;
}
if (clipRect->top > rd.top) {
rs.top += (clipRect->top - rd.top);
rd.top = clipRect->top;
}
if (clipRect->right < rd.right) {
rd.right = clipRect->right;
}
if (clipRect->bottom < rd.bottom) {
rd.bottom = clipRect->bottom;
}
if (rd.width() <= 0 || rd.height() <= 0)
return;
src = surface + rs.top * s->w + rs.left;
dst = _buffer + _screenWide * rd.top + rd.left;
// Surfaces are always transparent.
for (y = 0; y < rd.height(); y++) {
for (x = 0; x < rd.width(); x++) {
if (src[x])
dst[x] = src[x];
}
src += s->w;
dst += _screenWide;
}
updateRect(&rd);
}
/**
* Destroys a surface.
*/
void Screen::deleteSurface(byte *surface) {
free(surface);
}
/**
* Draws a sprite onto the screen. The type of the sprite can be a combination
* of the following flags, some of which are mutually exclusive:
* RDSPR_DISPLAYALIGN The sprite is drawn relative to the top left corner
* of the screen
* RDSPR_FLIP The sprite is mirrored
* RDSPR_TRANS The sprite has a transparent color zero
* RDSPR_BLEND The sprite is translucent
* RDSPR_SHADOW The sprite is affected by the light mask. (Scaled
* sprites always are.)
* RDSPR_NOCOMPRESSION The sprite data is not compressed
* RDSPR_RLE16 The sprite data is a 16-color compressed sprite
* RDSPR_RLE256 The sprite data is a 256-color compressed sprite
* @param s all the information needed to draw the sprite
* @warning Sprites will only be drawn onto the background, not over menubar
* areas.
*/
// FIXME: I'm sure this could be optimized. There's plenty of data copying and
// mallocing here.
int32 Screen::drawSprite(SpriteInfo *s) {
byte *src, *dst;
byte *sprite, *newSprite;
uint16 scale;
int16 i, j;
uint16 srcPitch;
bool freeSprite = false;
Common::Rect rd, rs;
// -----------------------------------------------------------------
// Decompression and mirroring
// -----------------------------------------------------------------
if (s->type & RDSPR_NOCOMPRESSION) {
if (Sword2Engine::isPsx()) { // PSX Uncompressed sprites
if (s->w > 254 && !s->isText) { // We need to recompose these frames
recomposePsxSprite(s);
}
// If the height is not an even value, fix it.
// Apparently it's a problem in the data of a few sprites
// of the PSX version. This should fix an evident problem
// in the foyer at the beginning of the game, where a line
// of pixels is missing near the stairs. But it should also
// fix a more subtle one in the glease gallery and in quaramonte
// police office.
if (s->h % 2)
s->h++;
freeSprite = true;
byte *tempBuf = (byte *)malloc(s->w * s->h * 2);
memset(tempBuf, 0, s->w * s->h * 2);
resizePsxSprite(tempBuf, s->data, s->w, s->h);
if (s->w > 254 && !s->isText) {
free(s->data);
}
sprite = tempBuf;
} else { // PC Uncompressed sprites
sprite = s->data;
}
} else {
freeSprite = true;
if ((s->type & 0xff00) == RDSPR_RLE16) {
if (Sword2Engine::isPsx()) { // PSX HIF16 sprites
uint32 decompData;
byte *tempBuf = (byte *)malloc(s->w * s->h);
memset(tempBuf, 0, s->w * s->h);
decompData = decompressHIF(s->data, tempBuf);
// Check that we correctly decompressed data
if (!decompData) {
free(tempBuf);
return RDERR_DECOMPRESSION;
}
s->w = (decompData / (s->h / 2)) * 2;
byte *tempBuf2 = (byte *)malloc(s->w * s->h * 10);
memset(tempBuf2, 0, s->w * s->h * 2);
unwindRaw16(tempBuf2, tempBuf, (s->w * (s->h / 2)), s->colorTable);
sprite = (byte *)malloc(s->w * s->h);
if (!sprite) {
free(tempBuf2);
free(tempBuf);
return RDERR_OUTOFMEMORY;
}
resizePsxSprite(sprite, tempBuf2, s->w, s->h);
free(tempBuf2);
free(tempBuf);
} else { // PC RLE16 sprites
sprite = (byte *)malloc(s->w * s->h);
if (!sprite)
return RDERR_OUTOFMEMORY;
if (decompressRLE16(sprite, s->data, s->w * s->h, s->colorTable)) {
free(sprite);
return RDERR_DECOMPRESSION;
}
}
} else {
if (Sword2Engine::isPsx()) { // PSX HIF256 sprites
if (s->w > 255) {
sprite = (byte *)malloc(s->w * s->h);
recomposeCompPsxSprite(s);
resizePsxSprite(sprite, s->data, s->w, s->h);
free(s->data);
} else {
byte *tempBuf = (byte *)malloc(s->w * s->h);
uint32 decompData = decompressHIF(s->data, tempBuf);
// Check that we correctly decompressed data
if (!decompData) {
free(tempBuf);
return RDERR_DECOMPRESSION;
}
s->w = (decompData / (s->h / 2));
sprite = (byte *)malloc(s->w * s->h);
if (!sprite) {
free(tempBuf);
return RDERR_OUTOFMEMORY;
}
resizePsxSprite(sprite, tempBuf, s->w, s->h);
free(tempBuf);
}
} else { // PC RLE256 sprites
sprite = (byte *)malloc(s->w * s->h);
if (!sprite)
return RDERR_OUTOFMEMORY;
if (decompressRLE256(sprite, s->data, s->w * s->h)) {
free(sprite);
return RDERR_DECOMPRESSION;
}
}
}
}
if (s->type & RDSPR_FLIP) {
newSprite = (byte *)malloc(s->w * s->h);
if (newSprite == NULL) {
if (freeSprite)
free(sprite);
return RDERR_OUTOFMEMORY;
}
mirrorSprite(newSprite, sprite, s->w, s->h);
if (freeSprite)
free(sprite);
sprite = newSprite;
freeSprite = true;
}
// -----------------------------------------------------------------
// Positioning and clipping.
// -----------------------------------------------------------------
int16 spriteX = s->x;
int16 spriteY = s->y;
if (!(s->type & RDSPR_DISPLAYALIGN)) {
spriteX += _parallaxScrollX;
spriteY += _parallaxScrollY;
}
spriteY += MENUDEEP;
// A scale factor 0 or 256 means don't scale. Why do they use two
// different values to mean the same thing? Normalize it here for
// convenience.
scale = (s->scale == 0) ? 256 : s->scale;
rs.top = 0;
rs.left = 0;
if (scale != 256) {
rs.right = s->scaledWidth;
rs.bottom = s->scaledHeight;
srcPitch = s->scaledWidth;
} else {
rs.right = s->w;
rs.bottom = s->h;
srcPitch = s->w;
}
rd.top = spriteY;
rd.left = spriteX;
if (!(s->type & RDSPR_DISPLAYALIGN)) {
rd.top -= _scrollY;
rd.left -= _scrollX;
}
rd.right = rd.left + rs.right;
rd.bottom = rd.top + rs.bottom;
// Check if the sprite would end up completely outside the screen.
if (rd.left > RENDERWIDE || rd.top > RENDERDEEP + MENUDEEP || rd.right < 0 || rd.bottom < MENUDEEP) {
if (freeSprite)
free(sprite);
return RD_OK;
}
if (rd.top < MENUDEEP) {
rs.top = MENUDEEP - rd.top;
rd.top = MENUDEEP;
}
if (rd.bottom > RENDERDEEP + MENUDEEP) {
rd.bottom = RENDERDEEP + MENUDEEP;
rs.bottom = rs.top + (rd.bottom - rd.top);
}
if (rd.left < 0) {
rs.left = -rd.left;
rd.left = 0;
}
if (rd.right > RENDERWIDE) {
rd.right = RENDERWIDE;
rs.right = rs.left + (rd.right - rd.left);
}
// -----------------------------------------------------------------
// Scaling
// -----------------------------------------------------------------
if (scale != 256) {
if (s->scaledWidth > SCALE_MAXWIDTH || s->scaledHeight > SCALE_MAXHEIGHT) {
if (freeSprite)
free(sprite);
return RDERR_NOTIMPLEMENTED;
}
newSprite = (byte *)malloc(s->scaledWidth * s->scaledHeight);
if (newSprite == NULL) {
if (freeSprite)
free(sprite);
return RDERR_OUTOFMEMORY;
}
// We cannot use good scaling for PSX version, as we are missing
// some required data.
if (_renderCaps & RDBLTFX_EDGEBLEND && !Sword2Engine::isPsx())
scaleImageGood(newSprite, s->scaledWidth, s->scaledWidth, s->scaledHeight, sprite, s->w, s->w, s->h, _buffer, rd.left, rd.top);
else
scaleImageFast(newSprite, s->scaledWidth, s->scaledWidth, s->scaledHeight, sprite, s->w, s->w, s->h);
if (freeSprite)
free(sprite);
sprite = newSprite;
freeSprite = true;
}
// -----------------------------------------------------------------
// Light masking
// -----------------------------------------------------------------
// The light mask is an optional layer that covers the entire room
// and which is used to simulate light and shadows. Scaled sprites
// (actors, presumably) are always affected.
// Light masking makes use of palette match table, so it's unavailable
// in PSX version.
if ((_renderCaps & RDBLTFX_SHADOWBLEND) && _lightMask && (scale != 256 || ((s->type & RDSPR_SHADOW) && !Sword2Engine::isPsx()) )) {
byte *lightMap;
// Make sure that we never apply the shadow to the original
// resource data. This could only ever happen in the
// RDSPR_NOCOMPRESSION case.
if (!freeSprite) {
newSprite = (byte *)malloc(s->w * s->h);
memcpy(newSprite, sprite, s->w * s->h);
sprite = newSprite;
freeSprite = true;
}
src = sprite + rs.top * srcPitch + rs.left;
lightMap = _lightMask + (rd.top + _scrollY - MENUDEEP) * _locationWide + rd.left + _scrollX;
for (i = 0; i < rs.height(); i++) {
for (j = 0; j < rs.width(); j++) {
if (src[j] && lightMap[j]) {
uint8 r = ((32 - lightMap[j]) * _palette[src[j] * 3 + 0]) >> 5;
uint8 g = ((32 - lightMap[j]) * _palette[src[j] * 3 + 1]) >> 5;
uint8 b = ((32 - lightMap[j]) * _palette[src[j] * 3 + 2]) >> 5;
src[j] = quickMatch(r, g, b);
}
}
src += srcPitch;
lightMap += _locationWide;
}
}
// -----------------------------------------------------------------
// Drawing
// -----------------------------------------------------------------
src = sprite + rs.top * srcPitch + rs.left;
dst = _buffer + _screenWide * rd.top + rd.left;
if (s->type & RDSPR_BLEND) {
// The original code had two different blending cases. One for
// s->blend & 0x01 and one for s->blend & 0x02. However, the
// only values that actually appear in the cluster files are
// 0, 513 and 1025 so the s->blend & 0x02 case was never used.
// Which is just as well since that code made no sense to me.
// TODO: In PSX version, blending is done through hardware transparency.
// The only correct way to simulate this would be using 16-bit mode.
// As this is not yet available for this engine, fake transparency is used
// as placeholder.
if (!(_renderCaps & RDBLTFX_SPRITEBLEND) || Sword2Engine::isPsx()) {
for (i = 0; i < rs.height(); i++) {
for (j = 0; j < rs.width(); j++) {
if (src[j] && ((i & 1) == (j & 1)))
dst[j] = src[j];
}
src += srcPitch;
dst += _screenWide;
}
} else {
uint8 n = s->blend >> 8;
for (i = 0; i < rs.height(); i++) {
for (j = 0; j < rs.width(); j++) {
if (src[j]) {
uint8 r1 = _palette[src[j] * 3 + 0];
uint8 g1 = _palette[src[j] * 3 + 1];
uint8 b1 = _palette[src[j] * 3 + 2];
uint8 r2 = _palette[dst[j] * 3 + 0];
uint8 g2 = _palette[dst[j] * 3 + 1];
uint8 b2 = _palette[dst[j] * 3 + 2];
uint8 r = (r1 * n + r2 * (8 - n)) >> 3;
uint8 g = (g1 * n + g2 * (8 - n)) >> 3;
uint8 b = (b1 * n + b2 * (8 - n)) >> 3;
dst[j] = quickMatch(r, g, b);
}
}
src += srcPitch;
dst += _screenWide;
}
}
} else {
if (s->type & RDSPR_TRANS) {
for (i = 0; i < rs.height(); i++) {
for (j = 0; j < rs.width(); j++) {
if (src[j])
dst[j] = src[j];
}
src += srcPitch;
dst += _screenWide;
}
} else {
for (i = 0; i < rs.height(); i++) {
memcpy(dst, src, rs.width());
src += srcPitch;
dst += _screenWide;
}
}
}
if (freeSprite)
free(sprite);
markAsDirty(rd.left, rd.top, rd.right - 1, rd.bottom - 1);
return RD_OK;
}
/**
* Opens the light masking sprite for a room.
*/
int32 Screen::openLightMask(SpriteInfo *s) {
// FIXME: The light mask is only needed on higher graphics detail
// settings, so to save memory we could simply ignore it on lower
// settings. But then we need to figure out how to ensure that it
// is properly loaded if the user changes the settings in mid-game.
if (_lightMask)
return RDERR_NOTCLOSED;
_lightMask = (byte *)malloc(s->w * s->h);
if (!_lightMask)
return RDERR_OUTOFMEMORY;
if (s->data == NULL) // Check, as there's no mask in psx version
return RDERR_NOTOPEN;
if (decompressRLE256(_lightMask, s->data, s->w * s->h))
return RDERR_DECOMPRESSION;
return RD_OK;
}
/**
* Closes the light masking sprite for a room.
*/
int32 Screen::closeLightMask() {
if (!_lightMask)
return RDERR_NOTOPEN;
free(_lightMask);
_lightMask = NULL;
return RD_OK;
}
} // End of namespace Sword2
| gpl-2.0 |
ojdkbuild/lookaside_java-1.8.0-openjdk | hotspot/src/share/vm/ci/ciSymbol.cpp | 47 | 4803 | /*
* Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#include "precompiled.hpp"
#include "ci/ciSymbol.hpp"
#include "ci/ciUtilities.hpp"
#include "memory/oopFactory.hpp"
// ------------------------------------------------------------------
// ciSymbol::ciSymbol
//
// Preallocated symbol variant. Used with symbols from vmSymbols.
ciSymbol::ciSymbol(Symbol* s, vmSymbols::SID sid)
: _symbol(s), _sid(sid)
{
assert(_symbol != NULL, "adding null symbol");
_symbol->increment_refcount(); // increment ref count
assert(sid_ok(), "must be in vmSymbols");
}
// Normal case for non-famous symbols.
ciSymbol::ciSymbol(Symbol* s)
: _symbol(s), _sid(vmSymbols::NO_SID)
{
assert(_symbol != NULL, "adding null symbol");
_symbol->increment_refcount(); // increment ref count
assert(sid_ok(), "must not be in vmSymbols");
}
// ciSymbol
//
// This class represents a Symbol* in the HotSpot virtual
// machine.
// ------------------------------------------------------------------
// ciSymbol::as_utf8
//
// The text of the symbol as a null-terminated C string.
const char* ciSymbol::as_utf8() {
VM_QUICK_ENTRY_MARK;
Symbol* s = get_symbol();
return s->as_utf8();
}
// The text of the symbol as a null-terminated C string.
const char* ciSymbol::as_quoted_ascii() {
GUARDED_VM_QUICK_ENTRY(return get_symbol()->as_quoted_ascii();)
}
// ------------------------------------------------------------------
// ciSymbol::base
const jbyte* ciSymbol::base() {
GUARDED_VM_ENTRY(return get_symbol()->base();)
}
// ------------------------------------------------------------------
// ciSymbol::byte_at
int ciSymbol::byte_at(int i) {
GUARDED_VM_ENTRY(return get_symbol()->byte_at(i);)
}
// ------------------------------------------------------------------
// ciSymbol::starts_with
//
// Tests if the symbol starts with the given prefix.
bool ciSymbol::starts_with(const char* prefix, int len) const {
GUARDED_VM_ENTRY(return get_symbol()->starts_with(prefix, len);)
}
bool ciSymbol::is_signature_polymorphic_name() const {
GUARDED_VM_ENTRY(return MethodHandles::is_signature_polymorphic_name(get_symbol());)
}
// ------------------------------------------------------------------
// ciSymbol::index_of
//
// Determines where the symbol contains the given substring.
int ciSymbol::index_of_at(int i, const char* str, int len) const {
GUARDED_VM_ENTRY(return get_symbol()->index_of_at(i, str, len);)
}
// ------------------------------------------------------------------
// ciSymbol::utf8_length
int ciSymbol::utf8_length() {
GUARDED_VM_ENTRY(return get_symbol()->utf8_length();)
}
// ------------------------------------------------------------------
// ciSymbol::print_impl
//
// Implementation of the print method
void ciSymbol::print_impl(outputStream* st) {
st->print(" value=");
print_symbol_on(st);
}
// ------------------------------------------------------------------
// ciSymbol::print_symbol_on
//
// Print the value of this symbol on an outputStream
void ciSymbol::print_symbol_on(outputStream *st) {
GUARDED_VM_ENTRY(get_symbol()->print_symbol_on(st);)
}
// ------------------------------------------------------------------
// ciSymbol::make_impl
//
// Make a ciSymbol from a C string (implementation).
ciSymbol* ciSymbol::make_impl(const char* s) {
EXCEPTION_CONTEXT;
TempNewSymbol sym = SymbolTable::new_symbol(s, THREAD);
if (HAS_PENDING_EXCEPTION) {
CLEAR_PENDING_EXCEPTION;
CURRENT_THREAD_ENV->record_out_of_memory_failure();
return ciEnv::_unloaded_cisymbol;
}
return CURRENT_THREAD_ENV->get_symbol(sym);
}
// ------------------------------------------------------------------
// ciSymbol::make
//
// Make a ciSymbol from a C string.
ciSymbol* ciSymbol::make(const char* s) {
GUARDED_VM_ENTRY(return make_impl(s);)
}
| gpl-2.0 |
dchadic/linux-cmps107 | drivers/net/wireless/intel/iwlwifi/mvm/power.c | 47 | 31809 | /******************************************************************************
*
* This file is provided under a dual BSD/GPLv2 license. When using or
* redistributing this file, you may do so under either license.
*
* GPL LICENSE SUMMARY
*
* Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
* Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH
* Copyright(c) 2015 Intel Deutschland GmbH
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110,
* USA
*
* The full GNU General Public License is included in this distribution
* in the file called COPYING.
*
* Contact Information:
* Intel Linux Wireless <linuxwifi@intel.com>
* Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*
* BSD LICENSE
*
* Copyright(c) 2012 - 2014 Intel Corporation. All rights reserved.
* Copyright(c) 2013 - 2014 Intel Mobile Communications GmbH
* Copyright(c) 2015 Intel Deutschland GmbH
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name Intel Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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 <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/etherdevice.h>
#include <net/mac80211.h>
#include "iwl-debug.h"
#include "mvm.h"
#include "iwl-modparams.h"
#include "fw-api-power.h"
#define POWER_KEEP_ALIVE_PERIOD_SEC 25
static
int iwl_mvm_beacon_filter_send_cmd(struct iwl_mvm *mvm,
struct iwl_beacon_filter_cmd *cmd,
u32 flags)
{
IWL_DEBUG_POWER(mvm, "ba_enable_beacon_abort is: %d\n",
le32_to_cpu(cmd->ba_enable_beacon_abort));
IWL_DEBUG_POWER(mvm, "ba_escape_timer is: %d\n",
le32_to_cpu(cmd->ba_escape_timer));
IWL_DEBUG_POWER(mvm, "bf_debug_flag is: %d\n",
le32_to_cpu(cmd->bf_debug_flag));
IWL_DEBUG_POWER(mvm, "bf_enable_beacon_filter is: %d\n",
le32_to_cpu(cmd->bf_enable_beacon_filter));
IWL_DEBUG_POWER(mvm, "bf_energy_delta is: %d\n",
le32_to_cpu(cmd->bf_energy_delta));
IWL_DEBUG_POWER(mvm, "bf_escape_timer is: %d\n",
le32_to_cpu(cmd->bf_escape_timer));
IWL_DEBUG_POWER(mvm, "bf_roaming_energy_delta is: %d\n",
le32_to_cpu(cmd->bf_roaming_energy_delta));
IWL_DEBUG_POWER(mvm, "bf_roaming_state is: %d\n",
le32_to_cpu(cmd->bf_roaming_state));
IWL_DEBUG_POWER(mvm, "bf_temp_threshold is: %d\n",
le32_to_cpu(cmd->bf_temp_threshold));
IWL_DEBUG_POWER(mvm, "bf_temp_fast_filter is: %d\n",
le32_to_cpu(cmd->bf_temp_fast_filter));
IWL_DEBUG_POWER(mvm, "bf_temp_slow_filter is: %d\n",
le32_to_cpu(cmd->bf_temp_slow_filter));
return iwl_mvm_send_cmd_pdu(mvm, REPLY_BEACON_FILTERING_CMD, flags,
sizeof(struct iwl_beacon_filter_cmd), cmd);
}
static
void iwl_mvm_beacon_filter_set_cqm_params(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_beacon_filter_cmd *cmd,
bool d0i3)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
if (vif->bss_conf.cqm_rssi_thold && !d0i3) {
cmd->bf_energy_delta =
cpu_to_le32(vif->bss_conf.cqm_rssi_hyst);
/* fw uses an absolute value for this */
cmd->bf_roaming_state =
cpu_to_le32(-vif->bss_conf.cqm_rssi_thold);
}
cmd->ba_enable_beacon_abort = cpu_to_le32(mvmvif->bf_data.ba_enabled);
}
static void iwl_mvm_power_log(struct iwl_mvm *mvm,
struct iwl_mac_power_cmd *cmd)
{
IWL_DEBUG_POWER(mvm,
"Sending power table command on mac id 0x%X for power level %d, flags = 0x%X\n",
cmd->id_and_color, iwlmvm_mod_params.power_scheme,
le16_to_cpu(cmd->flags));
IWL_DEBUG_POWER(mvm, "Keep alive = %u sec\n",
le16_to_cpu(cmd->keep_alive_seconds));
if (!(cmd->flags & cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK))) {
IWL_DEBUG_POWER(mvm, "Disable power management\n");
return;
}
IWL_DEBUG_POWER(mvm, "Rx timeout = %u usec\n",
le32_to_cpu(cmd->rx_data_timeout));
IWL_DEBUG_POWER(mvm, "Tx timeout = %u usec\n",
le32_to_cpu(cmd->tx_data_timeout));
if (cmd->flags & cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK))
IWL_DEBUG_POWER(mvm, "DTIM periods to skip = %u\n",
cmd->skip_dtim_periods);
if (cmd->flags & cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK))
IWL_DEBUG_POWER(mvm, "LP RX RSSI threshold = %u\n",
cmd->lprx_rssi_threshold);
if (cmd->flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK)) {
IWL_DEBUG_POWER(mvm, "uAPSD enabled\n");
IWL_DEBUG_POWER(mvm, "Rx timeout (uAPSD) = %u usec\n",
le32_to_cpu(cmd->rx_data_timeout_uapsd));
IWL_DEBUG_POWER(mvm, "Tx timeout (uAPSD) = %u usec\n",
le32_to_cpu(cmd->tx_data_timeout_uapsd));
IWL_DEBUG_POWER(mvm, "QNDP TID = %d\n", cmd->qndp_tid);
IWL_DEBUG_POWER(mvm, "ACs flags = 0x%x\n", cmd->uapsd_ac_flags);
IWL_DEBUG_POWER(mvm, "Max SP = %d\n", cmd->uapsd_max_sp);
}
}
static void iwl_mvm_power_configure_uapsd(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_mac_power_cmd *cmd)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
enum ieee80211_ac_numbers ac;
bool tid_found = false;
for (ac = IEEE80211_AC_VO; ac <= IEEE80211_AC_BK; ac++) {
if (!mvmvif->queue_params[ac].uapsd)
continue;
if (mvm->cur_ucode != IWL_UCODE_WOWLAN)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK);
cmd->uapsd_ac_flags |= BIT(ac);
/* QNDP TID - the highest TID with no admission control */
if (!tid_found && !mvmvif->queue_params[ac].acm) {
tid_found = true;
switch (ac) {
case IEEE80211_AC_VO:
cmd->qndp_tid = 6;
break;
case IEEE80211_AC_VI:
cmd->qndp_tid = 5;
break;
case IEEE80211_AC_BE:
cmd->qndp_tid = 0;
break;
case IEEE80211_AC_BK:
cmd->qndp_tid = 1;
break;
}
}
}
if (!(cmd->flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK))) {
#ifdef CONFIG_IWLWIFI_DEBUGFS
/* set advanced pm flag with no uapsd ACs to enable ps-poll */
if (mvmvif->dbgfs_pm.use_ps_poll)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK);
#endif
return;
}
cmd->flags |= cpu_to_le16(POWER_FLAGS_UAPSD_MISBEHAVING_ENA_MSK);
if (cmd->uapsd_ac_flags == (BIT(IEEE80211_AC_VO) |
BIT(IEEE80211_AC_VI) |
BIT(IEEE80211_AC_BE) |
BIT(IEEE80211_AC_BK))) {
cmd->flags |= cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK);
cmd->snooze_interval = cpu_to_le16(IWL_MVM_PS_SNOOZE_INTERVAL);
cmd->snooze_window = (mvm->cur_ucode == IWL_UCODE_WOWLAN) ?
cpu_to_le16(IWL_MVM_WOWLAN_PS_SNOOZE_WINDOW) :
cpu_to_le16(IWL_MVM_PS_SNOOZE_WINDOW);
}
cmd->uapsd_max_sp = IWL_UAPSD_MAX_SP;
if (mvm->cur_ucode == IWL_UCODE_WOWLAN || cmd->flags &
cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) {
cmd->rx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_WOWLAN_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_WOWLAN_PS_TX_DATA_TIMEOUT);
} else {
cmd->rx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_UAPSD_RX_DATA_TIMEOUT);
cmd->tx_data_timeout_uapsd =
cpu_to_le32(IWL_MVM_UAPSD_TX_DATA_TIMEOUT);
}
if (cmd->flags & cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)) {
cmd->heavy_tx_thld_packets =
IWL_MVM_PS_SNOOZE_HEAVY_TX_THLD_PACKETS;
cmd->heavy_rx_thld_packets =
IWL_MVM_PS_SNOOZE_HEAVY_RX_THLD_PACKETS;
} else {
cmd->heavy_tx_thld_packets =
IWL_MVM_PS_HEAVY_TX_THLD_PACKETS;
cmd->heavy_rx_thld_packets =
IWL_MVM_PS_HEAVY_RX_THLD_PACKETS;
}
cmd->heavy_tx_thld_percentage =
IWL_MVM_PS_HEAVY_TX_THLD_PERCENT;
cmd->heavy_rx_thld_percentage =
IWL_MVM_PS_HEAVY_RX_THLD_PERCENT;
}
static bool iwl_mvm_power_allow_uapsd(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
if (!memcmp(mvmvif->uapsd_misbehaving_bssid, vif->bss_conf.bssid,
ETH_ALEN))
return false;
if (vif->p2p &&
!(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_P2P_PS_UAPSD))
return false;
/*
* Avoid using uAPSD if P2P client is associated to GO that uses
* opportunistic power save. This is due to current FW limitation.
*/
if (vif->p2p &&
(vif->bss_conf.p2p_noa_attr.oppps_ctwindow &
IEEE80211_P2P_OPPPS_ENABLE_BIT))
return false;
/*
* Avoid using uAPSD if client is in DCM -
* low latency issue in Miracast
*/
if (iwl_mvm_phy_ctx_count(mvm) >= 2)
return false;
return true;
}
static bool iwl_mvm_power_is_radar(struct ieee80211_vif *vif)
{
struct ieee80211_chanctx_conf *chanctx_conf;
struct ieee80211_channel *chan;
bool radar_detect = false;
rcu_read_lock();
chanctx_conf = rcu_dereference(vif->chanctx_conf);
WARN_ON(!chanctx_conf);
if (chanctx_conf) {
chan = chanctx_conf->def.chan;
radar_detect = chan->flags & IEEE80211_CHAN_RADAR;
}
rcu_read_unlock();
return radar_detect;
}
static void iwl_mvm_power_config_skip_dtim(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_mac_power_cmd *cmd,
bool host_awake)
{
int dtimper = vif->bss_conf.dtim_period ?: 1;
int skip;
/* disable, in case we're supposed to override */
cmd->skip_dtim_periods = 0;
cmd->flags &= ~cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK);
if (iwl_mvm_power_is_radar(vif))
return;
if (dtimper >= 10)
return;
/* TODO: check that multicast wake lock is off */
if (host_awake) {
if (iwlmvm_mod_params.power_scheme != IWL_POWER_SCHEME_LP)
return;
skip = 2;
} else {
int dtimper_tu = dtimper * vif->bss_conf.beacon_int;
if (WARN_ON(!dtimper_tu))
return;
/* configure skip over dtim up to 306TU - 314 msec */
skip = max_t(u8, 1, 306 / dtimper_tu);
}
/* the firmware really expects "look at every X DTIMs", so add 1 */
cmd->skip_dtim_periods = 1 + skip;
cmd->flags |= cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK);
}
static void iwl_mvm_power_build_cmd(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_mac_power_cmd *cmd,
bool host_awake)
{
int dtimper, bi;
int keep_alive;
struct iwl_mvm_vif *mvmvif __maybe_unused =
iwl_mvm_vif_from_mac80211(vif);
cmd->id_and_color = cpu_to_le32(FW_CMD_ID_AND_COLOR(mvmvif->id,
mvmvif->color));
dtimper = vif->bss_conf.dtim_period;
bi = vif->bss_conf.beacon_int;
/*
* Regardless of power management state the driver must set
* keep alive period. FW will use it for sending keep alive NDPs
* immediately after association. Check that keep alive period
* is at least 3 * DTIM
*/
keep_alive = DIV_ROUND_UP(ieee80211_tu_to_usec(3 * dtimper * bi),
USEC_PER_SEC);
keep_alive = max(keep_alive, POWER_KEEP_ALIVE_PERIOD_SEC);
cmd->keep_alive_seconds = cpu_to_le16(keep_alive);
if (mvm->ps_disabled)
return;
cmd->flags |= cpu_to_le16(POWER_FLAGS_POWER_SAVE_ENA_MSK);
if (!vif->bss_conf.ps || !mvmvif->pm_enabled)
return;
if (iwl_mvm_vif_low_latency(mvmvif) && vif->p2p &&
(!fw_has_capa(&mvm->fw->ucode_capa,
IWL_UCODE_TLV_CAPA_SHORT_PM_TIMEOUTS) ||
!IWL_MVM_P2P_LOWLATENCY_PS_ENABLE))
return;
cmd->flags |= cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK);
if (vif->bss_conf.beacon_rate &&
(vif->bss_conf.beacon_rate->bitrate == 10 ||
vif->bss_conf.beacon_rate->bitrate == 60)) {
cmd->flags |= cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK);
cmd->lprx_rssi_threshold = POWER_LPRX_RSSI_THRESHOLD;
}
iwl_mvm_power_config_skip_dtim(mvm, vif, cmd, host_awake);
if (!host_awake) {
cmd->rx_data_timeout =
cpu_to_le32(IWL_MVM_WOWLAN_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout =
cpu_to_le32(IWL_MVM_WOWLAN_PS_TX_DATA_TIMEOUT);
} else if (iwl_mvm_vif_low_latency(mvmvif) && vif->p2p &&
fw_has_capa(&mvm->fw->ucode_capa,
IWL_UCODE_TLV_CAPA_SHORT_PM_TIMEOUTS)) {
cmd->tx_data_timeout =
cpu_to_le32(IWL_MVM_SHORT_PS_TX_DATA_TIMEOUT);
cmd->rx_data_timeout =
cpu_to_le32(IWL_MVM_SHORT_PS_RX_DATA_TIMEOUT);
} else {
cmd->rx_data_timeout =
cpu_to_le32(IWL_MVM_DEFAULT_PS_RX_DATA_TIMEOUT);
cmd->tx_data_timeout =
cpu_to_le32(IWL_MVM_DEFAULT_PS_TX_DATA_TIMEOUT);
}
if (iwl_mvm_power_allow_uapsd(mvm, vif))
iwl_mvm_power_configure_uapsd(mvm, vif, cmd);
#ifdef CONFIG_IWLWIFI_DEBUGFS
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_KEEP_ALIVE)
cmd->keep_alive_seconds =
cpu_to_le16(mvmvif->dbgfs_pm.keep_alive_seconds);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SKIP_OVER_DTIM) {
if (mvmvif->dbgfs_pm.skip_over_dtim)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK);
else
cmd->flags &=
cpu_to_le16(~POWER_FLAGS_SKIP_OVER_DTIM_MSK);
}
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_RX_DATA_TIMEOUT)
cmd->rx_data_timeout =
cpu_to_le32(mvmvif->dbgfs_pm.rx_data_timeout);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_TX_DATA_TIMEOUT)
cmd->tx_data_timeout =
cpu_to_le32(mvmvif->dbgfs_pm.tx_data_timeout);
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SKIP_DTIM_PERIODS)
cmd->skip_dtim_periods = mvmvif->dbgfs_pm.skip_dtim_periods;
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_LPRX_ENA) {
if (mvmvif->dbgfs_pm.lprx_ena)
cmd->flags |= cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK);
else
cmd->flags &= cpu_to_le16(~POWER_FLAGS_LPRX_ENA_MSK);
}
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_LPRX_RSSI_THRESHOLD)
cmd->lprx_rssi_threshold = mvmvif->dbgfs_pm.lprx_rssi_threshold;
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_SNOOZE_ENABLE) {
if (mvmvif->dbgfs_pm.snooze_ena)
cmd->flags |=
cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK);
else
cmd->flags &=
cpu_to_le16(~POWER_FLAGS_SNOOZE_ENA_MSK);
}
if (mvmvif->dbgfs_pm.mask & MVM_DEBUGFS_PM_UAPSD_MISBEHAVING) {
u16 flag = POWER_FLAGS_UAPSD_MISBEHAVING_ENA_MSK;
if (mvmvif->dbgfs_pm.uapsd_misbehaving)
cmd->flags |= cpu_to_le16(flag);
else
cmd->flags &= cpu_to_le16(flag);
}
#endif /* CONFIG_IWLWIFI_DEBUGFS */
}
static int iwl_mvm_power_send_cmd(struct iwl_mvm *mvm,
struct ieee80211_vif *vif)
{
struct iwl_mac_power_cmd cmd = {};
iwl_mvm_power_build_cmd(mvm, vif, &cmd,
mvm->cur_ucode != IWL_UCODE_WOWLAN);
iwl_mvm_power_log(mvm, &cmd);
#ifdef CONFIG_IWLWIFI_DEBUGFS
memcpy(&iwl_mvm_vif_from_mac80211(vif)->mac_pwr_cmd, &cmd, sizeof(cmd));
#endif
return iwl_mvm_send_cmd_pdu(mvm, MAC_PM_POWER_TABLE, 0,
sizeof(cmd), &cmd);
}
int iwl_mvm_power_update_device(struct iwl_mvm *mvm)
{
struct iwl_device_power_cmd cmd = {
.flags = 0,
};
if (iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_CAM)
mvm->ps_disabled = true;
if (!mvm->ps_disabled)
cmd.flags |= cpu_to_le16(DEVICE_POWER_FLAGS_POWER_SAVE_ENA_MSK);
#ifdef CONFIG_IWLWIFI_DEBUGFS
if ((mvm->cur_ucode == IWL_UCODE_WOWLAN) ? mvm->disable_power_off_d3 :
mvm->disable_power_off)
cmd.flags &=
cpu_to_le16(~DEVICE_POWER_FLAGS_POWER_SAVE_ENA_MSK);
#endif
IWL_DEBUG_POWER(mvm,
"Sending device power command with flags = 0x%X\n",
cmd.flags);
return iwl_mvm_send_cmd_pdu(mvm, POWER_TABLE_CMD, 0, sizeof(cmd),
&cmd);
}
void iwl_mvm_power_vif_assoc(struct iwl_mvm *mvm, struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
if (memcmp(vif->bss_conf.bssid, mvmvif->uapsd_misbehaving_bssid,
ETH_ALEN))
eth_zero_addr(mvmvif->uapsd_misbehaving_bssid);
}
static void iwl_mvm_power_uapsd_misbehav_ap_iterator(void *_data, u8 *mac,
struct ieee80211_vif *vif)
{
u8 *ap_sta_id = _data;
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
/* The ap_sta_id is not expected to change during current association
* so no explicit protection is needed
*/
if (mvmvif->ap_sta_id == *ap_sta_id)
memcpy(mvmvif->uapsd_misbehaving_bssid, vif->bss_conf.bssid,
ETH_ALEN);
}
void iwl_mvm_power_uapsd_misbehaving_ap_notif(struct iwl_mvm *mvm,
struct iwl_rx_cmd_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
struct iwl_uapsd_misbehaving_ap_notif *notif = (void *)pkt->data;
u8 ap_sta_id = le32_to_cpu(notif->sta_id);
ieee80211_iterate_active_interfaces_atomic(
mvm->hw, IEEE80211_IFACE_ITER_NORMAL,
iwl_mvm_power_uapsd_misbehav_ap_iterator, &ap_sta_id);
}
struct iwl_power_vifs {
struct iwl_mvm *mvm;
struct ieee80211_vif *bf_vif;
struct ieee80211_vif *bss_vif;
struct ieee80211_vif *p2p_vif;
struct ieee80211_vif *ap_vif;
struct ieee80211_vif *monitor_vif;
bool p2p_active;
bool bss_active;
bool ap_active;
bool monitor_active;
};
static void iwl_mvm_power_disable_pm_iterator(void *_data, u8* mac,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
mvmvif->pm_enabled = false;
}
static void iwl_mvm_power_ps_disabled_iterator(void *_data, u8* mac,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
bool *disable_ps = _data;
if (mvmvif->phy_ctxt)
if (mvmvif->phy_ctxt->id < MAX_PHYS)
*disable_ps |= mvmvif->ps_disabled;
}
static void iwl_mvm_power_get_vifs_iterator(void *_data, u8 *mac,
struct ieee80211_vif *vif)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_power_vifs *power_iterator = _data;
switch (ieee80211_vif_type_p2p(vif)) {
case NL80211_IFTYPE_P2P_DEVICE:
break;
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_AP:
/* only a single MAC of the same type */
WARN_ON(power_iterator->ap_vif);
power_iterator->ap_vif = vif;
if (mvmvif->phy_ctxt)
if (mvmvif->phy_ctxt->id < MAX_PHYS)
power_iterator->ap_active = true;
break;
case NL80211_IFTYPE_MONITOR:
/* only a single MAC of the same type */
WARN_ON(power_iterator->monitor_vif);
power_iterator->monitor_vif = vif;
if (mvmvif->phy_ctxt)
if (mvmvif->phy_ctxt->id < MAX_PHYS)
power_iterator->monitor_active = true;
break;
case NL80211_IFTYPE_P2P_CLIENT:
/* only a single MAC of the same type */
WARN_ON(power_iterator->p2p_vif);
power_iterator->p2p_vif = vif;
if (mvmvif->phy_ctxt)
if (mvmvif->phy_ctxt->id < MAX_PHYS)
power_iterator->p2p_active = true;
break;
case NL80211_IFTYPE_STATION:
power_iterator->bss_vif = vif;
if (mvmvif->phy_ctxt)
if (mvmvif->phy_ctxt->id < MAX_PHYS)
power_iterator->bss_active = true;
if (mvmvif->bf_data.bf_enabled &&
!WARN_ON(power_iterator->bf_vif))
power_iterator->bf_vif = vif;
break;
default:
break;
}
}
static void iwl_mvm_power_set_pm(struct iwl_mvm *mvm,
struct iwl_power_vifs *vifs)
{
struct iwl_mvm_vif *bss_mvmvif = NULL;
struct iwl_mvm_vif *p2p_mvmvif = NULL;
struct iwl_mvm_vif *ap_mvmvif = NULL;
bool client_same_channel = false;
bool ap_same_channel = false;
lockdep_assert_held(&mvm->mutex);
/* set pm_enable to false */
ieee80211_iterate_active_interfaces_atomic(mvm->hw,
IEEE80211_IFACE_ITER_NORMAL,
iwl_mvm_power_disable_pm_iterator,
NULL);
if (vifs->bss_vif)
bss_mvmvif = iwl_mvm_vif_from_mac80211(vifs->bss_vif);
if (vifs->p2p_vif)
p2p_mvmvif = iwl_mvm_vif_from_mac80211(vifs->p2p_vif);
if (vifs->ap_vif)
ap_mvmvif = iwl_mvm_vif_from_mac80211(vifs->ap_vif);
/* don't allow PM if any TDLS stations exist */
if (iwl_mvm_tdls_sta_count(mvm, NULL))
return;
/* enable PM on bss if bss stand alone */
if (vifs->bss_active && !vifs->p2p_active && !vifs->ap_active) {
bss_mvmvif->pm_enabled = true;
return;
}
/* enable PM on p2p if p2p stand alone */
if (vifs->p2p_active && !vifs->bss_active && !vifs->ap_active) {
if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_P2P_PM)
p2p_mvmvif->pm_enabled = true;
return;
}
if (vifs->bss_active && vifs->p2p_active)
client_same_channel = (bss_mvmvif->phy_ctxt->id ==
p2p_mvmvif->phy_ctxt->id);
if (vifs->bss_active && vifs->ap_active)
ap_same_channel = (bss_mvmvif->phy_ctxt->id ==
ap_mvmvif->phy_ctxt->id);
/* clients are not stand alone: enable PM if DCM */
if (!(client_same_channel || ap_same_channel) &&
(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_BSS_P2P_PS_DCM)) {
if (vifs->bss_active)
bss_mvmvif->pm_enabled = true;
if (vifs->p2p_active &&
(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_P2P_PM))
p2p_mvmvif->pm_enabled = true;
return;
}
/*
* There is only one channel in the system and there are only
* bss and p2p clients that share it
*/
if (client_same_channel && !vifs->ap_active &&
(mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_BSS_P2P_PS_SCM)) {
/* share same channel*/
bss_mvmvif->pm_enabled = true;
if (mvm->fw->ucode_capa.flags & IWL_UCODE_TLV_FLAGS_P2P_PM)
p2p_mvmvif->pm_enabled = true;
}
}
#ifdef CONFIG_IWLWIFI_DEBUGFS
int iwl_mvm_power_mac_dbgfs_read(struct iwl_mvm *mvm,
struct ieee80211_vif *vif, char *buf,
int bufsz)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_mac_power_cmd cmd = {};
int pos = 0;
mutex_lock(&mvm->mutex);
memcpy(&cmd, &mvmvif->mac_pwr_cmd, sizeof(cmd));
mutex_unlock(&mvm->mutex);
pos += scnprintf(buf+pos, bufsz-pos, "power_scheme = %d\n",
iwlmvm_mod_params.power_scheme);
pos += scnprintf(buf+pos, bufsz-pos, "flags = 0x%x\n",
le16_to_cpu(cmd.flags));
pos += scnprintf(buf+pos, bufsz-pos, "keep_alive = %d\n",
le16_to_cpu(cmd.keep_alive_seconds));
if (!(cmd.flags & cpu_to_le16(POWER_FLAGS_POWER_MANAGEMENT_ENA_MSK)))
return pos;
pos += scnprintf(buf+pos, bufsz-pos, "skip_over_dtim = %d\n",
(cmd.flags &
cpu_to_le16(POWER_FLAGS_SKIP_OVER_DTIM_MSK)) ? 1 : 0);
pos += scnprintf(buf+pos, bufsz-pos, "skip_dtim_periods = %d\n",
cmd.skip_dtim_periods);
if (!(cmd.flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK))) {
pos += scnprintf(buf+pos, bufsz-pos, "rx_data_timeout = %d\n",
le32_to_cpu(cmd.rx_data_timeout));
pos += scnprintf(buf+pos, bufsz-pos, "tx_data_timeout = %d\n",
le32_to_cpu(cmd.tx_data_timeout));
}
if (cmd.flags & cpu_to_le16(POWER_FLAGS_LPRX_ENA_MSK))
pos += scnprintf(buf+pos, bufsz-pos,
"lprx_rssi_threshold = %d\n",
cmd.lprx_rssi_threshold);
if (!(cmd.flags & cpu_to_le16(POWER_FLAGS_ADVANCE_PM_ENA_MSK)))
return pos;
pos += scnprintf(buf+pos, bufsz-pos, "rx_data_timeout_uapsd = %d\n",
le32_to_cpu(cmd.rx_data_timeout_uapsd));
pos += scnprintf(buf+pos, bufsz-pos, "tx_data_timeout_uapsd = %d\n",
le32_to_cpu(cmd.tx_data_timeout_uapsd));
pos += scnprintf(buf+pos, bufsz-pos, "qndp_tid = %d\n", cmd.qndp_tid);
pos += scnprintf(buf+pos, bufsz-pos, "uapsd_ac_flags = 0x%x\n",
cmd.uapsd_ac_flags);
pos += scnprintf(buf+pos, bufsz-pos, "uapsd_max_sp = %d\n",
cmd.uapsd_max_sp);
pos += scnprintf(buf+pos, bufsz-pos, "heavy_tx_thld_packets = %d\n",
cmd.heavy_tx_thld_packets);
pos += scnprintf(buf+pos, bufsz-pos, "heavy_rx_thld_packets = %d\n",
cmd.heavy_rx_thld_packets);
pos += scnprintf(buf+pos, bufsz-pos, "heavy_tx_thld_percentage = %d\n",
cmd.heavy_tx_thld_percentage);
pos += scnprintf(buf+pos, bufsz-pos, "heavy_rx_thld_percentage = %d\n",
cmd.heavy_rx_thld_percentage);
pos += scnprintf(buf+pos, bufsz-pos, "uapsd_misbehaving_enable = %d\n",
(cmd.flags &
cpu_to_le16(POWER_FLAGS_UAPSD_MISBEHAVING_ENA_MSK)) ?
1 : 0);
if (!(cmd.flags & cpu_to_le16(POWER_FLAGS_SNOOZE_ENA_MSK)))
return pos;
pos += scnprintf(buf+pos, bufsz-pos, "snooze_interval = %d\n",
cmd.snooze_interval);
pos += scnprintf(buf+pos, bufsz-pos, "snooze_window = %d\n",
cmd.snooze_window);
return pos;
}
void
iwl_mvm_beacon_filter_debugfs_parameters(struct ieee80211_vif *vif,
struct iwl_beacon_filter_cmd *cmd)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_dbgfs_bf *dbgfs_bf = &mvmvif->dbgfs_bf;
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ENERGY_DELTA)
cmd->bf_energy_delta = cpu_to_le32(dbgfs_bf->bf_energy_delta);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ROAMING_ENERGY_DELTA)
cmd->bf_roaming_energy_delta =
cpu_to_le32(dbgfs_bf->bf_roaming_energy_delta);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ROAMING_STATE)
cmd->bf_roaming_state = cpu_to_le32(dbgfs_bf->bf_roaming_state);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_THRESHOLD)
cmd->bf_temp_threshold =
cpu_to_le32(dbgfs_bf->bf_temp_threshold);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_FAST_FILTER)
cmd->bf_temp_fast_filter =
cpu_to_le32(dbgfs_bf->bf_temp_fast_filter);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_TEMP_SLOW_FILTER)
cmd->bf_temp_slow_filter =
cpu_to_le32(dbgfs_bf->bf_temp_slow_filter);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_DEBUG_FLAG)
cmd->bf_debug_flag = cpu_to_le32(dbgfs_bf->bf_debug_flag);
if (dbgfs_bf->mask & MVM_DEBUGFS_BF_ESCAPE_TIMER)
cmd->bf_escape_timer = cpu_to_le32(dbgfs_bf->bf_escape_timer);
if (dbgfs_bf->mask & MVM_DEBUGFS_BA_ESCAPE_TIMER)
cmd->ba_escape_timer = cpu_to_le32(dbgfs_bf->ba_escape_timer);
if (dbgfs_bf->mask & MVM_DEBUGFS_BA_ENABLE_BEACON_ABORT)
cmd->ba_enable_beacon_abort =
cpu_to_le32(dbgfs_bf->ba_enable_beacon_abort);
}
#endif
static int _iwl_mvm_enable_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
struct iwl_beacon_filter_cmd *cmd,
u32 cmd_flags,
bool d0i3)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
int ret;
if (mvmvif != mvm->bf_allowed_vif || !vif->bss_conf.dtim_period ||
vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
iwl_mvm_beacon_filter_set_cqm_params(mvm, vif, cmd, d0i3);
if (!d0i3)
iwl_mvm_beacon_filter_debugfs_parameters(vif, cmd);
ret = iwl_mvm_beacon_filter_send_cmd(mvm, cmd, cmd_flags);
/* don't change bf_enabled in case of temporary d0i3 configuration */
if (!ret && !d0i3)
mvmvif->bf_data.bf_enabled = true;
return ret;
}
int iwl_mvm_enable_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
u32 flags)
{
struct iwl_beacon_filter_cmd cmd = {
IWL_BF_CMD_CONFIG_DEFAULTS,
.bf_enable_beacon_filter = cpu_to_le32(1),
};
return _iwl_mvm_enable_beacon_filter(mvm, vif, &cmd, flags, false);
}
static int iwl_mvm_update_beacon_abort(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
bool enable)
{
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_beacon_filter_cmd cmd = {
IWL_BF_CMD_CONFIG_DEFAULTS,
.bf_enable_beacon_filter = cpu_to_le32(1),
};
if (!mvmvif->bf_data.bf_enabled)
return 0;
if (mvm->cur_ucode == IWL_UCODE_WOWLAN)
cmd.ba_escape_timer = cpu_to_le32(IWL_BA_ESCAPE_TIMER_D3);
mvmvif->bf_data.ba_enabled = enable;
return _iwl_mvm_enable_beacon_filter(mvm, vif, &cmd, 0, false);
}
int iwl_mvm_disable_beacon_filter(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
u32 flags)
{
struct iwl_beacon_filter_cmd cmd = {};
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
int ret;
if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
ret = iwl_mvm_beacon_filter_send_cmd(mvm, &cmd, flags);
if (!ret)
mvmvif->bf_data.bf_enabled = false;
return ret;
}
static int iwl_mvm_power_set_ps(struct iwl_mvm *mvm)
{
bool disable_ps;
int ret;
/* disable PS if CAM */
disable_ps = (iwlmvm_mod_params.power_scheme == IWL_POWER_SCHEME_CAM);
/* ...or if any of the vifs require PS to be off */
ieee80211_iterate_active_interfaces_atomic(mvm->hw,
IEEE80211_IFACE_ITER_NORMAL,
iwl_mvm_power_ps_disabled_iterator,
&disable_ps);
/* update device power state if it has changed */
if (mvm->ps_disabled != disable_ps) {
bool old_ps_disabled = mvm->ps_disabled;
mvm->ps_disabled = disable_ps;
ret = iwl_mvm_power_update_device(mvm);
if (ret) {
mvm->ps_disabled = old_ps_disabled;
return ret;
}
}
return 0;
}
static int iwl_mvm_power_set_ba(struct iwl_mvm *mvm,
struct iwl_power_vifs *vifs)
{
struct iwl_mvm_vif *mvmvif;
bool ba_enable;
if (!vifs->bf_vif)
return 0;
mvmvif = iwl_mvm_vif_from_mac80211(vifs->bf_vif);
ba_enable = !(!mvmvif->pm_enabled || mvm->ps_disabled ||
!vifs->bf_vif->bss_conf.ps ||
iwl_mvm_vif_low_latency(mvmvif));
return iwl_mvm_update_beacon_abort(mvm, vifs->bf_vif, ba_enable);
}
int iwl_mvm_power_update_ps(struct iwl_mvm *mvm)
{
struct iwl_power_vifs vifs = {
.mvm = mvm,
};
int ret;
lockdep_assert_held(&mvm->mutex);
/* get vifs info */
ieee80211_iterate_active_interfaces_atomic(mvm->hw,
IEEE80211_IFACE_ITER_NORMAL,
iwl_mvm_power_get_vifs_iterator, &vifs);
ret = iwl_mvm_power_set_ps(mvm);
if (ret)
return ret;
return iwl_mvm_power_set_ba(mvm, &vifs);
}
int iwl_mvm_power_update_mac(struct iwl_mvm *mvm)
{
struct iwl_power_vifs vifs = {
.mvm = mvm,
};
int ret;
lockdep_assert_held(&mvm->mutex);
/* get vifs info */
ieee80211_iterate_active_interfaces_atomic(mvm->hw,
IEEE80211_IFACE_ITER_NORMAL,
iwl_mvm_power_get_vifs_iterator, &vifs);
iwl_mvm_power_set_pm(mvm, &vifs);
ret = iwl_mvm_power_set_ps(mvm);
if (ret)
return ret;
if (vifs.bss_vif) {
ret = iwl_mvm_power_send_cmd(mvm, vifs.bss_vif);
if (ret)
return ret;
}
if (vifs.p2p_vif) {
ret = iwl_mvm_power_send_cmd(mvm, vifs.p2p_vif);
if (ret)
return ret;
}
return iwl_mvm_power_set_ba(mvm, &vifs);
}
int iwl_mvm_update_d0i3_power_mode(struct iwl_mvm *mvm,
struct ieee80211_vif *vif,
bool enable, u32 flags)
{
int ret;
struct iwl_mvm_vif *mvmvif = iwl_mvm_vif_from_mac80211(vif);
struct iwl_mac_power_cmd cmd = {};
if (vif->type != NL80211_IFTYPE_STATION || vif->p2p)
return 0;
if (!vif->bss_conf.assoc)
return 0;
iwl_mvm_power_build_cmd(mvm, vif, &cmd, !enable);
iwl_mvm_power_log(mvm, &cmd);
#ifdef CONFIG_IWLWIFI_DEBUGFS
memcpy(&mvmvif->mac_pwr_cmd, &cmd, sizeof(cmd));
#endif
ret = iwl_mvm_send_cmd_pdu(mvm, MAC_PM_POWER_TABLE, flags,
sizeof(cmd), &cmd);
if (ret)
return ret;
/* configure beacon filtering */
if (mvmvif != mvm->bf_allowed_vif)
return 0;
if (enable) {
struct iwl_beacon_filter_cmd cmd_bf = {
IWL_BF_CMD_CONFIG_D0I3,
.bf_enable_beacon_filter = cpu_to_le32(1),
};
ret = _iwl_mvm_enable_beacon_filter(mvm, vif, &cmd_bf,
flags, true);
} else {
if (mvmvif->bf_data.bf_enabled)
ret = iwl_mvm_enable_beacon_filter(mvm, vif, flags);
else
ret = iwl_mvm_disable_beacon_filter(mvm, vif, flags);
}
return ret;
}
| gpl-2.0 |
bftg/gcc-5.3.0 | libgfortran/generated/pack_c8.c | 47 | 7584 | /* Specific implementation of the PACK intrinsic
Copyright (C) 2002-2015 Free Software Foundation, Inc.
Contributed by Paul Brook <paul@nowt.org>
This file is part of the GNU Fortran runtime library (libgfortran).
Libgfortran is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
Ligbfortran is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#if defined (HAVE_GFC_COMPLEX_8)
/* PACK is specified as follows:
13.14.80 PACK (ARRAY, MASK, [VECTOR])
Description: Pack an array into an array of rank one under the
control of a mask.
Class: Transformational function.
Arguments:
ARRAY may be of any type. It shall not be scalar.
MASK shall be of type LOGICAL. It shall be conformable with ARRAY.
VECTOR (optional) shall be of the same type and type parameters
as ARRAY. VECTOR shall have at least as many elements as
there are true elements in MASK. If MASK is a scalar
with the value true, VECTOR shall have at least as many
elements as there are in ARRAY.
Result Characteristics: The result is an array of rank one with the
same type and type parameters as ARRAY. If VECTOR is present, the
result size is that of VECTOR; otherwise, the result size is the
number /t/ of true elements in MASK unless MASK is scalar with the
value true, in which case the result size is the size of ARRAY.
Result Value: Element /i/ of the result is the element of ARRAY
that corresponds to the /i/th true element of MASK, taking elements
in array element order, for /i/ = 1, 2, ..., /t/. If VECTOR is
present and has size /n/ > /t/, element /i/ of the result has the
value VECTOR(/i/), for /i/ = /t/ + 1, ..., /n/.
Examples: The nonzero elements of an array M with the value
| 0 0 0 |
| 9 0 0 | may be "gathered" by the function PACK. The result of
| 0 0 7 |
PACK (M, MASK = M.NE.0) is [9,7] and the result of PACK (M, M.NE.0,
VECTOR = (/ 2,4,6,8,10,12 /)) is [9,7,6,8,10,12].
There are two variants of the PACK intrinsic: one, where MASK is
array valued, and the other one where MASK is scalar. */
void
pack_c8 (gfc_array_c8 *ret, const gfc_array_c8 *array,
const gfc_array_l1 *mask, const gfc_array_c8 *vector)
{
/* r.* indicates the return array. */
index_type rstride0;
GFC_COMPLEX_8 * restrict rptr;
/* s.* indicates the source array. */
index_type sstride[GFC_MAX_DIMENSIONS];
index_type sstride0;
const GFC_COMPLEX_8 *sptr;
/* m.* indicates the mask array. */
index_type mstride[GFC_MAX_DIMENSIONS];
index_type mstride0;
const GFC_LOGICAL_1 *mptr;
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
int zero_sized;
index_type n;
index_type dim;
index_type nelem;
index_type total;
int mask_kind;
dim = GFC_DESCRIPTOR_RANK (array);
mptr = mask->base_addr;
/* Use the same loop for all logical types, by using GFC_LOGICAL_1
and using shifting to address size and endian issues. */
mask_kind = GFC_DESCRIPTOR_SIZE (mask);
if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8
#ifdef HAVE_GFC_LOGICAL_16
|| mask_kind == 16
#endif
)
{
/* Do not convert a NULL pointer as we use test for NULL below. */
if (mptr)
mptr = GFOR_POINTER_TO_L1 (mptr, mask_kind);
}
else
runtime_error ("Funny sized logical array");
zero_sized = 0;
for (n = 0; n < dim; n++)
{
count[n] = 0;
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
if (extent[n] <= 0)
zero_sized = 1;
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n);
mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n);
}
if (sstride[0] == 0)
sstride[0] = 1;
if (mstride[0] == 0)
mstride[0] = mask_kind;
if (zero_sized)
sptr = NULL;
else
sptr = array->base_addr;
if (ret->base_addr == NULL || unlikely (compile_options.bounds_check))
{
/* Count the elements, either for allocating memory or
for bounds checking. */
if (vector != NULL)
{
/* The return array will have as many
elements as there are in VECTOR. */
total = GFC_DESCRIPTOR_EXTENT(vector,0);
if (total < 0)
{
total = 0;
vector = NULL;
}
}
else
{
/* We have to count the true elements in MASK. */
total = count_0 (mask);
}
if (ret->base_addr == NULL)
{
/* Setup the array descriptor. */
GFC_DIMENSION_SET(ret->dim[0], 0, total-1, 1);
ret->offset = 0;
/* xmallocarray allocates a single byte for zero size. */
ret->base_addr = xmallocarray (total, sizeof (GFC_COMPLEX_8));
if (total == 0)
return;
}
else
{
/* We come here because of range checking. */
index_type ret_extent;
ret_extent = GFC_DESCRIPTOR_EXTENT(ret,0);
if (total != ret_extent)
runtime_error ("Incorrect extent in return value of PACK intrinsic;"
" is %ld, should be %ld", (long int) total,
(long int) ret_extent);
}
}
rstride0 = GFC_DESCRIPTOR_STRIDE(ret,0);
if (rstride0 == 0)
rstride0 = 1;
sstride0 = sstride[0];
mstride0 = mstride[0];
rptr = ret->base_addr;
while (sptr && mptr)
{
/* Test this element. */
if (*mptr)
{
/* Add it. */
*rptr = *sptr;
rptr += rstride0;
}
/* Advance to the next element. */
sptr += sstride0;
mptr += mstride0;
count[0]++;
n = 0;
while (count[n] == extent[n])
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
sptr -= sstride[n] * extent[n];
mptr -= mstride[n] * extent[n];
n++;
if (n >= dim)
{
/* Break out of the loop. */
sptr = NULL;
break;
}
else
{
count[n]++;
sptr += sstride[n];
mptr += mstride[n];
}
}
}
/* Add any remaining elements from VECTOR. */
if (vector)
{
n = GFC_DESCRIPTOR_EXTENT(vector,0);
nelem = ((rptr - ret->base_addr) / rstride0);
if (n > nelem)
{
sstride0 = GFC_DESCRIPTOR_STRIDE(vector,0);
if (sstride0 == 0)
sstride0 = 1;
sptr = vector->base_addr + sstride0 * nelem;
n -= nelem;
while (n--)
{
*rptr = *sptr;
rptr += rstride0;
sptr += sstride0;
}
}
}
}
#endif
| gpl-2.0 |
tiikerikissa/TrinityCore-4.3.4 | src/server/scripts/Outland/boss_doomwalker.cpp | 47 | 5557 | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
enum Texts
{
SAY_AGGRO = 0,
SAY_EARTHQUAKE = 1,
SAY_OVERRUN = 2,
SAY_SLAY = 3,
SAY_DEATH = 4
};
enum Spells
{
SPELL_EARTHQUAKE = 32686,
SPELL_SUNDER_ARMOR = 33661,
SPELL_CHAIN_LIGHTNING = 33665,
SPELL_OVERRUN = 32636,
SPELL_ENRAGE = 33653,
SPELL_MARK_DEATH = 37128,
SPELL_AURA_DEATH = 37131
};
enum Events
{
EVENT_ENRAGE = 1,
EVENT_ARMOR = 2,
EVENT_CHAIN = 3,
EVENT_QUAKE = 4,
EVENT_OVERRUN = 5
};
class boss_doomwalker : public CreatureScript
{
public:
boss_doomwalker() : CreatureScript("boss_doomwalker") { }
struct boss_doomwalkerAI : public ScriptedAI
{
boss_doomwalkerAI(Creature* creature) : ScriptedAI(creature)
{
}
void Reset()
{
_events.Reset();
_events.ScheduleEvent(EVENT_ENRAGE, 0);
_events.ScheduleEvent(EVENT_ARMOR, urand(5000, 13000));
_events.ScheduleEvent(EVENT_CHAIN, urand(10000, 30000));
_events.ScheduleEvent(EVENT_QUAKE, urand(25000, 35000));
_events.ScheduleEvent(EVENT_OVERRUN, urand(30000, 45000));
_inEnrage = false;
}
void KilledUnit(Unit* victim)
{
victim->CastSpell(victim, SPELL_MARK_DEATH, 0);
if (urand(0, 4))
return;
Talk(SAY_SLAY);
}
void JustDied(Unit* /*killer*/)
{
Talk(SAY_DEATH);
}
void EnterCombat(Unit* /*who*/)
{
Talk(SAY_AGGRO);
}
void MoveInLineOfSight(Unit* who)
{
if (who && who->GetTypeId() == TYPEID_PLAYER && me->IsValidAttackTarget(who))
if (who->HasAura(SPELL_MARK_DEATH, 0))
who->CastSpell(who, SPELL_AURA_DEATH, 1);
}
void UpdateAI(uint32 diff)
{
if (!UpdateVictim())
return;
_events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = _events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ENRAGE:
if (!HealthAbovePct(20))
{
DoCast(me, SPELL_ENRAGE);
_events.ScheduleEvent(EVENT_ENRAGE, 6000);
_inEnrage = true;
}
break;
case EVENT_OVERRUN:
Talk(SAY_OVERRUN);
DoCastVictim(SPELL_OVERRUN);
_events.ScheduleEvent(EVENT_OVERRUN, urand(25000, 40000));
break;
case EVENT_QUAKE:
if (urand(0, 1))
return;
Talk(SAY_EARTHQUAKE);
//remove enrage before casting earthquake because enrage + earthquake = 16000dmg over 8sec and all dead
if (_inEnrage)
me->RemoveAurasDueToSpell(SPELL_ENRAGE);
DoCast(me, SPELL_EARTHQUAKE);
_events.ScheduleEvent(EVENT_QUAKE, urand(30000, 55000));
break;
case EVENT_CHAIN:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true))
DoCast(target, SPELL_CHAIN_LIGHTNING);
_events.ScheduleEvent(EVENT_CHAIN, urand(7000, 27000));
break;
case EVENT_ARMOR:
DoCastVictim(SPELL_SUNDER_ARMOR);
_events.ScheduleEvent(EVENT_ARMOR, urand(10000, 25000));
break;
default:
break;
}
}
DoMeleeAttackIfReady();
}
private:
EventMap _events;
bool _inEnrage;
};
CreatureAI* GetAI(Creature* creature) const
{
return new boss_doomwalkerAI (creature);
}
};
void AddSC_boss_doomwalker()
{
new boss_doomwalker();
}
| gpl-2.0 |
CyanogenMod/android_kernel_samsung_klimtwifi | drivers/usb/dwc3/gadget.c | 47 | 59886 | /**
* gadget.c - DesignWare USB3 DRD Controller Gadget Framework Link
*
* Copyright (C) 2010-2011 Texas Instruments Incorporated - http://www.ti.com
*
* Authors: Felipe Balbi <balbi@ti.com>,
* Sebastian Andrzej Siewior <bigeasy@linutronix.de>
*
* 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.
* 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. The names of the above-listed copyright holders may not be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* ALTERNATIVELY, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2, as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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 <linux/kernel.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/list.h>
#include <linux/dma-mapping.h>
#include <linux/usb/ch9.h>
#include <linux/usb/gadget.h>
#include "core.h"
#include "gadget.h"
#include "io.h"
/**
* dwc3_gadget_set_test_mode - Enables USB2 Test Modes
* @dwc: pointer to our context structure
* @mode: the mode to set (J, K SE0 NAK, Force Enable)
*
* Caller should take care of locking. This function will
* return 0 on success or -EINVAL if wrong Test Selector
* is passed
*/
int dwc3_gadget_set_test_mode(struct dwc3 *dwc, int mode)
{
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg &= ~DWC3_DCTL_TSTCTRL_MASK;
switch (mode) {
case TEST_J:
case TEST_K:
case TEST_SE0_NAK:
case TEST_PACKET:
case TEST_FORCE_EN:
reg |= mode << 1;
break;
default:
return -EINVAL;
}
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
return 0;
}
/**
* dwc3_gadget_set_link_state - Sets USB Link to a particular State
* @dwc: pointer to our context structure
* @state: the state to put link into
*
* Caller should take care of locking. This function will
* return 0 on success or -ETIMEDOUT.
*/
int dwc3_gadget_set_link_state(struct dwc3 *dwc, enum dwc3_link_state state)
{
int retries = 10000;
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
/* set requested state */
reg |= DWC3_DCTL_ULSTCHNGREQ(state);
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
/* wait for a change in DSTS */
while (--retries) {
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
if (DWC3_DSTS_USBLNKST(reg) == state)
return 0;
udelay(5);
}
dev_vdbg(dwc->dev, "link state change request timed out\n");
return -ETIMEDOUT;
}
/**
* dwc3_gadget_resize_tx_fifos - reallocate fifo spaces for current use-case
* @dwc: pointer to our context structure
*
* This function will a best effort FIFO allocation in order
* to improve FIFO usage and throughput, while still allowing
* us to enable as many endpoints as possible.
*
* Keep in mind that this operation will be highly dependent
* on the configured size for RAM1 - which contains TxFifo -,
* the amount of endpoints enabled on coreConsultant tool, and
* the width of the Master Bus.
*
* In the ideal world, we would always be able to satisfy the
* following equation:
*
* ((512 + 2 * MDWIDTH-Bytes) + (Number of IN Endpoints - 1) * \
* (3 * (1024 + MDWIDTH-Bytes) + MDWIDTH-Bytes)) / MDWIDTH-Bytes
*
* Unfortunately, due to many variables that's not always the case.
*/
int dwc3_gadget_resize_tx_fifos(struct dwc3 *dwc)
{
int last_fifo_depth = 0;
int ram1_depth;
int fifo_size;
int mdwidth;
int num;
if (!dwc->needs_fifo_resize)
return 0;
ram1_depth = DWC3_RAM1_DEPTH(dwc->hwparams.hwparams7);
mdwidth = DWC3_MDWIDTH(dwc->hwparams.hwparams0);
/* MDWIDTH is represented in bits, we need it in bytes */
mdwidth >>= 3;
/*
* FIXME For now we will only allocate 1 wMaxPacketSize space
* for each enabled endpoint, later patches will come to
* improve this algorithm so that we better use the internal
* FIFO space
*/
for (num = 0; num < DWC3_ENDPOINTS_NUM; num++) {
struct dwc3_ep *dep = dwc->eps[num];
int fifo_number = dep->number >> 1;
int mult = 1;
int tmp;
if (!(dep->number & 1))
continue;
if (!(dep->flags & DWC3_EP_ENABLED))
continue;
if (usb_endpoint_xfer_bulk(dep->desc)
|| usb_endpoint_xfer_isoc(dep->desc))
mult = 3;
/*
* REVISIT: the following assumes we will always have enough
* space available on the FIFO RAM for all possible use cases.
* Make sure that's true somehow and change FIFO allocation
* accordingly.
*
* If we have Bulk or Isochronous endpoints, we want
* them to be able to be very, very fast. So we're giving
* those endpoints a fifo_size which is enough for 3 full
* packets
*/
tmp = mult * (dep->endpoint.maxpacket + mdwidth);
tmp += mdwidth;
fifo_size = DIV_ROUND_UP(tmp, mdwidth);
fifo_size |= (last_fifo_depth << 16);
dev_vdbg(dwc->dev, "%s: Fifo Addr %04x Size %d\n",
dep->name, last_fifo_depth, fifo_size & 0xffff);
dwc3_writel(dwc->regs, DWC3_GTXFIFOSIZ(fifo_number),
fifo_size);
last_fifo_depth += (fifo_size & 0xffff);
}
return 0;
}
void dwc3_gadget_giveback(struct dwc3_ep *dep, struct dwc3_request *req,
int status)
{
struct dwc3 *dwc = dep->dwc;
if (req->queued) {
if (req->request.num_mapped_sgs)
dep->busy_slot += req->request.num_mapped_sgs;
else
dep->busy_slot++;
/*
* Skip LINK TRB. We can't use req->trb and check for
* DWC3_TRBCTL_LINK_TRB because it points the TRB we just
* completed (not the LINK TRB).
*/
if (((dep->busy_slot & DWC3_TRB_MASK) == DWC3_TRB_NUM - 1) &&
usb_endpoint_xfer_isoc(dep->desc))
dep->busy_slot++;
}
list_del(&req->list);
req->trb = NULL;
if (req->request.status == -EINPROGRESS)
req->request.status = status;
if (dwc->ep0_bounced && dep->number == 0)
dwc->ep0_bounced = false;
else
usb_gadget_unmap_request(&dwc->gadget, &req->request,
req->direction);
dev_dbg(dwc->dev, "request %p from %s completed %d/%d ===> %d\n",
req, dep->name, req->request.actual,
req->request.length, status);
spin_unlock(&dwc->lock);
req->request.complete(&dep->endpoint, &req->request);
spin_lock(&dwc->lock);
}
static const char *dwc3_gadget_ep_cmd_string(u8 cmd)
{
switch (cmd) {
case DWC3_DEPCMD_DEPSTARTCFG:
return "Start New Configuration";
case DWC3_DEPCMD_ENDTRANSFER:
return "End Transfer";
case DWC3_DEPCMD_UPDATETRANSFER:
return "Update Transfer";
case DWC3_DEPCMD_STARTTRANSFER:
return "Start Transfer";
case DWC3_DEPCMD_CLEARSTALL:
return "Clear Stall";
case DWC3_DEPCMD_SETSTALL:
return "Set Stall";
case DWC3_DEPCMD_GETSEQNUMBER:
return "Get Data Sequence Number";
case DWC3_DEPCMD_SETTRANSFRESOURCE:
return "Set Endpoint Transfer Resource";
case DWC3_DEPCMD_SETEPCONFIG:
return "Set Endpoint Configuration";
default:
return "UNKNOWN command";
}
}
int dwc3_send_gadget_ep_cmd(struct dwc3 *dwc, unsigned ep,
unsigned cmd, struct dwc3_gadget_ep_cmd_params *params)
{
struct dwc3_ep *dep = dwc->eps[ep];
u32 timeout = 500;
u32 reg;
dev_vdbg(dwc->dev, "%s: cmd '%s' params %08x %08x %08x\n",
dep->name,
dwc3_gadget_ep_cmd_string(cmd), params->param0,
params->param1, params->param2);
dwc3_writel(dwc->regs, DWC3_DEPCMDPAR0(ep), params->param0);
dwc3_writel(dwc->regs, DWC3_DEPCMDPAR1(ep), params->param1);
dwc3_writel(dwc->regs, DWC3_DEPCMDPAR2(ep), params->param2);
dwc3_writel(dwc->regs, DWC3_DEPCMD(ep), cmd | DWC3_DEPCMD_CMDACT);
do {
reg = dwc3_readl(dwc->regs, DWC3_DEPCMD(ep));
if (!(reg & DWC3_DEPCMD_CMDACT)) {
dev_vdbg(dwc->dev, "Command Complete --> %d\n",
DWC3_DEPCMD_STATUS(reg));
return 0;
}
/*
* We can't sleep here, because it is also called from
* interrupt context.
*/
timeout--;
if (!timeout)
return -ETIMEDOUT;
udelay(1);
} while (1);
}
static dma_addr_t dwc3_trb_dma_offset(struct dwc3_ep *dep,
struct dwc3_trb *trb)
{
u32 offset = (char *) trb - (char *) dep->trb_pool;
return dep->trb_pool_dma + offset;
}
static int dwc3_alloc_trb_pool(struct dwc3_ep *dep)
{
struct dwc3 *dwc = dep->dwc;
if (dep->trb_pool)
return 0;
if (dep->number == 0 || dep->number == 1)
return 0;
dep->trb_pool = dma_alloc_coherent(dwc->dev,
sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
&dep->trb_pool_dma, GFP_KERNEL);
if (!dep->trb_pool) {
dev_err(dep->dwc->dev, "failed to allocate trb pool for %s\n",
dep->name);
return -ENOMEM;
}
return 0;
}
static void dwc3_free_trb_pool(struct dwc3_ep *dep)
{
struct dwc3 *dwc = dep->dwc;
dma_free_coherent(dwc->dev, sizeof(struct dwc3_trb) * DWC3_TRB_NUM,
dep->trb_pool, dep->trb_pool_dma);
dep->trb_pool = NULL;
dep->trb_pool_dma = 0;
}
static int dwc3_gadget_start_config(struct dwc3 *dwc, struct dwc3_ep *dep)
{
struct dwc3_gadget_ep_cmd_params params;
u32 cmd;
memset(¶ms, 0x00, sizeof(params));
if (dep->number != 1) {
cmd = DWC3_DEPCMD_DEPSTARTCFG;
/* XferRscIdx == 0 for ep0 and 2 for the remaining */
if (dep->number > 1) {
if (dwc->start_config_issued)
return 0;
dwc->start_config_issued = true;
cmd |= DWC3_DEPCMD_PARAM(2);
}
return dwc3_send_gadget_ep_cmd(dwc, 0, cmd, ¶ms);
}
return 0;
}
static int dwc3_gadget_set_ep_config(struct dwc3 *dwc, struct dwc3_ep *dep,
const struct usb_endpoint_descriptor *desc,
const struct usb_ss_ep_comp_descriptor *comp_desc)
{
struct dwc3_gadget_ep_cmd_params params;
memset(¶ms, 0x00, sizeof(params));
params.param0 = DWC3_DEPCFG_EP_TYPE(usb_endpoint_type(desc))
| DWC3_DEPCFG_MAX_PACKET_SIZE(usb_endpoint_maxp(desc))
| DWC3_DEPCFG_BURST_SIZE(dep->endpoint.maxburst);
params.param1 = DWC3_DEPCFG_XFER_COMPLETE_EN
| DWC3_DEPCFG_XFER_NOT_READY_EN;
if (usb_ss_max_streams(comp_desc) && usb_endpoint_xfer_bulk(desc)) {
params.param1 |= DWC3_DEPCFG_STREAM_CAPABLE
| DWC3_DEPCFG_STREAM_EVENT_EN;
dep->stream_capable = true;
}
if (usb_endpoint_xfer_isoc(desc))
params.param1 |= DWC3_DEPCFG_XFER_IN_PROGRESS_EN;
/*
* We are doing 1:1 mapping for endpoints, meaning
* Physical Endpoints 2 maps to Logical Endpoint 2 and
* so on. We consider the direction bit as part of the physical
* endpoint number. So USB endpoint 0x81 is 0x03.
*/
params.param1 |= DWC3_DEPCFG_EP_NUMBER(dep->number);
/*
* We must use the lower 16 TX FIFOs even though
* HW might have more
*/
if (dep->direction)
params.param0 |= DWC3_DEPCFG_FIFO_NUMBER(dep->number >> 1);
if (desc->bInterval) {
params.param1 |= DWC3_DEPCFG_BINTERVAL_M1(desc->bInterval - 1);
dep->interval = 1 << (desc->bInterval - 1);
}
return dwc3_send_gadget_ep_cmd(dwc, dep->number,
DWC3_DEPCMD_SETEPCONFIG, ¶ms);
}
static int dwc3_gadget_set_xfer_resource(struct dwc3 *dwc, struct dwc3_ep *dep)
{
struct dwc3_gadget_ep_cmd_params params;
memset(¶ms, 0x00, sizeof(params));
params.param0 = DWC3_DEPXFERCFG_NUM_XFER_RES(1);
return dwc3_send_gadget_ep_cmd(dwc, dep->number,
DWC3_DEPCMD_SETTRANSFRESOURCE, ¶ms);
}
/**
* __dwc3_gadget_ep_enable - Initializes a HW endpoint
* @dep: endpoint to be initialized
* @desc: USB Endpoint Descriptor
*
* Caller should take care of locking
*/
static int __dwc3_gadget_ep_enable(struct dwc3_ep *dep,
const struct usb_endpoint_descriptor *desc,
const struct usb_ss_ep_comp_descriptor *comp_desc)
{
struct dwc3 *dwc = dep->dwc;
u32 reg;
int ret = -ENOMEM;
if (!(dep->flags & DWC3_EP_ENABLED)) {
ret = dwc3_gadget_start_config(dwc, dep);
if (ret)
return ret;
}
ret = dwc3_gadget_set_ep_config(dwc, dep, desc, comp_desc);
if (ret)
return ret;
if (!(dep->flags & DWC3_EP_ENABLED)) {
struct dwc3_trb *trb_st_hw;
struct dwc3_trb *trb_link;
ret = dwc3_gadget_set_xfer_resource(dwc, dep);
if (ret)
return ret;
dep->desc = desc;
dep->comp_desc = comp_desc;
dep->type = usb_endpoint_type(desc);
dep->flags |= DWC3_EP_ENABLED;
reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
reg |= DWC3_DALEPENA_EP(dep->number);
dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
if (!usb_endpoint_xfer_isoc(desc))
return 0;
memset(&trb_link, 0, sizeof(trb_link));
/* Link TRB for ISOC. The HWO bit is never reset */
trb_st_hw = &dep->trb_pool[0];
trb_link = &dep->trb_pool[DWC3_TRB_NUM - 1];
trb_link->bpl = lower_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
trb_link->bph = upper_32_bits(dwc3_trb_dma_offset(dep, trb_st_hw));
trb_link->ctrl |= DWC3_TRBCTL_LINK_TRB;
trb_link->ctrl |= DWC3_TRB_CTRL_HWO;
}
return 0;
}
static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum);
static void dwc3_remove_requests(struct dwc3 *dwc, struct dwc3_ep *dep)
{
struct dwc3_request *req;
if (!list_empty(&dep->req_queued))
dwc3_stop_active_transfer(dwc, dep->number);
while (!list_empty(&dep->request_list)) {
req = next_request(&dep->request_list);
dwc3_gadget_giveback(dep, req, -ESHUTDOWN);
}
}
/**
* __dwc3_gadget_ep_disable - Disables a HW endpoint
* @dep: the endpoint to disable
*
* This function also removes requests which are currently processed ny the
* hardware and those which are not yet scheduled.
* Caller should take care of locking.
*/
static int __dwc3_gadget_ep_disable(struct dwc3_ep *dep)
{
struct dwc3 *dwc = dep->dwc;
u32 reg;
dwc3_remove_requests(dwc, dep);
/* make sure HW endpoint isn't stalled */
if (dep->flags & DWC3_EP_STALL)
__dwc3_gadget_ep_set_halt(dep, 0);
reg = dwc3_readl(dwc->regs, DWC3_DALEPENA);
reg &= ~DWC3_DALEPENA_EP(dep->number);
dwc3_writel(dwc->regs, DWC3_DALEPENA, reg);
dep->stream_capable = false;
dep->desc = NULL;
dep->endpoint.desc = NULL;
dep->comp_desc = NULL;
dep->type = 0;
dep->flags = 0;
return 0;
}
/* -------------------------------------------------------------------------- */
static int dwc3_gadget_ep0_enable(struct usb_ep *ep,
const struct usb_endpoint_descriptor *desc)
{
return -EINVAL;
}
static int dwc3_gadget_ep0_disable(struct usb_ep *ep)
{
return -EINVAL;
}
/* -------------------------------------------------------------------------- */
static int dwc3_gadget_ep_enable(struct usb_ep *ep,
const struct usb_endpoint_descriptor *desc)
{
struct dwc3_ep *dep;
struct dwc3 *dwc;
unsigned long flags;
int ret;
if (!ep || !desc || desc->bDescriptorType != USB_DT_ENDPOINT) {
pr_debug("dwc3: invalid parameters\n");
return -EINVAL;
}
if (!desc->wMaxPacketSize) {
pr_debug("dwc3: missing wMaxPacketSize\n");
return -EINVAL;
}
dep = to_dwc3_ep(ep);
dwc = dep->dwc;
switch (usb_endpoint_type(desc)) {
case USB_ENDPOINT_XFER_CONTROL:
strlcat(dep->name, "-control", sizeof(dep->name));
break;
case USB_ENDPOINT_XFER_ISOC:
strlcat(dep->name, "-isoc", sizeof(dep->name));
break;
case USB_ENDPOINT_XFER_BULK:
strlcat(dep->name, "-bulk", sizeof(dep->name));
break;
case USB_ENDPOINT_XFER_INT:
strlcat(dep->name, "-int", sizeof(dep->name));
break;
default:
dev_err(dwc->dev, "invalid endpoint transfer type\n");
}
if (dep->flags & DWC3_EP_ENABLED) {
dev_WARN_ONCE(dwc->dev, true, "%s is already enabled\n",
dep->name);
return 0;
}
dev_vdbg(dwc->dev, "Enabling %s\n", dep->name);
spin_lock_irqsave(&dwc->lock, flags);
ret = __dwc3_gadget_ep_enable(dep, desc, ep->comp_desc);
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static int dwc3_gadget_ep_disable(struct usb_ep *ep)
{
struct dwc3_ep *dep;
struct dwc3 *dwc;
unsigned long flags;
int ret;
if (!ep) {
pr_debug("dwc3: invalid parameters\n");
return -EINVAL;
}
dep = to_dwc3_ep(ep);
dwc = dep->dwc;
if (!(dep->flags & DWC3_EP_ENABLED)) {
dev_WARN_ONCE(dwc->dev, true, "%s is already disabled\n",
dep->name);
return 0;
}
snprintf(dep->name, sizeof(dep->name), "ep%d%s",
dep->number >> 1,
(dep->number & 1) ? "in" : "out");
spin_lock_irqsave(&dwc->lock, flags);
ret = __dwc3_gadget_ep_disable(dep);
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static struct usb_request *dwc3_gadget_ep_alloc_request(struct usb_ep *ep,
gfp_t gfp_flags)
{
struct dwc3_request *req;
struct dwc3_ep *dep = to_dwc3_ep(ep);
struct dwc3 *dwc = dep->dwc;
req = kzalloc(sizeof(*req), gfp_flags);
if (!req) {
dev_err(dwc->dev, "not enough memory\n");
return NULL;
}
req->epnum = dep->number;
req->dep = dep;
return &req->request;
}
static void dwc3_gadget_ep_free_request(struct usb_ep *ep,
struct usb_request *request)
{
struct dwc3_request *req = to_dwc3_request(request);
kfree(req);
}
/**
* dwc3_prepare_one_trb - setup one TRB from one request
* @dep: endpoint for which this request is prepared
* @req: dwc3_request pointer
*/
static void dwc3_prepare_one_trb(struct dwc3_ep *dep,
struct dwc3_request *req, dma_addr_t dma,
unsigned length, unsigned last, unsigned chain)
{
struct dwc3 *dwc = dep->dwc;
struct dwc3_trb *trb;
unsigned int cur_slot;
dev_vdbg(dwc->dev, "%s: req %p dma %08llx length %d%s%s\n",
dep->name, req, (unsigned long long) dma,
length, last ? " last" : "",
chain ? " chain" : "");
trb = &dep->trb_pool[dep->free_slot & DWC3_TRB_MASK];
cur_slot = dep->free_slot;
dep->free_slot++;
/* Skip the LINK-TRB on ISOC */
if (((cur_slot & DWC3_TRB_MASK) == DWC3_TRB_NUM - 1) &&
usb_endpoint_xfer_isoc(dep->desc))
return;
if (!req->trb) {
dwc3_gadget_move_request_queued(req);
req->trb = trb;
req->trb_dma = dwc3_trb_dma_offset(dep, trb);
}
trb->size = DWC3_TRB_SIZE_LENGTH(length);
trb->bpl = lower_32_bits(dma);
trb->bph = upper_32_bits(dma);
switch (usb_endpoint_type(dep->desc)) {
case USB_ENDPOINT_XFER_CONTROL:
trb->ctrl = DWC3_TRBCTL_CONTROL_SETUP;
break;
case USB_ENDPOINT_XFER_ISOC:
trb->ctrl = DWC3_TRBCTL_ISOCHRONOUS_FIRST;
/* IOC every DWC3_TRB_NUM / 4 so we can refill */
if (!(cur_slot % (DWC3_TRB_NUM / 4)))
trb->ctrl |= DWC3_TRB_CTRL_IOC;
break;
case USB_ENDPOINT_XFER_BULK:
case USB_ENDPOINT_XFER_INT:
trb->ctrl = DWC3_TRBCTL_NORMAL;
break;
default:
/*
* This is only possible with faulty memory because we
* checked it already :)
*/
BUG();
}
if (usb_endpoint_xfer_isoc(dep->desc)) {
trb->ctrl |= DWC3_TRB_CTRL_ISP_IMI;
trb->ctrl |= DWC3_TRB_CTRL_CSP;
} else {
if (chain)
trb->ctrl |= DWC3_TRB_CTRL_CHN;
if (last)
trb->ctrl |= DWC3_TRB_CTRL_LST;
}
if (usb_endpoint_xfer_bulk(dep->desc) && dep->stream_capable)
trb->ctrl |= DWC3_TRB_CTRL_SID_SOFN(req->request.stream_id);
trb->ctrl |= DWC3_TRB_CTRL_HWO;
}
/*
* dwc3_prepare_trbs - setup TRBs from requests
* @dep: endpoint for which requests are being prepared
* @starting: true if the endpoint is idle and no requests are queued.
*
* The function goes through the requests list and sets up TRBs for the
* transfers. The function returns once there are no more TRBs available or
* it runs out of requests.
*/
static void dwc3_prepare_trbs(struct dwc3_ep *dep, bool starting)
{
struct dwc3_request *req, *n;
u32 trbs_left;
u32 max;
unsigned int last_one = 0;
BUILD_BUG_ON_NOT_POWER_OF_2(DWC3_TRB_NUM);
/* the first request must not be queued */
trbs_left = (dep->busy_slot - dep->free_slot) & DWC3_TRB_MASK;
/* Can't wrap around on a non-isoc EP since there's no link TRB */
if (!usb_endpoint_xfer_isoc(dep->desc)) {
max = DWC3_TRB_NUM - (dep->free_slot & DWC3_TRB_MASK);
if (trbs_left > max)
trbs_left = max;
}
/*
* If busy & slot are equal than it is either full or empty. If we are
* starting to process requests then we are empty. Otherwise we are
* full and don't do anything
*/
if (!trbs_left) {
if (!starting)
return;
trbs_left = DWC3_TRB_NUM;
/*
* In case we start from scratch, we queue the ISOC requests
* starting from slot 1. This is done because we use ring
* buffer and have no LST bit to stop us. Instead, we place
* IOC bit every TRB_NUM/4. We try to avoid having an interrupt
* after the first request so we start at slot 1 and have
* 7 requests proceed before we hit the first IOC.
* Other transfer types don't use the ring buffer and are
* processed from the first TRB until the last one. Since we
* don't wrap around we have to start at the beginning.
*/
if (usb_endpoint_xfer_isoc(dep->desc)) {
dep->busy_slot = 1;
dep->free_slot = 1;
} else {
dep->busy_slot = 0;
dep->free_slot = 0;
}
}
/* The last TRB is a link TRB, not used for xfer */
if ((trbs_left <= 1) && usb_endpoint_xfer_isoc(dep->desc))
return;
list_for_each_entry_safe(req, n, &dep->request_list, list) {
unsigned length;
dma_addr_t dma;
if (req->request.num_mapped_sgs > 0) {
struct usb_request *request = &req->request;
struct scatterlist *sg = request->sg;
struct scatterlist *s;
int i;
for_each_sg(sg, s, request->num_mapped_sgs, i) {
unsigned chain = true;
length = sg_dma_len(s);
dma = sg_dma_address(s);
if (i == (request->num_mapped_sgs - 1) ||
sg_is_last(s)) {
last_one = true;
chain = false;
}
trbs_left--;
if (!trbs_left)
last_one = true;
if (last_one)
chain = false;
dwc3_prepare_one_trb(dep, req, dma, length,
last_one, chain);
if (last_one)
break;
}
} else {
dma = req->request.dma;
length = req->request.length;
trbs_left--;
if (!trbs_left)
last_one = 1;
/* Is this the last request? */
if (list_is_last(&req->list, &dep->request_list))
last_one = 1;
dwc3_prepare_one_trb(dep, req, dma, length,
last_one, false);
if (last_one)
break;
}
}
}
static int __dwc3_gadget_kick_transfer(struct dwc3_ep *dep, u16 cmd_param,
int start_new)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3_request *req;
struct dwc3 *dwc = dep->dwc;
int ret;
u32 cmd;
if (start_new && (dep->flags & DWC3_EP_BUSY)) {
dev_vdbg(dwc->dev, "%s: endpoint busy\n", dep->name);
return -EBUSY;
}
dep->flags &= ~DWC3_EP_PENDING_REQUEST;
/*
* If we are getting here after a short-out-packet we don't enqueue any
* new requests as we try to set the IOC bit only on the last request.
*/
if (start_new) {
if (list_empty(&dep->req_queued))
dwc3_prepare_trbs(dep, start_new);
/* req points to the first request which will be sent */
req = next_request(&dep->req_queued);
} else {
dwc3_prepare_trbs(dep, start_new);
/*
* req points to the first request where HWO changed from 0 to 1
*/
req = next_request(&dep->req_queued);
}
if (!req) {
dep->flags |= DWC3_EP_PENDING_REQUEST;
return 0;
}
memset(¶ms, 0, sizeof(params));
params.param0 = upper_32_bits(req->trb_dma);
params.param1 = lower_32_bits(req->trb_dma);
if (start_new)
cmd = DWC3_DEPCMD_STARTTRANSFER;
else
cmd = DWC3_DEPCMD_UPDATETRANSFER;
cmd |= DWC3_DEPCMD_PARAM(cmd_param);
ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, ¶ms);
if (ret < 0) {
dev_dbg(dwc->dev, "failed to send STARTTRANSFER command\n");
/*
* FIXME we need to iterate over the list of requests
* here and stop, unmap, free and del each of the linked
* requests instead of what we do now.
*/
usb_gadget_unmap_request(&dwc->gadget, &req->request,
req->direction);
list_del(&req->list);
return ret;
}
dep->flags |= DWC3_EP_BUSY;
dep->res_trans_idx = dwc3_gadget_ep_get_transfer_index(dwc,
dep->number);
WARN_ON_ONCE(!dep->res_trans_idx);
return 0;
}
static int __dwc3_gadget_ep_queue(struct dwc3_ep *dep, struct dwc3_request *req)
{
struct dwc3 *dwc = dep->dwc;
int ret;
req->request.actual = 0;
req->request.status = -EINPROGRESS;
req->direction = dep->direction;
req->epnum = dep->number;
/*
* We only add to our list of requests now and
* start consuming the list once we get XferNotReady
* IRQ.
*
* That way, we avoid doing anything that we don't need
* to do now and defer it until the point we receive a
* particular token from the Host side.
*
* This will also avoid Host cancelling URBs due to too
* many NAKs.
*/
ret = usb_gadget_map_request(&dwc->gadget, &req->request,
dep->direction);
if (ret)
return ret;
list_add_tail(&req->list, &dep->request_list);
/*
* There is one special case: XferNotReady with
* empty list of requests. We need to kick the
* transfer here in that situation, otherwise
* we will be NAKing forever.
*
* If we get XferNotReady before gadget driver
* has a chance to queue a request, we will ACK
* the IRQ but won't be able to receive the data
* until the next request is queued. The following
* code is handling exactly that.
*/
if (dep->flags & DWC3_EP_PENDING_REQUEST) {
int ret;
int start_trans;
start_trans = 1;
if (usb_endpoint_xfer_isoc(dep->desc) &&
(dep->flags & DWC3_EP_BUSY))
start_trans = 0;
ret = __dwc3_gadget_kick_transfer(dep, 0, start_trans);
if (ret && ret != -EBUSY) {
struct dwc3 *dwc = dep->dwc;
dev_dbg(dwc->dev, "%s: failed to kick transfers\n",
dep->name);
}
};
return 0;
}
static int dwc3_gadget_ep_queue(struct usb_ep *ep, struct usb_request *request,
gfp_t gfp_flags)
{
struct dwc3_request *req = to_dwc3_request(request);
struct dwc3_ep *dep = to_dwc3_ep(ep);
struct dwc3 *dwc = dep->dwc;
unsigned long flags;
int ret;
if (!dep->desc) {
dev_dbg(dwc->dev, "trying to queue request %p to disabled %s\n",
request, ep->name);
return -ESHUTDOWN;
}
dev_vdbg(dwc->dev, "queing request %p to %s length %d\n",
request, ep->name, request->length);
spin_lock_irqsave(&dwc->lock, flags);
ret = __dwc3_gadget_ep_queue(dep, req);
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static int dwc3_gadget_ep_dequeue(struct usb_ep *ep,
struct usb_request *request)
{
struct dwc3_request *req = to_dwc3_request(request);
struct dwc3_request *r = NULL;
struct dwc3_ep *dep = to_dwc3_ep(ep);
struct dwc3 *dwc = dep->dwc;
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&dwc->lock, flags);
list_for_each_entry(r, &dep->request_list, list) {
if (r == req)
break;
}
if (r != req) {
list_for_each_entry(r, &dep->req_queued, list) {
if (r == req)
break;
}
if (r == req) {
/* wait until it is processed */
dwc3_stop_active_transfer(dwc, dep->number);
goto out0;
}
dev_err(dwc->dev, "request %p was not queued to %s\n",
request, ep->name);
ret = -EINVAL;
goto out0;
}
/* giveback the request */
dwc3_gadget_giveback(dep, req, -ECONNRESET);
out0:
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
int __dwc3_gadget_ep_set_halt(struct dwc3_ep *dep, int value)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3 *dwc = dep->dwc;
int ret;
memset(¶ms, 0x00, sizeof(params));
if (value) {
if (dep->number == 0 || dep->number == 1) {
/*
* Whenever EP0 is stalled, we will restart
* the state machine, thus moving back to
* Setup Phase
*/
dwc->ep0state = EP0_SETUP_PHASE;
}
ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
DWC3_DEPCMD_SETSTALL, ¶ms);
if (ret)
dev_err(dwc->dev, "failed to %s STALL on %s\n",
value ? "set" : "clear",
dep->name);
else
dep->flags |= DWC3_EP_STALL;
} else {
ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
DWC3_DEPCMD_CLEARSTALL, ¶ms);
if (ret)
dev_err(dwc->dev, "failed to %s STALL on %s\n",
value ? "set" : "clear",
dep->name);
else
dep->flags &= ~(DWC3_EP_STALL | DWC3_EP_WEDGE);
}
return ret;
}
static int dwc3_gadget_ep_set_halt(struct usb_ep *ep, int value)
{
struct dwc3_ep *dep = to_dwc3_ep(ep);
struct dwc3 *dwc = dep->dwc;
unsigned long flags;
int ret;
spin_lock_irqsave(&dwc->lock, flags);
if (usb_endpoint_xfer_isoc(dep->desc)) {
dev_err(dwc->dev, "%s is of Isochronous type\n", dep->name);
ret = -EINVAL;
goto out;
}
ret = __dwc3_gadget_ep_set_halt(dep, value);
out:
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static int dwc3_gadget_ep_set_wedge(struct usb_ep *ep)
{
struct dwc3_ep *dep = to_dwc3_ep(ep);
struct dwc3 *dwc = dep->dwc;
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
dep->flags |= DWC3_EP_WEDGE;
spin_unlock_irqrestore(&dwc->lock, flags);
return dwc3_gadget_ep_set_halt(ep, 1);
}
/* -------------------------------------------------------------------------- */
static struct usb_endpoint_descriptor dwc3_gadget_ep0_desc = {
.bLength = USB_DT_ENDPOINT_SIZE,
.bDescriptorType = USB_DT_ENDPOINT,
.bmAttributes = USB_ENDPOINT_XFER_CONTROL,
};
static const struct usb_ep_ops dwc3_gadget_ep0_ops = {
.enable = dwc3_gadget_ep0_enable,
.disable = dwc3_gadget_ep0_disable,
.alloc_request = dwc3_gadget_ep_alloc_request,
.free_request = dwc3_gadget_ep_free_request,
.queue = dwc3_gadget_ep0_queue,
.dequeue = dwc3_gadget_ep_dequeue,
.set_halt = dwc3_gadget_ep_set_halt,
.set_wedge = dwc3_gadget_ep_set_wedge,
};
static const struct usb_ep_ops dwc3_gadget_ep_ops = {
.enable = dwc3_gadget_ep_enable,
.disable = dwc3_gadget_ep_disable,
.alloc_request = dwc3_gadget_ep_alloc_request,
.free_request = dwc3_gadget_ep_free_request,
.queue = dwc3_gadget_ep_queue,
.dequeue = dwc3_gadget_ep_dequeue,
.set_halt = dwc3_gadget_ep_set_halt,
.set_wedge = dwc3_gadget_ep_set_wedge,
};
/* -------------------------------------------------------------------------- */
static int dwc3_gadget_get_frame(struct usb_gadget *g)
{
struct dwc3 *dwc = gadget_to_dwc(g);
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
return DWC3_DSTS_SOFFN(reg);
}
static int dwc3_gadget_wakeup(struct usb_gadget *g)
{
struct dwc3 *dwc = gadget_to_dwc(g);
unsigned long timeout;
unsigned long flags;
u32 reg;
int ret = 0;
u8 link_state;
u8 speed;
spin_lock_irqsave(&dwc->lock, flags);
/*
* According to the Databook Remote wakeup request should
* be issued only when the device is in early suspend state.
*
* We can check that via USB Link State bits in DSTS register.
*/
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
speed = reg & DWC3_DSTS_CONNECTSPD;
if (speed == DWC3_DSTS_SUPERSPEED) {
dev_dbg(dwc->dev, "no wakeup on SuperSpeed\n");
ret = -EINVAL;
goto out;
}
link_state = DWC3_DSTS_USBLNKST(reg);
switch (link_state) {
case DWC3_LINK_STATE_RX_DET: /* in HS, means Early Suspend */
case DWC3_LINK_STATE_U3: /* in HS, means SUSPEND */
break;
default:
dev_dbg(dwc->dev, "can't wakeup from link state %d\n",
link_state);
ret = -EINVAL;
goto out;
}
ret = dwc3_gadget_set_link_state(dwc, DWC3_LINK_STATE_RECOV);
if (ret < 0) {
dev_err(dwc->dev, "failed to put link in Recovery\n");
goto out;
}
/* write zeroes to Link Change Request */
reg &= ~DWC3_DCTL_ULSTCHNGREQ_MASK;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
/* poll until Link State changes to ON */
timeout = jiffies + msecs_to_jiffies(100);
while (!time_after(jiffies, timeout)) {
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
/* in HS, means ON */
if (DWC3_DSTS_USBLNKST(reg) == DWC3_LINK_STATE_U0)
break;
}
if (DWC3_DSTS_USBLNKST(reg) != DWC3_LINK_STATE_U0) {
dev_err(dwc->dev, "failed to send remote wakeup\n");
ret = -EINVAL;
}
out:
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static int dwc3_gadget_set_selfpowered(struct usb_gadget *g,
int is_selfpowered)
{
struct dwc3 *dwc = gadget_to_dwc(g);
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
dwc->is_selfpowered = !!is_selfpowered;
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static void dwc3_gadget_run_stop(struct dwc3 *dwc, int is_on)
{
u32 reg;
u32 timeout = 500;
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
if (is_on) {
reg &= ~DWC3_DCTL_TRGTULST_MASK;
reg |= (DWC3_DCTL_RUN_STOP
| DWC3_DCTL_TRGTULST_RX_DET);
} else {
reg &= ~DWC3_DCTL_RUN_STOP;
}
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
do {
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
if (is_on) {
if (!(reg & DWC3_DSTS_DEVCTRLHLT))
break;
} else {
if (reg & DWC3_DSTS_DEVCTRLHLT)
break;
}
timeout--;
if (!timeout)
break;
udelay(1);
} while (1);
dev_vdbg(dwc->dev, "gadget %s data soft-%s\n",
dwc->gadget_driver
? dwc->gadget_driver->function : "no-function",
is_on ? "connect" : "disconnect");
}
static int dwc3_gadget_pullup(struct usb_gadget *g, int is_on)
{
struct dwc3 *dwc = gadget_to_dwc(g);
unsigned long flags;
is_on = !!is_on;
spin_lock_irqsave(&dwc->lock, flags);
dwc3_gadget_run_stop(dwc, is_on);
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static int dwc3_gadget_start(struct usb_gadget *g,
struct usb_gadget_driver *driver)
{
struct dwc3 *dwc = gadget_to_dwc(g);
struct dwc3_ep *dep;
unsigned long flags;
int ret = 0;
u32 reg;
spin_lock_irqsave(&dwc->lock, flags);
if (dwc->gadget_driver) {
dev_err(dwc->dev, "%s is already bound to %s\n",
dwc->gadget.name,
dwc->gadget_driver->driver.name);
ret = -EBUSY;
goto err0;
}
dwc->gadget_driver = driver;
dwc->gadget.dev.driver = &driver->driver;
reg = dwc3_readl(dwc->regs, DWC3_DCFG);
reg &= ~(DWC3_DCFG_SPEED_MASK);
reg |= dwc->maximum_speed;
dwc3_writel(dwc->regs, DWC3_DCFG, reg);
dwc->start_config_issued = false;
/* Start with SuperSpeed Default */
dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
dep = dwc->eps[0];
ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL);
if (ret) {
dev_err(dwc->dev, "failed to enable %s\n", dep->name);
goto err0;
}
dep = dwc->eps[1];
ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL);
if (ret) {
dev_err(dwc->dev, "failed to enable %s\n", dep->name);
goto err1;
}
/* begin to receive SETUP packets */
dwc->ep0state = EP0_SETUP_PHASE;
dwc3_ep0_out_start(dwc);
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
err1:
__dwc3_gadget_ep_disable(dwc->eps[0]);
err0:
dwc->gadget_driver = NULL;
spin_unlock_irqrestore(&dwc->lock, flags);
return ret;
}
static int dwc3_gadget_stop(struct usb_gadget *g,
struct usb_gadget_driver *driver)
{
struct dwc3 *dwc = gadget_to_dwc(g);
unsigned long flags;
spin_lock_irqsave(&dwc->lock, flags);
__dwc3_gadget_ep_disable(dwc->eps[0]);
__dwc3_gadget_ep_disable(dwc->eps[1]);
dwc->gadget_driver = NULL;
dwc->gadget.dev.driver = NULL;
spin_unlock_irqrestore(&dwc->lock, flags);
return 0;
}
static const struct usb_gadget_ops dwc3_gadget_ops = {
.get_frame = dwc3_gadget_get_frame,
.wakeup = dwc3_gadget_wakeup,
.set_selfpowered = dwc3_gadget_set_selfpowered,
.pullup = dwc3_gadget_pullup,
.udc_start = dwc3_gadget_start,
.udc_stop = dwc3_gadget_stop,
};
/* -------------------------------------------------------------------------- */
static int __devinit dwc3_gadget_init_endpoints(struct dwc3 *dwc)
{
struct dwc3_ep *dep;
u8 epnum;
INIT_LIST_HEAD(&dwc->gadget.ep_list);
for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
dep = kzalloc(sizeof(*dep), GFP_KERNEL);
if (!dep) {
dev_err(dwc->dev, "can't allocate endpoint %d\n",
epnum);
return -ENOMEM;
}
dep->dwc = dwc;
dep->number = epnum;
dwc->eps[epnum] = dep;
snprintf(dep->name, sizeof(dep->name), "ep%d%s", epnum >> 1,
(epnum & 1) ? "in" : "out");
dep->endpoint.name = dep->name;
dep->direction = (epnum & 1);
if (epnum == 0 || epnum == 1) {
dep->endpoint.maxpacket = 512;
dep->endpoint.maxburst = 1;
dep->endpoint.ops = &dwc3_gadget_ep0_ops;
if (!epnum)
dwc->gadget.ep0 = &dep->endpoint;
} else {
int ret;
dep->endpoint.maxpacket = 1024;
dep->endpoint.max_streams = 15;
dep->endpoint.ops = &dwc3_gadget_ep_ops;
list_add_tail(&dep->endpoint.ep_list,
&dwc->gadget.ep_list);
ret = dwc3_alloc_trb_pool(dep);
if (ret)
return ret;
}
INIT_LIST_HEAD(&dep->request_list);
INIT_LIST_HEAD(&dep->req_queued);
}
return 0;
}
static void dwc3_gadget_free_endpoints(struct dwc3 *dwc)
{
struct dwc3_ep *dep;
u8 epnum;
for (epnum = 0; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
dep = dwc->eps[epnum];
/*
* Physical endpoints 0 and 1 are special; they form the
* bi-directional USB endpoint 0.
*
* For those two physical endpoints, we don't allocate a TRB
* pool nor do we add them the endpoints list. Due to that, we
* shouldn't do these two operations otherwise we would end up
* with all sorts of bugs when removing dwc3.ko.
*/
if (epnum != 0 && epnum != 1) {
dwc3_free_trb_pool(dep);
list_del(&dep->endpoint.ep_list);
}
kfree(dep);
}
}
static void dwc3_gadget_release(struct device *dev)
{
dev_dbg(dev, "%s\n", __func__);
}
/* -------------------------------------------------------------------------- */
static int dwc3_cleanup_done_reqs(struct dwc3 *dwc, struct dwc3_ep *dep,
const struct dwc3_event_depevt *event, int status)
{
struct dwc3_request *req;
struct dwc3_trb *trb;
unsigned int count;
unsigned int s_pkt = 0;
do {
req = next_request(&dep->req_queued);
if (!req) {
WARN_ON_ONCE(1);
return 1;
}
trb = req->trb;
if ((trb->ctrl & DWC3_TRB_CTRL_HWO) && status != -ESHUTDOWN)
/*
* We continue despite the error. There is not much we
* can do. If we don't clean it up we loop forever. If
* we skip the TRB then it gets overwritten after a
* while since we use them in a ring buffer. A BUG()
* would help. Lets hope that if this occurs, someone
* fixes the root cause instead of looking away :)
*/
dev_err(dwc->dev, "%s's TRB (%p) still owned by HW\n",
dep->name, req->trb);
count = trb->size & DWC3_TRB_SIZE_MASK;
if (dep->direction) {
if (count) {
dev_err(dwc->dev, "incomplete IN transfer %s\n",
dep->name);
status = -ECONNRESET;
}
} else {
if (count && (event->status & DEPEVT_STATUS_SHORT))
s_pkt = 1;
}
/*
* We assume here we will always receive the entire data block
* which we should receive. Meaning, if we program RX to
* receive 4K but we receive only 2K, we assume that's all we
* should receive and we simply bounce the request back to the
* gadget driver for further processing.
*/
req->request.actual += req->request.length - count;
dwc3_gadget_giveback(dep, req, status);
if (s_pkt)
break;
if ((event->status & DEPEVT_STATUS_LST) &&
(trb->ctrl & DWC3_TRB_CTRL_LST))
break;
if ((event->status & DEPEVT_STATUS_IOC) &&
(trb->ctrl & DWC3_TRB_CTRL_IOC))
break;
} while (1);
if ((event->status & DEPEVT_STATUS_IOC) &&
(trb->ctrl & DWC3_TRB_CTRL_IOC))
return 0;
return 1;
}
static void dwc3_endpoint_transfer_complete(struct dwc3 *dwc,
struct dwc3_ep *dep, const struct dwc3_event_depevt *event,
int start_new)
{
unsigned status = 0;
int clean_busy;
if (event->status & DEPEVT_STATUS_BUSERR)
status = -ECONNRESET;
clean_busy = dwc3_cleanup_done_reqs(dwc, dep, event, status);
if (clean_busy)
dep->flags &= ~DWC3_EP_BUSY;
/*
* WORKAROUND: This is the 2nd half of U1/U2 -> U0 workaround.
* See dwc3_gadget_linksts_change_interrupt() for 1st half.
*/
if (dwc->revision < DWC3_REVISION_183A) {
u32 reg;
int i;
for (i = 0; i < DWC3_ENDPOINTS_NUM; i++) {
struct dwc3_ep *dep = dwc->eps[i];
if (!(dep->flags & DWC3_EP_ENABLED))
continue;
if (!list_empty(&dep->req_queued))
return;
}
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg |= dwc->u1u2;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
dwc->u1u2 = 0;
}
}
static void dwc3_gadget_start_isoc(struct dwc3 *dwc,
struct dwc3_ep *dep, const struct dwc3_event_depevt *event)
{
u32 uf, mask;
if (list_empty(&dep->request_list)) {
dev_vdbg(dwc->dev, "ISOC ep %s run out for requests.\n",
dep->name);
return;
}
mask = ~(dep->interval - 1);
uf = event->parameters & mask;
/* 4 micro frames in the future */
uf += dep->interval * 4;
__dwc3_gadget_kick_transfer(dep, uf, 1);
}
static void dwc3_process_ep_cmd_complete(struct dwc3_ep *dep,
const struct dwc3_event_depevt *event)
{
struct dwc3 *dwc = dep->dwc;
struct dwc3_event_depevt mod_ev = *event;
/*
* We were asked to remove one request. It is possible that this
* request and a few others were started together and have the same
* transfer index. Since we stopped the complete endpoint we don't
* know how many requests were already completed (and not yet)
* reported and how could be done (later). We purge them all until
* the end of the list.
*/
mod_ev.status = DEPEVT_STATUS_LST;
dwc3_cleanup_done_reqs(dwc, dep, &mod_ev, -ESHUTDOWN);
dep->flags &= ~DWC3_EP_BUSY;
/* pending requests are ignored and are queued on XferNotReady */
}
static void dwc3_ep_cmd_compl(struct dwc3_ep *dep,
const struct dwc3_event_depevt *event)
{
u32 param = event->parameters;
u32 cmd_type = (param >> 8) & ((1 << 5) - 1);
switch (cmd_type) {
case DWC3_DEPCMD_ENDTRANSFER:
dwc3_process_ep_cmd_complete(dep, event);
break;
case DWC3_DEPCMD_STARTTRANSFER:
dep->res_trans_idx = param & 0x7f;
break;
default:
printk(KERN_ERR "%s() unknown /unexpected type: %d\n",
__func__, cmd_type);
break;
};
}
static void dwc3_endpoint_interrupt(struct dwc3 *dwc,
const struct dwc3_event_depevt *event)
{
struct dwc3_ep *dep;
u8 epnum = event->endpoint_number;
dep = dwc->eps[epnum];
dev_vdbg(dwc->dev, "%s: %s\n", dep->name,
dwc3_ep_event_string(event->endpoint_event));
if (epnum == 0 || epnum == 1) {
dwc3_ep0_interrupt(dwc, event);
return;
}
switch (event->endpoint_event) {
case DWC3_DEPEVT_XFERCOMPLETE:
dep->res_trans_idx = 0;
if (usb_endpoint_xfer_isoc(dep->desc)) {
dev_dbg(dwc->dev, "%s is an Isochronous endpoint\n",
dep->name);
return;
}
dwc3_endpoint_transfer_complete(dwc, dep, event, 1);
break;
case DWC3_DEPEVT_XFERINPROGRESS:
if (!usb_endpoint_xfer_isoc(dep->desc)) {
dev_dbg(dwc->dev, "%s is not an Isochronous endpoint\n",
dep->name);
return;
}
dwc3_endpoint_transfer_complete(dwc, dep, event, 0);
break;
case DWC3_DEPEVT_XFERNOTREADY:
if (usb_endpoint_xfer_isoc(dep->desc)) {
dwc3_gadget_start_isoc(dwc, dep, event);
} else {
int ret;
dev_vdbg(dwc->dev, "%s: reason %s\n",
dep->name, event->status &
DEPEVT_STATUS_TRANSFER_ACTIVE
? "Transfer Active"
: "Transfer Not Active");
ret = __dwc3_gadget_kick_transfer(dep, 0, 1);
if (!ret || ret == -EBUSY)
return;
dev_dbg(dwc->dev, "%s: failed to kick transfers\n",
dep->name);
}
break;
case DWC3_DEPEVT_STREAMEVT:
if (!usb_endpoint_xfer_bulk(dep->desc)) {
dev_err(dwc->dev, "Stream event for non-Bulk %s\n",
dep->name);
return;
}
switch (event->status) {
case DEPEVT_STREAMEVT_FOUND:
dev_vdbg(dwc->dev, "Stream %d found and started\n",
event->parameters);
break;
case DEPEVT_STREAMEVT_NOTFOUND:
/* FALLTHROUGH */
default:
dev_dbg(dwc->dev, "Couldn't find suitable stream\n");
}
break;
case DWC3_DEPEVT_RXTXFIFOEVT:
dev_dbg(dwc->dev, "%s FIFO Overrun\n", dep->name);
break;
case DWC3_DEPEVT_EPCMDCMPLT:
dwc3_ep_cmd_compl(dep, event);
break;
}
}
static void dwc3_disconnect_gadget(struct dwc3 *dwc)
{
if (dwc->gadget_driver && dwc->gadget_driver->disconnect) {
spin_unlock(&dwc->lock);
dwc->gadget_driver->disconnect(&dwc->gadget);
spin_lock(&dwc->lock);
}
}
static void dwc3_stop_active_transfer(struct dwc3 *dwc, u32 epnum)
{
struct dwc3_ep *dep;
struct dwc3_gadget_ep_cmd_params params;
u32 cmd;
int ret;
dep = dwc->eps[epnum];
WARN_ON(!dep->res_trans_idx);
if (dep->res_trans_idx) {
cmd = DWC3_DEPCMD_ENDTRANSFER;
cmd |= DWC3_DEPCMD_HIPRI_FORCERM | DWC3_DEPCMD_CMDIOC;
cmd |= DWC3_DEPCMD_PARAM(dep->res_trans_idx);
memset(¶ms, 0, sizeof(params));
ret = dwc3_send_gadget_ep_cmd(dwc, dep->number, cmd, ¶ms);
WARN_ON_ONCE(ret);
dep->res_trans_idx = 0;
dep->flags &= ~DWC3_EP_BUSY;
}
}
static void dwc3_stop_active_transfers(struct dwc3 *dwc)
{
u32 epnum;
for (epnum = 2; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
struct dwc3_ep *dep;
dep = dwc->eps[epnum];
if (!(dep->flags & DWC3_EP_ENABLED))
continue;
dwc3_remove_requests(dwc, dep);
}
}
static void dwc3_clear_stall_all_ep(struct dwc3 *dwc)
{
u32 epnum;
for (epnum = 1; epnum < DWC3_ENDPOINTS_NUM; epnum++) {
struct dwc3_ep *dep;
struct dwc3_gadget_ep_cmd_params params;
int ret;
dep = dwc->eps[epnum];
if (!(dep->flags & DWC3_EP_STALL))
continue;
dep->flags &= ~DWC3_EP_STALL;
memset(¶ms, 0, sizeof(params));
ret = dwc3_send_gadget_ep_cmd(dwc, dep->number,
DWC3_DEPCMD_CLEARSTALL, ¶ms);
WARN_ON_ONCE(ret);
}
}
static void dwc3_gadget_disconnect_interrupt(struct dwc3 *dwc)
{
dev_vdbg(dwc->dev, "%s\n", __func__);
#if 0
XXX
U1/U2 is powersave optimization. Skip it for now. Anyway we need to
enable it before we can disable it.
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg &= ~DWC3_DCTL_INITU1ENA;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
reg &= ~DWC3_DCTL_INITU2ENA;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
#endif
dwc3_stop_active_transfers(dwc);
dwc3_disconnect_gadget(dwc);
dwc->start_config_issued = false;
dwc->gadget.speed = USB_SPEED_UNKNOWN;
dwc->setup_packet_pending = false;
}
static void dwc3_gadget_usb3_phy_power(struct dwc3 *dwc, int on)
{
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_GUSB3PIPECTL(0));
if (on)
reg &= ~DWC3_GUSB3PIPECTL_SUSPHY;
else
reg |= DWC3_GUSB3PIPECTL_SUSPHY;
dwc3_writel(dwc->regs, DWC3_GUSB3PIPECTL(0), reg);
}
static void dwc3_gadget_usb2_phy_power(struct dwc3 *dwc, int on)
{
u32 reg;
reg = dwc3_readl(dwc->regs, DWC3_GUSB2PHYCFG(0));
if (on)
reg &= ~DWC3_GUSB2PHYCFG_SUSPHY;
else
reg |= DWC3_GUSB2PHYCFG_SUSPHY;
dwc3_writel(dwc->regs, DWC3_GUSB2PHYCFG(0), reg);
}
static void dwc3_gadget_reset_interrupt(struct dwc3 *dwc)
{
u32 reg;
dev_vdbg(dwc->dev, "%s\n", __func__);
/*
* WORKAROUND: DWC3 revisions <1.88a have an issue which
* would cause a missing Disconnect Event if there's a
* pending Setup Packet in the FIFO.
*
* There's no suggested workaround on the official Bug
* report, which states that "unless the driver/application
* is doing any special handling of a disconnect event,
* there is no functional issue".
*
* Unfortunately, it turns out that we _do_ some special
* handling of a disconnect event, namely complete all
* pending transfers, notify gadget driver of the
* disconnection, and so on.
*
* Our suggested workaround is to follow the Disconnect
* Event steps here, instead, based on a setup_packet_pending
* flag. Such flag gets set whenever we have a XferNotReady
* event on EP0 and gets cleared on XferComplete for the
* same endpoint.
*
* Refers to:
*
* STAR#9000466709: RTL: Device : Disconnect event not
* generated if setup packet pending in FIFO
*/
if (dwc->revision < DWC3_REVISION_188A) {
if (dwc->setup_packet_pending)
dwc3_gadget_disconnect_interrupt(dwc);
}
/* after reset -> Default State */
dwc->dev_state = DWC3_DEFAULT_STATE;
/* Enable PHYs */
dwc3_gadget_usb2_phy_power(dwc, true);
dwc3_gadget_usb3_phy_power(dwc, true);
if (dwc->gadget.speed != USB_SPEED_UNKNOWN)
dwc3_disconnect_gadget(dwc);
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
reg &= ~DWC3_DCTL_TSTCTRL_MASK;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
dwc->test_mode = false;
dwc3_stop_active_transfers(dwc);
dwc3_clear_stall_all_ep(dwc);
dwc->start_config_issued = false;
/* Reset device address to zero */
reg = dwc3_readl(dwc->regs, DWC3_DCFG);
reg &= ~(DWC3_DCFG_DEVADDR_MASK);
dwc3_writel(dwc->regs, DWC3_DCFG, reg);
}
static void dwc3_update_ram_clk_sel(struct dwc3 *dwc, u32 speed)
{
u32 reg;
u32 usb30_clock = DWC3_GCTL_CLK_BUS;
/*
* We change the clock only at SS but I dunno why I would want to do
* this. Maybe it becomes part of the power saving plan.
*/
if (speed != DWC3_DSTS_SUPERSPEED)
return;
/*
* RAMClkSel is reset to 0 after USB reset, so it must be reprogrammed
* each time on Connect Done.
*/
if (!usb30_clock)
return;
reg = dwc3_readl(dwc->regs, DWC3_GCTL);
reg |= DWC3_GCTL_RAMCLKSEL(usb30_clock);
dwc3_writel(dwc->regs, DWC3_GCTL, reg);
}
static void dwc3_gadget_disable_phy(struct dwc3 *dwc, u8 speed)
{
switch (speed) {
case USB_SPEED_SUPER:
dwc3_gadget_usb2_phy_power(dwc, false);
break;
case USB_SPEED_HIGH:
case USB_SPEED_FULL:
case USB_SPEED_LOW:
dwc3_gadget_usb3_phy_power(dwc, false);
break;
}
}
static void dwc3_gadget_conndone_interrupt(struct dwc3 *dwc)
{
struct dwc3_gadget_ep_cmd_params params;
struct dwc3_ep *dep;
int ret;
u32 reg;
u8 speed;
dev_vdbg(dwc->dev, "%s\n", __func__);
memset(¶ms, 0x00, sizeof(params));
reg = dwc3_readl(dwc->regs, DWC3_DSTS);
speed = reg & DWC3_DSTS_CONNECTSPD;
dwc->speed = speed;
dwc3_update_ram_clk_sel(dwc, speed);
switch (speed) {
case DWC3_DCFG_SUPERSPEED:
/*
* WORKAROUND: DWC3 revisions <1.90a have an issue which
* would cause a missing USB3 Reset event.
*
* In such situations, we should force a USB3 Reset
* event by calling our dwc3_gadget_reset_interrupt()
* routine.
*
* Refers to:
*
* STAR#9000483510: RTL: SS : USB3 reset event may
* not be generated always when the link enters poll
*/
if (dwc->revision < DWC3_REVISION_190A)
dwc3_gadget_reset_interrupt(dwc);
dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(512);
dwc->gadget.ep0->maxpacket = 512;
dwc->gadget.speed = USB_SPEED_SUPER;
break;
case DWC3_DCFG_HIGHSPEED:
dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
dwc->gadget.ep0->maxpacket = 64;
dwc->gadget.speed = USB_SPEED_HIGH;
break;
case DWC3_DCFG_FULLSPEED2:
case DWC3_DCFG_FULLSPEED1:
dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(64);
dwc->gadget.ep0->maxpacket = 64;
dwc->gadget.speed = USB_SPEED_FULL;
break;
case DWC3_DCFG_LOWSPEED:
dwc3_gadget_ep0_desc.wMaxPacketSize = cpu_to_le16(8);
dwc->gadget.ep0->maxpacket = 8;
dwc->gadget.speed = USB_SPEED_LOW;
break;
}
/* Disable unneded PHY */
dwc3_gadget_disable_phy(dwc, dwc->gadget.speed);
dep = dwc->eps[0];
ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL);
if (ret) {
dev_err(dwc->dev, "failed to enable %s\n", dep->name);
return;
}
dep = dwc->eps[1];
ret = __dwc3_gadget_ep_enable(dep, &dwc3_gadget_ep0_desc, NULL);
if (ret) {
dev_err(dwc->dev, "failed to enable %s\n", dep->name);
return;
}
/*
* Configure PHY via GUSB3PIPECTLn if required.
*
* Update GTXFIFOSIZn
*
* In both cases reset values should be sufficient.
*/
}
static void dwc3_gadget_wakeup_interrupt(struct dwc3 *dwc)
{
dev_vdbg(dwc->dev, "%s\n", __func__);
/*
* TODO take core out of low power mode when that's
* implemented.
*/
dwc->gadget_driver->resume(&dwc->gadget);
}
static void dwc3_gadget_linksts_change_interrupt(struct dwc3 *dwc,
unsigned int evtinfo)
{
enum dwc3_link_state next = evtinfo & DWC3_LINK_STATE_MASK;
/*
* WORKAROUND: DWC3 Revisions <1.83a have an issue which, depending
* on the link partner, the USB session might do multiple entry/exit
* of low power states before a transfer takes place.
*
* Due to this problem, we might experience lower throughput. The
* suggested workaround is to disable DCTL[12:9] bits if we're
* transitioning from U1/U2 to U0 and enable those bits again
* after a transfer completes and there are no pending transfers
* on any of the enabled endpoints.
*
* This is the first half of that workaround.
*
* Refers to:
*
* STAR#9000446952: RTL: Device SS : if U1/U2 ->U0 takes >128us
* core send LGO_Ux entering U0
*/
if (dwc->revision < DWC3_REVISION_183A) {
if (next == DWC3_LINK_STATE_U0) {
u32 u1u2;
u32 reg;
switch (dwc->link_state) {
case DWC3_LINK_STATE_U1:
case DWC3_LINK_STATE_U2:
reg = dwc3_readl(dwc->regs, DWC3_DCTL);
u1u2 = reg & (DWC3_DCTL_INITU2ENA
| DWC3_DCTL_ACCEPTU2ENA
| DWC3_DCTL_INITU1ENA
| DWC3_DCTL_ACCEPTU1ENA);
if (!dwc->u1u2)
dwc->u1u2 = reg & u1u2;
reg &= ~u1u2;
dwc3_writel(dwc->regs, DWC3_DCTL, reg);
break;
default:
/* do nothing */
break;
}
}
}
dwc->link_state = next;
dev_vdbg(dwc->dev, "%s link %d\n", __func__, dwc->link_state);
}
static void dwc3_gadget_interrupt(struct dwc3 *dwc,
const struct dwc3_event_devt *event)
{
switch (event->type) {
case DWC3_DEVICE_EVENT_DISCONNECT:
dwc3_gadget_disconnect_interrupt(dwc);
break;
case DWC3_DEVICE_EVENT_RESET:
dwc3_gadget_reset_interrupt(dwc);
break;
case DWC3_DEVICE_EVENT_CONNECT_DONE:
dwc3_gadget_conndone_interrupt(dwc);
break;
case DWC3_DEVICE_EVENT_WAKEUP:
dwc3_gadget_wakeup_interrupt(dwc);
break;
case DWC3_DEVICE_EVENT_LINK_STATUS_CHANGE:
dwc3_gadget_linksts_change_interrupt(dwc, event->event_info);
break;
case DWC3_DEVICE_EVENT_EOPF:
dev_vdbg(dwc->dev, "End of Periodic Frame\n");
break;
case DWC3_DEVICE_EVENT_SOF:
dev_vdbg(dwc->dev, "Start of Periodic Frame\n");
break;
case DWC3_DEVICE_EVENT_ERRATIC_ERROR:
dev_vdbg(dwc->dev, "Erratic Error\n");
break;
case DWC3_DEVICE_EVENT_CMD_CMPL:
dev_vdbg(dwc->dev, "Command Complete\n");
break;
case DWC3_DEVICE_EVENT_OVERFLOW:
dev_vdbg(dwc->dev, "Overflow\n");
break;
default:
dev_dbg(dwc->dev, "UNKNOWN IRQ %d\n", event->type);
}
}
static void dwc3_process_event_entry(struct dwc3 *dwc,
const union dwc3_event *event)
{
/* Endpoint IRQ, handle it and return early */
if (event->type.is_devspec == 0) {
/* depevt */
return dwc3_endpoint_interrupt(dwc, &event->depevt);
}
switch (event->type.type) {
case DWC3_EVENT_TYPE_DEV:
dwc3_gadget_interrupt(dwc, &event->devt);
break;
/* REVISIT what to do with Carkit and I2C events ? */
default:
dev_err(dwc->dev, "UNKNOWN IRQ type %d\n", event->raw);
}
}
static irqreturn_t dwc3_process_event_buf(struct dwc3 *dwc, u32 buf)
{
struct dwc3_event_buffer *evt;
int left;
u32 count;
count = dwc3_readl(dwc->regs, DWC3_GEVNTCOUNT(buf));
count &= DWC3_GEVNTCOUNT_MASK;
if (!count)
return IRQ_NONE;
evt = dwc->ev_buffs[buf];
left = count;
while (left > 0) {
union dwc3_event event;
event.raw = *(u32 *) (evt->buf + evt->lpos);
dwc3_process_event_entry(dwc, &event);
/*
* XXX we wrap around correctly to the next entry as almost all
* entries are 4 bytes in size. There is one entry which has 12
* bytes which is a regular entry followed by 8 bytes data. ATM
* I don't know how things are organized if were get next to the
* a boundary so I worry about that once we try to handle that.
*/
evt->lpos = (evt->lpos + 4) % DWC3_EVENT_BUFFERS_SIZE;
left -= 4;
dwc3_writel(dwc->regs, DWC3_GEVNTCOUNT(buf), 4);
}
return IRQ_HANDLED;
}
static irqreturn_t dwc3_interrupt(int irq, void *_dwc)
{
struct dwc3 *dwc = _dwc;
int i;
irqreturn_t ret = IRQ_NONE;
spin_lock(&dwc->lock);
for (i = 0; i < dwc->num_event_buffers; i++) {
irqreturn_t status;
status = dwc3_process_event_buf(dwc, i);
if (status == IRQ_HANDLED)
ret = status;
}
spin_unlock(&dwc->lock);
return ret;
}
/**
* dwc3_gadget_init - Initializes gadget related registers
* @dwc: pointer to our controller context structure
*
* Returns 0 on success otherwise negative errno.
*/
int __devinit dwc3_gadget_init(struct dwc3 *dwc)
{
u32 reg;
int ret;
int irq;
dwc->ctrl_req = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
&dwc->ctrl_req_addr, GFP_KERNEL);
if (!dwc->ctrl_req) {
dev_err(dwc->dev, "failed to allocate ctrl request\n");
ret = -ENOMEM;
goto err0;
}
dwc->ep0_trb = dma_alloc_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
&dwc->ep0_trb_addr, GFP_KERNEL);
if (!dwc->ep0_trb) {
dev_err(dwc->dev, "failed to allocate ep0 trb\n");
ret = -ENOMEM;
goto err1;
}
dwc->setup_buf = kzalloc(sizeof(*dwc->setup_buf) * 2,
GFP_KERNEL);
if (!dwc->setup_buf) {
dev_err(dwc->dev, "failed to allocate setup buffer\n");
ret = -ENOMEM;
goto err2;
}
dwc->ep0_bounce = dma_alloc_coherent(dwc->dev,
512, &dwc->ep0_bounce_addr, GFP_KERNEL);
if (!dwc->ep0_bounce) {
dev_err(dwc->dev, "failed to allocate ep0 bounce buffer\n");
ret = -ENOMEM;
goto err3;
}
dev_set_name(&dwc->gadget.dev, "gadget");
dwc->gadget.ops = &dwc3_gadget_ops;
dwc->gadget.max_speed = USB_SPEED_SUPER;
dwc->gadget.speed = USB_SPEED_UNKNOWN;
dwc->gadget.dev.parent = dwc->dev;
dwc->gadget.sg_supported = true;
dma_set_coherent_mask(&dwc->gadget.dev, dwc->dev->coherent_dma_mask);
dwc->gadget.dev.dma_parms = dwc->dev->dma_parms;
dwc->gadget.dev.dma_mask = dwc->dev->dma_mask;
dwc->gadget.dev.release = dwc3_gadget_release;
dwc->gadget.name = "dwc3-gadget";
/*
* REVISIT: Here we should clear all pending IRQs to be
* sure we're starting from a well known location.
*/
ret = dwc3_gadget_init_endpoints(dwc);
if (ret)
goto err4;
irq = platform_get_irq(to_platform_device(dwc->dev), 0);
ret = request_irq(irq, dwc3_interrupt, IRQF_SHARED,
"dwc3", dwc);
if (ret) {
dev_err(dwc->dev, "failed to request irq #%d --> %d\n",
irq, ret);
goto err5;
}
/* Enable all but Start and End of Frame IRQs */
reg = (DWC3_DEVTEN_VNDRDEVTSTRCVEDEN |
DWC3_DEVTEN_EVNTOVERFLOWEN |
DWC3_DEVTEN_CMDCMPLTEN |
DWC3_DEVTEN_ERRTICERREN |
DWC3_DEVTEN_WKUPEVTEN |
DWC3_DEVTEN_ULSTCNGEN |
DWC3_DEVTEN_CONNECTDONEEN |
DWC3_DEVTEN_USBRSTEN |
DWC3_DEVTEN_DISCONNEVTEN);
dwc3_writel(dwc->regs, DWC3_DEVTEN, reg);
ret = device_register(&dwc->gadget.dev);
if (ret) {
dev_err(dwc->dev, "failed to register gadget device\n");
put_device(&dwc->gadget.dev);
goto err6;
}
ret = usb_add_gadget_udc(dwc->dev, &dwc->gadget);
if (ret) {
dev_err(dwc->dev, "failed to register udc\n");
goto err7;
}
return 0;
err7:
device_unregister(&dwc->gadget.dev);
err6:
dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
free_irq(irq, dwc);
err5:
dwc3_gadget_free_endpoints(dwc);
err4:
dma_free_coherent(dwc->dev, 512, dwc->ep0_bounce,
dwc->ep0_bounce_addr);
err3:
kfree(dwc->setup_buf);
err2:
dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
dwc->ep0_trb, dwc->ep0_trb_addr);
err1:
dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
dwc->ctrl_req, dwc->ctrl_req_addr);
err0:
return ret;
}
void dwc3_gadget_exit(struct dwc3 *dwc)
{
int irq;
usb_del_gadget_udc(&dwc->gadget);
irq = platform_get_irq(to_platform_device(dwc->dev), 0);
dwc3_writel(dwc->regs, DWC3_DEVTEN, 0x00);
free_irq(irq, dwc);
dwc3_gadget_free_endpoints(dwc);
dma_free_coherent(dwc->dev, 512, dwc->ep0_bounce,
dwc->ep0_bounce_addr);
kfree(dwc->setup_buf);
dma_free_coherent(dwc->dev, sizeof(*dwc->ep0_trb),
dwc->ep0_trb, dwc->ep0_trb_addr);
dma_free_coherent(dwc->dev, sizeof(*dwc->ctrl_req),
dwc->ctrl_req, dwc->ctrl_req_addr);
device_unregister(&dwc->gadget.dev);
}
| gpl-2.0 |
jonpry/linux_t100 | net/wireless/nl80211.c | 47 | 318804 | /*
* This is the new netlink-based wireless configuration interface.
*
* Copyright 2006-2010 Johannes Berg <johannes@sipsolutions.net>
*/
#include <linux/if.h>
#include <linux/module.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/list.h>
#include <linux/if_ether.h>
#include <linux/ieee80211.h>
#include <linux/nl80211.h>
#include <linux/rtnetlink.h>
#include <linux/netlink.h>
#include <linux/etherdevice.h>
#include <net/net_namespace.h>
#include <net/genetlink.h>
#include <net/cfg80211.h>
#include <net/sock.h>
#include <net/inet_connection_sock.h>
#include "core.h"
#include "nl80211.h"
#include "reg.h"
#include "rdev-ops.h"
static int nl80211_crypto_settings(struct cfg80211_registered_device *rdev,
struct genl_info *info,
struct cfg80211_crypto_settings *settings,
int cipher_limit);
static int nl80211_pre_doit(const struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
static void nl80211_post_doit(const struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info);
/* the netlink family */
static struct genl_family nl80211_fam = {
.id = GENL_ID_GENERATE, /* don't bother with a hardcoded ID */
.name = NL80211_GENL_NAME, /* have users key off the name instead */
.hdrsize = 0, /* no private header */
.version = 1, /* no particular meaning now */
.maxattr = NL80211_ATTR_MAX,
.netnsok = true,
.pre_doit = nl80211_pre_doit,
.post_doit = nl80211_post_doit,
};
/* multicast groups */
enum nl80211_multicast_groups {
NL80211_MCGRP_CONFIG,
NL80211_MCGRP_SCAN,
NL80211_MCGRP_REGULATORY,
NL80211_MCGRP_MLME,
NL80211_MCGRP_VENDOR,
NL80211_MCGRP_TESTMODE /* keep last - ifdef! */
};
static const struct genl_multicast_group nl80211_mcgrps[] = {
[NL80211_MCGRP_CONFIG] = { .name = "config", },
[NL80211_MCGRP_SCAN] = { .name = "scan", },
[NL80211_MCGRP_REGULATORY] = { .name = "regulatory", },
[NL80211_MCGRP_MLME] = { .name = "mlme", },
[NL80211_MCGRP_VENDOR] = { .name = "vendor", },
#ifdef CONFIG_NL80211_TESTMODE
[NL80211_MCGRP_TESTMODE] = { .name = "testmode", }
#endif
};
/* returns ERR_PTR values */
static struct wireless_dev *
__cfg80211_wdev_from_attrs(struct net *netns, struct nlattr **attrs)
{
struct cfg80211_registered_device *rdev;
struct wireless_dev *result = NULL;
bool have_ifidx = attrs[NL80211_ATTR_IFINDEX];
bool have_wdev_id = attrs[NL80211_ATTR_WDEV];
u64 wdev_id;
int wiphy_idx = -1;
int ifidx = -1;
ASSERT_RTNL();
if (!have_ifidx && !have_wdev_id)
return ERR_PTR(-EINVAL);
if (have_ifidx)
ifidx = nla_get_u32(attrs[NL80211_ATTR_IFINDEX]);
if (have_wdev_id) {
wdev_id = nla_get_u64(attrs[NL80211_ATTR_WDEV]);
wiphy_idx = wdev_id >> 32;
}
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
struct wireless_dev *wdev;
if (wiphy_net(&rdev->wiphy) != netns)
continue;
if (have_wdev_id && rdev->wiphy_idx != wiphy_idx)
continue;
list_for_each_entry(wdev, &rdev->wdev_list, list) {
if (have_ifidx && wdev->netdev &&
wdev->netdev->ifindex == ifidx) {
result = wdev;
break;
}
if (have_wdev_id && wdev->identifier == (u32)wdev_id) {
result = wdev;
break;
}
}
if (result)
break;
}
if (result)
return result;
return ERR_PTR(-ENODEV);
}
static struct cfg80211_registered_device *
__cfg80211_rdev_from_attrs(struct net *netns, struct nlattr **attrs)
{
struct cfg80211_registered_device *rdev = NULL, *tmp;
struct net_device *netdev;
ASSERT_RTNL();
if (!attrs[NL80211_ATTR_WIPHY] &&
!attrs[NL80211_ATTR_IFINDEX] &&
!attrs[NL80211_ATTR_WDEV])
return ERR_PTR(-EINVAL);
if (attrs[NL80211_ATTR_WIPHY])
rdev = cfg80211_rdev_by_wiphy_idx(
nla_get_u32(attrs[NL80211_ATTR_WIPHY]));
if (attrs[NL80211_ATTR_WDEV]) {
u64 wdev_id = nla_get_u64(attrs[NL80211_ATTR_WDEV]);
struct wireless_dev *wdev;
bool found = false;
tmp = cfg80211_rdev_by_wiphy_idx(wdev_id >> 32);
if (tmp) {
/* make sure wdev exists */
list_for_each_entry(wdev, &tmp->wdev_list, list) {
if (wdev->identifier != (u32)wdev_id)
continue;
found = true;
break;
}
if (!found)
tmp = NULL;
if (rdev && tmp != rdev)
return ERR_PTR(-EINVAL);
rdev = tmp;
}
}
if (attrs[NL80211_ATTR_IFINDEX]) {
int ifindex = nla_get_u32(attrs[NL80211_ATTR_IFINDEX]);
netdev = __dev_get_by_index(netns, ifindex);
if (netdev) {
if (netdev->ieee80211_ptr)
tmp = wiphy_to_dev(
netdev->ieee80211_ptr->wiphy);
else
tmp = NULL;
/* not wireless device -- return error */
if (!tmp)
return ERR_PTR(-EINVAL);
/* mismatch -- return error */
if (rdev && tmp != rdev)
return ERR_PTR(-EINVAL);
rdev = tmp;
}
}
if (!rdev)
return ERR_PTR(-ENODEV);
if (netns != wiphy_net(&rdev->wiphy))
return ERR_PTR(-ENODEV);
return rdev;
}
/*
* This function returns a pointer to the driver
* that the genl_info item that is passed refers to.
*
* The result of this can be a PTR_ERR and hence must
* be checked with IS_ERR() for errors.
*/
static struct cfg80211_registered_device *
cfg80211_get_dev_from_info(struct net *netns, struct genl_info *info)
{
return __cfg80211_rdev_from_attrs(netns, info->attrs);
}
/* policy for the attributes */
static const struct nla_policy nl80211_policy[NL80211_ATTR_MAX+1] = {
[NL80211_ATTR_WIPHY] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_NAME] = { .type = NLA_NUL_STRING,
.len = 20-1 },
[NL80211_ATTR_WIPHY_TXQ_PARAMS] = { .type = NLA_NESTED },
[NL80211_ATTR_WIPHY_FREQ] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_CHANNEL_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_CHANNEL_WIDTH] = { .type = NLA_U32 },
[NL80211_ATTR_CENTER_FREQ1] = { .type = NLA_U32 },
[NL80211_ATTR_CENTER_FREQ2] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_RETRY_SHORT] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_RETRY_LONG] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_FRAG_THRESHOLD] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_RTS_THRESHOLD] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_COVERAGE_CLASS] = { .type = NLA_U8 },
[NL80211_ATTR_IFTYPE] = { .type = NLA_U32 },
[NL80211_ATTR_IFINDEX] = { .type = NLA_U32 },
[NL80211_ATTR_IFNAME] = { .type = NLA_NUL_STRING, .len = IFNAMSIZ-1 },
[NL80211_ATTR_MAC] = { .len = ETH_ALEN },
[NL80211_ATTR_PREV_BSSID] = { .len = ETH_ALEN },
[NL80211_ATTR_KEY] = { .type = NLA_NESTED, },
[NL80211_ATTR_KEY_DATA] = { .type = NLA_BINARY,
.len = WLAN_MAX_KEY_LEN },
[NL80211_ATTR_KEY_IDX] = { .type = NLA_U8 },
[NL80211_ATTR_KEY_CIPHER] = { .type = NLA_U32 },
[NL80211_ATTR_KEY_DEFAULT] = { .type = NLA_FLAG },
[NL80211_ATTR_KEY_SEQ] = { .type = NLA_BINARY, .len = 16 },
[NL80211_ATTR_KEY_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_BEACON_INTERVAL] = { .type = NLA_U32 },
[NL80211_ATTR_DTIM_PERIOD] = { .type = NLA_U32 },
[NL80211_ATTR_BEACON_HEAD] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_BEACON_TAIL] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_STA_AID] = { .type = NLA_U16 },
[NL80211_ATTR_STA_FLAGS] = { .type = NLA_NESTED },
[NL80211_ATTR_STA_LISTEN_INTERVAL] = { .type = NLA_U16 },
[NL80211_ATTR_STA_SUPPORTED_RATES] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
[NL80211_ATTR_STA_PLINK_ACTION] = { .type = NLA_U8 },
[NL80211_ATTR_STA_VLAN] = { .type = NLA_U32 },
[NL80211_ATTR_MNTR_FLAGS] = { /* NLA_NESTED can't be empty */ },
[NL80211_ATTR_MESH_ID] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_MESH_ID_LEN },
[NL80211_ATTR_MPATH_NEXT_HOP] = { .type = NLA_U32 },
[NL80211_ATTR_REG_ALPHA2] = { .type = NLA_STRING, .len = 2 },
[NL80211_ATTR_REG_RULES] = { .type = NLA_NESTED },
[NL80211_ATTR_BSS_CTS_PROT] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_SHORT_PREAMBLE] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_SHORT_SLOT_TIME] = { .type = NLA_U8 },
[NL80211_ATTR_BSS_BASIC_RATES] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
[NL80211_ATTR_BSS_HT_OPMODE] = { .type = NLA_U16 },
[NL80211_ATTR_MESH_CONFIG] = { .type = NLA_NESTED },
[NL80211_ATTR_SUPPORT_MESH_AUTH] = { .type = NLA_FLAG },
[NL80211_ATTR_HT_CAPABILITY] = { .len = NL80211_HT_CAPABILITY_LEN },
[NL80211_ATTR_MGMT_SUBTYPE] = { .type = NLA_U8 },
[NL80211_ATTR_IE] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_SCAN_FREQUENCIES] = { .type = NLA_NESTED },
[NL80211_ATTR_SCAN_SSIDS] = { .type = NLA_NESTED },
[NL80211_ATTR_SSID] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_SSID_LEN },
[NL80211_ATTR_AUTH_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_REASON_CODE] = { .type = NLA_U16 },
[NL80211_ATTR_FREQ_FIXED] = { .type = NLA_FLAG },
[NL80211_ATTR_TIMED_OUT] = { .type = NLA_FLAG },
[NL80211_ATTR_USE_MFP] = { .type = NLA_U32 },
[NL80211_ATTR_STA_FLAGS2] = {
.len = sizeof(struct nl80211_sta_flag_update),
},
[NL80211_ATTR_CONTROL_PORT] = { .type = NLA_FLAG },
[NL80211_ATTR_CONTROL_PORT_ETHERTYPE] = { .type = NLA_U16 },
[NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT] = { .type = NLA_FLAG },
[NL80211_ATTR_PRIVACY] = { .type = NLA_FLAG },
[NL80211_ATTR_CIPHER_SUITE_GROUP] = { .type = NLA_U32 },
[NL80211_ATTR_WPA_VERSIONS] = { .type = NLA_U32 },
[NL80211_ATTR_PID] = { .type = NLA_U32 },
[NL80211_ATTR_4ADDR] = { .type = NLA_U8 },
[NL80211_ATTR_PMKID] = { .type = NLA_BINARY,
.len = WLAN_PMKID_LEN },
[NL80211_ATTR_DURATION] = { .type = NLA_U32 },
[NL80211_ATTR_COOKIE] = { .type = NLA_U64 },
[NL80211_ATTR_TX_RATES] = { .type = NLA_NESTED },
[NL80211_ATTR_FRAME] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_FRAME_MATCH] = { .type = NLA_BINARY, },
[NL80211_ATTR_PS_STATE] = { .type = NLA_U32 },
[NL80211_ATTR_CQM] = { .type = NLA_NESTED, },
[NL80211_ATTR_LOCAL_STATE_CHANGE] = { .type = NLA_FLAG },
[NL80211_ATTR_AP_ISOLATE] = { .type = NLA_U8 },
[NL80211_ATTR_WIPHY_TX_POWER_SETTING] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_TX_POWER_LEVEL] = { .type = NLA_U32 },
[NL80211_ATTR_FRAME_TYPE] = { .type = NLA_U16 },
[NL80211_ATTR_WIPHY_ANTENNA_TX] = { .type = NLA_U32 },
[NL80211_ATTR_WIPHY_ANTENNA_RX] = { .type = NLA_U32 },
[NL80211_ATTR_MCAST_RATE] = { .type = NLA_U32 },
[NL80211_ATTR_OFFCHANNEL_TX_OK] = { .type = NLA_FLAG },
[NL80211_ATTR_KEY_DEFAULT_TYPES] = { .type = NLA_NESTED },
[NL80211_ATTR_WOWLAN_TRIGGERS] = { .type = NLA_NESTED },
[NL80211_ATTR_STA_PLINK_STATE] = { .type = NLA_U8 },
[NL80211_ATTR_SCHED_SCAN_INTERVAL] = { .type = NLA_U32 },
[NL80211_ATTR_REKEY_DATA] = { .type = NLA_NESTED },
[NL80211_ATTR_SCAN_SUPP_RATES] = { .type = NLA_NESTED },
[NL80211_ATTR_HIDDEN_SSID] = { .type = NLA_U32 },
[NL80211_ATTR_IE_PROBE_RESP] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_IE_ASSOC_RESP] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_ROAM_SUPPORT] = { .type = NLA_FLAG },
[NL80211_ATTR_SCHED_SCAN_MATCH] = { .type = NLA_NESTED },
[NL80211_ATTR_TX_NO_CCK_RATE] = { .type = NLA_FLAG },
[NL80211_ATTR_TDLS_ACTION] = { .type = NLA_U8 },
[NL80211_ATTR_TDLS_DIALOG_TOKEN] = { .type = NLA_U8 },
[NL80211_ATTR_TDLS_OPERATION] = { .type = NLA_U8 },
[NL80211_ATTR_TDLS_SUPPORT] = { .type = NLA_FLAG },
[NL80211_ATTR_TDLS_EXTERNAL_SETUP] = { .type = NLA_FLAG },
[NL80211_ATTR_DONT_WAIT_FOR_ACK] = { .type = NLA_FLAG },
[NL80211_ATTR_PROBE_RESP] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_DFS_REGION] = { .type = NLA_U8 },
[NL80211_ATTR_DISABLE_HT] = { .type = NLA_FLAG },
[NL80211_ATTR_HT_CAPABILITY_MASK] = {
.len = NL80211_HT_CAPABILITY_LEN
},
[NL80211_ATTR_NOACK_MAP] = { .type = NLA_U16 },
[NL80211_ATTR_INACTIVITY_TIMEOUT] = { .type = NLA_U16 },
[NL80211_ATTR_BG_SCAN_PERIOD] = { .type = NLA_U16 },
[NL80211_ATTR_WDEV] = { .type = NLA_U64 },
[NL80211_ATTR_USER_REG_HINT_TYPE] = { .type = NLA_U32 },
[NL80211_ATTR_SAE_DATA] = { .type = NLA_BINARY, },
[NL80211_ATTR_VHT_CAPABILITY] = { .len = NL80211_VHT_CAPABILITY_LEN },
[NL80211_ATTR_SCAN_FLAGS] = { .type = NLA_U32 },
[NL80211_ATTR_P2P_CTWINDOW] = { .type = NLA_U8 },
[NL80211_ATTR_P2P_OPPPS] = { .type = NLA_U8 },
[NL80211_ATTR_ACL_POLICY] = {. type = NLA_U32 },
[NL80211_ATTR_MAC_ADDRS] = { .type = NLA_NESTED },
[NL80211_ATTR_STA_CAPABILITY] = { .type = NLA_U16 },
[NL80211_ATTR_STA_EXT_CAPABILITY] = { .type = NLA_BINARY, },
[NL80211_ATTR_SPLIT_WIPHY_DUMP] = { .type = NLA_FLAG, },
[NL80211_ATTR_DISABLE_VHT] = { .type = NLA_FLAG },
[NL80211_ATTR_VHT_CAPABILITY_MASK] = {
.len = NL80211_VHT_CAPABILITY_LEN,
},
[NL80211_ATTR_MDID] = { .type = NLA_U16 },
[NL80211_ATTR_IE_RIC] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_ATTR_PEER_AID] = { .type = NLA_U16 },
[NL80211_ATTR_CH_SWITCH_COUNT] = { .type = NLA_U32 },
[NL80211_ATTR_CH_SWITCH_BLOCK_TX] = { .type = NLA_FLAG },
[NL80211_ATTR_CSA_IES] = { .type = NLA_NESTED },
[NL80211_ATTR_CSA_C_OFF_BEACON] = { .type = NLA_U16 },
[NL80211_ATTR_CSA_C_OFF_PRESP] = { .type = NLA_U16 },
[NL80211_ATTR_STA_SUPPORTED_CHANNELS] = { .type = NLA_BINARY },
[NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES] = { .type = NLA_BINARY },
[NL80211_ATTR_HANDLE_DFS] = { .type = NLA_FLAG },
[NL80211_ATTR_OPMODE_NOTIF] = { .type = NLA_U8 },
[NL80211_ATTR_VENDOR_ID] = { .type = NLA_U32 },
[NL80211_ATTR_VENDOR_SUBCMD] = { .type = NLA_U32 },
[NL80211_ATTR_VENDOR_DATA] = { .type = NLA_BINARY },
[NL80211_ATTR_QOS_MAP] = { .type = NLA_BINARY,
.len = IEEE80211_QOS_MAP_LEN_MAX },
[NL80211_ATTR_MAC_HINT] = { .len = ETH_ALEN },
[NL80211_ATTR_WIPHY_FREQ_HINT] = { .type = NLA_U32 },
[NL80211_ATTR_TDLS_PEER_CAPABILITY] = { .type = NLA_U32 },
};
/* policy for the key attributes */
static const struct nla_policy nl80211_key_policy[NL80211_KEY_MAX + 1] = {
[NL80211_KEY_DATA] = { .type = NLA_BINARY, .len = WLAN_MAX_KEY_LEN },
[NL80211_KEY_IDX] = { .type = NLA_U8 },
[NL80211_KEY_CIPHER] = { .type = NLA_U32 },
[NL80211_KEY_SEQ] = { .type = NLA_BINARY, .len = 16 },
[NL80211_KEY_DEFAULT] = { .type = NLA_FLAG },
[NL80211_KEY_DEFAULT_MGMT] = { .type = NLA_FLAG },
[NL80211_KEY_TYPE] = { .type = NLA_U32 },
[NL80211_KEY_DEFAULT_TYPES] = { .type = NLA_NESTED },
};
/* policy for the key default flags */
static const struct nla_policy
nl80211_key_default_policy[NUM_NL80211_KEY_DEFAULT_TYPES] = {
[NL80211_KEY_DEFAULT_TYPE_UNICAST] = { .type = NLA_FLAG },
[NL80211_KEY_DEFAULT_TYPE_MULTICAST] = { .type = NLA_FLAG },
};
/* policy for WoWLAN attributes */
static const struct nla_policy
nl80211_wowlan_policy[NUM_NL80211_WOWLAN_TRIG] = {
[NL80211_WOWLAN_TRIG_ANY] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_DISCONNECT] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_MAGIC_PKT] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_PKT_PATTERN] = { .type = NLA_NESTED },
[NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_RFKILL_RELEASE] = { .type = NLA_FLAG },
[NL80211_WOWLAN_TRIG_TCP_CONNECTION] = { .type = NLA_NESTED },
};
static const struct nla_policy
nl80211_wowlan_tcp_policy[NUM_NL80211_WOWLAN_TCP] = {
[NL80211_WOWLAN_TCP_SRC_IPV4] = { .type = NLA_U32 },
[NL80211_WOWLAN_TCP_DST_IPV4] = { .type = NLA_U32 },
[NL80211_WOWLAN_TCP_DST_MAC] = { .len = ETH_ALEN },
[NL80211_WOWLAN_TCP_SRC_PORT] = { .type = NLA_U16 },
[NL80211_WOWLAN_TCP_DST_PORT] = { .type = NLA_U16 },
[NL80211_WOWLAN_TCP_DATA_PAYLOAD] = { .len = 1 },
[NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ] = {
.len = sizeof(struct nl80211_wowlan_tcp_data_seq)
},
[NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN] = {
.len = sizeof(struct nl80211_wowlan_tcp_data_token)
},
[NL80211_WOWLAN_TCP_DATA_INTERVAL] = { .type = NLA_U32 },
[NL80211_WOWLAN_TCP_WAKE_PAYLOAD] = { .len = 1 },
[NL80211_WOWLAN_TCP_WAKE_MASK] = { .len = 1 },
};
/* policy for coalesce rule attributes */
static const struct nla_policy
nl80211_coalesce_policy[NUM_NL80211_ATTR_COALESCE_RULE] = {
[NL80211_ATTR_COALESCE_RULE_DELAY] = { .type = NLA_U32 },
[NL80211_ATTR_COALESCE_RULE_CONDITION] = { .type = NLA_U32 },
[NL80211_ATTR_COALESCE_RULE_PKT_PATTERN] = { .type = NLA_NESTED },
};
/* policy for GTK rekey offload attributes */
static const struct nla_policy
nl80211_rekey_policy[NUM_NL80211_REKEY_DATA] = {
[NL80211_REKEY_DATA_KEK] = { .len = NL80211_KEK_LEN },
[NL80211_REKEY_DATA_KCK] = { .len = NL80211_KCK_LEN },
[NL80211_REKEY_DATA_REPLAY_CTR] = { .len = NL80211_REPLAY_CTR_LEN },
};
static const struct nla_policy
nl80211_match_policy[NL80211_SCHED_SCAN_MATCH_ATTR_MAX + 1] = {
[NL80211_SCHED_SCAN_MATCH_ATTR_SSID] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_SSID_LEN },
[NL80211_SCHED_SCAN_MATCH_ATTR_RSSI] = { .type = NLA_U32 },
};
static int nl80211_prepare_wdev_dump(struct sk_buff *skb,
struct netlink_callback *cb,
struct cfg80211_registered_device **rdev,
struct wireless_dev **wdev)
{
int err;
rtnl_lock();
if (!cb->args[0]) {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (err)
goto out_unlock;
*wdev = __cfg80211_wdev_from_attrs(sock_net(skb->sk),
nl80211_fam.attrbuf);
if (IS_ERR(*wdev)) {
err = PTR_ERR(*wdev);
goto out_unlock;
}
*rdev = wiphy_to_dev((*wdev)->wiphy);
/* 0 is the first index - add 1 to parse only once */
cb->args[0] = (*rdev)->wiphy_idx + 1;
cb->args[1] = (*wdev)->identifier;
} else {
/* subtract the 1 again here */
struct wiphy *wiphy = wiphy_idx_to_wiphy(cb->args[0] - 1);
struct wireless_dev *tmp;
if (!wiphy) {
err = -ENODEV;
goto out_unlock;
}
*rdev = wiphy_to_dev(wiphy);
*wdev = NULL;
list_for_each_entry(tmp, &(*rdev)->wdev_list, list) {
if (tmp->identifier == cb->args[1]) {
*wdev = tmp;
break;
}
}
if (!*wdev) {
err = -ENODEV;
goto out_unlock;
}
}
return 0;
out_unlock:
rtnl_unlock();
return err;
}
static void nl80211_finish_wdev_dump(struct cfg80211_registered_device *rdev)
{
rtnl_unlock();
}
/* IE validation */
static bool is_valid_ie_attr(const struct nlattr *attr)
{
const u8 *pos;
int len;
if (!attr)
return true;
pos = nla_data(attr);
len = nla_len(attr);
while (len) {
u8 elemlen;
if (len < 2)
return false;
len -= 2;
elemlen = pos[1];
if (elemlen > len)
return false;
len -= elemlen;
pos += 2 + elemlen;
}
return true;
}
/* message building helper */
static inline void *nl80211hdr_put(struct sk_buff *skb, u32 portid, u32 seq,
int flags, u8 cmd)
{
/* since there is no private header just add the generic one */
return genlmsg_put(skb, portid, seq, &nl80211_fam, flags, cmd);
}
static int nl80211_msg_put_channel(struct sk_buff *msg,
struct ieee80211_channel *chan,
bool large)
{
if (nla_put_u32(msg, NL80211_FREQUENCY_ATTR_FREQ,
chan->center_freq))
goto nla_put_failure;
if ((chan->flags & IEEE80211_CHAN_DISABLED) &&
nla_put_flag(msg, NL80211_FREQUENCY_ATTR_DISABLED))
goto nla_put_failure;
if (chan->flags & IEEE80211_CHAN_NO_IR) {
if (nla_put_flag(msg, NL80211_FREQUENCY_ATTR_NO_IR))
goto nla_put_failure;
if (nla_put_flag(msg, __NL80211_FREQUENCY_ATTR_NO_IBSS))
goto nla_put_failure;
}
if (chan->flags & IEEE80211_CHAN_RADAR) {
if (nla_put_flag(msg, NL80211_FREQUENCY_ATTR_RADAR))
goto nla_put_failure;
if (large) {
u32 time;
time = elapsed_jiffies_msecs(chan->dfs_state_entered);
if (nla_put_u32(msg, NL80211_FREQUENCY_ATTR_DFS_STATE,
chan->dfs_state))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_FREQUENCY_ATTR_DFS_TIME,
time))
goto nla_put_failure;
if (nla_put_u32(msg,
NL80211_FREQUENCY_ATTR_DFS_CAC_TIME,
chan->dfs_cac_ms))
goto nla_put_failure;
}
}
if (large) {
if ((chan->flags & IEEE80211_CHAN_NO_HT40MINUS) &&
nla_put_flag(msg, NL80211_FREQUENCY_ATTR_NO_HT40_MINUS))
goto nla_put_failure;
if ((chan->flags & IEEE80211_CHAN_NO_HT40PLUS) &&
nla_put_flag(msg, NL80211_FREQUENCY_ATTR_NO_HT40_PLUS))
goto nla_put_failure;
if ((chan->flags & IEEE80211_CHAN_NO_80MHZ) &&
nla_put_flag(msg, NL80211_FREQUENCY_ATTR_NO_80MHZ))
goto nla_put_failure;
if ((chan->flags & IEEE80211_CHAN_NO_160MHZ) &&
nla_put_flag(msg, NL80211_FREQUENCY_ATTR_NO_160MHZ))
goto nla_put_failure;
}
if (nla_put_u32(msg, NL80211_FREQUENCY_ATTR_MAX_TX_POWER,
DBM_TO_MBM(chan->max_power)))
goto nla_put_failure;
return 0;
nla_put_failure:
return -ENOBUFS;
}
/* netlink command implementations */
struct key_parse {
struct key_params p;
int idx;
int type;
bool def, defmgmt;
bool def_uni, def_multi;
};
static int nl80211_parse_key_new(struct nlattr *key, struct key_parse *k)
{
struct nlattr *tb[NL80211_KEY_MAX + 1];
int err = nla_parse_nested(tb, NL80211_KEY_MAX, key,
nl80211_key_policy);
if (err)
return err;
k->def = !!tb[NL80211_KEY_DEFAULT];
k->defmgmt = !!tb[NL80211_KEY_DEFAULT_MGMT];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (tb[NL80211_KEY_IDX])
k->idx = nla_get_u8(tb[NL80211_KEY_IDX]);
if (tb[NL80211_KEY_DATA]) {
k->p.key = nla_data(tb[NL80211_KEY_DATA]);
k->p.key_len = nla_len(tb[NL80211_KEY_DATA]);
}
if (tb[NL80211_KEY_SEQ]) {
k->p.seq = nla_data(tb[NL80211_KEY_SEQ]);
k->p.seq_len = nla_len(tb[NL80211_KEY_SEQ]);
}
if (tb[NL80211_KEY_CIPHER])
k->p.cipher = nla_get_u32(tb[NL80211_KEY_CIPHER]);
if (tb[NL80211_KEY_TYPE]) {
k->type = nla_get_u32(tb[NL80211_KEY_TYPE]);
if (k->type < 0 || k->type >= NUM_NL80211_KEYTYPES)
return -EINVAL;
}
if (tb[NL80211_KEY_DEFAULT_TYPES]) {
struct nlattr *kdt[NUM_NL80211_KEY_DEFAULT_TYPES];
err = nla_parse_nested(kdt, NUM_NL80211_KEY_DEFAULT_TYPES - 1,
tb[NL80211_KEY_DEFAULT_TYPES],
nl80211_key_default_policy);
if (err)
return err;
k->def_uni = kdt[NL80211_KEY_DEFAULT_TYPE_UNICAST];
k->def_multi = kdt[NL80211_KEY_DEFAULT_TYPE_MULTICAST];
}
return 0;
}
static int nl80211_parse_key_old(struct genl_info *info, struct key_parse *k)
{
if (info->attrs[NL80211_ATTR_KEY_DATA]) {
k->p.key = nla_data(info->attrs[NL80211_ATTR_KEY_DATA]);
k->p.key_len = nla_len(info->attrs[NL80211_ATTR_KEY_DATA]);
}
if (info->attrs[NL80211_ATTR_KEY_SEQ]) {
k->p.seq = nla_data(info->attrs[NL80211_ATTR_KEY_SEQ]);
k->p.seq_len = nla_len(info->attrs[NL80211_ATTR_KEY_SEQ]);
}
if (info->attrs[NL80211_ATTR_KEY_IDX])
k->idx = nla_get_u8(info->attrs[NL80211_ATTR_KEY_IDX]);
if (info->attrs[NL80211_ATTR_KEY_CIPHER])
k->p.cipher = nla_get_u32(info->attrs[NL80211_ATTR_KEY_CIPHER]);
k->def = !!info->attrs[NL80211_ATTR_KEY_DEFAULT];
k->defmgmt = !!info->attrs[NL80211_ATTR_KEY_DEFAULT_MGMT];
if (k->def) {
k->def_uni = true;
k->def_multi = true;
}
if (k->defmgmt)
k->def_multi = true;
if (info->attrs[NL80211_ATTR_KEY_TYPE]) {
k->type = nla_get_u32(info->attrs[NL80211_ATTR_KEY_TYPE]);
if (k->type < 0 || k->type >= NUM_NL80211_KEYTYPES)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_KEY_DEFAULT_TYPES]) {
struct nlattr *kdt[NUM_NL80211_KEY_DEFAULT_TYPES];
int err = nla_parse_nested(
kdt, NUM_NL80211_KEY_DEFAULT_TYPES - 1,
info->attrs[NL80211_ATTR_KEY_DEFAULT_TYPES],
nl80211_key_default_policy);
if (err)
return err;
k->def_uni = kdt[NL80211_KEY_DEFAULT_TYPE_UNICAST];
k->def_multi = kdt[NL80211_KEY_DEFAULT_TYPE_MULTICAST];
}
return 0;
}
static int nl80211_parse_key(struct genl_info *info, struct key_parse *k)
{
int err;
memset(k, 0, sizeof(*k));
k->idx = -1;
k->type = -1;
if (info->attrs[NL80211_ATTR_KEY])
err = nl80211_parse_key_new(info->attrs[NL80211_ATTR_KEY], k);
else
err = nl80211_parse_key_old(info, k);
if (err)
return err;
if (k->def && k->defmgmt)
return -EINVAL;
if (k->defmgmt) {
if (k->def_uni || !k->def_multi)
return -EINVAL;
}
if (k->idx != -1) {
if (k->defmgmt) {
if (k->idx < 4 || k->idx > 5)
return -EINVAL;
} else if (k->def) {
if (k->idx < 0 || k->idx > 3)
return -EINVAL;
} else {
if (k->idx < 0 || k->idx > 5)
return -EINVAL;
}
}
return 0;
}
static struct cfg80211_cached_keys *
nl80211_parse_connkeys(struct cfg80211_registered_device *rdev,
struct nlattr *keys, bool *no_ht)
{
struct key_parse parse;
struct nlattr *key;
struct cfg80211_cached_keys *result;
int rem, err, def = 0;
result = kzalloc(sizeof(*result), GFP_KERNEL);
if (!result)
return ERR_PTR(-ENOMEM);
result->def = -1;
result->defmgmt = -1;
nla_for_each_nested(key, keys, rem) {
memset(&parse, 0, sizeof(parse));
parse.idx = -1;
err = nl80211_parse_key_new(key, &parse);
if (err)
goto error;
err = -EINVAL;
if (!parse.p.key)
goto error;
if (parse.idx < 0 || parse.idx > 4)
goto error;
if (parse.def) {
if (def)
goto error;
def = 1;
result->def = parse.idx;
if (!parse.def_uni || !parse.def_multi)
goto error;
} else if (parse.defmgmt)
goto error;
err = cfg80211_validate_key_settings(rdev, &parse.p,
parse.idx, false, NULL);
if (err)
goto error;
result->params[parse.idx].cipher = parse.p.cipher;
result->params[parse.idx].key_len = parse.p.key_len;
result->params[parse.idx].key = result->data[parse.idx];
memcpy(result->data[parse.idx], parse.p.key, parse.p.key_len);
if (parse.p.cipher == WLAN_CIPHER_SUITE_WEP40 ||
parse.p.cipher == WLAN_CIPHER_SUITE_WEP104) {
if (no_ht)
*no_ht = true;
}
}
return result;
error:
kfree(result);
return ERR_PTR(err);
}
static int nl80211_key_allowed(struct wireless_dev *wdev)
{
ASSERT_WDEV_LOCK(wdev);
switch (wdev->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_MESH_POINT:
break;
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
if (!wdev->current_bss)
return -ENOLINK;
break;
default:
return -EINVAL;
}
return 0;
}
static struct ieee80211_channel *nl80211_get_valid_chan(struct wiphy *wiphy,
struct nlattr *tb)
{
struct ieee80211_channel *chan;
if (tb == NULL)
return NULL;
chan = ieee80211_get_channel(wiphy, nla_get_u32(tb));
if (!chan || chan->flags & IEEE80211_CHAN_DISABLED)
return NULL;
return chan;
}
static int nl80211_put_iftypes(struct sk_buff *msg, u32 attr, u16 ifmodes)
{
struct nlattr *nl_modes = nla_nest_start(msg, attr);
int i;
if (!nl_modes)
goto nla_put_failure;
i = 0;
while (ifmodes) {
if ((ifmodes & 1) && nla_put_flag(msg, i))
goto nla_put_failure;
ifmodes >>= 1;
i++;
}
nla_nest_end(msg, nl_modes);
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_put_iface_combinations(struct wiphy *wiphy,
struct sk_buff *msg,
bool large)
{
struct nlattr *nl_combis;
int i, j;
nl_combis = nla_nest_start(msg,
NL80211_ATTR_INTERFACE_COMBINATIONS);
if (!nl_combis)
goto nla_put_failure;
for (i = 0; i < wiphy->n_iface_combinations; i++) {
const struct ieee80211_iface_combination *c;
struct nlattr *nl_combi, *nl_limits;
c = &wiphy->iface_combinations[i];
nl_combi = nla_nest_start(msg, i + 1);
if (!nl_combi)
goto nla_put_failure;
nl_limits = nla_nest_start(msg, NL80211_IFACE_COMB_LIMITS);
if (!nl_limits)
goto nla_put_failure;
for (j = 0; j < c->n_limits; j++) {
struct nlattr *nl_limit;
nl_limit = nla_nest_start(msg, j + 1);
if (!nl_limit)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_IFACE_LIMIT_MAX,
c->limits[j].max))
goto nla_put_failure;
if (nl80211_put_iftypes(msg, NL80211_IFACE_LIMIT_TYPES,
c->limits[j].types))
goto nla_put_failure;
nla_nest_end(msg, nl_limit);
}
nla_nest_end(msg, nl_limits);
if (c->beacon_int_infra_match &&
nla_put_flag(msg, NL80211_IFACE_COMB_STA_AP_BI_MATCH))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_IFACE_COMB_NUM_CHANNELS,
c->num_different_channels) ||
nla_put_u32(msg, NL80211_IFACE_COMB_MAXNUM,
c->max_interfaces))
goto nla_put_failure;
if (large &&
nla_put_u32(msg, NL80211_IFACE_COMB_RADAR_DETECT_WIDTHS,
c->radar_detect_widths))
goto nla_put_failure;
nla_nest_end(msg, nl_combi);
}
nla_nest_end(msg, nl_combis);
return 0;
nla_put_failure:
return -ENOBUFS;
}
#ifdef CONFIG_PM
static int nl80211_send_wowlan_tcp_caps(struct cfg80211_registered_device *rdev,
struct sk_buff *msg)
{
const struct wiphy_wowlan_tcp_support *tcp = rdev->wiphy.wowlan->tcp;
struct nlattr *nl_tcp;
if (!tcp)
return 0;
nl_tcp = nla_nest_start(msg, NL80211_WOWLAN_TRIG_TCP_CONNECTION);
if (!nl_tcp)
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD,
tcp->data_payload_max))
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD,
tcp->data_payload_max))
return -ENOBUFS;
if (tcp->seq && nla_put_flag(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ))
return -ENOBUFS;
if (tcp->tok && nla_put(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN,
sizeof(*tcp->tok), tcp->tok))
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_WOWLAN_TCP_DATA_INTERVAL,
tcp->data_interval_max))
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_WOWLAN_TCP_WAKE_PAYLOAD,
tcp->wake_payload_max))
return -ENOBUFS;
nla_nest_end(msg, nl_tcp);
return 0;
}
static int nl80211_send_wowlan(struct sk_buff *msg,
struct cfg80211_registered_device *dev,
bool large)
{
struct nlattr *nl_wowlan;
if (!dev->wiphy.wowlan)
return 0;
nl_wowlan = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS_SUPPORTED);
if (!nl_wowlan)
return -ENOBUFS;
if (((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_ANY) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_ANY)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_DISCONNECT) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_DISCONNECT)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_MAGIC_PKT) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_SUPPORTS_GTK_REKEY) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_SUPPORTED)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_GTK_REKEY_FAILURE) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_EAP_IDENTITY_REQ) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_4WAY_HANDSHAKE) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE)) ||
((dev->wiphy.wowlan->flags & WIPHY_WOWLAN_RFKILL_RELEASE) &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_RFKILL_RELEASE)))
return -ENOBUFS;
if (dev->wiphy.wowlan->n_patterns) {
struct nl80211_pattern_support pat = {
.max_patterns = dev->wiphy.wowlan->n_patterns,
.min_pattern_len = dev->wiphy.wowlan->pattern_min_len,
.max_pattern_len = dev->wiphy.wowlan->pattern_max_len,
.max_pkt_offset = dev->wiphy.wowlan->max_pkt_offset,
};
if (nla_put(msg, NL80211_WOWLAN_TRIG_PKT_PATTERN,
sizeof(pat), &pat))
return -ENOBUFS;
}
if (large && nl80211_send_wowlan_tcp_caps(dev, msg))
return -ENOBUFS;
nla_nest_end(msg, nl_wowlan);
return 0;
}
#endif
static int nl80211_send_coalesce(struct sk_buff *msg,
struct cfg80211_registered_device *dev)
{
struct nl80211_coalesce_rule_support rule;
if (!dev->wiphy.coalesce)
return 0;
rule.max_rules = dev->wiphy.coalesce->n_rules;
rule.max_delay = dev->wiphy.coalesce->max_delay;
rule.pat.max_patterns = dev->wiphy.coalesce->n_patterns;
rule.pat.min_pattern_len = dev->wiphy.coalesce->pattern_min_len;
rule.pat.max_pattern_len = dev->wiphy.coalesce->pattern_max_len;
rule.pat.max_pkt_offset = dev->wiphy.coalesce->max_pkt_offset;
if (nla_put(msg, NL80211_ATTR_COALESCE_RULE, sizeof(rule), &rule))
return -ENOBUFS;
return 0;
}
static int nl80211_send_band_rateinfo(struct sk_buff *msg,
struct ieee80211_supported_band *sband)
{
struct nlattr *nl_rates, *nl_rate;
struct ieee80211_rate *rate;
int i;
/* add HT info */
if (sband->ht_cap.ht_supported &&
(nla_put(msg, NL80211_BAND_ATTR_HT_MCS_SET,
sizeof(sband->ht_cap.mcs),
&sband->ht_cap.mcs) ||
nla_put_u16(msg, NL80211_BAND_ATTR_HT_CAPA,
sband->ht_cap.cap) ||
nla_put_u8(msg, NL80211_BAND_ATTR_HT_AMPDU_FACTOR,
sband->ht_cap.ampdu_factor) ||
nla_put_u8(msg, NL80211_BAND_ATTR_HT_AMPDU_DENSITY,
sband->ht_cap.ampdu_density)))
return -ENOBUFS;
/* add VHT info */
if (sband->vht_cap.vht_supported &&
(nla_put(msg, NL80211_BAND_ATTR_VHT_MCS_SET,
sizeof(sband->vht_cap.vht_mcs),
&sband->vht_cap.vht_mcs) ||
nla_put_u32(msg, NL80211_BAND_ATTR_VHT_CAPA,
sband->vht_cap.cap)))
return -ENOBUFS;
/* add bitrates */
nl_rates = nla_nest_start(msg, NL80211_BAND_ATTR_RATES);
if (!nl_rates)
return -ENOBUFS;
for (i = 0; i < sband->n_bitrates; i++) {
nl_rate = nla_nest_start(msg, i);
if (!nl_rate)
return -ENOBUFS;
rate = &sband->bitrates[i];
if (nla_put_u32(msg, NL80211_BITRATE_ATTR_RATE,
rate->bitrate))
return -ENOBUFS;
if ((rate->flags & IEEE80211_RATE_SHORT_PREAMBLE) &&
nla_put_flag(msg,
NL80211_BITRATE_ATTR_2GHZ_SHORTPREAMBLE))
return -ENOBUFS;
nla_nest_end(msg, nl_rate);
}
nla_nest_end(msg, nl_rates);
return 0;
}
static int
nl80211_send_mgmt_stypes(struct sk_buff *msg,
const struct ieee80211_txrx_stypes *mgmt_stypes)
{
u16 stypes;
struct nlattr *nl_ftypes, *nl_ifs;
enum nl80211_iftype ift;
int i;
if (!mgmt_stypes)
return 0;
nl_ifs = nla_nest_start(msg, NL80211_ATTR_TX_FRAME_TYPES);
if (!nl_ifs)
return -ENOBUFS;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
return -ENOBUFS;
i = 0;
stypes = mgmt_stypes[ift].tx;
while (stypes) {
if ((stypes & 1) &&
nla_put_u16(msg, NL80211_ATTR_FRAME_TYPE,
(i << 4) | IEEE80211_FTYPE_MGMT))
return -ENOBUFS;
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
nl_ifs = nla_nest_start(msg, NL80211_ATTR_RX_FRAME_TYPES);
if (!nl_ifs)
return -ENOBUFS;
for (ift = 0; ift < NUM_NL80211_IFTYPES; ift++) {
nl_ftypes = nla_nest_start(msg, ift);
if (!nl_ftypes)
return -ENOBUFS;
i = 0;
stypes = mgmt_stypes[ift].rx;
while (stypes) {
if ((stypes & 1) &&
nla_put_u16(msg, NL80211_ATTR_FRAME_TYPE,
(i << 4) | IEEE80211_FTYPE_MGMT))
return -ENOBUFS;
stypes >>= 1;
i++;
}
nla_nest_end(msg, nl_ftypes);
}
nla_nest_end(msg, nl_ifs);
return 0;
}
struct nl80211_dump_wiphy_state {
s64 filter_wiphy;
long start;
long split_start, band_start, chan_start;
bool split;
};
static int nl80211_send_wiphy(struct cfg80211_registered_device *dev,
struct sk_buff *msg, u32 portid, u32 seq,
int flags, struct nl80211_dump_wiphy_state *state)
{
void *hdr;
struct nlattr *nl_bands, *nl_band;
struct nlattr *nl_freqs, *nl_freq;
struct nlattr *nl_cmds;
enum ieee80211_band band;
struct ieee80211_channel *chan;
int i;
const struct ieee80211_txrx_stypes *mgmt_stypes =
dev->wiphy.mgmt_stypes;
u32 features;
hdr = nl80211hdr_put(msg, portid, seq, flags, NL80211_CMD_NEW_WIPHY);
if (!hdr)
return -ENOBUFS;
if (WARN_ON(!state))
return -EINVAL;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, dev->wiphy_idx) ||
nla_put_string(msg, NL80211_ATTR_WIPHY_NAME,
wiphy_name(&dev->wiphy)) ||
nla_put_u32(msg, NL80211_ATTR_GENERATION,
cfg80211_rdev_list_generation))
goto nla_put_failure;
switch (state->split_start) {
case 0:
if (nla_put_u8(msg, NL80211_ATTR_WIPHY_RETRY_SHORT,
dev->wiphy.retry_short) ||
nla_put_u8(msg, NL80211_ATTR_WIPHY_RETRY_LONG,
dev->wiphy.retry_long) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_FRAG_THRESHOLD,
dev->wiphy.frag_threshold) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_RTS_THRESHOLD,
dev->wiphy.rts_threshold) ||
nla_put_u8(msg, NL80211_ATTR_WIPHY_COVERAGE_CLASS,
dev->wiphy.coverage_class) ||
nla_put_u8(msg, NL80211_ATTR_MAX_NUM_SCAN_SSIDS,
dev->wiphy.max_scan_ssids) ||
nla_put_u8(msg, NL80211_ATTR_MAX_NUM_SCHED_SCAN_SSIDS,
dev->wiphy.max_sched_scan_ssids) ||
nla_put_u16(msg, NL80211_ATTR_MAX_SCAN_IE_LEN,
dev->wiphy.max_scan_ie_len) ||
nla_put_u16(msg, NL80211_ATTR_MAX_SCHED_SCAN_IE_LEN,
dev->wiphy.max_sched_scan_ie_len) ||
nla_put_u8(msg, NL80211_ATTR_MAX_MATCH_SETS,
dev->wiphy.max_match_sets))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_IBSS_RSN) &&
nla_put_flag(msg, NL80211_ATTR_SUPPORT_IBSS_RSN))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_MESH_AUTH) &&
nla_put_flag(msg, NL80211_ATTR_SUPPORT_MESH_AUTH))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_AP_UAPSD) &&
nla_put_flag(msg, NL80211_ATTR_SUPPORT_AP_UAPSD))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_FW_ROAM) &&
nla_put_flag(msg, NL80211_ATTR_ROAM_SUPPORT))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_TDLS) &&
nla_put_flag(msg, NL80211_ATTR_TDLS_SUPPORT))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_TDLS_EXTERNAL_SETUP) &&
nla_put_flag(msg, NL80211_ATTR_TDLS_EXTERNAL_SETUP))
goto nla_put_failure;
state->split_start++;
if (state->split)
break;
case 1:
if (nla_put(msg, NL80211_ATTR_CIPHER_SUITES,
sizeof(u32) * dev->wiphy.n_cipher_suites,
dev->wiphy.cipher_suites))
goto nla_put_failure;
if (nla_put_u8(msg, NL80211_ATTR_MAX_NUM_PMKIDS,
dev->wiphy.max_num_pmkids))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_CONTROL_PORT_PROTOCOL) &&
nla_put_flag(msg, NL80211_ATTR_CONTROL_PORT_ETHERTYPE))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_TX,
dev->wiphy.available_antennas_tx) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_ANTENNA_AVAIL_RX,
dev->wiphy.available_antennas_rx))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_AP_PROBE_RESP_OFFLOAD) &&
nla_put_u32(msg, NL80211_ATTR_PROBE_RESP_OFFLOAD,
dev->wiphy.probe_resp_offload))
goto nla_put_failure;
if ((dev->wiphy.available_antennas_tx ||
dev->wiphy.available_antennas_rx) &&
dev->ops->get_antenna) {
u32 tx_ant = 0, rx_ant = 0;
int res;
res = rdev_get_antenna(dev, &tx_ant, &rx_ant);
if (!res) {
if (nla_put_u32(msg,
NL80211_ATTR_WIPHY_ANTENNA_TX,
tx_ant) ||
nla_put_u32(msg,
NL80211_ATTR_WIPHY_ANTENNA_RX,
rx_ant))
goto nla_put_failure;
}
}
state->split_start++;
if (state->split)
break;
case 2:
if (nl80211_put_iftypes(msg, NL80211_ATTR_SUPPORTED_IFTYPES,
dev->wiphy.interface_modes))
goto nla_put_failure;
state->split_start++;
if (state->split)
break;
case 3:
nl_bands = nla_nest_start(msg, NL80211_ATTR_WIPHY_BANDS);
if (!nl_bands)
goto nla_put_failure;
for (band = state->band_start;
band < IEEE80211_NUM_BANDS; band++) {
struct ieee80211_supported_band *sband;
sband = dev->wiphy.bands[band];
if (!sband)
continue;
nl_band = nla_nest_start(msg, band);
if (!nl_band)
goto nla_put_failure;
switch (state->chan_start) {
case 0:
if (nl80211_send_band_rateinfo(msg, sband))
goto nla_put_failure;
state->chan_start++;
if (state->split)
break;
default:
/* add frequencies */
nl_freqs = nla_nest_start(
msg, NL80211_BAND_ATTR_FREQS);
if (!nl_freqs)
goto nla_put_failure;
for (i = state->chan_start - 1;
i < sband->n_channels;
i++) {
nl_freq = nla_nest_start(msg, i);
if (!nl_freq)
goto nla_put_failure;
chan = &sband->channels[i];
if (nl80211_msg_put_channel(
msg, chan,
state->split))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
if (state->split)
break;
}
if (i < sband->n_channels)
state->chan_start = i + 2;
else
state->chan_start = 0;
nla_nest_end(msg, nl_freqs);
}
nla_nest_end(msg, nl_band);
if (state->split) {
/* start again here */
if (state->chan_start)
band--;
break;
}
}
nla_nest_end(msg, nl_bands);
if (band < IEEE80211_NUM_BANDS)
state->band_start = band + 1;
else
state->band_start = 0;
/* if bands & channels are done, continue outside */
if (state->band_start == 0 && state->chan_start == 0)
state->split_start++;
if (state->split)
break;
case 4:
nl_cmds = nla_nest_start(msg, NL80211_ATTR_SUPPORTED_COMMANDS);
if (!nl_cmds)
goto nla_put_failure;
i = 0;
#define CMD(op, n) \
do { \
if (dev->ops->op) { \
i++; \
if (nla_put_u32(msg, i, NL80211_CMD_ ## n)) \
goto nla_put_failure; \
} \
} while (0)
CMD(add_virtual_intf, NEW_INTERFACE);
CMD(change_virtual_intf, SET_INTERFACE);
CMD(add_key, NEW_KEY);
CMD(start_ap, START_AP);
CMD(add_station, NEW_STATION);
CMD(add_mpath, NEW_MPATH);
CMD(update_mesh_config, SET_MESH_CONFIG);
CMD(change_bss, SET_BSS);
CMD(auth, AUTHENTICATE);
CMD(assoc, ASSOCIATE);
CMD(deauth, DEAUTHENTICATE);
CMD(disassoc, DISASSOCIATE);
CMD(join_ibss, JOIN_IBSS);
CMD(join_mesh, JOIN_MESH);
CMD(set_pmksa, SET_PMKSA);
CMD(del_pmksa, DEL_PMKSA);
CMD(flush_pmksa, FLUSH_PMKSA);
if (dev->wiphy.flags & WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL)
CMD(remain_on_channel, REMAIN_ON_CHANNEL);
CMD(set_bitrate_mask, SET_TX_BITRATE_MASK);
CMD(mgmt_tx, FRAME);
CMD(mgmt_tx_cancel_wait, FRAME_WAIT_CANCEL);
if (dev->wiphy.flags & WIPHY_FLAG_NETNS_OK) {
i++;
if (nla_put_u32(msg, i, NL80211_CMD_SET_WIPHY_NETNS))
goto nla_put_failure;
}
if (dev->ops->set_monitor_channel || dev->ops->start_ap ||
dev->ops->join_mesh) {
i++;
if (nla_put_u32(msg, i, NL80211_CMD_SET_CHANNEL))
goto nla_put_failure;
}
CMD(set_wds_peer, SET_WDS_PEER);
if (dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_TDLS) {
CMD(tdls_mgmt, TDLS_MGMT);
CMD(tdls_oper, TDLS_OPER);
}
if (dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN)
CMD(sched_scan_start, START_SCHED_SCAN);
CMD(probe_client, PROBE_CLIENT);
CMD(set_noack_map, SET_NOACK_MAP);
if (dev->wiphy.flags & WIPHY_FLAG_REPORTS_OBSS) {
i++;
if (nla_put_u32(msg, i, NL80211_CMD_REGISTER_BEACONS))
goto nla_put_failure;
}
CMD(start_p2p_device, START_P2P_DEVICE);
CMD(set_mcast_rate, SET_MCAST_RATE);
if (state->split) {
CMD(crit_proto_start, CRIT_PROTOCOL_START);
CMD(crit_proto_stop, CRIT_PROTOCOL_STOP);
if (dev->wiphy.flags & WIPHY_FLAG_HAS_CHANNEL_SWITCH)
CMD(channel_switch, CHANNEL_SWITCH);
}
CMD(set_qos_map, SET_QOS_MAP);
#ifdef CONFIG_NL80211_TESTMODE
CMD(testmode_cmd, TESTMODE);
#endif
#undef CMD
if (dev->ops->connect || dev->ops->auth) {
i++;
if (nla_put_u32(msg, i, NL80211_CMD_CONNECT))
goto nla_put_failure;
}
if (dev->ops->disconnect || dev->ops->deauth) {
i++;
if (nla_put_u32(msg, i, NL80211_CMD_DISCONNECT))
goto nla_put_failure;
}
nla_nest_end(msg, nl_cmds);
state->split_start++;
if (state->split)
break;
case 5:
if (dev->ops->remain_on_channel &&
(dev->wiphy.flags & WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL) &&
nla_put_u32(msg,
NL80211_ATTR_MAX_REMAIN_ON_CHANNEL_DURATION,
dev->wiphy.max_remain_on_channel_duration))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_OFFCHAN_TX) &&
nla_put_flag(msg, NL80211_ATTR_OFFCHANNEL_TX_OK))
goto nla_put_failure;
if (nl80211_send_mgmt_stypes(msg, mgmt_stypes))
goto nla_put_failure;
state->split_start++;
if (state->split)
break;
case 6:
#ifdef CONFIG_PM
if (nl80211_send_wowlan(msg, dev, state->split))
goto nla_put_failure;
state->split_start++;
if (state->split)
break;
#else
state->split_start++;
#endif
case 7:
if (nl80211_put_iftypes(msg, NL80211_ATTR_SOFTWARE_IFTYPES,
dev->wiphy.software_iftypes))
goto nla_put_failure;
if (nl80211_put_iface_combinations(&dev->wiphy, msg,
state->split))
goto nla_put_failure;
state->split_start++;
if (state->split)
break;
case 8:
if ((dev->wiphy.flags & WIPHY_FLAG_HAVE_AP_SME) &&
nla_put_u32(msg, NL80211_ATTR_DEVICE_AP_SME,
dev->wiphy.ap_sme_capa))
goto nla_put_failure;
features = dev->wiphy.features;
/*
* We can only add the per-channel limit information if the
* dump is split, otherwise it makes it too big. Therefore
* only advertise it in that case.
*/
if (state->split)
features |= NL80211_FEATURE_ADVERTISE_CHAN_LIMITS;
if (nla_put_u32(msg, NL80211_ATTR_FEATURE_FLAGS, features))
goto nla_put_failure;
if (dev->wiphy.ht_capa_mod_mask &&
nla_put(msg, NL80211_ATTR_HT_CAPABILITY_MASK,
sizeof(*dev->wiphy.ht_capa_mod_mask),
dev->wiphy.ht_capa_mod_mask))
goto nla_put_failure;
if (dev->wiphy.flags & WIPHY_FLAG_HAVE_AP_SME &&
dev->wiphy.max_acl_mac_addrs &&
nla_put_u32(msg, NL80211_ATTR_MAC_ACL_MAX,
dev->wiphy.max_acl_mac_addrs))
goto nla_put_failure;
/*
* Any information below this point is only available to
* applications that can deal with it being split. This
* helps ensure that newly added capabilities don't break
* older tools by overrunning their buffers.
*
* We still increment split_start so that in the split
* case we'll continue with more data in the next round,
* but break unconditionally so unsplit data stops here.
*/
state->split_start++;
break;
case 9:
if (dev->wiphy.extended_capabilities &&
(nla_put(msg, NL80211_ATTR_EXT_CAPA,
dev->wiphy.extended_capabilities_len,
dev->wiphy.extended_capabilities) ||
nla_put(msg, NL80211_ATTR_EXT_CAPA_MASK,
dev->wiphy.extended_capabilities_len,
dev->wiphy.extended_capabilities_mask)))
goto nla_put_failure;
if (dev->wiphy.vht_capa_mod_mask &&
nla_put(msg, NL80211_ATTR_VHT_CAPABILITY_MASK,
sizeof(*dev->wiphy.vht_capa_mod_mask),
dev->wiphy.vht_capa_mod_mask))
goto nla_put_failure;
state->split_start++;
break;
case 10:
if (nl80211_send_coalesce(msg, dev))
goto nla_put_failure;
if ((dev->wiphy.flags & WIPHY_FLAG_SUPPORTS_5_10_MHZ) &&
(nla_put_flag(msg, NL80211_ATTR_SUPPORT_5_MHZ) ||
nla_put_flag(msg, NL80211_ATTR_SUPPORT_10_MHZ)))
goto nla_put_failure;
if (dev->wiphy.max_ap_assoc_sta &&
nla_put_u32(msg, NL80211_ATTR_MAX_AP_ASSOC_STA,
dev->wiphy.max_ap_assoc_sta))
goto nla_put_failure;
state->split_start++;
break;
case 11:
if (dev->wiphy.n_vendor_commands) {
const struct nl80211_vendor_cmd_info *info;
struct nlattr *nested;
nested = nla_nest_start(msg, NL80211_ATTR_VENDOR_DATA);
if (!nested)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.n_vendor_commands; i++) {
info = &dev->wiphy.vendor_commands[i].info;
if (nla_put(msg, i + 1, sizeof(*info), info))
goto nla_put_failure;
}
nla_nest_end(msg, nested);
}
if (dev->wiphy.n_vendor_events) {
const struct nl80211_vendor_cmd_info *info;
struct nlattr *nested;
nested = nla_nest_start(msg,
NL80211_ATTR_VENDOR_EVENTS);
if (!nested)
goto nla_put_failure;
for (i = 0; i < dev->wiphy.n_vendor_events; i++) {
info = &dev->wiphy.vendor_events[i];
if (nla_put(msg, i + 1, sizeof(*info), info))
goto nla_put_failure;
}
nla_nest_end(msg, nested);
}
/* done */
state->split_start = 0;
break;
}
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_wiphy_parse(struct sk_buff *skb,
struct netlink_callback *cb,
struct nl80211_dump_wiphy_state *state)
{
struct nlattr **tb = nl80211_fam.attrbuf;
int ret = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
tb, nl80211_fam.maxattr, nl80211_policy);
/* ignore parse errors for backward compatibility */
if (ret)
return 0;
state->split = tb[NL80211_ATTR_SPLIT_WIPHY_DUMP];
if (tb[NL80211_ATTR_WIPHY])
state->filter_wiphy = nla_get_u32(tb[NL80211_ATTR_WIPHY]);
if (tb[NL80211_ATTR_WDEV])
state->filter_wiphy = nla_get_u64(tb[NL80211_ATTR_WDEV]) >> 32;
if (tb[NL80211_ATTR_IFINDEX]) {
struct net_device *netdev;
struct cfg80211_registered_device *rdev;
int ifidx = nla_get_u32(tb[NL80211_ATTR_IFINDEX]);
netdev = __dev_get_by_index(sock_net(skb->sk), ifidx);
if (!netdev)
return -ENODEV;
if (netdev->ieee80211_ptr) {
rdev = wiphy_to_dev(
netdev->ieee80211_ptr->wiphy);
state->filter_wiphy = rdev->wiphy_idx;
}
}
return 0;
}
static int nl80211_dump_wiphy(struct sk_buff *skb, struct netlink_callback *cb)
{
int idx = 0, ret;
struct nl80211_dump_wiphy_state *state = (void *)cb->args[0];
struct cfg80211_registered_device *dev;
rtnl_lock();
if (!state) {
state = kzalloc(sizeof(*state), GFP_KERNEL);
if (!state) {
rtnl_unlock();
return -ENOMEM;
}
state->filter_wiphy = -1;
ret = nl80211_dump_wiphy_parse(skb, cb, state);
if (ret) {
kfree(state);
rtnl_unlock();
return ret;
}
cb->args[0] = (long)state;
}
list_for_each_entry(dev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&dev->wiphy), sock_net(skb->sk)))
continue;
if (++idx <= state->start)
continue;
if (state->filter_wiphy != -1 &&
state->filter_wiphy != dev->wiphy_idx)
continue;
/* attempt to fit multiple wiphy data chunks into the skb */
do {
ret = nl80211_send_wiphy(dev, skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq,
NLM_F_MULTI, state);
if (ret < 0) {
/*
* If sending the wiphy data didn't fit (ENOBUFS
* or EMSGSIZE returned), this SKB is still
* empty (so it's not too big because another
* wiphy dataset is already in the skb) and
* we've not tried to adjust the dump allocation
* yet ... then adjust the alloc size to be
* bigger, and return 1 but with the empty skb.
* This results in an empty message being RX'ed
* in userspace, but that is ignored.
*
* We can then retry with the larger buffer.
*/
if ((ret == -ENOBUFS || ret == -EMSGSIZE) &&
!skb->len && !state->split &&
cb->min_dump_alloc < 4096) {
cb->min_dump_alloc = 4096;
state->split_start = 0;
rtnl_unlock();
return 1;
}
idx--;
break;
}
} while (state->split_start > 0);
break;
}
rtnl_unlock();
state->start = idx;
return skb->len;
}
static int nl80211_dump_wiphy_done(struct netlink_callback *cb)
{
kfree((void *)cb->args[0]);
return 0;
}
static int nl80211_get_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct cfg80211_registered_device *dev = info->user_ptr[0];
struct nl80211_dump_wiphy_state state = {};
msg = nlmsg_new(4096, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_wiphy(dev, msg, info->snd_portid, info->snd_seq, 0,
&state) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy txq_params_policy[NL80211_TXQ_ATTR_MAX + 1] = {
[NL80211_TXQ_ATTR_QUEUE] = { .type = NLA_U8 },
[NL80211_TXQ_ATTR_TXOP] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_CWMIN] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_CWMAX] = { .type = NLA_U16 },
[NL80211_TXQ_ATTR_AIFS] = { .type = NLA_U8 },
};
static int parse_txq_params(struct nlattr *tb[],
struct ieee80211_txq_params *txq_params)
{
if (!tb[NL80211_TXQ_ATTR_AC] || !tb[NL80211_TXQ_ATTR_TXOP] ||
!tb[NL80211_TXQ_ATTR_CWMIN] || !tb[NL80211_TXQ_ATTR_CWMAX] ||
!tb[NL80211_TXQ_ATTR_AIFS])
return -EINVAL;
txq_params->ac = nla_get_u8(tb[NL80211_TXQ_ATTR_AC]);
txq_params->txop = nla_get_u16(tb[NL80211_TXQ_ATTR_TXOP]);
txq_params->cwmin = nla_get_u16(tb[NL80211_TXQ_ATTR_CWMIN]);
txq_params->cwmax = nla_get_u16(tb[NL80211_TXQ_ATTR_CWMAX]);
txq_params->aifs = nla_get_u8(tb[NL80211_TXQ_ATTR_AIFS]);
if (txq_params->ac >= NL80211_NUM_ACS)
return -EINVAL;
return 0;
}
static bool nl80211_can_set_dev_channel(struct wireless_dev *wdev)
{
/*
* You can only set the channel explicitly for WDS interfaces,
* all others have their channel managed via their respective
* "establish a connection" command (connect, join, ...)
*
* For AP/GO and mesh mode, the channel can be set with the
* channel userspace API, but is only stored and passed to the
* low-level driver when the AP starts or the mesh is joined.
* This is for backward compatibility, userspace can also give
* the channel in the start-ap or join-mesh commands instead.
*
* Monitors are special as they are normally slaved to
* whatever else is going on, so they have their own special
* operation to set the monitor channel if possible.
*/
return !wdev ||
wdev->iftype == NL80211_IFTYPE_AP ||
wdev->iftype == NL80211_IFTYPE_MESH_POINT ||
wdev->iftype == NL80211_IFTYPE_MONITOR ||
wdev->iftype == NL80211_IFTYPE_P2P_GO;
}
static int nl80211_parse_chandef(struct cfg80211_registered_device *rdev,
struct genl_info *info,
struct cfg80211_chan_def *chandef)
{
u32 control_freq;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
control_freq = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_FREQ]);
chandef->chan = ieee80211_get_channel(&rdev->wiphy, control_freq);
chandef->width = NL80211_CHAN_WIDTH_20_NOHT;
chandef->center_freq1 = control_freq;
chandef->center_freq2 = 0;
/* Primary channel not allowed */
if (!chandef->chan || chandef->chan->flags & IEEE80211_CHAN_DISABLED)
return -EINVAL;
if (info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]) {
enum nl80211_channel_type chantype;
chantype = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_CHANNEL_TYPE]);
switch (chantype) {
case NL80211_CHAN_NO_HT:
case NL80211_CHAN_HT20:
case NL80211_CHAN_HT40PLUS:
case NL80211_CHAN_HT40MINUS:
cfg80211_chandef_create(chandef, chandef->chan,
chantype);
break;
default:
return -EINVAL;
}
} else if (info->attrs[NL80211_ATTR_CHANNEL_WIDTH]) {
chandef->width =
nla_get_u32(info->attrs[NL80211_ATTR_CHANNEL_WIDTH]);
if (info->attrs[NL80211_ATTR_CENTER_FREQ1])
chandef->center_freq1 =
nla_get_u32(
info->attrs[NL80211_ATTR_CENTER_FREQ1]);
if (info->attrs[NL80211_ATTR_CENTER_FREQ2])
chandef->center_freq2 =
nla_get_u32(
info->attrs[NL80211_ATTR_CENTER_FREQ2]);
}
if (!cfg80211_chandef_valid(chandef))
return -EINVAL;
if (!cfg80211_chandef_usable(&rdev->wiphy, chandef,
IEEE80211_CHAN_DISABLED))
return -EINVAL;
if ((chandef->width == NL80211_CHAN_WIDTH_5 ||
chandef->width == NL80211_CHAN_WIDTH_10) &&
!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_5_10_MHZ))
return -EINVAL;
return 0;
}
static int __nl80211_set_channel(struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev,
struct genl_info *info)
{
struct cfg80211_chan_def chandef;
int result;
enum nl80211_iftype iftype = NL80211_IFTYPE_MONITOR;
if (wdev)
iftype = wdev->iftype;
if (!nl80211_can_set_dev_channel(wdev))
return -EOPNOTSUPP;
result = nl80211_parse_chandef(rdev, info, &chandef);
if (result)
return result;
switch (iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
if (wdev->beacon_interval) {
result = -EBUSY;
break;
}
if (!cfg80211_reg_can_beacon(&rdev->wiphy, &chandef)) {
result = -EINVAL;
break;
}
wdev->preset_chandef = chandef;
result = 0;
break;
case NL80211_IFTYPE_MESH_POINT:
result = cfg80211_set_mesh_channel(rdev, wdev, &chandef);
break;
case NL80211_IFTYPE_MONITOR:
result = cfg80211_set_monitor_channel(rdev, &chandef);
break;
default:
result = -EINVAL;
}
return result;
}
static int nl80211_set_channel(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *netdev = info->user_ptr[1];
return __nl80211_set_channel(rdev, netdev->ieee80211_ptr, info);
}
static int nl80211_set_wds_peer(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
const u8 *bssid;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
if (!rdev->ops->set_wds_peer)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_WDS)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
return rdev_set_wds_peer(rdev, dev, bssid);
}
static int nl80211_set_wiphy(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev;
struct net_device *netdev = NULL;
struct wireless_dev *wdev;
int result = 0, rem_txq_params = 0;
struct nlattr *nl_txq_params;
u32 changed;
u8 retry_short = 0, retry_long = 0;
u32 frag_threshold = 0, rts_threshold = 0;
u8 coverage_class = 0;
ASSERT_RTNL();
/*
* Try to find the wiphy and netdev. Normally this
* function shouldn't need the netdev, but this is
* done for backward compatibility -- previously
* setting the channel was done per wiphy, but now
* it is per netdev. Previous userland like hostapd
* also passed a netdev to set_wiphy, so that it is
* possible to let that go to the right netdev!
*/
if (info->attrs[NL80211_ATTR_IFINDEX]) {
int ifindex = nla_get_u32(info->attrs[NL80211_ATTR_IFINDEX]);
netdev = __dev_get_by_index(genl_info_net(info), ifindex);
if (netdev && netdev->ieee80211_ptr)
rdev = wiphy_to_dev(netdev->ieee80211_ptr->wiphy);
else
netdev = NULL;
}
if (!netdev) {
rdev = __cfg80211_rdev_from_attrs(genl_info_net(info),
info->attrs);
if (IS_ERR(rdev))
return PTR_ERR(rdev);
wdev = NULL;
netdev = NULL;
result = 0;
} else
wdev = netdev->ieee80211_ptr;
/*
* end workaround code, by now the rdev is available
* and locked, and wdev may or may not be NULL.
*/
if (info->attrs[NL80211_ATTR_WIPHY_NAME])
result = cfg80211_dev_rename(
rdev, nla_data(info->attrs[NL80211_ATTR_WIPHY_NAME]));
if (result)
return result;
if (info->attrs[NL80211_ATTR_WIPHY_TXQ_PARAMS]) {
struct ieee80211_txq_params txq_params;
struct nlattr *tb[NL80211_TXQ_ATTR_MAX + 1];
if (!rdev->ops->set_txq_params)
return -EOPNOTSUPP;
if (!netdev)
return -EINVAL;
if (netdev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
netdev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
if (!netif_running(netdev))
return -ENETDOWN;
nla_for_each_nested(nl_txq_params,
info->attrs[NL80211_ATTR_WIPHY_TXQ_PARAMS],
rem_txq_params) {
result = nla_parse(tb, NL80211_TXQ_ATTR_MAX,
nla_data(nl_txq_params),
nla_len(nl_txq_params),
txq_params_policy);
if (result)
return result;
result = parse_txq_params(tb, &txq_params);
if (result)
return result;
result = rdev_set_txq_params(rdev, netdev,
&txq_params);
if (result)
return result;
}
}
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
result = __nl80211_set_channel(rdev,
nl80211_can_set_dev_channel(wdev) ? wdev : NULL,
info);
if (result)
return result;
}
if (info->attrs[NL80211_ATTR_WIPHY_TX_POWER_SETTING]) {
struct wireless_dev *txp_wdev = wdev;
enum nl80211_tx_power_setting type;
int idx, mbm = 0;
if (!(rdev->wiphy.features & NL80211_FEATURE_VIF_TXPOWER))
txp_wdev = NULL;
if (!rdev->ops->set_tx_power)
return -EOPNOTSUPP;
idx = NL80211_ATTR_WIPHY_TX_POWER_SETTING;
type = nla_get_u32(info->attrs[idx]);
if (!info->attrs[NL80211_ATTR_WIPHY_TX_POWER_LEVEL] &&
(type != NL80211_TX_POWER_AUTOMATIC))
return -EINVAL;
if (type != NL80211_TX_POWER_AUTOMATIC) {
idx = NL80211_ATTR_WIPHY_TX_POWER_LEVEL;
mbm = nla_get_u32(info->attrs[idx]);
}
result = rdev_set_tx_power(rdev, txp_wdev, type, mbm);
if (result)
return result;
}
if (info->attrs[NL80211_ATTR_WIPHY_ANTENNA_TX] &&
info->attrs[NL80211_ATTR_WIPHY_ANTENNA_RX]) {
u32 tx_ant, rx_ant;
if ((!rdev->wiphy.available_antennas_tx &&
!rdev->wiphy.available_antennas_rx) ||
!rdev->ops->set_antenna)
return -EOPNOTSUPP;
tx_ant = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_ANTENNA_TX]);
rx_ant = nla_get_u32(info->attrs[NL80211_ATTR_WIPHY_ANTENNA_RX]);
/* reject antenna configurations which don't match the
* available antenna masks, except for the "all" mask */
if ((~tx_ant && (tx_ant & ~rdev->wiphy.available_antennas_tx)) ||
(~rx_ant && (rx_ant & ~rdev->wiphy.available_antennas_rx)))
return -EINVAL;
tx_ant = tx_ant & rdev->wiphy.available_antennas_tx;
rx_ant = rx_ant & rdev->wiphy.available_antennas_rx;
result = rdev_set_antenna(rdev, tx_ant, rx_ant);
if (result)
return result;
}
changed = 0;
if (info->attrs[NL80211_ATTR_WIPHY_RETRY_SHORT]) {
retry_short = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_RETRY_SHORT]);
if (retry_short == 0)
return -EINVAL;
changed |= WIPHY_PARAM_RETRY_SHORT;
}
if (info->attrs[NL80211_ATTR_WIPHY_RETRY_LONG]) {
retry_long = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_RETRY_LONG]);
if (retry_long == 0)
return -EINVAL;
changed |= WIPHY_PARAM_RETRY_LONG;
}
if (info->attrs[NL80211_ATTR_WIPHY_FRAG_THRESHOLD]) {
frag_threshold = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_FRAG_THRESHOLD]);
if (frag_threshold < 256)
return -EINVAL;
if (frag_threshold != (u32) -1) {
/*
* Fragments (apart from the last one) are required to
* have even length. Make the fragmentation code
* simpler by stripping LSB should someone try to use
* odd threshold value.
*/
frag_threshold &= ~0x1;
}
changed |= WIPHY_PARAM_FRAG_THRESHOLD;
}
if (info->attrs[NL80211_ATTR_WIPHY_RTS_THRESHOLD]) {
rts_threshold = nla_get_u32(
info->attrs[NL80211_ATTR_WIPHY_RTS_THRESHOLD]);
changed |= WIPHY_PARAM_RTS_THRESHOLD;
}
if (info->attrs[NL80211_ATTR_WIPHY_COVERAGE_CLASS]) {
coverage_class = nla_get_u8(
info->attrs[NL80211_ATTR_WIPHY_COVERAGE_CLASS]);
changed |= WIPHY_PARAM_COVERAGE_CLASS;
}
if (changed) {
u8 old_retry_short, old_retry_long;
u32 old_frag_threshold, old_rts_threshold;
u8 old_coverage_class;
if (!rdev->ops->set_wiphy_params)
return -EOPNOTSUPP;
old_retry_short = rdev->wiphy.retry_short;
old_retry_long = rdev->wiphy.retry_long;
old_frag_threshold = rdev->wiphy.frag_threshold;
old_rts_threshold = rdev->wiphy.rts_threshold;
old_coverage_class = rdev->wiphy.coverage_class;
if (changed & WIPHY_PARAM_RETRY_SHORT)
rdev->wiphy.retry_short = retry_short;
if (changed & WIPHY_PARAM_RETRY_LONG)
rdev->wiphy.retry_long = retry_long;
if (changed & WIPHY_PARAM_FRAG_THRESHOLD)
rdev->wiphy.frag_threshold = frag_threshold;
if (changed & WIPHY_PARAM_RTS_THRESHOLD)
rdev->wiphy.rts_threshold = rts_threshold;
if (changed & WIPHY_PARAM_COVERAGE_CLASS)
rdev->wiphy.coverage_class = coverage_class;
result = rdev_set_wiphy_params(rdev, changed);
if (result) {
rdev->wiphy.retry_short = old_retry_short;
rdev->wiphy.retry_long = old_retry_long;
rdev->wiphy.frag_threshold = old_frag_threshold;
rdev->wiphy.rts_threshold = old_rts_threshold;
rdev->wiphy.coverage_class = old_coverage_class;
}
}
return 0;
}
static inline u64 wdev_id(struct wireless_dev *wdev)
{
return (u64)wdev->identifier |
((u64)wiphy_to_dev(wdev->wiphy)->wiphy_idx << 32);
}
static int nl80211_send_chandef(struct sk_buff *msg,
const struct cfg80211_chan_def *chandef)
{
WARN_ON(!cfg80211_chandef_valid(chandef));
if (nla_put_u32(msg, NL80211_ATTR_WIPHY_FREQ,
chandef->chan->center_freq))
return -ENOBUFS;
switch (chandef->width) {
case NL80211_CHAN_WIDTH_20_NOHT:
case NL80211_CHAN_WIDTH_20:
case NL80211_CHAN_WIDTH_40:
if (nla_put_u32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
cfg80211_get_chandef_type(chandef)))
return -ENOBUFS;
break;
default:
break;
}
if (nla_put_u32(msg, NL80211_ATTR_CHANNEL_WIDTH, chandef->width))
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_ATTR_CENTER_FREQ1, chandef->center_freq1))
return -ENOBUFS;
if (chandef->center_freq2 &&
nla_put_u32(msg, NL80211_ATTR_CENTER_FREQ2, chandef->center_freq2))
return -ENOBUFS;
return 0;
}
static int nl80211_send_iface(struct sk_buff *msg, u32 portid, u32 seq, int flags,
struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev)
{
struct net_device *dev = wdev->netdev;
void *hdr;
hdr = nl80211hdr_put(msg, portid, seq, flags, NL80211_CMD_NEW_INTERFACE);
if (!hdr)
return -1;
if (dev &&
(nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put_string(msg, NL80211_ATTR_IFNAME, dev->name)))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFTYPE, wdev->iftype) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, wdev_address(wdev)) ||
nla_put_u32(msg, NL80211_ATTR_GENERATION,
rdev->devlist_generation ^
(cfg80211_rdev_list_generation << 2)))
goto nla_put_failure;
if (rdev->ops->get_channel) {
int ret;
struct cfg80211_chan_def chandef;
ret = rdev_get_channel(rdev, wdev, &chandef);
if (ret == 0) {
if (nl80211_send_chandef(msg, &chandef))
goto nla_put_failure;
}
}
if (wdev->ssid_len) {
if (nla_put(msg, NL80211_ATTR_SSID, wdev->ssid_len, wdev->ssid))
goto nla_put_failure;
}
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_interface(struct sk_buff *skb, struct netlink_callback *cb)
{
int wp_idx = 0;
int if_idx = 0;
int wp_start = cb->args[0];
int if_start = cb->args[1];
struct cfg80211_registered_device *rdev;
struct wireless_dev *wdev;
rtnl_lock();
list_for_each_entry(rdev, &cfg80211_rdev_list, list) {
if (!net_eq(wiphy_net(&rdev->wiphy), sock_net(skb->sk)))
continue;
if (wp_idx < wp_start) {
wp_idx++;
continue;
}
if_idx = 0;
list_for_each_entry(wdev, &rdev->wdev_list, list) {
if (if_idx < if_start) {
if_idx++;
continue;
}
if (nl80211_send_iface(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev) < 0) {
goto out;
}
if_idx++;
}
wp_idx++;
}
out:
rtnl_unlock();
cb->args[0] = wp_idx;
cb->args[1] = if_idx;
return skb->len;
}
static int nl80211_get_interface(struct sk_buff *skb, struct genl_info *info)
{
struct sk_buff *msg;
struct cfg80211_registered_device *dev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_iface(msg, info->snd_portid, info->snd_seq, 0,
dev, wdev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static const struct nla_policy mntr_flags_policy[NL80211_MNTR_FLAG_MAX + 1] = {
[NL80211_MNTR_FLAG_FCSFAIL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_PLCPFAIL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_CONTROL] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_OTHER_BSS] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_COOK_FRAMES] = { .type = NLA_FLAG },
[NL80211_MNTR_FLAG_ACTIVE] = { .type = NLA_FLAG },
};
static int parse_monitor_flags(struct nlattr *nla, u32 *mntrflags)
{
struct nlattr *flags[NL80211_MNTR_FLAG_MAX + 1];
int flag;
*mntrflags = 0;
if (!nla)
return -EINVAL;
if (nla_parse_nested(flags, NL80211_MNTR_FLAG_MAX,
nla, mntr_flags_policy))
return -EINVAL;
for (flag = 1; flag <= NL80211_MNTR_FLAG_MAX; flag++)
if (flags[flag])
*mntrflags |= (1<<flag);
return 0;
}
static int nl80211_valid_4addr(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u8 use_4addr,
enum nl80211_iftype iftype)
{
if (!use_4addr) {
if (netdev && (netdev->priv_flags & IFF_BRIDGE_PORT))
return -EBUSY;
return 0;
}
switch (iftype) {
case NL80211_IFTYPE_AP_VLAN:
if (rdev->wiphy.flags & WIPHY_FLAG_4ADDR_AP)
return 0;
break;
case NL80211_IFTYPE_STATION:
if (rdev->wiphy.flags & WIPHY_FLAG_4ADDR_STATION)
return 0;
break;
default:
break;
}
return -EOPNOTSUPP;
}
static int nl80211_set_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct vif_params params;
int err;
enum nl80211_iftype otype, ntype;
struct net_device *dev = info->user_ptr[1];
u32 _flags, *flags = NULL;
bool change = false;
memset(¶ms, 0, sizeof(params));
otype = ntype = dev->ieee80211_ptr->iftype;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
ntype = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (otype != ntype)
change = true;
if (ntype > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_MESH_ID]) {
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (ntype != NL80211_IFTYPE_MESH_POINT)
return -EINVAL;
if (netif_running(dev))
return -EBUSY;
wdev_lock(wdev);
BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN !=
IEEE80211_MAX_MESH_ID_LEN);
wdev->mesh_id_up_len =
nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
memcpy(wdev->ssid, nla_data(info->attrs[NL80211_ATTR_MESH_ID]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
}
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
change = true;
err = nl80211_valid_4addr(rdev, dev, params.use_4addr, ntype);
if (err)
return err;
} else {
params.use_4addr = -1;
}
if (info->attrs[NL80211_ATTR_MNTR_FLAGS]) {
if (ntype != NL80211_IFTYPE_MONITOR)
return -EINVAL;
err = parse_monitor_flags(info->attrs[NL80211_ATTR_MNTR_FLAGS],
&_flags);
if (err)
return err;
flags = &_flags;
change = true;
}
if (flags && (*flags & MONITOR_FLAG_ACTIVE) &&
!(rdev->wiphy.features & NL80211_FEATURE_ACTIVE_MONITOR))
return -EOPNOTSUPP;
if (change)
err = cfg80211_change_iface(rdev, dev, ntype, flags, ¶ms);
else
err = 0;
if (!err && params.use_4addr != -1)
dev->ieee80211_ptr->use_4addr = params.use_4addr;
return err;
}
static int nl80211_new_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct vif_params params;
struct wireless_dev *wdev;
struct sk_buff *msg;
int err;
enum nl80211_iftype type = NL80211_IFTYPE_UNSPECIFIED;
u32 flags;
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_IFNAME])
return -EINVAL;
if (info->attrs[NL80211_ATTR_IFTYPE]) {
type = nla_get_u32(info->attrs[NL80211_ATTR_IFTYPE]);
if (type > NL80211_IFTYPE_MAX)
return -EINVAL;
}
if (!rdev->ops->add_virtual_intf ||
!(rdev->wiphy.interface_modes & (1 << type)))
return -EOPNOTSUPP;
if (type == NL80211_IFTYPE_P2P_DEVICE && info->attrs[NL80211_ATTR_MAC]) {
nla_memcpy(params.macaddr, info->attrs[NL80211_ATTR_MAC],
ETH_ALEN);
if (!is_valid_ether_addr(params.macaddr))
return -EADDRNOTAVAIL;
}
if (info->attrs[NL80211_ATTR_4ADDR]) {
params.use_4addr = !!nla_get_u8(info->attrs[NL80211_ATTR_4ADDR]);
err = nl80211_valid_4addr(rdev, NULL, params.use_4addr, type);
if (err)
return err;
}
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
err = parse_monitor_flags(type == NL80211_IFTYPE_MONITOR ?
info->attrs[NL80211_ATTR_MNTR_FLAGS] : NULL,
&flags);
if (!err && (flags & MONITOR_FLAG_ACTIVE) &&
!(rdev->wiphy.features & NL80211_FEATURE_ACTIVE_MONITOR))
return -EOPNOTSUPP;
wdev = rdev_add_virtual_intf(rdev,
nla_data(info->attrs[NL80211_ATTR_IFNAME]),
type, err ? NULL : &flags, ¶ms);
if (IS_ERR(wdev)) {
nlmsg_free(msg);
return PTR_ERR(wdev);
}
switch (type) {
case NL80211_IFTYPE_MESH_POINT:
if (!info->attrs[NL80211_ATTR_MESH_ID])
break;
wdev_lock(wdev);
BUILD_BUG_ON(IEEE80211_MAX_SSID_LEN !=
IEEE80211_MAX_MESH_ID_LEN);
wdev->mesh_id_up_len =
nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
memcpy(wdev->ssid, nla_data(info->attrs[NL80211_ATTR_MESH_ID]),
wdev->mesh_id_up_len);
wdev_unlock(wdev);
break;
case NL80211_IFTYPE_P2P_DEVICE:
/*
* P2P Device doesn't have a netdev, so doesn't go
* through the netdev notifier and must be added here
*/
mutex_init(&wdev->mtx);
INIT_LIST_HEAD(&wdev->event_list);
spin_lock_init(&wdev->event_lock);
INIT_LIST_HEAD(&wdev->mgmt_registrations);
spin_lock_init(&wdev->mgmt_registrations_lock);
wdev->identifier = ++rdev->wdev_id;
list_add_rcu(&wdev->list, &rdev->wdev_list);
rdev->devlist_generation++;
break;
default:
break;
}
if (nl80211_send_iface(msg, info->snd_portid, info->snd_seq, 0,
rdev, wdev) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static int nl80211_del_interface(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
if (!rdev->ops->del_virtual_intf)
return -EOPNOTSUPP;
/*
* If we remove a wireless device without a netdev then clear
* user_ptr[1] so that nl80211_post_doit won't dereference it
* to check if it needs to do dev_put(). Otherwise it crashes
* since the wdev has been freed, unlike with a netdev where
* we need the dev_put() for the netdev to really be freed.
*/
if (!wdev->netdev)
info->user_ptr[1] = NULL;
return rdev_del_virtual_intf(rdev, wdev);
}
static int nl80211_set_noack_map(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 noack_map;
if (!info->attrs[NL80211_ATTR_NOACK_MAP])
return -EINVAL;
if (!rdev->ops->set_noack_map)
return -EOPNOTSUPP;
noack_map = nla_get_u16(info->attrs[NL80211_ATTR_NOACK_MAP]);
return rdev_set_noack_map(rdev, dev, noack_map);
}
struct get_key_cookie {
struct sk_buff *msg;
int error;
int idx;
};
static void get_key_callback(void *c, struct key_params *params)
{
struct nlattr *key;
struct get_key_cookie *cookie = c;
if ((params->key &&
nla_put(cookie->msg, NL80211_ATTR_KEY_DATA,
params->key_len, params->key)) ||
(params->seq &&
nla_put(cookie->msg, NL80211_ATTR_KEY_SEQ,
params->seq_len, params->seq)) ||
(params->cipher &&
nla_put_u32(cookie->msg, NL80211_ATTR_KEY_CIPHER,
params->cipher)))
goto nla_put_failure;
key = nla_nest_start(cookie->msg, NL80211_ATTR_KEY);
if (!key)
goto nla_put_failure;
if ((params->key &&
nla_put(cookie->msg, NL80211_KEY_DATA,
params->key_len, params->key)) ||
(params->seq &&
nla_put(cookie->msg, NL80211_KEY_SEQ,
params->seq_len, params->seq)) ||
(params->cipher &&
nla_put_u32(cookie->msg, NL80211_KEY_CIPHER,
params->cipher)))
goto nla_put_failure;
if (nla_put_u8(cookie->msg, NL80211_ATTR_KEY_IDX, cookie->idx))
goto nla_put_failure;
nla_nest_end(cookie->msg, key);
return;
nla_put_failure:
cookie->error = 1;
}
static int nl80211_get_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 key_idx = 0;
const u8 *mac_addr = NULL;
bool pairwise;
struct get_key_cookie cookie = {
.error = 0,
};
void *hdr;
struct sk_buff *msg;
if (info->attrs[NL80211_ATTR_KEY_IDX])
key_idx = nla_get_u8(info->attrs[NL80211_ATTR_KEY_IDX]);
if (key_idx > 5)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
pairwise = !!mac_addr;
if (info->attrs[NL80211_ATTR_KEY_TYPE]) {
u32 kt = nla_get_u32(info->attrs[NL80211_ATTR_KEY_TYPE]);
if (kt >= NUM_NL80211_KEYTYPES)
return -EINVAL;
if (kt != NL80211_KEYTYPE_GROUP &&
kt != NL80211_KEYTYPE_PAIRWISE)
return -EINVAL;
pairwise = kt == NL80211_KEYTYPE_PAIRWISE;
}
if (!rdev->ops->get_key)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_NEW_KEY);
if (!hdr)
goto nla_put_failure;
cookie.msg = msg;
cookie.idx = key_idx;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put_u8(msg, NL80211_ATTR_KEY_IDX, key_idx))
goto nla_put_failure;
if (mac_addr &&
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr))
goto nla_put_failure;
if (pairwise && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
return -ENOENT;
err = rdev_get_key(rdev, dev, key_idx, pairwise, mac_addr, &cookie,
get_key_callback);
if (err)
goto free_msg;
if (cookie.error)
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_set_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct key_parse key;
int err;
struct net_device *dev = info->user_ptr[1];
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx < 0)
return -EINVAL;
/* only support setting default key */
if (!key.def && !key.defmgmt)
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
if (key.def) {
if (!rdev->ops->set_default_key) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev_set_default_key(rdev, dev, key.idx,
key.def_uni, key.def_multi);
if (err)
goto out;
#ifdef CONFIG_CFG80211_WEXT
dev->ieee80211_ptr->wext.default_key = key.idx;
#endif
} else {
if (key.def_uni || !key.def_multi) {
err = -EINVAL;
goto out;
}
if (!rdev->ops->set_default_mgmt_key) {
err = -EOPNOTSUPP;
goto out;
}
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (err)
goto out;
err = rdev_set_default_mgmt_key(rdev, dev, key.idx);
if (err)
goto out;
#ifdef CONFIG_CFG80211_WEXT
dev->ieee80211_ptr->wext.default_mgmt_key = key.idx;
#endif
}
out:
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_new_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct key_parse key;
const u8 *mac_addr = NULL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (!key.p.key)
return -EINVAL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = NL80211_KEYTYPE_PAIRWISE;
else
key.type = NL80211_KEYTYPE_GROUP;
}
/* for now */
if (key.type != NL80211_KEYTYPE_PAIRWISE &&
key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!rdev->ops->add_key)
return -EOPNOTSUPP;
if (cfg80211_validate_key_settings(rdev, &key.p, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr))
return -EINVAL;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (!err)
err = rdev_add_key(rdev, dev, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr, &key.p);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_del_key(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
struct key_parse key;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (key.type == -1) {
if (mac_addr)
key.type = NL80211_KEYTYPE_PAIRWISE;
else
key.type = NL80211_KEYTYPE_GROUP;
}
/* for now */
if (key.type != NL80211_KEYTYPE_PAIRWISE &&
key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!rdev->ops->del_key)
return -EOPNOTSUPP;
wdev_lock(dev->ieee80211_ptr);
err = nl80211_key_allowed(dev->ieee80211_ptr);
if (key.type == NL80211_KEYTYPE_PAIRWISE && mac_addr &&
!(rdev->wiphy.flags & WIPHY_FLAG_IBSS_RSN))
err = -ENOENT;
if (!err)
err = rdev_del_key(rdev, dev, key.idx,
key.type == NL80211_KEYTYPE_PAIRWISE,
mac_addr);
#ifdef CONFIG_CFG80211_WEXT
if (!err) {
if (key.idx == dev->ieee80211_ptr->wext.default_key)
dev->ieee80211_ptr->wext.default_key = -1;
else if (key.idx == dev->ieee80211_ptr->wext.default_mgmt_key)
dev->ieee80211_ptr->wext.default_mgmt_key = -1;
}
#endif
wdev_unlock(dev->ieee80211_ptr);
return err;
}
/* This function returns an error or the number of nested attributes */
static int validate_acl_mac_addrs(struct nlattr *nl_attr)
{
struct nlattr *attr;
int n_entries = 0, tmp;
nla_for_each_nested(attr, nl_attr, tmp) {
if (nla_len(attr) != ETH_ALEN)
return -EINVAL;
n_entries++;
}
return n_entries;
}
/*
* This function parses ACL information and allocates memory for ACL data.
* On successful return, the calling function is responsible to free the
* ACL buffer returned by this function.
*/
static struct cfg80211_acl_data *parse_acl_data(struct wiphy *wiphy,
struct genl_info *info)
{
enum nl80211_acl_policy acl_policy;
struct nlattr *attr;
struct cfg80211_acl_data *acl;
int i = 0, n_entries, tmp;
if (!wiphy->max_acl_mac_addrs)
return ERR_PTR(-EOPNOTSUPP);
if (!info->attrs[NL80211_ATTR_ACL_POLICY])
return ERR_PTR(-EINVAL);
acl_policy = nla_get_u32(info->attrs[NL80211_ATTR_ACL_POLICY]);
if (acl_policy != NL80211_ACL_POLICY_ACCEPT_UNLESS_LISTED &&
acl_policy != NL80211_ACL_POLICY_DENY_UNLESS_LISTED)
return ERR_PTR(-EINVAL);
if (!info->attrs[NL80211_ATTR_MAC_ADDRS])
return ERR_PTR(-EINVAL);
n_entries = validate_acl_mac_addrs(info->attrs[NL80211_ATTR_MAC_ADDRS]);
if (n_entries < 0)
return ERR_PTR(n_entries);
if (n_entries > wiphy->max_acl_mac_addrs)
return ERR_PTR(-ENOTSUPP);
acl = kzalloc(sizeof(*acl) + (sizeof(struct mac_address) * n_entries),
GFP_KERNEL);
if (!acl)
return ERR_PTR(-ENOMEM);
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_MAC_ADDRS], tmp) {
memcpy(acl->mac_addrs[i].addr, nla_data(attr), ETH_ALEN);
i++;
}
acl->n_acl_entries = n_entries;
acl->acl_policy = acl_policy;
return acl;
}
static int nl80211_set_mac_acl(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_acl_data *acl;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
if (!dev->ieee80211_ptr->beacon_interval)
return -EINVAL;
acl = parse_acl_data(&rdev->wiphy, info);
if (IS_ERR(acl))
return PTR_ERR(acl);
err = rdev_set_mac_acl(rdev, dev, acl);
kfree(acl);
return err;
}
static int nl80211_parse_beacon(struct nlattr *attrs[],
struct cfg80211_beacon_data *bcn)
{
bool haveinfo = false;
if (!is_valid_ie_attr(attrs[NL80211_ATTR_BEACON_TAIL]) ||
!is_valid_ie_attr(attrs[NL80211_ATTR_IE]) ||
!is_valid_ie_attr(attrs[NL80211_ATTR_IE_PROBE_RESP]) ||
!is_valid_ie_attr(attrs[NL80211_ATTR_IE_ASSOC_RESP]))
return -EINVAL;
memset(bcn, 0, sizeof(*bcn));
if (attrs[NL80211_ATTR_BEACON_HEAD]) {
bcn->head = nla_data(attrs[NL80211_ATTR_BEACON_HEAD]);
bcn->head_len = nla_len(attrs[NL80211_ATTR_BEACON_HEAD]);
if (!bcn->head_len)
return -EINVAL;
haveinfo = true;
}
if (attrs[NL80211_ATTR_BEACON_TAIL]) {
bcn->tail = nla_data(attrs[NL80211_ATTR_BEACON_TAIL]);
bcn->tail_len = nla_len(attrs[NL80211_ATTR_BEACON_TAIL]);
haveinfo = true;
}
if (!haveinfo)
return -EINVAL;
if (attrs[NL80211_ATTR_IE]) {
bcn->beacon_ies = nla_data(attrs[NL80211_ATTR_IE]);
bcn->beacon_ies_len = nla_len(attrs[NL80211_ATTR_IE]);
}
if (attrs[NL80211_ATTR_IE_PROBE_RESP]) {
bcn->proberesp_ies =
nla_data(attrs[NL80211_ATTR_IE_PROBE_RESP]);
bcn->proberesp_ies_len =
nla_len(attrs[NL80211_ATTR_IE_PROBE_RESP]);
}
if (attrs[NL80211_ATTR_IE_ASSOC_RESP]) {
bcn->assocresp_ies =
nla_data(attrs[NL80211_ATTR_IE_ASSOC_RESP]);
bcn->assocresp_ies_len =
nla_len(attrs[NL80211_ATTR_IE_ASSOC_RESP]);
}
if (attrs[NL80211_ATTR_PROBE_RESP]) {
bcn->probe_resp = nla_data(attrs[NL80211_ATTR_PROBE_RESP]);
bcn->probe_resp_len = nla_len(attrs[NL80211_ATTR_PROBE_RESP]);
}
return 0;
}
static bool nl80211_get_ap_channel(struct cfg80211_registered_device *rdev,
struct cfg80211_ap_settings *params)
{
struct wireless_dev *wdev;
bool ret = false;
list_for_each_entry(wdev, &rdev->wdev_list, list) {
if (wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO)
continue;
if (!wdev->preset_chandef.chan)
continue;
params->chandef = wdev->preset_chandef;
ret = true;
break;
}
return ret;
}
static bool nl80211_valid_auth_type(struct cfg80211_registered_device *rdev,
enum nl80211_auth_type auth_type,
enum nl80211_commands cmd)
{
if (auth_type > NL80211_AUTHTYPE_MAX)
return false;
switch (cmd) {
case NL80211_CMD_AUTHENTICATE:
if (!(rdev->wiphy.features & NL80211_FEATURE_SAE) &&
auth_type == NL80211_AUTHTYPE_SAE)
return false;
return true;
case NL80211_CMD_CONNECT:
case NL80211_CMD_START_AP:
/* SAE not supported yet */
if (auth_type == NL80211_AUTHTYPE_SAE)
return false;
return true;
default:
return false;
}
}
static int nl80211_start_ap(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_ap_settings params;
int err;
u8 radar_detect_width = 0;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
if (!rdev->ops->start_ap)
return -EOPNOTSUPP;
if (wdev->beacon_interval)
return -EALREADY;
memset(¶ms, 0, sizeof(params));
/* these are required for START_AP */
if (!info->attrs[NL80211_ATTR_BEACON_INTERVAL] ||
!info->attrs[NL80211_ATTR_DTIM_PERIOD] ||
!info->attrs[NL80211_ATTR_BEACON_HEAD])
return -EINVAL;
err = nl80211_parse_beacon(info->attrs, ¶ms.beacon);
if (err)
return err;
params.beacon_interval =
nla_get_u32(info->attrs[NL80211_ATTR_BEACON_INTERVAL]);
params.dtim_period =
nla_get_u32(info->attrs[NL80211_ATTR_DTIM_PERIOD]);
err = cfg80211_validate_beacon_int(rdev, params.beacon_interval);
if (err)
return err;
/*
* In theory, some of these attributes should be required here
* but since they were not used when the command was originally
* added, keep them optional for old user space programs to let
* them continue to work with drivers that do not need the
* additional information -- drivers must check!
*/
if (info->attrs[NL80211_ATTR_SSID]) {
params.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
params.ssid_len =
nla_len(info->attrs[NL80211_ATTR_SSID]);
if (params.ssid_len == 0 ||
params.ssid_len > IEEE80211_MAX_SSID_LEN)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_HIDDEN_SSID]) {
params.hidden_ssid = nla_get_u32(
info->attrs[NL80211_ATTR_HIDDEN_SSID]);
if (params.hidden_ssid != NL80211_HIDDEN_SSID_NOT_IN_USE &&
params.hidden_ssid != NL80211_HIDDEN_SSID_ZERO_LEN &&
params.hidden_ssid != NL80211_HIDDEN_SSID_ZERO_CONTENTS)
return -EINVAL;
}
params.privacy = !!info->attrs[NL80211_ATTR_PRIVACY];
if (info->attrs[NL80211_ATTR_AUTH_TYPE]) {
params.auth_type = nla_get_u32(
info->attrs[NL80211_ATTR_AUTH_TYPE]);
if (!nl80211_valid_auth_type(rdev, params.auth_type,
NL80211_CMD_START_AP))
return -EINVAL;
} else
params.auth_type = NL80211_AUTHTYPE_AUTOMATIC;
err = nl80211_crypto_settings(rdev, info, ¶ms.crypto,
NL80211_MAX_NR_CIPHER_SUITES);
if (err)
return err;
if (info->attrs[NL80211_ATTR_INACTIVITY_TIMEOUT]) {
if (!(rdev->wiphy.features & NL80211_FEATURE_INACTIVITY_TIMER))
return -EOPNOTSUPP;
params.inactivity_timeout = nla_get_u16(
info->attrs[NL80211_ATTR_INACTIVITY_TIMEOUT]);
}
if (info->attrs[NL80211_ATTR_P2P_CTWINDOW]) {
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
params.p2p_ctwindow =
nla_get_u8(info->attrs[NL80211_ATTR_P2P_CTWINDOW]);
if (params.p2p_ctwindow > 127)
return -EINVAL;
if (params.p2p_ctwindow != 0 &&
!(rdev->wiphy.features & NL80211_FEATURE_P2P_GO_CTWIN))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_P2P_OPPPS]) {
u8 tmp;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
tmp = nla_get_u8(info->attrs[NL80211_ATTR_P2P_OPPPS]);
if (tmp > 1)
return -EINVAL;
params.p2p_opp_ps = tmp;
if (params.p2p_opp_ps != 0 &&
!(rdev->wiphy.features & NL80211_FEATURE_P2P_GO_OPPPS))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
err = nl80211_parse_chandef(rdev, info, ¶ms.chandef);
if (err)
return err;
} else if (wdev->preset_chandef.chan) {
params.chandef = wdev->preset_chandef;
} else if (!nl80211_get_ap_channel(rdev, ¶ms))
return -EINVAL;
if (!cfg80211_reg_can_beacon(&rdev->wiphy, ¶ms.chandef))
return -EINVAL;
err = cfg80211_chandef_dfs_required(wdev->wiphy, ¶ms.chandef);
if (err < 0)
return err;
if (err) {
radar_detect_width = BIT(params.chandef.width);
params.radar_required = true;
}
err = cfg80211_can_use_iftype_chan(rdev, wdev, wdev->iftype,
params.chandef.chan,
CHAN_MODE_SHARED,
radar_detect_width);
if (err)
return err;
if (info->attrs[NL80211_ATTR_ACL_POLICY]) {
params.acl = parse_acl_data(&rdev->wiphy, info);
if (IS_ERR(params.acl))
return PTR_ERR(params.acl);
}
wdev_lock(wdev);
err = rdev_start_ap(rdev, dev, ¶ms);
if (!err) {
wdev->preset_chandef = params.chandef;
wdev->beacon_interval = params.beacon_interval;
wdev->chandef = params.chandef;
wdev->ssid_len = params.ssid_len;
memcpy(wdev->ssid, params.ssid, wdev->ssid_len);
}
wdev_unlock(wdev);
kfree(params.acl);
return err;
}
static int nl80211_set_beacon(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_beacon_data params;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
if (!rdev->ops->change_beacon)
return -EOPNOTSUPP;
if (!wdev->beacon_interval)
return -EINVAL;
err = nl80211_parse_beacon(info->attrs, ¶ms);
if (err)
return err;
wdev_lock(wdev);
err = rdev_change_beacon(rdev, dev, ¶ms);
wdev_unlock(wdev);
return err;
}
static int nl80211_stop_ap(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
return cfg80211_stop_ap(rdev, dev, false);
}
static const struct nla_policy sta_flags_policy[NL80211_STA_FLAG_MAX + 1] = {
[NL80211_STA_FLAG_AUTHORIZED] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_SHORT_PREAMBLE] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_WME] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_MFP] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_AUTHENTICATED] = { .type = NLA_FLAG },
[NL80211_STA_FLAG_TDLS_PEER] = { .type = NLA_FLAG },
};
static int parse_station_flags(struct genl_info *info,
enum nl80211_iftype iftype,
struct station_parameters *params)
{
struct nlattr *flags[NL80211_STA_FLAG_MAX + 1];
struct nlattr *nla;
int flag;
/*
* Try parsing the new attribute first so userspace
* can specify both for older kernels.
*/
nla = info->attrs[NL80211_ATTR_STA_FLAGS2];
if (nla) {
struct nl80211_sta_flag_update *sta_flags;
sta_flags = nla_data(nla);
params->sta_flags_mask = sta_flags->mask;
params->sta_flags_set = sta_flags->set;
params->sta_flags_set &= params->sta_flags_mask;
if ((params->sta_flags_mask |
params->sta_flags_set) & BIT(__NL80211_STA_FLAG_INVALID))
return -EINVAL;
return 0;
}
/* if present, parse the old attribute */
nla = info->attrs[NL80211_ATTR_STA_FLAGS];
if (!nla)
return 0;
if (nla_parse_nested(flags, NL80211_STA_FLAG_MAX,
nla, sta_flags_policy))
return -EINVAL;
/*
* Only allow certain flags for interface types so that
* other attributes are silently ignored. Remember that
* this is backward compatibility code with old userspace
* and shouldn't be hit in other cases anyway.
*/
switch (iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
params->sta_flags_mask = BIT(NL80211_STA_FLAG_AUTHORIZED) |
BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) |
BIT(NL80211_STA_FLAG_WME) |
BIT(NL80211_STA_FLAG_MFP);
break;
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_STATION:
params->sta_flags_mask = BIT(NL80211_STA_FLAG_AUTHORIZED) |
BIT(NL80211_STA_FLAG_TDLS_PEER);
break;
case NL80211_IFTYPE_MESH_POINT:
params->sta_flags_mask = BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_MFP) |
BIT(NL80211_STA_FLAG_AUTHORIZED);
default:
return -EINVAL;
}
for (flag = 1; flag <= NL80211_STA_FLAG_MAX; flag++) {
if (flags[flag]) {
params->sta_flags_set |= (1<<flag);
/* no longer support new API additions in old API */
if (flag > NL80211_STA_FLAG_MAX_OLD_API)
return -EINVAL;
}
}
return 0;
}
static bool nl80211_put_sta_rate(struct sk_buff *msg, struct rate_info *info,
int attr)
{
struct nlattr *rate;
u32 bitrate;
u16 bitrate_compat;
rate = nla_nest_start(msg, attr);
if (!rate)
return false;
/* cfg80211_calculate_bitrate will return 0 for mcs >= 32 */
bitrate = cfg80211_calculate_bitrate(info);
/* report 16-bit bitrate only if we can */
bitrate_compat = bitrate < (1UL << 16) ? bitrate : 0;
if (bitrate > 0 &&
nla_put_u32(msg, NL80211_RATE_INFO_BITRATE32, bitrate))
return false;
if (bitrate_compat > 0 &&
nla_put_u16(msg, NL80211_RATE_INFO_BITRATE, bitrate_compat))
return false;
if (info->flags & RATE_INFO_FLAGS_MCS) {
if (nla_put_u8(msg, NL80211_RATE_INFO_MCS, info->mcs))
return false;
if (info->flags & RATE_INFO_FLAGS_40_MHZ_WIDTH &&
nla_put_flag(msg, NL80211_RATE_INFO_40_MHZ_WIDTH))
return false;
if (info->flags & RATE_INFO_FLAGS_SHORT_GI &&
nla_put_flag(msg, NL80211_RATE_INFO_SHORT_GI))
return false;
} else if (info->flags & RATE_INFO_FLAGS_VHT_MCS) {
if (nla_put_u8(msg, NL80211_RATE_INFO_VHT_MCS, info->mcs))
return false;
if (nla_put_u8(msg, NL80211_RATE_INFO_VHT_NSS, info->nss))
return false;
if (info->flags & RATE_INFO_FLAGS_40_MHZ_WIDTH &&
nla_put_flag(msg, NL80211_RATE_INFO_40_MHZ_WIDTH))
return false;
if (info->flags & RATE_INFO_FLAGS_80_MHZ_WIDTH &&
nla_put_flag(msg, NL80211_RATE_INFO_80_MHZ_WIDTH))
return false;
if (info->flags & RATE_INFO_FLAGS_80P80_MHZ_WIDTH &&
nla_put_flag(msg, NL80211_RATE_INFO_80P80_MHZ_WIDTH))
return false;
if (info->flags & RATE_INFO_FLAGS_160_MHZ_WIDTH &&
nla_put_flag(msg, NL80211_RATE_INFO_160_MHZ_WIDTH))
return false;
if (info->flags & RATE_INFO_FLAGS_SHORT_GI &&
nla_put_flag(msg, NL80211_RATE_INFO_SHORT_GI))
return false;
}
nla_nest_end(msg, rate);
return true;
}
static bool nl80211_put_signal(struct sk_buff *msg, u8 mask, s8 *signal,
int id)
{
void *attr;
int i = 0;
if (!mask)
return true;
attr = nla_nest_start(msg, id);
if (!attr)
return false;
for (i = 0; i < IEEE80211_MAX_CHAINS; i++) {
if (!(mask & BIT(i)))
continue;
if (nla_put_u8(msg, i, signal[i]))
return false;
}
nla_nest_end(msg, attr);
return true;
}
static int nl80211_send_station(struct sk_buff *msg, u32 portid, u32 seq,
int flags,
struct cfg80211_registered_device *rdev,
struct net_device *dev,
const u8 *mac_addr, struct station_info *sinfo)
{
void *hdr;
struct nlattr *sinfoattr, *bss_param;
hdr = nl80211hdr_put(msg, portid, seq, flags, NL80211_CMD_NEW_STATION);
if (!hdr)
return -1;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr) ||
nla_put_u32(msg, NL80211_ATTR_GENERATION, sinfo->generation))
goto nla_put_failure;
sinfoattr = nla_nest_start(msg, NL80211_ATTR_STA_INFO);
if (!sinfoattr)
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_CONNECTED_TIME) &&
nla_put_u32(msg, NL80211_STA_INFO_CONNECTED_TIME,
sinfo->connected_time))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_INACTIVE_TIME) &&
nla_put_u32(msg, NL80211_STA_INFO_INACTIVE_TIME,
sinfo->inactive_time))
goto nla_put_failure;
if ((sinfo->filled & (STATION_INFO_RX_BYTES |
STATION_INFO_RX_BYTES64)) &&
nla_put_u32(msg, NL80211_STA_INFO_RX_BYTES,
(u32)sinfo->rx_bytes))
goto nla_put_failure;
if ((sinfo->filled & (STATION_INFO_TX_BYTES |
STATION_INFO_TX_BYTES64)) &&
nla_put_u32(msg, NL80211_STA_INFO_TX_BYTES,
(u32)sinfo->tx_bytes))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_RX_BYTES64) &&
nla_put_u64(msg, NL80211_STA_INFO_RX_BYTES64,
sinfo->rx_bytes))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_TX_BYTES64) &&
nla_put_u64(msg, NL80211_STA_INFO_TX_BYTES64,
sinfo->tx_bytes))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_LLID) &&
nla_put_u16(msg, NL80211_STA_INFO_LLID, sinfo->llid))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_PLID) &&
nla_put_u16(msg, NL80211_STA_INFO_PLID, sinfo->plid))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_PLINK_STATE) &&
nla_put_u8(msg, NL80211_STA_INFO_PLINK_STATE,
sinfo->plink_state))
goto nla_put_failure;
switch (rdev->wiphy.signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
if ((sinfo->filled & STATION_INFO_SIGNAL) &&
nla_put_u8(msg, NL80211_STA_INFO_SIGNAL,
sinfo->signal))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_SIGNAL_AVG) &&
nla_put_u8(msg, NL80211_STA_INFO_SIGNAL_AVG,
sinfo->signal_avg))
goto nla_put_failure;
break;
default:
break;
}
if (sinfo->filled & STATION_INFO_CHAIN_SIGNAL) {
if (!nl80211_put_signal(msg, sinfo->chains,
sinfo->chain_signal,
NL80211_STA_INFO_CHAIN_SIGNAL))
goto nla_put_failure;
}
if (sinfo->filled & STATION_INFO_CHAIN_SIGNAL_AVG) {
if (!nl80211_put_signal(msg, sinfo->chains,
sinfo->chain_signal_avg,
NL80211_STA_INFO_CHAIN_SIGNAL_AVG))
goto nla_put_failure;
}
if (sinfo->filled & STATION_INFO_TX_BITRATE) {
if (!nl80211_put_sta_rate(msg, &sinfo->txrate,
NL80211_STA_INFO_TX_BITRATE))
goto nla_put_failure;
}
if (sinfo->filled & STATION_INFO_RX_BITRATE) {
if (!nl80211_put_sta_rate(msg, &sinfo->rxrate,
NL80211_STA_INFO_RX_BITRATE))
goto nla_put_failure;
}
if ((sinfo->filled & STATION_INFO_RX_PACKETS) &&
nla_put_u32(msg, NL80211_STA_INFO_RX_PACKETS,
sinfo->rx_packets))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_TX_PACKETS) &&
nla_put_u32(msg, NL80211_STA_INFO_TX_PACKETS,
sinfo->tx_packets))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_TX_RETRIES) &&
nla_put_u32(msg, NL80211_STA_INFO_TX_RETRIES,
sinfo->tx_retries))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_TX_FAILED) &&
nla_put_u32(msg, NL80211_STA_INFO_TX_FAILED,
sinfo->tx_failed))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_BEACON_LOSS_COUNT) &&
nla_put_u32(msg, NL80211_STA_INFO_BEACON_LOSS,
sinfo->beacon_loss_count))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_LOCAL_PM) &&
nla_put_u32(msg, NL80211_STA_INFO_LOCAL_PM,
sinfo->local_pm))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_PEER_PM) &&
nla_put_u32(msg, NL80211_STA_INFO_PEER_PM,
sinfo->peer_pm))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_NONPEER_PM) &&
nla_put_u32(msg, NL80211_STA_INFO_NONPEER_PM,
sinfo->nonpeer_pm))
goto nla_put_failure;
if (sinfo->filled & STATION_INFO_BSS_PARAM) {
bss_param = nla_nest_start(msg, NL80211_STA_INFO_BSS_PARAM);
if (!bss_param)
goto nla_put_failure;
if (((sinfo->bss_param.flags & BSS_PARAM_FLAGS_CTS_PROT) &&
nla_put_flag(msg, NL80211_STA_BSS_PARAM_CTS_PROT)) ||
((sinfo->bss_param.flags & BSS_PARAM_FLAGS_SHORT_PREAMBLE) &&
nla_put_flag(msg, NL80211_STA_BSS_PARAM_SHORT_PREAMBLE)) ||
((sinfo->bss_param.flags & BSS_PARAM_FLAGS_SHORT_SLOT_TIME) &&
nla_put_flag(msg, NL80211_STA_BSS_PARAM_SHORT_SLOT_TIME)) ||
nla_put_u8(msg, NL80211_STA_BSS_PARAM_DTIM_PERIOD,
sinfo->bss_param.dtim_period) ||
nla_put_u16(msg, NL80211_STA_BSS_PARAM_BEACON_INTERVAL,
sinfo->bss_param.beacon_interval))
goto nla_put_failure;
nla_nest_end(msg, bss_param);
}
if ((sinfo->filled & STATION_INFO_STA_FLAGS) &&
nla_put(msg, NL80211_STA_INFO_STA_FLAGS,
sizeof(struct nl80211_sta_flag_update),
&sinfo->sta_flags))
goto nla_put_failure;
if ((sinfo->filled & STATION_INFO_T_OFFSET) &&
nla_put_u64(msg, NL80211_STA_INFO_T_OFFSET,
sinfo->t_offset))
goto nla_put_failure;
nla_nest_end(msg, sinfoattr);
if ((sinfo->filled & STATION_INFO_ASSOC_REQ_IES) &&
nla_put(msg, NL80211_ATTR_IE, sinfo->assoc_req_ies_len,
sinfo->assoc_req_ies))
goto nla_put_failure;
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_station(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct station_info sinfo;
struct cfg80211_registered_device *dev;
struct wireless_dev *wdev;
u8 mac_addr[ETH_ALEN];
int sta_idx = cb->args[2];
int err;
err = nl80211_prepare_wdev_dump(skb, cb, &dev, &wdev);
if (err)
return err;
if (!wdev->netdev) {
err = -EINVAL;
goto out_err;
}
if (!dev->ops->dump_station) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
memset(&sinfo, 0, sizeof(sinfo));
err = rdev_dump_station(dev, wdev->netdev, sta_idx,
mac_addr, &sinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (nl80211_send_station(skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
dev, wdev->netdev, mac_addr,
&sinfo) < 0)
goto out;
sta_idx++;
}
out:
cb->args[2] = sta_idx;
err = skb->len;
out_err:
nl80211_finish_wdev_dump(dev);
return err;
}
static int nl80211_get_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct station_info sinfo;
struct sk_buff *msg;
u8 *mac_addr = NULL;
int err;
memset(&sinfo, 0, sizeof(sinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_station)
return -EOPNOTSUPP;
err = rdev_get_station(rdev, dev, mac_addr, &sinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_station(msg, info->snd_portid, info->snd_seq, 0,
rdev, dev, mac_addr, &sinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
int cfg80211_check_station_change(struct wiphy *wiphy,
struct station_parameters *params,
enum cfg80211_station_type statype)
{
if (params->listen_interval != -1)
return -EINVAL;
if (params->aid)
return -EINVAL;
/* When you run into this, adjust the code below for the new flag */
BUILD_BUG_ON(NL80211_STA_FLAG_MAX != 7);
switch (statype) {
case CFG80211_STA_MESH_PEER_KERNEL:
case CFG80211_STA_MESH_PEER_USER:
/*
* No ignoring the TDLS flag here -- the userspace mesh
* code doesn't have the bug of including TDLS in the
* mask everywhere.
*/
if (params->sta_flags_mask &
~(BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_MFP) |
BIT(NL80211_STA_FLAG_AUTHORIZED)))
return -EINVAL;
break;
case CFG80211_STA_TDLS_PEER_SETUP:
case CFG80211_STA_TDLS_PEER_ACTIVE:
if (!(params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER)))
return -EINVAL;
/* ignore since it can't change */
params->sta_flags_mask &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
break;
default:
/* disallow mesh-specific things */
if (params->plink_action != NL80211_PLINK_ACTION_NO_ACTION)
return -EINVAL;
if (params->local_pm)
return -EINVAL;
if (params->sta_modify_mask & STATION_PARAM_APPLY_PLINK_STATE)
return -EINVAL;
}
if (statype != CFG80211_STA_TDLS_PEER_SETUP &&
statype != CFG80211_STA_TDLS_PEER_ACTIVE) {
/* TDLS can't be set, ... */
if (params->sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER))
return -EINVAL;
/*
* ... but don't bother the driver with it. This works around
* a hostapd/wpa_supplicant issue -- it always includes the
* TLDS_PEER flag in the mask even for AP mode.
*/
params->sta_flags_mask &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
}
if (statype != CFG80211_STA_TDLS_PEER_SETUP) {
/* reject other things that can't change */
if (params->sta_modify_mask & STATION_PARAM_APPLY_UAPSD)
return -EINVAL;
if (params->sta_modify_mask & STATION_PARAM_APPLY_CAPABILITY)
return -EINVAL;
if (params->supported_rates)
return -EINVAL;
if (params->ext_capab || params->ht_capa || params->vht_capa)
return -EINVAL;
}
if (statype != CFG80211_STA_AP_CLIENT) {
if (params->vlan)
return -EINVAL;
}
switch (statype) {
case CFG80211_STA_AP_MLME_CLIENT:
/* Use this only for authorizing/unauthorizing a station */
if (!(params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)))
return -EOPNOTSUPP;
break;
case CFG80211_STA_AP_CLIENT:
/* accept only the listed bits */
if (params->sta_flags_mask &
~(BIT(NL80211_STA_FLAG_AUTHORIZED) |
BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED) |
BIT(NL80211_STA_FLAG_SHORT_PREAMBLE) |
BIT(NL80211_STA_FLAG_WME) |
BIT(NL80211_STA_FLAG_MFP)))
return -EINVAL;
/* but authenticated/associated only if driver handles it */
if (!(wiphy->features & NL80211_FEATURE_FULL_AP_CLIENT_STATE) &&
params->sta_flags_mask &
(BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED)))
return -EINVAL;
break;
case CFG80211_STA_IBSS:
case CFG80211_STA_AP_STA:
/* reject any changes other than AUTHORIZED */
if (params->sta_flags_mask & ~BIT(NL80211_STA_FLAG_AUTHORIZED))
return -EINVAL;
break;
case CFG80211_STA_TDLS_PEER_SETUP:
/* reject any changes other than AUTHORIZED or WME */
if (params->sta_flags_mask & ~(BIT(NL80211_STA_FLAG_AUTHORIZED) |
BIT(NL80211_STA_FLAG_WME)))
return -EINVAL;
/* force (at least) rates when authorizing */
if (params->sta_flags_set & BIT(NL80211_STA_FLAG_AUTHORIZED) &&
!params->supported_rates)
return -EINVAL;
break;
case CFG80211_STA_TDLS_PEER_ACTIVE:
/* reject any changes */
return -EINVAL;
case CFG80211_STA_MESH_PEER_KERNEL:
if (params->sta_modify_mask & STATION_PARAM_APPLY_PLINK_STATE)
return -EINVAL;
break;
case CFG80211_STA_MESH_PEER_USER:
if (params->plink_action != NL80211_PLINK_ACTION_NO_ACTION)
return -EINVAL;
break;
}
return 0;
}
EXPORT_SYMBOL(cfg80211_check_station_change);
/*
* Get vlan interface making sure it is running and on the right wiphy.
*/
static struct net_device *get_vlan(struct genl_info *info,
struct cfg80211_registered_device *rdev)
{
struct nlattr *vlanattr = info->attrs[NL80211_ATTR_STA_VLAN];
struct net_device *v;
int ret;
if (!vlanattr)
return NULL;
v = dev_get_by_index(genl_info_net(info), nla_get_u32(vlanattr));
if (!v)
return ERR_PTR(-ENODEV);
if (!v->ieee80211_ptr || v->ieee80211_ptr->wiphy != &rdev->wiphy) {
ret = -EINVAL;
goto error;
}
if (v->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
v->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
v->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO) {
ret = -EINVAL;
goto error;
}
if (!netif_running(v)) {
ret = -ENETDOWN;
goto error;
}
return v;
error:
dev_put(v);
return ERR_PTR(ret);
}
static const struct nla_policy
nl80211_sta_wme_policy[NL80211_STA_WME_MAX + 1] = {
[NL80211_STA_WME_UAPSD_QUEUES] = { .type = NLA_U8 },
[NL80211_STA_WME_MAX_SP] = { .type = NLA_U8 },
};
static int nl80211_parse_sta_wme(struct genl_info *info,
struct station_parameters *params)
{
struct nlattr *tb[NL80211_STA_WME_MAX + 1];
struct nlattr *nla;
int err;
/* parse WME attributes if present */
if (!info->attrs[NL80211_ATTR_STA_WME])
return 0;
nla = info->attrs[NL80211_ATTR_STA_WME];
err = nla_parse_nested(tb, NL80211_STA_WME_MAX, nla,
nl80211_sta_wme_policy);
if (err)
return err;
if (tb[NL80211_STA_WME_UAPSD_QUEUES])
params->uapsd_queues = nla_get_u8(
tb[NL80211_STA_WME_UAPSD_QUEUES]);
if (params->uapsd_queues & ~IEEE80211_WMM_IE_STA_QOSINFO_AC_MASK)
return -EINVAL;
if (tb[NL80211_STA_WME_MAX_SP])
params->max_sp = nla_get_u8(tb[NL80211_STA_WME_MAX_SP]);
if (params->max_sp & ~IEEE80211_WMM_IE_STA_QOSINFO_SP_MASK)
return -EINVAL;
params->sta_modify_mask |= STATION_PARAM_APPLY_UAPSD;
return 0;
}
static int nl80211_parse_sta_channel_info(struct genl_info *info,
struct station_parameters *params)
{
if (info->attrs[NL80211_ATTR_STA_SUPPORTED_CHANNELS]) {
params->supported_channels =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_CHANNELS]);
params->supported_channels_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_CHANNELS]);
/*
* Need to include at least one (first channel, number of
* channels) tuple for each subband, and must have proper
* tuples for the rest of the data as well.
*/
if (params->supported_channels_len < 2)
return -EINVAL;
if (params->supported_channels_len % 2)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES]) {
params->supported_oper_classes =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES]);
params->supported_oper_classes_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_OPER_CLASSES]);
/*
* The value of the Length field of the Supported Operating
* Classes element is between 2 and 253.
*/
if (params->supported_oper_classes_len < 2 ||
params->supported_oper_classes_len > 253)
return -EINVAL;
}
return 0;
}
static int nl80211_set_station_tdls(struct genl_info *info,
struct station_parameters *params)
{
int err;
/* Dummy STA entry gets updated once the peer capabilities are known */
if (info->attrs[NL80211_ATTR_PEER_AID])
params->aid = nla_get_u16(info->attrs[NL80211_ATTR_PEER_AID]);
if (info->attrs[NL80211_ATTR_HT_CAPABILITY])
params->ht_capa =
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]);
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY])
params->vht_capa =
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY]);
err = nl80211_parse_sta_channel_info(info, params);
if (err)
return err;
return nl80211_parse_sta_wme(info, params);
}
static int nl80211_set_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr;
int err;
memset(¶ms, 0, sizeof(params));
params.listen_interval = -1;
if (!rdev->ops->change_station)
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_STA_AID])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]) {
params.supported_rates =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.supported_rates_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
}
if (info->attrs[NL80211_ATTR_STA_CAPABILITY]) {
params.capability =
nla_get_u16(info->attrs[NL80211_ATTR_STA_CAPABILITY]);
params.sta_modify_mask |= STATION_PARAM_APPLY_CAPABILITY;
}
if (info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]) {
params.ext_capab =
nla_data(info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]);
params.ext_capab_len =
nla_len(info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]);
}
if (info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL])
return -EINVAL;
if (parse_station_flags(info, dev->ieee80211_ptr->iftype, ¶ms))
return -EINVAL;
if (info->attrs[NL80211_ATTR_STA_PLINK_ACTION]) {
params.plink_action =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_ACTION]);
if (params.plink_action >= NUM_NL80211_PLINK_ACTIONS)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_STA_PLINK_STATE]) {
params.plink_state =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_STATE]);
if (params.plink_state >= NUM_NL80211_PLINK_STATES)
return -EINVAL;
params.sta_modify_mask |= STATION_PARAM_APPLY_PLINK_STATE;
}
if (info->attrs[NL80211_ATTR_LOCAL_MESH_POWER_MODE]) {
enum nl80211_mesh_power_mode pm = nla_get_u32(
info->attrs[NL80211_ATTR_LOCAL_MESH_POWER_MODE]);
if (pm <= NL80211_MESH_POWER_UNKNOWN ||
pm > NL80211_MESH_POWER_MAX)
return -EINVAL;
params.local_pm = pm;
}
/* Include parameters for TDLS peer (will check later) */
err = nl80211_set_station_tdls(info, ¶ms);
if (err)
return err;
params.vlan = get_vlan(info, rdev);
if (IS_ERR(params.vlan))
return PTR_ERR(params.vlan);
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_MESH_POINT:
break;
default:
err = -EOPNOTSUPP;
goto out_put_vlan;
}
/* driver will call cfg80211_check_station_change() */
err = rdev_change_station(rdev, dev, mac_addr, ¶ms);
out_put_vlan:
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_new_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct station_parameters params;
u8 *mac_addr = NULL;
memset(¶ms, 0, sizeof(params));
if (!rdev->ops->add_station)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_STA_AID] &&
!info->attrs[NL80211_ATTR_PEER_AID])
return -EINVAL;
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
params.supported_rates =
nla_data(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.supported_rates_len =
nla_len(info->attrs[NL80211_ATTR_STA_SUPPORTED_RATES]);
params.listen_interval =
nla_get_u16(info->attrs[NL80211_ATTR_STA_LISTEN_INTERVAL]);
if (info->attrs[NL80211_ATTR_PEER_AID])
params.aid = nla_get_u16(info->attrs[NL80211_ATTR_PEER_AID]);
else
params.aid = nla_get_u16(info->attrs[NL80211_ATTR_STA_AID]);
if (!params.aid || params.aid > IEEE80211_MAX_AID)
return -EINVAL;
if (info->attrs[NL80211_ATTR_STA_CAPABILITY]) {
params.capability =
nla_get_u16(info->attrs[NL80211_ATTR_STA_CAPABILITY]);
params.sta_modify_mask |= STATION_PARAM_APPLY_CAPABILITY;
}
if (info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]) {
params.ext_capab =
nla_data(info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]);
params.ext_capab_len =
nla_len(info->attrs[NL80211_ATTR_STA_EXT_CAPABILITY]);
}
if (info->attrs[NL80211_ATTR_HT_CAPABILITY])
params.ht_capa =
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]);
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY])
params.vht_capa =
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY]);
if (info->attrs[NL80211_ATTR_OPMODE_NOTIF]) {
params.opmode_notif_used = true;
params.opmode_notif =
nla_get_u8(info->attrs[NL80211_ATTR_OPMODE_NOTIF]);
}
if (info->attrs[NL80211_ATTR_STA_PLINK_ACTION]) {
params.plink_action =
nla_get_u8(info->attrs[NL80211_ATTR_STA_PLINK_ACTION]);
if (params.plink_action >= NUM_NL80211_PLINK_ACTIONS)
return -EINVAL;
}
err = nl80211_parse_sta_channel_info(info, ¶ms);
if (err)
return err;
err = nl80211_parse_sta_wme(info, ¶ms);
if (err)
return err;
if (parse_station_flags(info, dev->ieee80211_ptr->iftype, ¶ms))
return -EINVAL;
/* When you run into this, adjust the code below for the new flag */
BUILD_BUG_ON(NL80211_STA_FLAG_MAX != 7);
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
/* ignore WME attributes if iface/sta is not capable */
if (!(rdev->wiphy.flags & WIPHY_FLAG_AP_UAPSD) ||
!(params.sta_flags_set & BIT(NL80211_STA_FLAG_WME)))
params.sta_modify_mask &= ~STATION_PARAM_APPLY_UAPSD;
/* TDLS peers cannot be added */
if ((params.sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER)) ||
info->attrs[NL80211_ATTR_PEER_AID])
return -EINVAL;
/* but don't bother the driver with it */
params.sta_flags_mask &= ~BIT(NL80211_STA_FLAG_TDLS_PEER);
/* allow authenticated/associated only if driver handles it */
if (!(rdev->wiphy.features &
NL80211_FEATURE_FULL_AP_CLIENT_STATE) &&
params.sta_flags_mask &
(BIT(NL80211_STA_FLAG_AUTHENTICATED) |
BIT(NL80211_STA_FLAG_ASSOCIATED)))
return -EINVAL;
/* must be last in here for error handling */
params.vlan = get_vlan(info, rdev);
if (IS_ERR(params.vlan))
return PTR_ERR(params.vlan);
break;
case NL80211_IFTYPE_MESH_POINT:
/* ignore uAPSD data */
params.sta_modify_mask &= ~STATION_PARAM_APPLY_UAPSD;
/* associated is disallowed */
if (params.sta_flags_mask & BIT(NL80211_STA_FLAG_ASSOCIATED))
return -EINVAL;
/* TDLS peers cannot be added */
if ((params.sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER)) ||
info->attrs[NL80211_ATTR_PEER_AID])
return -EINVAL;
break;
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_P2P_CLIENT:
/* ignore uAPSD data */
params.sta_modify_mask &= ~STATION_PARAM_APPLY_UAPSD;
/* these are disallowed */
if (params.sta_flags_mask &
(BIT(NL80211_STA_FLAG_ASSOCIATED) |
BIT(NL80211_STA_FLAG_AUTHENTICATED)))
return -EINVAL;
/* Only TDLS peers can be added */
if (!(params.sta_flags_set & BIT(NL80211_STA_FLAG_TDLS_PEER)))
return -EINVAL;
/* Can only add if TDLS ... */
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_TDLS))
return -EOPNOTSUPP;
/* ... with external setup is supported */
if (!(rdev->wiphy.flags & WIPHY_FLAG_TDLS_EXTERNAL_SETUP))
return -EOPNOTSUPP;
/*
* Older wpa_supplicant versions always mark the TDLS peer
* as authorized, but it shouldn't yet be.
*/
params.sta_flags_mask &= ~BIT(NL80211_STA_FLAG_AUTHORIZED);
break;
default:
return -EOPNOTSUPP;
}
/* be aware of params.vlan when changing code here */
err = rdev_add_station(rdev, dev, mac_addr, ¶ms);
if (params.vlan)
dev_put(params.vlan);
return err;
}
static int nl80211_del_station(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *mac_addr = NULL;
if (info->attrs[NL80211_ATTR_MAC])
mac_addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP_VLAN &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
if (!rdev->ops->del_station)
return -EOPNOTSUPP;
return rdev_del_station(rdev, dev, mac_addr);
}
static int nl80211_send_mpath(struct sk_buff *msg, u32 portid, u32 seq,
int flags, struct net_device *dev,
u8 *dst, u8 *next_hop,
struct mpath_info *pinfo)
{
void *hdr;
struct nlattr *pinfoattr;
hdr = nl80211hdr_put(msg, portid, seq, flags, NL80211_CMD_NEW_STATION);
if (!hdr)
return -1;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, dst) ||
nla_put(msg, NL80211_ATTR_MPATH_NEXT_HOP, ETH_ALEN, next_hop) ||
nla_put_u32(msg, NL80211_ATTR_GENERATION, pinfo->generation))
goto nla_put_failure;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_MPATH_INFO);
if (!pinfoattr)
goto nla_put_failure;
if ((pinfo->filled & MPATH_INFO_FRAME_QLEN) &&
nla_put_u32(msg, NL80211_MPATH_INFO_FRAME_QLEN,
pinfo->frame_qlen))
goto nla_put_failure;
if (((pinfo->filled & MPATH_INFO_SN) &&
nla_put_u32(msg, NL80211_MPATH_INFO_SN, pinfo->sn)) ||
((pinfo->filled & MPATH_INFO_METRIC) &&
nla_put_u32(msg, NL80211_MPATH_INFO_METRIC,
pinfo->metric)) ||
((pinfo->filled & MPATH_INFO_EXPTIME) &&
nla_put_u32(msg, NL80211_MPATH_INFO_EXPTIME,
pinfo->exptime)) ||
((pinfo->filled & MPATH_INFO_FLAGS) &&
nla_put_u8(msg, NL80211_MPATH_INFO_FLAGS,
pinfo->flags)) ||
((pinfo->filled & MPATH_INFO_DISCOVERY_TIMEOUT) &&
nla_put_u32(msg, NL80211_MPATH_INFO_DISCOVERY_TIMEOUT,
pinfo->discovery_timeout)) ||
((pinfo->filled & MPATH_INFO_DISCOVERY_RETRIES) &&
nla_put_u8(msg, NL80211_MPATH_INFO_DISCOVERY_RETRIES,
pinfo->discovery_retries)))
goto nla_put_failure;
nla_nest_end(msg, pinfoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_mpath(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct mpath_info pinfo;
struct cfg80211_registered_device *dev;
struct wireless_dev *wdev;
u8 dst[ETH_ALEN];
u8 next_hop[ETH_ALEN];
int path_idx = cb->args[2];
int err;
err = nl80211_prepare_wdev_dump(skb, cb, &dev, &wdev);
if (err)
return err;
if (!dev->ops->dump_mpath) {
err = -EOPNOTSUPP;
goto out_err;
}
if (wdev->iftype != NL80211_IFTYPE_MESH_POINT) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
err = rdev_dump_mpath(dev, wdev->netdev, path_idx, dst,
next_hop, &pinfo);
if (err == -ENOENT)
break;
if (err)
goto out_err;
if (nl80211_send_mpath(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
wdev->netdev, dst, next_hop,
&pinfo) < 0)
goto out;
path_idx++;
}
out:
cb->args[2] = path_idx;
err = skb->len;
out_err:
nl80211_finish_wdev_dump(dev);
return err;
}
static int nl80211_get_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int err;
struct net_device *dev = info->user_ptr[1];
struct mpath_info pinfo;
struct sk_buff *msg;
u8 *dst = NULL;
u8 next_hop[ETH_ALEN];
memset(&pinfo, 0, sizeof(pinfo));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->get_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
err = rdev_get_mpath(rdev, dev, dst, next_hop, &pinfo);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
if (nl80211_send_mpath(msg, info->snd_portid, info->snd_seq, 0,
dev, dst, next_hop, &pinfo) < 0) {
nlmsg_free(msg);
return -ENOBUFS;
}
return genlmsg_reply(msg, info);
}
static int nl80211_set_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MPATH_NEXT_HOP])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[NL80211_ATTR_MPATH_NEXT_HOP]);
if (!rdev->ops->change_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
return rdev_change_mpath(rdev, dev, dst, next_hop);
}
static int nl80211_new_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
u8 *next_hop = NULL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MPATH_NEXT_HOP])
return -EINVAL;
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
next_hop = nla_data(info->attrs[NL80211_ATTR_MPATH_NEXT_HOP]);
if (!rdev->ops->add_mpath)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
return rdev_add_mpath(rdev, dev, dst, next_hop);
}
static int nl80211_del_mpath(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 *dst = NULL;
if (info->attrs[NL80211_ATTR_MAC])
dst = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!rdev->ops->del_mpath)
return -EOPNOTSUPP;
return rdev_del_mpath(rdev, dev, dst);
}
static int nl80211_set_bss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct bss_parameters params;
int err;
memset(¶ms, 0, sizeof(params));
/* default to not changing parameters */
params.use_cts_prot = -1;
params.use_short_preamble = -1;
params.use_short_slot_time = -1;
params.ap_isolate = -1;
params.ht_opmode = -1;
params.p2p_ctwindow = -1;
params.p2p_opp_ps = -1;
if (info->attrs[NL80211_ATTR_BSS_CTS_PROT])
params.use_cts_prot =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_CTS_PROT]);
if (info->attrs[NL80211_ATTR_BSS_SHORT_PREAMBLE])
params.use_short_preamble =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_SHORT_PREAMBLE]);
if (info->attrs[NL80211_ATTR_BSS_SHORT_SLOT_TIME])
params.use_short_slot_time =
nla_get_u8(info->attrs[NL80211_ATTR_BSS_SHORT_SLOT_TIME]);
if (info->attrs[NL80211_ATTR_BSS_BASIC_RATES]) {
params.basic_rates =
nla_data(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
params.basic_rates_len =
nla_len(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
}
if (info->attrs[NL80211_ATTR_AP_ISOLATE])
params.ap_isolate = !!nla_get_u8(info->attrs[NL80211_ATTR_AP_ISOLATE]);
if (info->attrs[NL80211_ATTR_BSS_HT_OPMODE])
params.ht_opmode =
nla_get_u16(info->attrs[NL80211_ATTR_BSS_HT_OPMODE]);
if (info->attrs[NL80211_ATTR_P2P_CTWINDOW]) {
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
params.p2p_ctwindow =
nla_get_s8(info->attrs[NL80211_ATTR_P2P_CTWINDOW]);
if (params.p2p_ctwindow < 0)
return -EINVAL;
if (params.p2p_ctwindow != 0 &&
!(rdev->wiphy.features & NL80211_FEATURE_P2P_GO_CTWIN))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_P2P_OPPPS]) {
u8 tmp;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
tmp = nla_get_u8(info->attrs[NL80211_ATTR_P2P_OPPPS]);
if (tmp > 1)
return -EINVAL;
params.p2p_opp_ps = tmp;
if (params.p2p_opp_ps &&
!(rdev->wiphy.features & NL80211_FEATURE_P2P_GO_OPPPS))
return -EINVAL;
}
if (!rdev->ops->change_bss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_AP &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
wdev_lock(wdev);
err = rdev_change_bss(rdev, dev, ¶ms);
wdev_unlock(wdev);
return err;
}
static const struct nla_policy reg_rule_policy[NL80211_REG_RULE_ATTR_MAX + 1] = {
[NL80211_ATTR_REG_RULE_FLAGS] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_START] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_END] = { .type = NLA_U32 },
[NL80211_ATTR_FREQ_RANGE_MAX_BW] = { .type = NLA_U32 },
[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN] = { .type = NLA_U32 },
[NL80211_ATTR_POWER_RULE_MAX_EIRP] = { .type = NLA_U32 },
[NL80211_ATTR_DFS_CAC_TIME] = { .type = NLA_U32 },
};
static int parse_reg_rule(struct nlattr *tb[],
struct ieee80211_reg_rule *reg_rule)
{
struct ieee80211_freq_range *freq_range = ®_rule->freq_range;
struct ieee80211_power_rule *power_rule = ®_rule->power_rule;
if (!tb[NL80211_ATTR_REG_RULE_FLAGS])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_START])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_END])
return -EINVAL;
if (!tb[NL80211_ATTR_FREQ_RANGE_MAX_BW])
return -EINVAL;
if (!tb[NL80211_ATTR_POWER_RULE_MAX_EIRP])
return -EINVAL;
reg_rule->flags = nla_get_u32(tb[NL80211_ATTR_REG_RULE_FLAGS]);
freq_range->start_freq_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_START]);
freq_range->end_freq_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_END]);
freq_range->max_bandwidth_khz =
nla_get_u32(tb[NL80211_ATTR_FREQ_RANGE_MAX_BW]);
power_rule->max_eirp =
nla_get_u32(tb[NL80211_ATTR_POWER_RULE_MAX_EIRP]);
if (tb[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN])
power_rule->max_antenna_gain =
nla_get_u32(tb[NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN]);
if (tb[NL80211_ATTR_DFS_CAC_TIME])
reg_rule->dfs_cac_ms =
nla_get_u32(tb[NL80211_ATTR_DFS_CAC_TIME]);
return 0;
}
static int nl80211_req_set_reg(struct sk_buff *skb, struct genl_info *info)
{
int r;
char *data = NULL;
enum nl80211_user_reg_hint_type user_reg_hint_type;
/*
* You should only get this when cfg80211 hasn't yet initialized
* completely when built-in to the kernel right between the time
* window between nl80211_init() and regulatory_init(), if that is
* even possible.
*/
if (unlikely(!rcu_access_pointer(cfg80211_regdomain)))
return -EINPROGRESS;
if (!info->attrs[NL80211_ATTR_REG_ALPHA2])
return -EINVAL;
data = nla_data(info->attrs[NL80211_ATTR_REG_ALPHA2]);
if (info->attrs[NL80211_ATTR_USER_REG_HINT_TYPE])
user_reg_hint_type =
nla_get_u32(info->attrs[NL80211_ATTR_USER_REG_HINT_TYPE]);
else
user_reg_hint_type = NL80211_USER_REG_HINT_USER;
switch (user_reg_hint_type) {
case NL80211_USER_REG_HINT_USER:
case NL80211_USER_REG_HINT_CELL_BASE:
break;
default:
return -EINVAL;
}
r = regulatory_hint_user(data, user_reg_hint_type);
return r;
}
static int nl80211_get_mesh_config(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cur_params;
int err = 0;
void *hdr;
struct nlattr *pinfoattr;
struct sk_buff *msg;
if (wdev->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->get_mesh_config)
return -EOPNOTSUPP;
wdev_lock(wdev);
/* If not connected, get default parameters */
if (!wdev->mesh_id_len)
memcpy(&cur_params, &default_mesh_config, sizeof(cur_params));
else
err = rdev_get_mesh_config(rdev, dev, &cur_params);
wdev_unlock(wdev);
if (err)
return err;
/* Draw up a netlink message to send back */
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_MESH_CONFIG);
if (!hdr)
goto out;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_MESH_CONFIG);
if (!pinfoattr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put_u16(msg, NL80211_MESHCONF_RETRY_TIMEOUT,
cur_params.dot11MeshRetryTimeout) ||
nla_put_u16(msg, NL80211_MESHCONF_CONFIRM_TIMEOUT,
cur_params.dot11MeshConfirmTimeout) ||
nla_put_u16(msg, NL80211_MESHCONF_HOLDING_TIMEOUT,
cur_params.dot11MeshHoldingTimeout) ||
nla_put_u16(msg, NL80211_MESHCONF_MAX_PEER_LINKS,
cur_params.dot11MeshMaxPeerLinks) ||
nla_put_u8(msg, NL80211_MESHCONF_MAX_RETRIES,
cur_params.dot11MeshMaxRetries) ||
nla_put_u8(msg, NL80211_MESHCONF_TTL,
cur_params.dot11MeshTTL) ||
nla_put_u8(msg, NL80211_MESHCONF_ELEMENT_TTL,
cur_params.element_ttl) ||
nla_put_u8(msg, NL80211_MESHCONF_AUTO_OPEN_PLINKS,
cur_params.auto_open_plinks) ||
nla_put_u32(msg, NL80211_MESHCONF_SYNC_OFFSET_MAX_NEIGHBOR,
cur_params.dot11MeshNbrOffsetMaxNeighbor) ||
nla_put_u8(msg, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES,
cur_params.dot11MeshHWMPmaxPREQretries) ||
nla_put_u32(msg, NL80211_MESHCONF_PATH_REFRESH_TIME,
cur_params.path_refresh_time) ||
nla_put_u16(msg, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT,
cur_params.min_discovery_timeout) ||
nla_put_u32(msg, NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT,
cur_params.dot11MeshHWMPactivePathTimeout) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL,
cur_params.dot11MeshHWMPpreqMinInterval) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_PERR_MIN_INTERVAL,
cur_params.dot11MeshHWMPperrMinInterval) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME,
cur_params.dot11MeshHWMPnetDiameterTraversalTime) ||
nla_put_u8(msg, NL80211_MESHCONF_HWMP_ROOTMODE,
cur_params.dot11MeshHWMPRootMode) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_RANN_INTERVAL,
cur_params.dot11MeshHWMPRannInterval) ||
nla_put_u8(msg, NL80211_MESHCONF_GATE_ANNOUNCEMENTS,
cur_params.dot11MeshGateAnnouncementProtocol) ||
nla_put_u8(msg, NL80211_MESHCONF_FORWARDING,
cur_params.dot11MeshForwarding) ||
nla_put_u32(msg, NL80211_MESHCONF_RSSI_THRESHOLD,
cur_params.rssi_threshold) ||
nla_put_u32(msg, NL80211_MESHCONF_HT_OPMODE,
cur_params.ht_opmode) ||
nla_put_u32(msg, NL80211_MESHCONF_HWMP_PATH_TO_ROOT_TIMEOUT,
cur_params.dot11MeshHWMPactivePathToRootTimeout) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_ROOT_INTERVAL,
cur_params.dot11MeshHWMProotInterval) ||
nla_put_u16(msg, NL80211_MESHCONF_HWMP_CONFIRMATION_INTERVAL,
cur_params.dot11MeshHWMPconfirmationInterval) ||
nla_put_u32(msg, NL80211_MESHCONF_POWER_MODE,
cur_params.power_mode) ||
nla_put_u16(msg, NL80211_MESHCONF_AWAKE_WINDOW,
cur_params.dot11MeshAwakeWindowDuration) ||
nla_put_u32(msg, NL80211_MESHCONF_PLINK_TIMEOUT,
cur_params.plink_timeout))
goto nla_put_failure;
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
genlmsg_cancel(msg, hdr);
out:
nlmsg_free(msg);
return -ENOBUFS;
}
static const struct nla_policy nl80211_meshconf_params_policy[NL80211_MESHCONF_ATTR_MAX+1] = {
[NL80211_MESHCONF_RETRY_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_CONFIRM_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_HOLDING_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_MAX_PEER_LINKS] = { .type = NLA_U16 },
[NL80211_MESHCONF_MAX_RETRIES] = { .type = NLA_U8 },
[NL80211_MESHCONF_TTL] = { .type = NLA_U8 },
[NL80211_MESHCONF_ELEMENT_TTL] = { .type = NLA_U8 },
[NL80211_MESHCONF_AUTO_OPEN_PLINKS] = { .type = NLA_U8 },
[NL80211_MESHCONF_SYNC_OFFSET_MAX_NEIGHBOR] = { .type = NLA_U32 },
[NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES] = { .type = NLA_U8 },
[NL80211_MESHCONF_PATH_REFRESH_TIME] = { .type = NLA_U32 },
[NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT] = { .type = NLA_U32 },
[NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_PERR_MIN_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_ROOTMODE] = { .type = NLA_U8 },
[NL80211_MESHCONF_HWMP_RANN_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_GATE_ANNOUNCEMENTS] = { .type = NLA_U8 },
[NL80211_MESHCONF_FORWARDING] = { .type = NLA_U8 },
[NL80211_MESHCONF_RSSI_THRESHOLD] = { .type = NLA_U32 },
[NL80211_MESHCONF_HT_OPMODE] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_PATH_TO_ROOT_TIMEOUT] = { .type = NLA_U32 },
[NL80211_MESHCONF_HWMP_ROOT_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_HWMP_CONFIRMATION_INTERVAL] = { .type = NLA_U16 },
[NL80211_MESHCONF_POWER_MODE] = { .type = NLA_U32 },
[NL80211_MESHCONF_AWAKE_WINDOW] = { .type = NLA_U16 },
[NL80211_MESHCONF_PLINK_TIMEOUT] = { .type = NLA_U32 },
};
static const struct nla_policy
nl80211_mesh_setup_params_policy[NL80211_MESH_SETUP_ATTR_MAX+1] = {
[NL80211_MESH_SETUP_ENABLE_VENDOR_SYNC] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_USERSPACE_AUTH] = { .type = NLA_FLAG },
[NL80211_MESH_SETUP_AUTH_PROTOCOL] = { .type = NLA_U8 },
[NL80211_MESH_SETUP_USERSPACE_MPM] = { .type = NLA_FLAG },
[NL80211_MESH_SETUP_IE] = { .type = NLA_BINARY,
.len = IEEE80211_MAX_DATA_LEN },
[NL80211_MESH_SETUP_USERSPACE_AMPE] = { .type = NLA_FLAG },
};
static int nl80211_parse_mesh_config(struct genl_info *info,
struct mesh_config *cfg,
u32 *mask_out)
{
struct nlattr *tb[NL80211_MESHCONF_ATTR_MAX + 1];
u32 mask = 0;
#define FILL_IN_MESH_PARAM_IF_SET(tb, cfg, param, min, max, mask, attr, fn) \
do { \
if (tb[attr]) { \
if (fn(tb[attr]) < min || fn(tb[attr]) > max) \
return -EINVAL; \
cfg->param = fn(tb[attr]); \
mask |= (1 << (attr - 1)); \
} \
} while (0)
if (!info->attrs[NL80211_ATTR_MESH_CONFIG])
return -EINVAL;
if (nla_parse_nested(tb, NL80211_MESHCONF_ATTR_MAX,
info->attrs[NL80211_ATTR_MESH_CONFIG],
nl80211_meshconf_params_policy))
return -EINVAL;
/* This makes sure that there aren't more than 32 mesh config
* parameters (otherwise our bitfield scheme would not work.) */
BUILD_BUG_ON(NL80211_MESHCONF_ATTR_MAX > 32);
/* Fill in the params struct */
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshRetryTimeout, 1, 255,
mask, NL80211_MESHCONF_RETRY_TIMEOUT,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshConfirmTimeout, 1, 255,
mask, NL80211_MESHCONF_CONFIRM_TIMEOUT,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHoldingTimeout, 1, 255,
mask, NL80211_MESHCONF_HOLDING_TIMEOUT,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshMaxPeerLinks, 0, 255,
mask, NL80211_MESHCONF_MAX_PEER_LINKS,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshMaxRetries, 0, 16,
mask, NL80211_MESHCONF_MAX_RETRIES,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshTTL, 1, 255,
mask, NL80211_MESHCONF_TTL, nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, element_ttl, 1, 255,
mask, NL80211_MESHCONF_ELEMENT_TTL,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, auto_open_plinks, 0, 1,
mask, NL80211_MESHCONF_AUTO_OPEN_PLINKS,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshNbrOffsetMaxNeighbor,
1, 255, mask,
NL80211_MESHCONF_SYNC_OFFSET_MAX_NEIGHBOR,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPmaxPREQretries, 0, 255,
mask, NL80211_MESHCONF_HWMP_MAX_PREQ_RETRIES,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, path_refresh_time, 1, 65535,
mask, NL80211_MESHCONF_PATH_REFRESH_TIME,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, min_discovery_timeout, 1, 65535,
mask, NL80211_MESHCONF_MIN_DISCOVERY_TIMEOUT,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPactivePathTimeout,
1, 65535, mask,
NL80211_MESHCONF_HWMP_ACTIVE_PATH_TIMEOUT,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPpreqMinInterval,
1, 65535, mask,
NL80211_MESHCONF_HWMP_PREQ_MIN_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPperrMinInterval,
1, 65535, mask,
NL80211_MESHCONF_HWMP_PERR_MIN_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg,
dot11MeshHWMPnetDiameterTraversalTime,
1, 65535, mask,
NL80211_MESHCONF_HWMP_NET_DIAM_TRVS_TIME,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPRootMode, 0, 4,
mask, NL80211_MESHCONF_HWMP_ROOTMODE,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPRannInterval, 1, 65535,
mask, NL80211_MESHCONF_HWMP_RANN_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg,
dot11MeshGateAnnouncementProtocol, 0, 1,
mask, NL80211_MESHCONF_GATE_ANNOUNCEMENTS,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshForwarding, 0, 1,
mask, NL80211_MESHCONF_FORWARDING,
nla_get_u8);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, rssi_threshold, -255, 0,
mask, NL80211_MESHCONF_RSSI_THRESHOLD,
nla_get_s32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, ht_opmode, 0, 16,
mask, NL80211_MESHCONF_HT_OPMODE,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMPactivePathToRootTimeout,
1, 65535, mask,
NL80211_MESHCONF_HWMP_PATH_TO_ROOT_TIMEOUT,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshHWMProotInterval, 1, 65535,
mask, NL80211_MESHCONF_HWMP_ROOT_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg,
dot11MeshHWMPconfirmationInterval,
1, 65535, mask,
NL80211_MESHCONF_HWMP_CONFIRMATION_INTERVAL,
nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, power_mode,
NL80211_MESH_POWER_ACTIVE,
NL80211_MESH_POWER_MAX,
mask, NL80211_MESHCONF_POWER_MODE,
nla_get_u32);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, dot11MeshAwakeWindowDuration,
0, 65535, mask,
NL80211_MESHCONF_AWAKE_WINDOW, nla_get_u16);
FILL_IN_MESH_PARAM_IF_SET(tb, cfg, plink_timeout, 1, 0xffffffff,
mask, NL80211_MESHCONF_PLINK_TIMEOUT,
nla_get_u32);
if (mask_out)
*mask_out = mask;
return 0;
#undef FILL_IN_MESH_PARAM_IF_SET
}
static int nl80211_parse_mesh_setup(struct genl_info *info,
struct mesh_setup *setup)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct nlattr *tb[NL80211_MESH_SETUP_ATTR_MAX + 1];
if (!info->attrs[NL80211_ATTR_MESH_SETUP])
return -EINVAL;
if (nla_parse_nested(tb, NL80211_MESH_SETUP_ATTR_MAX,
info->attrs[NL80211_ATTR_MESH_SETUP],
nl80211_mesh_setup_params_policy))
return -EINVAL;
if (tb[NL80211_MESH_SETUP_ENABLE_VENDOR_SYNC])
setup->sync_method =
(nla_get_u8(tb[NL80211_MESH_SETUP_ENABLE_VENDOR_SYNC])) ?
IEEE80211_SYNC_METHOD_VENDOR :
IEEE80211_SYNC_METHOD_NEIGHBOR_OFFSET;
if (tb[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL])
setup->path_sel_proto =
(nla_get_u8(tb[NL80211_MESH_SETUP_ENABLE_VENDOR_PATH_SEL])) ?
IEEE80211_PATH_PROTOCOL_VENDOR :
IEEE80211_PATH_PROTOCOL_HWMP;
if (tb[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC])
setup->path_metric =
(nla_get_u8(tb[NL80211_MESH_SETUP_ENABLE_VENDOR_METRIC])) ?
IEEE80211_PATH_METRIC_VENDOR :
IEEE80211_PATH_METRIC_AIRTIME;
if (tb[NL80211_MESH_SETUP_IE]) {
struct nlattr *ieattr =
tb[NL80211_MESH_SETUP_IE];
if (!is_valid_ie_attr(ieattr))
return -EINVAL;
setup->ie = nla_data(ieattr);
setup->ie_len = nla_len(ieattr);
}
if (tb[NL80211_MESH_SETUP_USERSPACE_MPM] &&
!(rdev->wiphy.features & NL80211_FEATURE_USERSPACE_MPM))
return -EINVAL;
setup->user_mpm = nla_get_flag(tb[NL80211_MESH_SETUP_USERSPACE_MPM]);
setup->is_authenticated = nla_get_flag(tb[NL80211_MESH_SETUP_USERSPACE_AUTH]);
setup->is_secure = nla_get_flag(tb[NL80211_MESH_SETUP_USERSPACE_AMPE]);
if (setup->is_secure)
setup->user_mpm = true;
if (tb[NL80211_MESH_SETUP_AUTH_PROTOCOL]) {
if (!setup->user_mpm)
return -EINVAL;
setup->auth_id =
nla_get_u8(tb[NL80211_MESH_SETUP_AUTH_PROTOCOL]);
}
return 0;
}
static int nl80211_update_mesh_config(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct mesh_config cfg;
u32 mask;
int err;
if (wdev->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->update_mesh_config)
return -EOPNOTSUPP;
err = nl80211_parse_mesh_config(info, &cfg, &mask);
if (err)
return err;
wdev_lock(wdev);
if (!wdev->mesh_id_len)
err = -ENOLINK;
if (!err)
err = rdev_update_mesh_config(rdev, dev, mask, &cfg);
wdev_unlock(wdev);
return err;
}
static int nl80211_get_reg(struct sk_buff *skb, struct genl_info *info)
{
const struct ieee80211_regdomain *regdom;
struct sk_buff *msg;
void *hdr = NULL;
struct nlattr *nl_reg_rules;
unsigned int i;
if (!cfg80211_regdomain)
return -EINVAL;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOBUFS;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_REG);
if (!hdr)
goto put_failure;
if (reg_last_request_cell_base() &&
nla_put_u32(msg, NL80211_ATTR_USER_REG_HINT_TYPE,
NL80211_USER_REG_HINT_CELL_BASE))
goto nla_put_failure;
rcu_read_lock();
regdom = rcu_dereference(cfg80211_regdomain);
if (nla_put_string(msg, NL80211_ATTR_REG_ALPHA2, regdom->alpha2) ||
(regdom->dfs_region &&
nla_put_u8(msg, NL80211_ATTR_DFS_REGION, regdom->dfs_region)))
goto nla_put_failure_rcu;
nl_reg_rules = nla_nest_start(msg, NL80211_ATTR_REG_RULES);
if (!nl_reg_rules)
goto nla_put_failure_rcu;
for (i = 0; i < regdom->n_reg_rules; i++) {
struct nlattr *nl_reg_rule;
const struct ieee80211_reg_rule *reg_rule;
const struct ieee80211_freq_range *freq_range;
const struct ieee80211_power_rule *power_rule;
unsigned int max_bandwidth_khz;
reg_rule = ®dom->reg_rules[i];
freq_range = ®_rule->freq_range;
power_rule = ®_rule->power_rule;
nl_reg_rule = nla_nest_start(msg, i);
if (!nl_reg_rule)
goto nla_put_failure_rcu;
max_bandwidth_khz = freq_range->max_bandwidth_khz;
if (!max_bandwidth_khz)
max_bandwidth_khz = reg_get_max_bandwidth(regdom,
reg_rule);
if (nla_put_u32(msg, NL80211_ATTR_REG_RULE_FLAGS,
reg_rule->flags) ||
nla_put_u32(msg, NL80211_ATTR_FREQ_RANGE_START,
freq_range->start_freq_khz) ||
nla_put_u32(msg, NL80211_ATTR_FREQ_RANGE_END,
freq_range->end_freq_khz) ||
nla_put_u32(msg, NL80211_ATTR_FREQ_RANGE_MAX_BW,
max_bandwidth_khz) ||
nla_put_u32(msg, NL80211_ATTR_POWER_RULE_MAX_ANT_GAIN,
power_rule->max_antenna_gain) ||
nla_put_u32(msg, NL80211_ATTR_POWER_RULE_MAX_EIRP,
power_rule->max_eirp) ||
nla_put_u32(msg, NL80211_ATTR_DFS_CAC_TIME,
reg_rule->dfs_cac_ms))
goto nla_put_failure_rcu;
nla_nest_end(msg, nl_reg_rule);
}
rcu_read_unlock();
nla_nest_end(msg, nl_reg_rules);
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure_rcu:
rcu_read_unlock();
nla_put_failure:
genlmsg_cancel(msg, hdr);
put_failure:
nlmsg_free(msg);
return -EMSGSIZE;
}
static int nl80211_set_reg(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *tb[NL80211_REG_RULE_ATTR_MAX + 1];
struct nlattr *nl_reg_rule;
char *alpha2 = NULL;
int rem_reg_rules = 0, r = 0;
u32 num_rules = 0, rule_idx = 0, size_of_regd;
enum nl80211_dfs_regions dfs_region = NL80211_DFS_UNSET;
struct ieee80211_regdomain *rd = NULL;
if (!info->attrs[NL80211_ATTR_REG_ALPHA2])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REG_RULES])
return -EINVAL;
alpha2 = nla_data(info->attrs[NL80211_ATTR_REG_ALPHA2]);
if (info->attrs[NL80211_ATTR_DFS_REGION])
dfs_region = nla_get_u8(info->attrs[NL80211_ATTR_DFS_REGION]);
nla_for_each_nested(nl_reg_rule, info->attrs[NL80211_ATTR_REG_RULES],
rem_reg_rules) {
num_rules++;
if (num_rules > NL80211_MAX_SUPP_REG_RULES)
return -EINVAL;
}
if (!reg_is_valid_request(alpha2))
return -EINVAL;
size_of_regd = sizeof(struct ieee80211_regdomain) +
num_rules * sizeof(struct ieee80211_reg_rule);
rd = kzalloc(size_of_regd, GFP_KERNEL);
if (!rd)
return -ENOMEM;
rd->n_reg_rules = num_rules;
rd->alpha2[0] = alpha2[0];
rd->alpha2[1] = alpha2[1];
/*
* Disable DFS master mode if the DFS region was
* not supported or known on this kernel.
*/
if (reg_supported_dfs_region(dfs_region))
rd->dfs_region = dfs_region;
nla_for_each_nested(nl_reg_rule, info->attrs[NL80211_ATTR_REG_RULES],
rem_reg_rules) {
r = nla_parse(tb, NL80211_REG_RULE_ATTR_MAX,
nla_data(nl_reg_rule), nla_len(nl_reg_rule),
reg_rule_policy);
if (r)
goto bad_reg;
r = parse_reg_rule(tb, &rd->reg_rules[rule_idx]);
if (r)
goto bad_reg;
rule_idx++;
if (rule_idx > NL80211_MAX_SUPP_REG_RULES) {
r = -EINVAL;
goto bad_reg;
}
}
r = set_regdom(rd);
/* set_regdom took ownership */
rd = NULL;
bad_reg:
kfree(rd);
return r;
}
static int validate_scan_freqs(struct nlattr *freqs)
{
struct nlattr *attr1, *attr2;
int n_channels = 0, tmp1, tmp2;
nla_for_each_nested(attr1, freqs, tmp1) {
n_channels++;
/*
* Some hardware has a limited channel list for
* scanning, and it is pretty much nonsensical
* to scan for a channel twice, so disallow that
* and don't require drivers to check that the
* channel list they get isn't longer than what
* they can scan, as long as they can scan all
* the channels they registered at once.
*/
nla_for_each_nested(attr2, freqs, tmp2)
if (attr1 != attr2 &&
nla_get_u32(attr1) == nla_get_u32(attr2))
return 0;
}
return n_channels;
}
static int nl80211_trigger_scan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
struct cfg80211_scan_request *request;
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_channels, i;
size_t ie_len;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
wiphy = &rdev->wiphy;
if (!rdev->ops->scan)
return -EOPNOTSUPP;
if (rdev->scan_req || rdev->scan_msg) {
err = -EBUSY;
goto unlock;
}
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels) {
err = -EINVAL;
goto unlock;
}
} else {
n_channels = ieee80211_get_num_supported_channels(wiphy);
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp)
n_ssids++;
if (n_ssids > wiphy->max_scan_ssids) {
err = -EINVAL;
goto unlock;
}
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_scan_ie_len) {
err = -EINVAL;
goto unlock;
}
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request) {
err = -ENOMEM;
goto unlock;
}
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_FREQUENCIES], tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
enum ieee80211_band band;
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS], tmp) {
if (nla_len(attr) > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
request->ssids[i].ssid_len = nla_len(attr);
memcpy(request->ssids[i].ssid, nla_data(attr), nla_len(attr));
i++;
}
}
if (info->attrs[NL80211_ATTR_IE]) {
request->ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
for (i = 0; i < IEEE80211_NUM_BANDS; i++)
if (wiphy->bands[i])
request->rates[i] =
(1 << wiphy->bands[i]->n_bitrates) - 1;
if (info->attrs[NL80211_ATTR_SCAN_SUPP_RATES]) {
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCAN_SUPP_RATES],
tmp) {
enum ieee80211_band band = nla_type(attr);
if (band < 0 || band >= IEEE80211_NUM_BANDS) {
err = -EINVAL;
goto out_free;
}
if (!wiphy->bands[band])
continue;
err = ieee80211_get_ratemask(wiphy->bands[band],
nla_data(attr),
nla_len(attr),
&request->rates[band]);
if (err)
goto out_free;
}
}
if (info->attrs[NL80211_ATTR_SCAN_FLAGS]) {
request->flags = nla_get_u32(
info->attrs[NL80211_ATTR_SCAN_FLAGS]);
if ((request->flags & NL80211_SCAN_FLAG_LOW_PRIORITY) &&
!(wiphy->features & NL80211_FEATURE_LOW_PRIORITY_SCAN)) {
err = -EOPNOTSUPP;
goto out_free;
}
}
request->no_cck =
nla_get_flag(info->attrs[NL80211_ATTR_TX_NO_CCK_RATE]);
request->wdev = wdev;
request->wiphy = &rdev->wiphy;
request->scan_start = jiffies;
rdev->scan_req = request;
err = rdev_scan(rdev, request);
if (!err) {
nl80211_send_scan_start(rdev, wdev);
if (wdev->netdev)
dev_hold(wdev->netdev);
} else {
out_free:
rdev->scan_req = NULL;
kfree(request);
}
unlock:
return err;
}
static int nl80211_start_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_sched_scan_request *request;
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct nlattr *attr;
struct wiphy *wiphy;
int err, tmp, n_ssids = 0, n_match_sets = 0, n_channels, i;
u32 interval;
enum ieee80211_band band;
size_t ie_len;
struct nlattr *tb[NL80211_SCHED_SCAN_MATCH_ATTR_MAX + 1];
s32 default_match_rssi = NL80211_SCAN_RSSI_THOLD_OFF;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_start)
return -EOPNOTSUPP;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL])
return -EINVAL;
interval = nla_get_u32(info->attrs[NL80211_ATTR_SCHED_SCAN_INTERVAL]);
if (interval == 0)
return -EINVAL;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
n_channels = validate_scan_freqs(
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]);
if (!n_channels)
return -EINVAL;
} else {
n_channels = ieee80211_get_num_supported_channels(wiphy);
}
if (info->attrs[NL80211_ATTR_SCAN_SSIDS])
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp)
n_ssids++;
if (n_ssids > wiphy->max_sched_scan_ssids)
return -EINVAL;
/*
* First, count the number of 'real' matchsets. Due to an issue with
* the old implementation, matchsets containing only the RSSI attribute
* (NL80211_SCHED_SCAN_MATCH_ATTR_RSSI) are considered as the 'default'
* RSSI for all matchsets, rather than their own matchset for reporting
* all APs with a strong RSSI. This is needed to be compatible with
* older userspace that treated a matchset with only the RSSI as the
* global RSSI for all other matchsets - if there are other matchsets.
*/
if (info->attrs[NL80211_ATTR_SCHED_SCAN_MATCH]) {
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCHED_SCAN_MATCH],
tmp) {
struct nlattr *rssi;
err = nla_parse(tb, NL80211_SCHED_SCAN_MATCH_ATTR_MAX,
nla_data(attr), nla_len(attr),
nl80211_match_policy);
if (err)
return err;
/* add other standalone attributes here */
if (tb[NL80211_SCHED_SCAN_MATCH_ATTR_SSID]) {
n_match_sets++;
continue;
}
rssi = tb[NL80211_SCHED_SCAN_MATCH_ATTR_RSSI];
if (rssi)
default_match_rssi = nla_get_s32(rssi);
}
}
/* However, if there's no other matchset, add the RSSI one */
if (!n_match_sets && default_match_rssi != NL80211_SCAN_RSSI_THOLD_OFF)
n_match_sets = 1;
if (n_match_sets > wiphy->max_match_sets)
return -EINVAL;
if (info->attrs[NL80211_ATTR_IE])
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
else
ie_len = 0;
if (ie_len > wiphy->max_sched_scan_ie_len)
return -EINVAL;
if (rdev->sched_scan_req) {
err = -EINPROGRESS;
goto out;
}
request = kzalloc(sizeof(*request)
+ sizeof(*request->ssids) * n_ssids
+ sizeof(*request->match_sets) * n_match_sets
+ sizeof(*request->channels) * n_channels
+ ie_len, GFP_KERNEL);
if (!request) {
err = -ENOMEM;
goto out;
}
if (n_ssids)
request->ssids = (void *)&request->channels[n_channels];
request->n_ssids = n_ssids;
if (ie_len) {
if (request->ssids)
request->ie = (void *)(request->ssids + n_ssids);
else
request->ie = (void *)(request->channels + n_channels);
}
if (n_match_sets) {
if (request->ie)
request->match_sets = (void *)(request->ie + ie_len);
else if (request->ssids)
request->match_sets =
(void *)(request->ssids + n_ssids);
else
request->match_sets =
(void *)(request->channels + n_channels);
}
request->n_match_sets = n_match_sets;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_FREQUENCIES]) {
/* user specified, bail out if channel not found */
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCAN_FREQUENCIES],
tmp) {
struct ieee80211_channel *chan;
chan = ieee80211_get_channel(wiphy, nla_get_u32(attr));
if (!chan) {
err = -EINVAL;
goto out_free;
}
/* ignore disabled channels */
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
} else {
/* all channels */
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
int j;
if (!wiphy->bands[band])
continue;
for (j = 0; j < wiphy->bands[band]->n_channels; j++) {
struct ieee80211_channel *chan;
chan = &wiphy->bands[band]->channels[j];
if (chan->flags & IEEE80211_CHAN_DISABLED)
continue;
request->channels[i] = chan;
i++;
}
}
}
if (!i) {
err = -EINVAL;
goto out_free;
}
request->n_channels = i;
i = 0;
if (info->attrs[NL80211_ATTR_SCAN_SSIDS]) {
nla_for_each_nested(attr, info->attrs[NL80211_ATTR_SCAN_SSIDS],
tmp) {
if (nla_len(attr) > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
request->ssids[i].ssid_len = nla_len(attr);
memcpy(request->ssids[i].ssid, nla_data(attr),
nla_len(attr));
i++;
}
}
i = 0;
if (info->attrs[NL80211_ATTR_SCHED_SCAN_MATCH]) {
nla_for_each_nested(attr,
info->attrs[NL80211_ATTR_SCHED_SCAN_MATCH],
tmp) {
struct nlattr *ssid, *rssi;
err = nla_parse(tb, NL80211_SCHED_SCAN_MATCH_ATTR_MAX,
nla_data(attr), nla_len(attr),
nl80211_match_policy);
if (err)
goto out_free;
ssid = tb[NL80211_SCHED_SCAN_MATCH_ATTR_SSID];
if (ssid) {
if (WARN_ON(i >= n_match_sets)) {
/* this indicates a programming error,
* the loop above should have verified
* things properly
*/
err = -EINVAL;
goto out_free;
}
if (nla_len(ssid) > IEEE80211_MAX_SSID_LEN) {
err = -EINVAL;
goto out_free;
}
memcpy(request->match_sets[i].ssid.ssid,
nla_data(ssid), nla_len(ssid));
request->match_sets[i].ssid.ssid_len =
nla_len(ssid);
/* special attribute - old implemenation w/a */
request->match_sets[i].rssi_thold =
default_match_rssi;
rssi = tb[NL80211_SCHED_SCAN_MATCH_ATTR_RSSI];
if (rssi)
request->match_sets[i].rssi_thold =
nla_get_s32(rssi);
}
i++;
}
/* there was no other matchset, so the RSSI one is alone */
if (i == 0)
request->match_sets[0].rssi_thold = default_match_rssi;
request->min_rssi_thold = INT_MAX;
for (i = 0; i < n_match_sets; i++)
request->min_rssi_thold =
min(request->match_sets[i].rssi_thold,
request->min_rssi_thold);
} else {
request->min_rssi_thold = NL80211_SCAN_RSSI_THOLD_OFF;
}
if (ie_len) {
request->ie_len = ie_len;
memcpy((void *)request->ie,
nla_data(info->attrs[NL80211_ATTR_IE]),
request->ie_len);
}
if (info->attrs[NL80211_ATTR_SCAN_FLAGS]) {
request->flags = nla_get_u32(
info->attrs[NL80211_ATTR_SCAN_FLAGS]);
if ((request->flags & NL80211_SCAN_FLAG_LOW_PRIORITY) &&
!(wiphy->features & NL80211_FEATURE_LOW_PRIORITY_SCAN)) {
err = -EOPNOTSUPP;
goto out_free;
}
}
request->dev = dev;
request->wiphy = &rdev->wiphy;
request->interval = interval;
request->scan_start = jiffies;
err = rdev_sched_scan_start(rdev, dev, request);
if (!err) {
rdev->sched_scan_req = request;
nl80211_send_sched_scan(rdev, dev,
NL80211_CMD_START_SCHED_SCAN);
goto out;
}
out_free:
kfree(request);
out:
return err;
}
static int nl80211_stop_sched_scan(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_SCHED_SCAN) ||
!rdev->ops->sched_scan_stop)
return -EOPNOTSUPP;
return __cfg80211_stop_sched_scan(rdev, false);
}
static int nl80211_start_radar_detection(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_chan_def chandef;
enum nl80211_dfs_regions dfs_region;
unsigned int cac_time_ms;
int err;
dfs_region = reg_get_dfs_region(wdev->wiphy);
if (dfs_region == NL80211_DFS_UNSET)
return -EINVAL;
err = nl80211_parse_chandef(rdev, info, &chandef);
if (err)
return err;
if (netif_carrier_ok(dev))
return -EBUSY;
if (wdev->cac_started)
return -EBUSY;
err = cfg80211_chandef_dfs_required(wdev->wiphy, &chandef);
if (err < 0)
return err;
if (err == 0)
return -EINVAL;
if (!cfg80211_chandef_dfs_usable(wdev->wiphy, &chandef))
return -EINVAL;
if (!rdev->ops->start_radar_detection)
return -EOPNOTSUPP;
err = cfg80211_can_use_iftype_chan(rdev, wdev, wdev->iftype,
chandef.chan, CHAN_MODE_SHARED,
BIT(chandef.width));
if (err)
return err;
cac_time_ms = cfg80211_chandef_dfs_cac_time(&rdev->wiphy, &chandef);
if (WARN_ON(!cac_time_ms))
cac_time_ms = IEEE80211_DFS_MIN_CAC_TIME_MS;
err = rdev->ops->start_radar_detection(&rdev->wiphy, dev, &chandef,
cac_time_ms);
if (!err) {
wdev->chandef = chandef;
wdev->cac_started = true;
wdev->cac_start_time = jiffies;
wdev->cac_time_ms = cac_time_ms;
}
return err;
}
static int nl80211_channel_switch(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_csa_settings params;
/* csa_attrs is defined static to avoid waste of stack size - this
* function is called under RTNL lock, so this should not be a problem.
*/
static struct nlattr *csa_attrs[NL80211_ATTR_MAX+1];
u8 radar_detect_width = 0;
int err;
bool need_new_beacon = false;
if (!rdev->ops->channel_switch ||
!(rdev->wiphy.flags & WIPHY_FLAG_HAS_CHANNEL_SWITCH))
return -EOPNOTSUPP;
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
need_new_beacon = true;
/* useless if AP is not running */
if (!wdev->beacon_interval)
return -ENOTCONN;
break;
case NL80211_IFTYPE_ADHOC:
if (!wdev->ssid_len)
return -ENOTCONN;
break;
case NL80211_IFTYPE_MESH_POINT:
if (!wdev->mesh_id_len)
return -ENOTCONN;
break;
default:
return -EOPNOTSUPP;
}
memset(¶ms, 0, sizeof(params));
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ] ||
!info->attrs[NL80211_ATTR_CH_SWITCH_COUNT])
return -EINVAL;
/* only important for AP, IBSS and mesh create IEs internally */
if (need_new_beacon && !info->attrs[NL80211_ATTR_CSA_IES])
return -EINVAL;
params.count = nla_get_u32(info->attrs[NL80211_ATTR_CH_SWITCH_COUNT]);
if (!need_new_beacon)
goto skip_beacons;
err = nl80211_parse_beacon(info->attrs, ¶ms.beacon_after);
if (err)
return err;
err = nla_parse_nested(csa_attrs, NL80211_ATTR_MAX,
info->attrs[NL80211_ATTR_CSA_IES],
nl80211_policy);
if (err)
return err;
err = nl80211_parse_beacon(csa_attrs, ¶ms.beacon_csa);
if (err)
return err;
if (!csa_attrs[NL80211_ATTR_CSA_C_OFF_BEACON])
return -EINVAL;
params.counter_offset_beacon =
nla_get_u16(csa_attrs[NL80211_ATTR_CSA_C_OFF_BEACON]);
if (params.counter_offset_beacon >= params.beacon_csa.tail_len)
return -EINVAL;
/* sanity check - counters should be the same */
if (params.beacon_csa.tail[params.counter_offset_beacon] !=
params.count)
return -EINVAL;
if (csa_attrs[NL80211_ATTR_CSA_C_OFF_PRESP]) {
params.counter_offset_presp =
nla_get_u16(csa_attrs[NL80211_ATTR_CSA_C_OFF_PRESP]);
if (params.counter_offset_presp >=
params.beacon_csa.probe_resp_len)
return -EINVAL;
if (params.beacon_csa.probe_resp[params.counter_offset_presp] !=
params.count)
return -EINVAL;
}
skip_beacons:
err = nl80211_parse_chandef(rdev, info, ¶ms.chandef);
if (err)
return err;
if (!cfg80211_reg_can_beacon(&rdev->wiphy, ¶ms.chandef))
return -EINVAL;
switch (dev->ieee80211_ptr->iftype) {
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_MESH_POINT:
err = cfg80211_chandef_dfs_required(wdev->wiphy,
¶ms.chandef);
if (err < 0)
return err;
if (err) {
radar_detect_width = BIT(params.chandef.width);
params.radar_required = true;
}
break;
default:
break;
}
err = cfg80211_can_use_iftype_chan(rdev, wdev, wdev->iftype,
params.chandef.chan,
CHAN_MODE_SHARED,
radar_detect_width);
if (err)
return err;
if (info->attrs[NL80211_ATTR_CH_SWITCH_BLOCK_TX])
params.block_tx = true;
wdev_lock(wdev);
err = rdev_channel_switch(rdev, dev, ¶ms);
wdev_unlock(wdev);
return err;
}
static int nl80211_send_bss(struct sk_buff *msg, struct netlink_callback *cb,
u32 seq, int flags,
struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev,
struct cfg80211_internal_bss *intbss)
{
struct cfg80211_bss *res = &intbss->pub;
const struct cfg80211_bss_ies *ies;
void *hdr;
struct nlattr *bss;
bool tsf = false;
ASSERT_WDEV_LOCK(wdev);
hdr = nl80211hdr_put(msg, NETLINK_CB(cb->skb).portid, seq, flags,
NL80211_CMD_NEW_SCAN_RESULTS);
if (!hdr)
return -1;
genl_dump_check_consistent(cb, hdr, &nl80211_fam);
if (nla_put_u32(msg, NL80211_ATTR_GENERATION, rdev->bss_generation))
goto nla_put_failure;
if (wdev->netdev &&
nla_put_u32(msg, NL80211_ATTR_IFINDEX, wdev->netdev->ifindex))
goto nla_put_failure;
if (nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto nla_put_failure;
bss = nla_nest_start(msg, NL80211_ATTR_BSS);
if (!bss)
goto nla_put_failure;
if ((!is_zero_ether_addr(res->bssid) &&
nla_put(msg, NL80211_BSS_BSSID, ETH_ALEN, res->bssid)))
goto nla_put_failure;
rcu_read_lock();
ies = rcu_dereference(res->ies);
if (ies) {
if (nla_put_u64(msg, NL80211_BSS_TSF, ies->tsf))
goto fail_unlock_rcu;
tsf = true;
if (ies->len && nla_put(msg, NL80211_BSS_INFORMATION_ELEMENTS,
ies->len, ies->data))
goto fail_unlock_rcu;
}
ies = rcu_dereference(res->beacon_ies);
if (ies) {
if (!tsf && nla_put_u64(msg, NL80211_BSS_TSF, ies->tsf))
goto fail_unlock_rcu;
if (ies->len && nla_put(msg, NL80211_BSS_BEACON_IES,
ies->len, ies->data))
goto fail_unlock_rcu;
}
rcu_read_unlock();
if (res->beacon_interval &&
nla_put_u16(msg, NL80211_BSS_BEACON_INTERVAL, res->beacon_interval))
goto nla_put_failure;
if (nla_put_u16(msg, NL80211_BSS_CAPABILITY, res->capability) ||
nla_put_u32(msg, NL80211_BSS_FREQUENCY, res->channel->center_freq) ||
nla_put_u32(msg, NL80211_BSS_CHAN_WIDTH, res->scan_width) ||
nla_put_u32(msg, NL80211_BSS_SEEN_MS_AGO,
jiffies_to_msecs(jiffies - intbss->ts)))
goto nla_put_failure;
switch (rdev->wiphy.signal_type) {
case CFG80211_SIGNAL_TYPE_MBM:
if (nla_put_u32(msg, NL80211_BSS_SIGNAL_MBM, res->signal))
goto nla_put_failure;
break;
case CFG80211_SIGNAL_TYPE_UNSPEC:
if (nla_put_u8(msg, NL80211_BSS_SIGNAL_UNSPEC, res->signal))
goto nla_put_failure;
break;
default:
break;
}
switch (wdev->iftype) {
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_STATION:
if (intbss == wdev->current_bss &&
nla_put_u32(msg, NL80211_BSS_STATUS,
NL80211_BSS_STATUS_ASSOCIATED))
goto nla_put_failure;
break;
case NL80211_IFTYPE_ADHOC:
if (intbss == wdev->current_bss &&
nla_put_u32(msg, NL80211_BSS_STATUS,
NL80211_BSS_STATUS_IBSS_JOINED))
goto nla_put_failure;
break;
default:
break;
}
nla_nest_end(msg, bss);
return genlmsg_end(msg, hdr);
fail_unlock_rcu:
rcu_read_unlock();
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_scan(struct sk_buff *skb, struct netlink_callback *cb)
{
struct cfg80211_registered_device *rdev;
struct cfg80211_internal_bss *scan;
struct wireless_dev *wdev;
int start = cb->args[2], idx = 0;
int err;
err = nl80211_prepare_wdev_dump(skb, cb, &rdev, &wdev);
if (err)
return err;
wdev_lock(wdev);
spin_lock_bh(&rdev->bss_lock);
cfg80211_bss_expire(rdev);
cb->seq = rdev->bss_generation;
list_for_each_entry(scan, &rdev->bss_list, list) {
if (++idx <= start)
continue;
if (nl80211_send_bss(skb, cb,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
rdev, wdev, scan) < 0) {
idx--;
break;
}
}
spin_unlock_bh(&rdev->bss_lock);
wdev_unlock(wdev);
cb->args[2] = idx;
nl80211_finish_wdev_dump(rdev);
return skb->len;
}
static int nl80211_send_survey(struct sk_buff *msg, u32 portid, u32 seq,
int flags, struct net_device *dev,
struct survey_info *survey)
{
void *hdr;
struct nlattr *infoattr;
hdr = nl80211hdr_put(msg, portid, seq, flags,
NL80211_CMD_NEW_SURVEY_RESULTS);
if (!hdr)
return -ENOMEM;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex))
goto nla_put_failure;
infoattr = nla_nest_start(msg, NL80211_ATTR_SURVEY_INFO);
if (!infoattr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_SURVEY_INFO_FREQUENCY,
survey->channel->center_freq))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_NOISE_DBM) &&
nla_put_u8(msg, NL80211_SURVEY_INFO_NOISE, survey->noise))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_IN_USE) &&
nla_put_flag(msg, NL80211_SURVEY_INFO_IN_USE))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_CHANNEL_TIME) &&
nla_put_u64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME,
survey->channel_time))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_CHANNEL_TIME_BUSY) &&
nla_put_u64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_BUSY,
survey->channel_time_busy))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_CHANNEL_TIME_EXT_BUSY) &&
nla_put_u64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_EXT_BUSY,
survey->channel_time_ext_busy))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_CHANNEL_TIME_RX) &&
nla_put_u64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_RX,
survey->channel_time_rx))
goto nla_put_failure;
if ((survey->filled & SURVEY_INFO_CHANNEL_TIME_TX) &&
nla_put_u64(msg, NL80211_SURVEY_INFO_CHANNEL_TIME_TX,
survey->channel_time_tx))
goto nla_put_failure;
nla_nest_end(msg, infoattr);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int nl80211_dump_survey(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct survey_info survey;
struct cfg80211_registered_device *dev;
struct wireless_dev *wdev;
int survey_idx = cb->args[2];
int res;
res = nl80211_prepare_wdev_dump(skb, cb, &dev, &wdev);
if (res)
return res;
if (!wdev->netdev) {
res = -EINVAL;
goto out_err;
}
if (!dev->ops->dump_survey) {
res = -EOPNOTSUPP;
goto out_err;
}
while (1) {
struct ieee80211_channel *chan;
res = rdev_dump_survey(dev, wdev->netdev, survey_idx, &survey);
if (res == -ENOENT)
break;
if (res)
goto out_err;
/* Survey without a channel doesn't make sense */
if (!survey.channel) {
res = -EINVAL;
goto out;
}
chan = ieee80211_get_channel(&dev->wiphy,
survey.channel->center_freq);
if (!chan || chan->flags & IEEE80211_CHAN_DISABLED) {
survey_idx++;
continue;
}
if (nl80211_send_survey(skb,
NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
wdev->netdev, &survey) < 0)
goto out;
survey_idx++;
}
out:
cb->args[2] = survey_idx;
res = skb->len;
out_err:
nl80211_finish_wdev_dump(dev);
return res;
}
static bool nl80211_valid_wpa_versions(u32 wpa_versions)
{
return !(wpa_versions & ~(NL80211_WPA_VERSION_1 |
NL80211_WPA_VERSION_2));
}
static int nl80211_authenticate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
const u8 *bssid, *ssid, *ie = NULL, *sae_data = NULL;
int err, ssid_len, ie_len = 0, sae_data_len = 0;
enum nl80211_auth_type auth_type;
struct key_parse key;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_AUTH_TYPE])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
err = nl80211_parse_key(info, &key);
if (err)
return err;
if (key.idx >= 0) {
if (key.type != -1 && key.type != NL80211_KEYTYPE_GROUP)
return -EINVAL;
if (!key.p.key || !key.p.key_len)
return -EINVAL;
if ((key.p.cipher != WLAN_CIPHER_SUITE_WEP40 ||
key.p.key_len != WLAN_KEY_LEN_WEP40) &&
(key.p.cipher != WLAN_CIPHER_SUITE_WEP104 ||
key.p.key_len != WLAN_KEY_LEN_WEP104))
return -EINVAL;
if (key.idx > 4)
return -EINVAL;
} else {
key.p.key_len = 0;
key.p.key = NULL;
}
if (key.idx >= 0) {
int i;
bool ok = false;
for (i = 0; i < rdev->wiphy.n_cipher_suites; i++) {
if (key.p.cipher == rdev->wiphy.cipher_suites[i]) {
ok = true;
break;
}
}
if (!ok)
return -EINVAL;
}
if (!rdev->ops->auth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = nl80211_get_valid_chan(&rdev->wiphy,
info->attrs[NL80211_ATTR_WIPHY_FREQ]);
if (!chan)
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
auth_type = nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]);
if (!nl80211_valid_auth_type(rdev, auth_type, NL80211_CMD_AUTHENTICATE))
return -EINVAL;
if (auth_type == NL80211_AUTHTYPE_SAE &&
!info->attrs[NL80211_ATTR_SAE_DATA])
return -EINVAL;
if (info->attrs[NL80211_ATTR_SAE_DATA]) {
if (auth_type != NL80211_AUTHTYPE_SAE)
return -EINVAL;
sae_data = nla_data(info->attrs[NL80211_ATTR_SAE_DATA]);
sae_data_len = nla_len(info->attrs[NL80211_ATTR_SAE_DATA]);
/* need to include at least Auth Transaction and Status Code */
if (sae_data_len < 4)
return -EINVAL;
}
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
/*
* Since we no longer track auth state, ignore
* requests to only change local state.
*/
if (local_state_change)
return 0;
wdev_lock(dev->ieee80211_ptr);
err = cfg80211_mlme_auth(rdev, dev, chan, auth_type, bssid,
ssid, ssid_len, ie, ie_len,
key.p.key, key.p.key_len, key.idx,
sae_data, sae_data_len);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_crypto_settings(struct cfg80211_registered_device *rdev,
struct genl_info *info,
struct cfg80211_crypto_settings *settings,
int cipher_limit)
{
memset(settings, 0, sizeof(*settings));
settings->control_port = info->attrs[NL80211_ATTR_CONTROL_PORT];
if (info->attrs[NL80211_ATTR_CONTROL_PORT_ETHERTYPE]) {
u16 proto;
proto = nla_get_u16(
info->attrs[NL80211_ATTR_CONTROL_PORT_ETHERTYPE]);
settings->control_port_ethertype = cpu_to_be16(proto);
if (!(rdev->wiphy.flags & WIPHY_FLAG_CONTROL_PORT_PROTOCOL) &&
proto != ETH_P_PAE)
return -EINVAL;
if (info->attrs[NL80211_ATTR_CONTROL_PORT_NO_ENCRYPT])
settings->control_port_no_encrypt = true;
} else
settings->control_port_ethertype = cpu_to_be16(ETH_P_PAE);
if (info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]) {
void *data;
int len, i;
data = nla_data(info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]);
len = nla_len(info->attrs[NL80211_ATTR_CIPHER_SUITES_PAIRWISE]);
settings->n_ciphers_pairwise = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
if (settings->n_ciphers_pairwise > cipher_limit)
return -EINVAL;
memcpy(settings->ciphers_pairwise, data, len);
for (i = 0; i < settings->n_ciphers_pairwise; i++)
if (!cfg80211_supported_cipher_suite(
&rdev->wiphy,
settings->ciphers_pairwise[i]))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_CIPHER_SUITE_GROUP]) {
settings->cipher_group =
nla_get_u32(info->attrs[NL80211_ATTR_CIPHER_SUITE_GROUP]);
if (!cfg80211_supported_cipher_suite(&rdev->wiphy,
settings->cipher_group))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_WPA_VERSIONS]) {
settings->wpa_versions =
nla_get_u32(info->attrs[NL80211_ATTR_WPA_VERSIONS]);
if (!nl80211_valid_wpa_versions(settings->wpa_versions))
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_AKM_SUITES]) {
void *data;
int len;
data = nla_data(info->attrs[NL80211_ATTR_AKM_SUITES]);
len = nla_len(info->attrs[NL80211_ATTR_AKM_SUITES]);
settings->n_akm_suites = len / sizeof(u32);
if (len % sizeof(u32))
return -EINVAL;
if (settings->n_akm_suites > NL80211_MAX_NR_AKM_SUITES)
return -EINVAL;
memcpy(settings->akm_suites, data, len);
}
return 0;
}
static int nl80211_associate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct ieee80211_channel *chan;
struct cfg80211_assoc_request req = {};
const u8 *bssid, *ssid;
int err, ssid_len = 0;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC] ||
!info->attrs[NL80211_ATTR_SSID] ||
!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
if (!rdev->ops->assoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
chan = nl80211_get_valid_chan(&rdev->wiphy,
info->attrs[NL80211_ATTR_WIPHY_FREQ]);
if (!chan)
return -EINVAL;
ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
req.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
req.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[NL80211_ATTR_USE_MFP]) {
enum nl80211_mfp mfp =
nla_get_u32(info->attrs[NL80211_ATTR_USE_MFP]);
if (mfp == NL80211_MFP_REQUIRED)
req.use_mfp = true;
else if (mfp != NL80211_MFP_NO)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_PREV_BSSID])
req.prev_bssid = nla_data(info->attrs[NL80211_ATTR_PREV_BSSID]);
if (nla_get_flag(info->attrs[NL80211_ATTR_DISABLE_HT]))
req.flags |= ASSOC_REQ_DISABLE_HT;
if (info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK])
memcpy(&req.ht_capa_mask,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK]),
sizeof(req.ht_capa_mask));
if (info->attrs[NL80211_ATTR_HT_CAPABILITY]) {
if (!info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK])
return -EINVAL;
memcpy(&req.ht_capa,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]),
sizeof(req.ht_capa));
}
if (nla_get_flag(info->attrs[NL80211_ATTR_DISABLE_VHT]))
req.flags |= ASSOC_REQ_DISABLE_VHT;
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK])
memcpy(&req.vht_capa_mask,
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK]),
sizeof(req.vht_capa_mask));
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY]) {
if (!info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK])
return -EINVAL;
memcpy(&req.vht_capa,
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY]),
sizeof(req.vht_capa));
}
err = nl80211_crypto_settings(rdev, info, &req.crypto, 1);
if (!err) {
wdev_lock(dev->ieee80211_ptr);
err = cfg80211_mlme_assoc(rdev, dev, chan, bssid,
ssid, ssid_len, &req);
wdev_unlock(dev->ieee80211_ptr);
}
return err;
}
static int nl80211_deauthenticate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0, err;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
return -EINVAL;
if (!rdev->ops->deauth)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
wdev_lock(dev->ieee80211_ptr);
err = cfg80211_mlme_deauth(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static int nl80211_disassociate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
const u8 *ie = NULL, *bssid;
int ie_len = 0, err;
u16 reason_code;
bool local_state_change;
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
return -EINVAL;
if (!rdev->ops->disassoc)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
reason_code = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason_code == 0) {
/* Reason Code 0 is reserved */
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_IE]) {
ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
local_state_change = !!info->attrs[NL80211_ATTR_LOCAL_STATE_CHANGE];
wdev_lock(dev->ieee80211_ptr);
err = cfg80211_mlme_disassoc(rdev, dev, bssid, ie, ie_len, reason_code,
local_state_change);
wdev_unlock(dev->ieee80211_ptr);
return err;
}
static bool
nl80211_parse_mcast_rate(struct cfg80211_registered_device *rdev,
int mcast_rate[IEEE80211_NUM_BANDS],
int rateval)
{
struct wiphy *wiphy = &rdev->wiphy;
bool found = false;
int band, i;
for (band = 0; band < IEEE80211_NUM_BANDS; band++) {
struct ieee80211_supported_band *sband;
sband = wiphy->bands[band];
if (!sband)
continue;
for (i = 0; i < sband->n_bitrates; i++) {
if (sband->bitrates[i].bitrate == rateval) {
mcast_rate[band] = i + 1;
found = true;
break;
}
}
}
return found;
}
static int nl80211_join_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_ibss_params ibss;
struct wiphy *wiphy;
struct cfg80211_cached_keys *connkeys = NULL;
int err;
memset(&ibss, 0, sizeof(ibss));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
ibss.beacon_interval = 100;
if (info->attrs[NL80211_ATTR_BEACON_INTERVAL]) {
ibss.beacon_interval =
nla_get_u32(info->attrs[NL80211_ATTR_BEACON_INTERVAL]);
if (ibss.beacon_interval < 1 || ibss.beacon_interval > 10000)
return -EINVAL;
}
if (!rdev->ops->join_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
if (info->attrs[NL80211_ATTR_MAC]) {
ibss.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (!is_valid_ether_addr(ibss.bssid))
return -EINVAL;
}
ibss.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
ibss.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
ibss.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ibss.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
err = nl80211_parse_chandef(rdev, info, &ibss.chandef);
if (err)
return err;
if (!cfg80211_reg_can_beacon(&rdev->wiphy, &ibss.chandef))
return -EINVAL;
switch (ibss.chandef.width) {
case NL80211_CHAN_WIDTH_5:
case NL80211_CHAN_WIDTH_10:
case NL80211_CHAN_WIDTH_20_NOHT:
break;
case NL80211_CHAN_WIDTH_20:
case NL80211_CHAN_WIDTH_40:
if (rdev->wiphy.features & NL80211_FEATURE_HT_IBSS)
break;
default:
return -EINVAL;
}
ibss.channel_fixed = !!info->attrs[NL80211_ATTR_FREQ_FIXED];
ibss.privacy = !!info->attrs[NL80211_ATTR_PRIVACY];
if (info->attrs[NL80211_ATTR_BSS_BASIC_RATES]) {
u8 *rates =
nla_data(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
int n_rates =
nla_len(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
struct ieee80211_supported_band *sband =
wiphy->bands[ibss.chandef.chan->band];
err = ieee80211_get_ratemask(sband, rates, n_rates,
&ibss.basic_rates);
if (err)
return err;
}
if (info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK])
memcpy(&ibss.ht_capa_mask,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK]),
sizeof(ibss.ht_capa_mask));
if (info->attrs[NL80211_ATTR_HT_CAPABILITY]) {
if (!info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK])
return -EINVAL;
memcpy(&ibss.ht_capa,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]),
sizeof(ibss.ht_capa));
}
if (info->attrs[NL80211_ATTR_MCAST_RATE] &&
!nl80211_parse_mcast_rate(rdev, ibss.mcast_rate,
nla_get_u32(info->attrs[NL80211_ATTR_MCAST_RATE])))
return -EINVAL;
if (ibss.privacy && info->attrs[NL80211_ATTR_KEYS]) {
bool no_ht = false;
connkeys = nl80211_parse_connkeys(rdev,
info->attrs[NL80211_ATTR_KEYS],
&no_ht);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
if ((ibss.chandef.width != NL80211_CHAN_WIDTH_20_NOHT) &&
no_ht) {
kfree(connkeys);
return -EINVAL;
}
}
ibss.control_port =
nla_get_flag(info->attrs[NL80211_ATTR_CONTROL_PORT]);
ibss.userspace_handles_dfs =
nla_get_flag(info->attrs[NL80211_ATTR_HANDLE_DFS]);
err = cfg80211_join_ibss(rdev, dev, &ibss, connkeys);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_leave_ibss(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->leave_ibss)
return -EOPNOTSUPP;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC)
return -EOPNOTSUPP;
return cfg80211_leave_ibss(rdev, dev, false);
}
static int nl80211_set_mcast_rate(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
int mcast_rate[IEEE80211_NUM_BANDS];
u32 nla_rate;
int err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_ADHOC &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_MESH_POINT)
return -EOPNOTSUPP;
if (!rdev->ops->set_mcast_rate)
return -EOPNOTSUPP;
memset(mcast_rate, 0, sizeof(mcast_rate));
if (!info->attrs[NL80211_ATTR_MCAST_RATE])
return -EINVAL;
nla_rate = nla_get_u32(info->attrs[NL80211_ATTR_MCAST_RATE]);
if (!nl80211_parse_mcast_rate(rdev, mcast_rate, nla_rate))
return -EINVAL;
err = rdev->ops->set_mcast_rate(&rdev->wiphy, dev, mcast_rate);
return err;
}
static struct sk_buff *
__cfg80211_alloc_vendor_skb(struct cfg80211_registered_device *rdev,
int approxlen, u32 portid, u32 seq,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
const struct nl80211_vendor_cmd_info *info,
gfp_t gfp)
{
struct sk_buff *skb;
void *hdr;
struct nlattr *data;
skb = nlmsg_new(approxlen + 100, gfp);
if (!skb)
return NULL;
hdr = nl80211hdr_put(skb, portid, seq, 0, cmd);
if (!hdr) {
kfree_skb(skb);
return NULL;
}
if (nla_put_u32(skb, NL80211_ATTR_WIPHY, rdev->wiphy_idx))
goto nla_put_failure;
if (info) {
if (nla_put_u32(skb, NL80211_ATTR_VENDOR_ID,
info->vendor_id))
goto nla_put_failure;
if (nla_put_u32(skb, NL80211_ATTR_VENDOR_SUBCMD,
info->subcmd))
goto nla_put_failure;
}
data = nla_nest_start(skb, attr);
((void **)skb->cb)[0] = rdev;
((void **)skb->cb)[1] = hdr;
((void **)skb->cb)[2] = data;
return skb;
nla_put_failure:
kfree_skb(skb);
return NULL;
}
struct sk_buff *__cfg80211_alloc_event_skb(struct wiphy *wiphy,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
int vendor_event_idx,
int approxlen, gfp_t gfp)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
const struct nl80211_vendor_cmd_info *info;
switch (cmd) {
case NL80211_CMD_TESTMODE:
if (WARN_ON(vendor_event_idx != -1))
return NULL;
info = NULL;
break;
case NL80211_CMD_VENDOR:
if (WARN_ON(vendor_event_idx < 0 ||
vendor_event_idx >= wiphy->n_vendor_events))
return NULL;
info = &wiphy->vendor_events[vendor_event_idx];
break;
default:
WARN_ON(1);
return NULL;
}
return __cfg80211_alloc_vendor_skb(rdev, approxlen, 0, 0,
cmd, attr, info, gfp);
}
EXPORT_SYMBOL(__cfg80211_alloc_event_skb);
void __cfg80211_send_event_skb(struct sk_buff *skb, gfp_t gfp)
{
struct cfg80211_registered_device *rdev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
enum nl80211_multicast_groups mcgrp = NL80211_MCGRP_TESTMODE;
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
if (data->nla_type == NL80211_ATTR_VENDOR_DATA)
mcgrp = NL80211_MCGRP_VENDOR;
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), skb, 0,
mcgrp, gfp);
}
EXPORT_SYMBOL(__cfg80211_send_event_skb);
#ifdef CONFIG_NL80211_TESTMODE
static int nl80211_testmode_do(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev =
__cfg80211_wdev_from_attrs(genl_info_net(info), info->attrs);
int err;
if (!rdev->ops->testmode_cmd)
return -EOPNOTSUPP;
if (IS_ERR(wdev)) {
err = PTR_ERR(wdev);
if (err != -EINVAL)
return err;
wdev = NULL;
} else if (wdev->wiphy != &rdev->wiphy) {
return -EINVAL;
}
if (!info->attrs[NL80211_ATTR_TESTDATA])
return -EINVAL;
rdev->cur_cmd_info = info;
err = rdev_testmode_cmd(rdev, wdev,
nla_data(info->attrs[NL80211_ATTR_TESTDATA]),
nla_len(info->attrs[NL80211_ATTR_TESTDATA]));
rdev->cur_cmd_info = NULL;
return err;
}
static int nl80211_testmode_dump(struct sk_buff *skb,
struct netlink_callback *cb)
{
struct cfg80211_registered_device *rdev;
int err;
long phy_idx;
void *data = NULL;
int data_len = 0;
rtnl_lock();
if (cb->args[0]) {
/*
* 0 is a valid index, but not valid for args[0],
* so we need to offset by 1.
*/
phy_idx = cb->args[0] - 1;
} else {
err = nlmsg_parse(cb->nlh, GENL_HDRLEN + nl80211_fam.hdrsize,
nl80211_fam.attrbuf, nl80211_fam.maxattr,
nl80211_policy);
if (err)
goto out_err;
rdev = __cfg80211_rdev_from_attrs(sock_net(skb->sk),
nl80211_fam.attrbuf);
if (IS_ERR(rdev)) {
err = PTR_ERR(rdev);
goto out_err;
}
phy_idx = rdev->wiphy_idx;
rdev = NULL;
if (nl80211_fam.attrbuf[NL80211_ATTR_TESTDATA])
cb->args[1] =
(long)nl80211_fam.attrbuf[NL80211_ATTR_TESTDATA];
}
if (cb->args[1]) {
data = nla_data((void *)cb->args[1]);
data_len = nla_len((void *)cb->args[1]);
}
rdev = cfg80211_rdev_by_wiphy_idx(phy_idx);
if (!rdev) {
err = -ENOENT;
goto out_err;
}
if (!rdev->ops->testmode_dump) {
err = -EOPNOTSUPP;
goto out_err;
}
while (1) {
void *hdr = nl80211hdr_put(skb, NETLINK_CB(cb->skb).portid,
cb->nlh->nlmsg_seq, NLM_F_MULTI,
NL80211_CMD_TESTMODE);
struct nlattr *tmdata;
if (!hdr)
break;
if (nla_put_u32(skb, NL80211_ATTR_WIPHY, phy_idx)) {
genlmsg_cancel(skb, hdr);
break;
}
tmdata = nla_nest_start(skb, NL80211_ATTR_TESTDATA);
if (!tmdata) {
genlmsg_cancel(skb, hdr);
break;
}
err = rdev_testmode_dump(rdev, skb, cb, data, data_len);
nla_nest_end(skb, tmdata);
if (err == -ENOBUFS || err == -ENOENT) {
genlmsg_cancel(skb, hdr);
break;
} else if (err) {
genlmsg_cancel(skb, hdr);
goto out_err;
}
genlmsg_end(skb, hdr);
}
err = skb->len;
/* see above */
cb->args[0] = phy_idx + 1;
out_err:
rtnl_unlock();
return err;
}
#endif
static int nl80211_connect(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct cfg80211_connect_params connect;
struct wiphy *wiphy;
struct cfg80211_cached_keys *connkeys = NULL;
int err;
memset(&connect, 0, sizeof(connect));
if (!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
if (!info->attrs[NL80211_ATTR_SSID] ||
!nla_len(info->attrs[NL80211_ATTR_SSID]))
return -EINVAL;
if (info->attrs[NL80211_ATTR_AUTH_TYPE]) {
connect.auth_type =
nla_get_u32(info->attrs[NL80211_ATTR_AUTH_TYPE]);
if (!nl80211_valid_auth_type(rdev, connect.auth_type,
NL80211_CMD_CONNECT))
return -EINVAL;
} else
connect.auth_type = NL80211_AUTHTYPE_AUTOMATIC;
connect.privacy = info->attrs[NL80211_ATTR_PRIVACY];
err = nl80211_crypto_settings(rdev, info, &connect.crypto,
NL80211_MAX_NR_CIPHER_SUITES);
if (err)
return err;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
wiphy = &rdev->wiphy;
connect.bg_scan_period = -1;
if (info->attrs[NL80211_ATTR_BG_SCAN_PERIOD] &&
(wiphy->flags & WIPHY_FLAG_SUPPORTS_FW_ROAM)) {
connect.bg_scan_period =
nla_get_u16(info->attrs[NL80211_ATTR_BG_SCAN_PERIOD]);
}
if (info->attrs[NL80211_ATTR_MAC])
connect.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
else if (info->attrs[NL80211_ATTR_MAC_HINT])
connect.bssid_hint =
nla_data(info->attrs[NL80211_ATTR_MAC_HINT]);
connect.ssid = nla_data(info->attrs[NL80211_ATTR_SSID]);
connect.ssid_len = nla_len(info->attrs[NL80211_ATTR_SSID]);
if (info->attrs[NL80211_ATTR_IE]) {
connect.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
connect.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
}
if (info->attrs[NL80211_ATTR_USE_MFP]) {
connect.mfp = nla_get_u32(info->attrs[NL80211_ATTR_USE_MFP]);
if (connect.mfp != NL80211_MFP_REQUIRED &&
connect.mfp != NL80211_MFP_NO)
return -EINVAL;
} else {
connect.mfp = NL80211_MFP_NO;
}
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
connect.channel = nl80211_get_valid_chan(
wiphy, info->attrs[NL80211_ATTR_WIPHY_FREQ]);
if (!connect.channel)
return -EINVAL;
} else if (info->attrs[NL80211_ATTR_WIPHY_FREQ_HINT]) {
connect.channel_hint = nl80211_get_valid_chan(
wiphy, info->attrs[NL80211_ATTR_WIPHY_FREQ_HINT]);
if (!connect.channel_hint)
return -EINVAL;
}
if (connect.privacy && info->attrs[NL80211_ATTR_KEYS]) {
connkeys = nl80211_parse_connkeys(rdev,
info->attrs[NL80211_ATTR_KEYS], NULL);
if (IS_ERR(connkeys))
return PTR_ERR(connkeys);
}
if (nla_get_flag(info->attrs[NL80211_ATTR_DISABLE_HT]))
connect.flags |= ASSOC_REQ_DISABLE_HT;
if (info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK])
memcpy(&connect.ht_capa_mask,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK]),
sizeof(connect.ht_capa_mask));
if (info->attrs[NL80211_ATTR_HT_CAPABILITY]) {
if (!info->attrs[NL80211_ATTR_HT_CAPABILITY_MASK]) {
kfree(connkeys);
return -EINVAL;
}
memcpy(&connect.ht_capa,
nla_data(info->attrs[NL80211_ATTR_HT_CAPABILITY]),
sizeof(connect.ht_capa));
}
if (nla_get_flag(info->attrs[NL80211_ATTR_DISABLE_VHT]))
connect.flags |= ASSOC_REQ_DISABLE_VHT;
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK])
memcpy(&connect.vht_capa_mask,
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK]),
sizeof(connect.vht_capa_mask));
if (info->attrs[NL80211_ATTR_VHT_CAPABILITY]) {
if (!info->attrs[NL80211_ATTR_VHT_CAPABILITY_MASK]) {
kfree(connkeys);
return -EINVAL;
}
memcpy(&connect.vht_capa,
nla_data(info->attrs[NL80211_ATTR_VHT_CAPABILITY]),
sizeof(connect.vht_capa));
}
wdev_lock(dev->ieee80211_ptr);
err = cfg80211_connect(rdev, dev, &connect, connkeys, NULL);
wdev_unlock(dev->ieee80211_ptr);
if (err)
kfree(connkeys);
return err;
}
static int nl80211_disconnect(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u16 reason;
int ret;
if (!info->attrs[NL80211_ATTR_REASON_CODE])
reason = WLAN_REASON_DEAUTH_LEAVING;
else
reason = nla_get_u16(info->attrs[NL80211_ATTR_REASON_CODE]);
if (reason == 0)
return -EINVAL;
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
wdev_lock(dev->ieee80211_ptr);
ret = cfg80211_disconnect(rdev, dev, reason, true);
wdev_unlock(dev->ieee80211_ptr);
return ret;
}
static int nl80211_wiphy_netns(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net *net;
int err;
u32 pid;
if (!info->attrs[NL80211_ATTR_PID])
return -EINVAL;
pid = nla_get_u32(info->attrs[NL80211_ATTR_PID]);
net = get_net_ns_by_pid(pid);
if (IS_ERR(net))
return PTR_ERR(net);
err = 0;
/* check if anything to do */
if (!net_eq(wiphy_net(&rdev->wiphy), net))
err = cfg80211_switch_netns(rdev, net);
put_net(net);
return err;
}
static int nl80211_setdel_pmksa(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
int (*rdev_ops)(struct wiphy *wiphy, struct net_device *dev,
struct cfg80211_pmksa *pmksa) = NULL;
struct net_device *dev = info->user_ptr[1];
struct cfg80211_pmksa pmksa;
memset(&pmksa, 0, sizeof(struct cfg80211_pmksa));
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!info->attrs[NL80211_ATTR_PMKID])
return -EINVAL;
pmksa.pmkid = nla_data(info->attrs[NL80211_ATTR_PMKID]);
pmksa.bssid = nla_data(info->attrs[NL80211_ATTR_MAC]);
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
switch (info->genlhdr->cmd) {
case NL80211_CMD_SET_PMKSA:
rdev_ops = rdev->ops->set_pmksa;
break;
case NL80211_CMD_DEL_PMKSA:
rdev_ops = rdev->ops->del_pmksa;
break;
default:
WARN_ON(1);
break;
}
if (!rdev_ops)
return -EOPNOTSUPP;
return rdev_ops(&rdev->wiphy, dev, &pmksa);
}
static int nl80211_flush_pmksa(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
if (dev->ieee80211_ptr->iftype != NL80211_IFTYPE_STATION &&
dev->ieee80211_ptr->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
if (!rdev->ops->flush_pmksa)
return -EOPNOTSUPP;
return rdev_flush_pmksa(rdev, dev);
}
static int nl80211_tdls_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
u8 action_code, dialog_token;
u32 peer_capability = 0;
u16 status_code;
u8 *peer;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_TDLS) ||
!rdev->ops->tdls_mgmt)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_TDLS_ACTION] ||
!info->attrs[NL80211_ATTR_STATUS_CODE] ||
!info->attrs[NL80211_ATTR_TDLS_DIALOG_TOKEN] ||
!info->attrs[NL80211_ATTR_IE] ||
!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
peer = nla_data(info->attrs[NL80211_ATTR_MAC]);
action_code = nla_get_u8(info->attrs[NL80211_ATTR_TDLS_ACTION]);
status_code = nla_get_u16(info->attrs[NL80211_ATTR_STATUS_CODE]);
dialog_token = nla_get_u8(info->attrs[NL80211_ATTR_TDLS_DIALOG_TOKEN]);
if (info->attrs[NL80211_ATTR_TDLS_PEER_CAPABILITY])
peer_capability =
nla_get_u32(info->attrs[NL80211_ATTR_TDLS_PEER_CAPABILITY]);
return rdev_tdls_mgmt(rdev, dev, peer, action_code,
dialog_token, status_code, peer_capability,
nla_data(info->attrs[NL80211_ATTR_IE]),
nla_len(info->attrs[NL80211_ATTR_IE]));
}
static int nl80211_tdls_oper(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
enum nl80211_tdls_operation operation;
u8 *peer;
if (!(rdev->wiphy.flags & WIPHY_FLAG_SUPPORTS_TDLS) ||
!rdev->ops->tdls_oper)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_TDLS_OPERATION] ||
!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
operation = nla_get_u8(info->attrs[NL80211_ATTR_TDLS_OPERATION]);
peer = nla_data(info->attrs[NL80211_ATTR_MAC]);
return rdev_tdls_oper(rdev, dev, peer, operation);
}
static int nl80211_remain_on_channel(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
struct cfg80211_chan_def chandef;
struct sk_buff *msg;
void *hdr;
u64 cookie;
u32 duration;
int err;
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ] ||
!info->attrs[NL80211_ATTR_DURATION])
return -EINVAL;
duration = nla_get_u32(info->attrs[NL80211_ATTR_DURATION]);
if (!rdev->ops->remain_on_channel ||
!(rdev->wiphy.flags & WIPHY_FLAG_HAS_REMAIN_ON_CHANNEL))
return -EOPNOTSUPP;
/*
* We should be on that channel for at least a minimum amount of
* time (10ms) but no longer than the driver supports.
*/
if (duration < NL80211_MIN_REMAIN_ON_CHANNEL_TIME ||
duration > rdev->wiphy.max_remain_on_channel_duration)
return -EINVAL;
err = nl80211_parse_chandef(rdev, info, &chandef);
if (err)
return err;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_REMAIN_ON_CHANNEL);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
err = rdev_remain_on_channel(rdev, wdev, chandef.chan,
duration, &cookie);
if (err)
goto free_msg;
if (nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_cancel_remain_on_channel(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops->cancel_remain_on_channel)
return -EOPNOTSUPP;
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev_cancel_remain_on_channel(rdev, wdev, cookie);
}
static u32 rateset_to_mask(struct ieee80211_supported_band *sband,
u8 *rates, u8 rates_len)
{
u8 i;
u32 mask = 0;
for (i = 0; i < rates_len; i++) {
int rate = (rates[i] & 0x7f) * 5;
int ridx;
for (ridx = 0; ridx < sband->n_bitrates; ridx++) {
struct ieee80211_rate *srate =
&sband->bitrates[ridx];
if (rate == srate->bitrate) {
mask |= 1 << ridx;
break;
}
}
if (ridx == sband->n_bitrates)
return 0; /* rate not found */
}
return mask;
}
static bool ht_rateset_to_mask(struct ieee80211_supported_band *sband,
u8 *rates, u8 rates_len,
u8 mcs[IEEE80211_HT_MCS_MASK_LEN])
{
u8 i;
memset(mcs, 0, IEEE80211_HT_MCS_MASK_LEN);
for (i = 0; i < rates_len; i++) {
int ridx, rbit;
ridx = rates[i] / 8;
rbit = BIT(rates[i] % 8);
/* check validity */
if ((ridx < 0) || (ridx >= IEEE80211_HT_MCS_MASK_LEN))
return false;
/* check availability */
if (sband->ht_cap.mcs.rx_mask[ridx] & rbit)
mcs[ridx] |= rbit;
else
return false;
}
return true;
}
static u16 vht_mcs_map_to_mcs_mask(u8 vht_mcs_map)
{
u16 mcs_mask = 0;
switch (vht_mcs_map) {
case IEEE80211_VHT_MCS_NOT_SUPPORTED:
break;
case IEEE80211_VHT_MCS_SUPPORT_0_7:
mcs_mask = 0x00FF;
break;
case IEEE80211_VHT_MCS_SUPPORT_0_8:
mcs_mask = 0x01FF;
break;
case IEEE80211_VHT_MCS_SUPPORT_0_9:
mcs_mask = 0x03FF;
break;
default:
break;
}
return mcs_mask;
}
static void vht_build_mcs_mask(u16 vht_mcs_map,
u16 vht_mcs_mask[NL80211_VHT_NSS_MAX])
{
u8 nss;
for (nss = 0; nss < NL80211_VHT_NSS_MAX; nss++) {
vht_mcs_mask[nss] = vht_mcs_map_to_mcs_mask(vht_mcs_map & 0x03);
vht_mcs_map >>= 2;
}
}
static bool vht_set_mcs_mask(struct ieee80211_supported_band *sband,
struct nl80211_txrate_vht *txrate,
u16 mcs[NL80211_VHT_NSS_MAX])
{
u16 tx_mcs_map = le16_to_cpu(sband->vht_cap.vht_mcs.tx_mcs_map);
u16 tx_mcs_mask[NL80211_VHT_NSS_MAX] = {};
u8 i;
if (!sband->vht_cap.vht_supported)
return false;
memset(mcs, 0, sizeof(u16) * NL80211_VHT_NSS_MAX);
/* Build vht_mcs_mask from VHT capabilities */
vht_build_mcs_mask(tx_mcs_map, tx_mcs_mask);
for (i = 0; i < NL80211_VHT_NSS_MAX; i++) {
if ((tx_mcs_mask[i] & txrate->mcs[i]) == txrate->mcs[i])
mcs[i] = txrate->mcs[i];
else
return false;
}
return true;
}
static const struct nla_policy nl80211_txattr_policy[NL80211_TXRATE_MAX + 1] = {
[NL80211_TXRATE_LEGACY] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_RATES },
[NL80211_TXRATE_HT] = { .type = NLA_BINARY,
.len = NL80211_MAX_SUPP_HT_RATES },
[NL80211_TXRATE_VHT] = { .len = sizeof(struct nl80211_txrate_vht)},
[NL80211_TXRATE_GI] = { .type = NLA_U8 },
};
static int nl80211_set_tx_bitrate_mask(struct sk_buff *skb,
struct genl_info *info)
{
struct nlattr *tb[NL80211_TXRATE_MAX + 1];
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct cfg80211_bitrate_mask mask;
int rem, i;
struct net_device *dev = info->user_ptr[1];
struct nlattr *tx_rates;
struct ieee80211_supported_band *sband;
u16 vht_tx_mcs_map;
if (!rdev->ops->set_bitrate_mask)
return -EOPNOTSUPP;
memset(&mask, 0, sizeof(mask));
/* Default to all rates enabled */
for (i = 0; i < IEEE80211_NUM_BANDS; i++) {
sband = rdev->wiphy.bands[i];
if (!sband)
continue;
mask.control[i].legacy = (1 << sband->n_bitrates) - 1;
memcpy(mask.control[i].ht_mcs,
sband->ht_cap.mcs.rx_mask,
sizeof(mask.control[i].ht_mcs));
if (!sband->vht_cap.vht_supported)
continue;
vht_tx_mcs_map = le16_to_cpu(sband->vht_cap.vht_mcs.tx_mcs_map);
vht_build_mcs_mask(vht_tx_mcs_map, mask.control[i].vht_mcs);
}
/* if no rates are given set it back to the defaults */
if (!info->attrs[NL80211_ATTR_TX_RATES])
goto out;
/*
* The nested attribute uses enum nl80211_band as the index. This maps
* directly to the enum ieee80211_band values used in cfg80211.
*/
BUILD_BUG_ON(NL80211_MAX_SUPP_HT_RATES > IEEE80211_HT_MCS_MASK_LEN * 8);
nla_for_each_nested(tx_rates, info->attrs[NL80211_ATTR_TX_RATES], rem) {
enum ieee80211_band band = nla_type(tx_rates);
int err;
if (band < 0 || band >= IEEE80211_NUM_BANDS)
return -EINVAL;
sband = rdev->wiphy.bands[band];
if (sband == NULL)
return -EINVAL;
err = nla_parse(tb, NL80211_TXRATE_MAX, nla_data(tx_rates),
nla_len(tx_rates), nl80211_txattr_policy);
if (err)
return err;
if (tb[NL80211_TXRATE_LEGACY]) {
mask.control[band].legacy = rateset_to_mask(
sband,
nla_data(tb[NL80211_TXRATE_LEGACY]),
nla_len(tb[NL80211_TXRATE_LEGACY]));
if ((mask.control[band].legacy == 0) &&
nla_len(tb[NL80211_TXRATE_LEGACY]))
return -EINVAL;
}
if (tb[NL80211_TXRATE_HT]) {
if (!ht_rateset_to_mask(
sband,
nla_data(tb[NL80211_TXRATE_HT]),
nla_len(tb[NL80211_TXRATE_HT]),
mask.control[band].ht_mcs))
return -EINVAL;
}
if (tb[NL80211_TXRATE_VHT]) {
if (!vht_set_mcs_mask(
sband,
nla_data(tb[NL80211_TXRATE_VHT]),
mask.control[band].vht_mcs))
return -EINVAL;
}
if (tb[NL80211_TXRATE_GI]) {
mask.control[band].gi =
nla_get_u8(tb[NL80211_TXRATE_GI]);
if (mask.control[band].gi > NL80211_TXRATE_FORCE_LGI)
return -EINVAL;
}
if (mask.control[band].legacy == 0) {
/* don't allow empty legacy rates if HT or VHT
* are not even supported.
*/
if (!(rdev->wiphy.bands[band]->ht_cap.ht_supported ||
rdev->wiphy.bands[band]->vht_cap.vht_supported))
return -EINVAL;
for (i = 0; i < IEEE80211_HT_MCS_MASK_LEN; i++)
if (mask.control[band].ht_mcs[i])
goto out;
for (i = 0; i < NL80211_VHT_NSS_MAX; i++)
if (mask.control[band].vht_mcs[i])
goto out;
/* legacy and mcs rates may not be both empty */
return -EINVAL;
}
}
out:
return rdev_set_bitrate_mask(rdev, dev, NULL, &mask);
}
static int nl80211_register_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
u16 frame_type = IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_ACTION;
if (!info->attrs[NL80211_ATTR_FRAME_MATCH])
return -EINVAL;
if (info->attrs[NL80211_ATTR_FRAME_TYPE])
frame_type = nla_get_u16(info->attrs[NL80211_ATTR_FRAME_TYPE]);
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_MESH_POINT:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
break;
default:
return -EOPNOTSUPP;
}
/* not much point in registering if we can't reply */
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
return cfg80211_mlme_register_mgmt(wdev, info->snd_portid, frame_type,
nla_data(info->attrs[NL80211_ATTR_FRAME_MATCH]),
nla_len(info->attrs[NL80211_ATTR_FRAME_MATCH]));
}
static int nl80211_tx_mgmt(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
struct cfg80211_chan_def chandef;
int err;
void *hdr = NULL;
u64 cookie;
struct sk_buff *msg = NULL;
struct cfg80211_mgmt_tx_params params = {
.dont_wait_for_ack =
info->attrs[NL80211_ATTR_DONT_WAIT_FOR_ACK],
};
if (!info->attrs[NL80211_ATTR_FRAME])
return -EINVAL;
if (!rdev->ops->mgmt_tx)
return -EOPNOTSUPP;
switch (wdev->iftype) {
case NL80211_IFTYPE_P2P_DEVICE:
if (!info->attrs[NL80211_ATTR_WIPHY_FREQ])
return -EINVAL;
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_MESH_POINT:
case NL80211_IFTYPE_P2P_GO:
break;
default:
return -EOPNOTSUPP;
}
if (info->attrs[NL80211_ATTR_DURATION]) {
if (!(rdev->wiphy.flags & WIPHY_FLAG_OFFCHAN_TX))
return -EINVAL;
params.wait = nla_get_u32(info->attrs[NL80211_ATTR_DURATION]);
/*
* We should wait on the channel for at least a minimum amount
* of time (10ms) but no longer than the driver supports.
*/
if (params.wait < NL80211_MIN_REMAIN_ON_CHANNEL_TIME ||
params.wait > rdev->wiphy.max_remain_on_channel_duration)
return -EINVAL;
}
params.offchan = info->attrs[NL80211_ATTR_OFFCHANNEL_TX_OK];
if (params.offchan && !(rdev->wiphy.flags & WIPHY_FLAG_OFFCHAN_TX))
return -EINVAL;
params.no_cck = nla_get_flag(info->attrs[NL80211_ATTR_TX_NO_CCK_RATE]);
/* get the channel if any has been specified, otherwise pass NULL to
* the driver. The latter will use the current one
*/
chandef.chan = NULL;
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
err = nl80211_parse_chandef(rdev, info, &chandef);
if (err)
return err;
}
if (!chandef.chan && params.offchan)
return -EINVAL;
if (!params.dont_wait_for_ack) {
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_FRAME);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
}
params.buf = nla_data(info->attrs[NL80211_ATTR_FRAME]);
params.len = nla_len(info->attrs[NL80211_ATTR_FRAME]);
params.chan = chandef.chan;
err = cfg80211_mlme_mgmt_tx(rdev, wdev, ¶ms, &cookie);
if (err)
goto free_msg;
if (msg) {
if (nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
}
return 0;
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_tx_mgmt_cancel_wait(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
u64 cookie;
if (!info->attrs[NL80211_ATTR_COOKIE])
return -EINVAL;
if (!rdev->ops->mgmt_tx_cancel_wait)
return -EOPNOTSUPP;
switch (wdev->iftype) {
case NL80211_IFTYPE_STATION:
case NL80211_IFTYPE_ADHOC:
case NL80211_IFTYPE_P2P_CLIENT:
case NL80211_IFTYPE_AP:
case NL80211_IFTYPE_AP_VLAN:
case NL80211_IFTYPE_P2P_GO:
case NL80211_IFTYPE_P2P_DEVICE:
break;
default:
return -EOPNOTSUPP;
}
cookie = nla_get_u64(info->attrs[NL80211_ATTR_COOKIE]);
return rdev_mgmt_tx_cancel_wait(rdev, wdev, cookie);
}
static int nl80211_set_power_save(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
u8 ps_state;
bool state;
int err;
if (!info->attrs[NL80211_ATTR_PS_STATE])
return -EINVAL;
ps_state = nla_get_u32(info->attrs[NL80211_ATTR_PS_STATE]);
if (ps_state != NL80211_PS_DISABLED && ps_state != NL80211_PS_ENABLED)
return -EINVAL;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
state = (ps_state == NL80211_PS_ENABLED) ? true : false;
if (state == wdev->ps)
return 0;
err = rdev_set_power_mgmt(rdev, dev, state, wdev->ps_timeout);
if (!err)
wdev->ps = state;
return err;
}
static int nl80211_get_power_save(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
enum nl80211_ps_state ps_state;
struct wireless_dev *wdev;
struct net_device *dev = info->user_ptr[1];
struct sk_buff *msg;
void *hdr;
int err;
wdev = dev->ieee80211_ptr;
if (!rdev->ops->set_power_mgmt)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_POWER_SAVE);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
if (wdev->ps)
ps_state = NL80211_PS_ENABLED;
else
ps_state = NL80211_PS_DISABLED;
if (nla_put_u32(msg, NL80211_ATTR_PS_STATE, ps_state))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static const struct nla_policy
nl80211_attr_cqm_policy[NL80211_ATTR_CQM_MAX + 1] = {
[NL80211_ATTR_CQM_RSSI_THOLD] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_RSSI_HYST] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_TXE_RATE] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_TXE_PKTS] = { .type = NLA_U32 },
[NL80211_ATTR_CQM_TXE_INTVL] = { .type = NLA_U32 },
};
static int nl80211_set_cqm_txe(struct genl_info *info,
u32 rate, u32 pkts, u32 intvl)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (rate > 100 || intvl > NL80211_CQM_TXE_MAX_INTVL)
return -EINVAL;
if (!rdev->ops->set_cqm_txe_config)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
return rdev_set_cqm_txe_config(rdev, dev, rate, pkts, intvl);
}
static int nl80211_set_cqm_rssi(struct genl_info *info,
s32 threshold, u32 hysteresis)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (threshold > 0)
return -EINVAL;
/* disabling - hysteresis should also be zero then */
if (threshold == 0)
hysteresis = 0;
if (!rdev->ops->set_cqm_rssi_config)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_STATION &&
wdev->iftype != NL80211_IFTYPE_P2P_CLIENT)
return -EOPNOTSUPP;
return rdev_set_cqm_rssi_config(rdev, dev, threshold, hysteresis);
}
static int nl80211_set_cqm(struct sk_buff *skb, struct genl_info *info)
{
struct nlattr *attrs[NL80211_ATTR_CQM_MAX + 1];
struct nlattr *cqm;
int err;
cqm = info->attrs[NL80211_ATTR_CQM];
if (!cqm)
return -EINVAL;
err = nla_parse_nested(attrs, NL80211_ATTR_CQM_MAX, cqm,
nl80211_attr_cqm_policy);
if (err)
return err;
if (attrs[NL80211_ATTR_CQM_RSSI_THOLD] &&
attrs[NL80211_ATTR_CQM_RSSI_HYST]) {
s32 threshold = nla_get_s32(attrs[NL80211_ATTR_CQM_RSSI_THOLD]);
u32 hysteresis = nla_get_u32(attrs[NL80211_ATTR_CQM_RSSI_HYST]);
return nl80211_set_cqm_rssi(info, threshold, hysteresis);
}
if (attrs[NL80211_ATTR_CQM_TXE_RATE] &&
attrs[NL80211_ATTR_CQM_TXE_PKTS] &&
attrs[NL80211_ATTR_CQM_TXE_INTVL]) {
u32 rate = nla_get_u32(attrs[NL80211_ATTR_CQM_TXE_RATE]);
u32 pkts = nla_get_u32(attrs[NL80211_ATTR_CQM_TXE_PKTS]);
u32 intvl = nla_get_u32(attrs[NL80211_ATTR_CQM_TXE_INTVL]);
return nl80211_set_cqm_txe(info, rate, pkts, intvl);
}
return -EINVAL;
}
static int nl80211_join_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct mesh_config cfg;
struct mesh_setup setup;
int err;
/* start with default */
memcpy(&cfg, &default_mesh_config, sizeof(cfg));
memcpy(&setup, &default_mesh_setup, sizeof(setup));
if (info->attrs[NL80211_ATTR_MESH_CONFIG]) {
/* and parse parameters if given */
err = nl80211_parse_mesh_config(info, &cfg, NULL);
if (err)
return err;
}
if (!info->attrs[NL80211_ATTR_MESH_ID] ||
!nla_len(info->attrs[NL80211_ATTR_MESH_ID]))
return -EINVAL;
setup.mesh_id = nla_data(info->attrs[NL80211_ATTR_MESH_ID]);
setup.mesh_id_len = nla_len(info->attrs[NL80211_ATTR_MESH_ID]);
if (info->attrs[NL80211_ATTR_MCAST_RATE] &&
!nl80211_parse_mcast_rate(rdev, setup.mcast_rate,
nla_get_u32(info->attrs[NL80211_ATTR_MCAST_RATE])))
return -EINVAL;
if (info->attrs[NL80211_ATTR_BEACON_INTERVAL]) {
setup.beacon_interval =
nla_get_u32(info->attrs[NL80211_ATTR_BEACON_INTERVAL]);
if (setup.beacon_interval < 10 ||
setup.beacon_interval > 10000)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_DTIM_PERIOD]) {
setup.dtim_period =
nla_get_u32(info->attrs[NL80211_ATTR_DTIM_PERIOD]);
if (setup.dtim_period < 1 || setup.dtim_period > 100)
return -EINVAL;
}
if (info->attrs[NL80211_ATTR_MESH_SETUP]) {
/* parse additional setup parameters if given */
err = nl80211_parse_mesh_setup(info, &setup);
if (err)
return err;
}
if (setup.user_mpm)
cfg.auto_open_plinks = false;
if (info->attrs[NL80211_ATTR_WIPHY_FREQ]) {
err = nl80211_parse_chandef(rdev, info, &setup.chandef);
if (err)
return err;
} else {
/* cfg80211_join_mesh() will sort it out */
setup.chandef.chan = NULL;
}
if (info->attrs[NL80211_ATTR_BSS_BASIC_RATES]) {
u8 *rates = nla_data(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
int n_rates =
nla_len(info->attrs[NL80211_ATTR_BSS_BASIC_RATES]);
struct ieee80211_supported_band *sband;
if (!setup.chandef.chan)
return -EINVAL;
sband = rdev->wiphy.bands[setup.chandef.chan->band];
err = ieee80211_get_ratemask(sband, rates, n_rates,
&setup.basic_rates);
if (err)
return err;
}
return cfg80211_join_mesh(rdev, dev, &setup, &cfg);
}
static int nl80211_leave_mesh(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
return cfg80211_leave_mesh(rdev, dev);
}
#ifdef CONFIG_PM
static int nl80211_send_wowlan_patterns(struct sk_buff *msg,
struct cfg80211_registered_device *rdev)
{
struct cfg80211_wowlan *wowlan = rdev->wiphy.wowlan_config;
struct nlattr *nl_pats, *nl_pat;
int i, pat_len;
if (!wowlan->n_patterns)
return 0;
nl_pats = nla_nest_start(msg, NL80211_WOWLAN_TRIG_PKT_PATTERN);
if (!nl_pats)
return -ENOBUFS;
for (i = 0; i < wowlan->n_patterns; i++) {
nl_pat = nla_nest_start(msg, i + 1);
if (!nl_pat)
return -ENOBUFS;
pat_len = wowlan->patterns[i].pattern_len;
if (nla_put(msg, NL80211_PKTPAT_MASK, DIV_ROUND_UP(pat_len, 8),
wowlan->patterns[i].mask) ||
nla_put(msg, NL80211_PKTPAT_PATTERN, pat_len,
wowlan->patterns[i].pattern) ||
nla_put_u32(msg, NL80211_PKTPAT_OFFSET,
wowlan->patterns[i].pkt_offset))
return -ENOBUFS;
nla_nest_end(msg, nl_pat);
}
nla_nest_end(msg, nl_pats);
return 0;
}
static int nl80211_send_wowlan_tcp(struct sk_buff *msg,
struct cfg80211_wowlan_tcp *tcp)
{
struct nlattr *nl_tcp;
if (!tcp)
return 0;
nl_tcp = nla_nest_start(msg, NL80211_WOWLAN_TRIG_TCP_CONNECTION);
if (!nl_tcp)
return -ENOBUFS;
if (nla_put_be32(msg, NL80211_WOWLAN_TCP_SRC_IPV4, tcp->src) ||
nla_put_be32(msg, NL80211_WOWLAN_TCP_DST_IPV4, tcp->dst) ||
nla_put(msg, NL80211_WOWLAN_TCP_DST_MAC, ETH_ALEN, tcp->dst_mac) ||
nla_put_u16(msg, NL80211_WOWLAN_TCP_SRC_PORT, tcp->src_port) ||
nla_put_u16(msg, NL80211_WOWLAN_TCP_DST_PORT, tcp->dst_port) ||
nla_put(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD,
tcp->payload_len, tcp->payload) ||
nla_put_u32(msg, NL80211_WOWLAN_TCP_DATA_INTERVAL,
tcp->data_interval) ||
nla_put(msg, NL80211_WOWLAN_TCP_WAKE_PAYLOAD,
tcp->wake_len, tcp->wake_data) ||
nla_put(msg, NL80211_WOWLAN_TCP_WAKE_MASK,
DIV_ROUND_UP(tcp->wake_len, 8), tcp->wake_mask))
return -ENOBUFS;
if (tcp->payload_seq.len &&
nla_put(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ,
sizeof(tcp->payload_seq), &tcp->payload_seq))
return -ENOBUFS;
if (tcp->payload_tok.len &&
nla_put(msg, NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN,
sizeof(tcp->payload_tok) + tcp->tokens_size,
&tcp->payload_tok))
return -ENOBUFS;
nla_nest_end(msg, nl_tcp);
return 0;
}
static int nl80211_get_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct sk_buff *msg;
void *hdr;
u32 size = NLMSG_DEFAULT_SIZE;
if (!rdev->wiphy.wowlan)
return -EOPNOTSUPP;
if (rdev->wiphy.wowlan_config && rdev->wiphy.wowlan_config->tcp) {
/* adjust size to have room for all the data */
size += rdev->wiphy.wowlan_config->tcp->tokens_size +
rdev->wiphy.wowlan_config->tcp->payload_len +
rdev->wiphy.wowlan_config->tcp->wake_len +
rdev->wiphy.wowlan_config->tcp->wake_len / 8;
}
msg = nlmsg_new(size, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_WOWLAN);
if (!hdr)
goto nla_put_failure;
if (rdev->wiphy.wowlan_config) {
struct nlattr *nl_wowlan;
nl_wowlan = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS);
if (!nl_wowlan)
goto nla_put_failure;
if ((rdev->wiphy.wowlan_config->any &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_ANY)) ||
(rdev->wiphy.wowlan_config->disconnect &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_DISCONNECT)) ||
(rdev->wiphy.wowlan_config->magic_pkt &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT)) ||
(rdev->wiphy.wowlan_config->gtk_rekey_failure &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE)) ||
(rdev->wiphy.wowlan_config->eap_identity_req &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST)) ||
(rdev->wiphy.wowlan_config->four_way_handshake &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE)) ||
(rdev->wiphy.wowlan_config->rfkill_release &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_RFKILL_RELEASE)))
goto nla_put_failure;
if (nl80211_send_wowlan_patterns(msg, rdev))
goto nla_put_failure;
if (nl80211_send_wowlan_tcp(msg,
rdev->wiphy.wowlan_config->tcp))
goto nla_put_failure;
nla_nest_end(msg, nl_wowlan);
}
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
static int nl80211_parse_wowlan_tcp(struct cfg80211_registered_device *rdev,
struct nlattr *attr,
struct cfg80211_wowlan *trig)
{
struct nlattr *tb[NUM_NL80211_WOWLAN_TCP];
struct cfg80211_wowlan_tcp *cfg;
struct nl80211_wowlan_tcp_data_token *tok = NULL;
struct nl80211_wowlan_tcp_data_seq *seq = NULL;
u32 size;
u32 data_size, wake_size, tokens_size = 0, wake_mask_size;
int err, port;
if (!rdev->wiphy.wowlan->tcp)
return -EINVAL;
err = nla_parse(tb, MAX_NL80211_WOWLAN_TCP,
nla_data(attr), nla_len(attr),
nl80211_wowlan_tcp_policy);
if (err)
return err;
if (!tb[NL80211_WOWLAN_TCP_SRC_IPV4] ||
!tb[NL80211_WOWLAN_TCP_DST_IPV4] ||
!tb[NL80211_WOWLAN_TCP_DST_MAC] ||
!tb[NL80211_WOWLAN_TCP_DST_PORT] ||
!tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD] ||
!tb[NL80211_WOWLAN_TCP_DATA_INTERVAL] ||
!tb[NL80211_WOWLAN_TCP_WAKE_PAYLOAD] ||
!tb[NL80211_WOWLAN_TCP_WAKE_MASK])
return -EINVAL;
data_size = nla_len(tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD]);
if (data_size > rdev->wiphy.wowlan->tcp->data_payload_max)
return -EINVAL;
if (nla_get_u32(tb[NL80211_WOWLAN_TCP_DATA_INTERVAL]) >
rdev->wiphy.wowlan->tcp->data_interval_max ||
nla_get_u32(tb[NL80211_WOWLAN_TCP_DATA_INTERVAL]) == 0)
return -EINVAL;
wake_size = nla_len(tb[NL80211_WOWLAN_TCP_WAKE_PAYLOAD]);
if (wake_size > rdev->wiphy.wowlan->tcp->wake_payload_max)
return -EINVAL;
wake_mask_size = nla_len(tb[NL80211_WOWLAN_TCP_WAKE_MASK]);
if (wake_mask_size != DIV_ROUND_UP(wake_size, 8))
return -EINVAL;
if (tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN]) {
u32 tokln = nla_len(tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN]);
tok = nla_data(tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD_TOKEN]);
tokens_size = tokln - sizeof(*tok);
if (!tok->len || tokens_size % tok->len)
return -EINVAL;
if (!rdev->wiphy.wowlan->tcp->tok)
return -EINVAL;
if (tok->len > rdev->wiphy.wowlan->tcp->tok->max_len)
return -EINVAL;
if (tok->len < rdev->wiphy.wowlan->tcp->tok->min_len)
return -EINVAL;
if (tokens_size > rdev->wiphy.wowlan->tcp->tok->bufsize)
return -EINVAL;
if (tok->offset + tok->len > data_size)
return -EINVAL;
}
if (tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ]) {
seq = nla_data(tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD_SEQ]);
if (!rdev->wiphy.wowlan->tcp->seq)
return -EINVAL;
if (seq->len == 0 || seq->len > 4)
return -EINVAL;
if (seq->len + seq->offset > data_size)
return -EINVAL;
}
size = sizeof(*cfg);
size += data_size;
size += wake_size + wake_mask_size;
size += tokens_size;
cfg = kzalloc(size, GFP_KERNEL);
if (!cfg)
return -ENOMEM;
cfg->src = nla_get_be32(tb[NL80211_WOWLAN_TCP_SRC_IPV4]);
cfg->dst = nla_get_be32(tb[NL80211_WOWLAN_TCP_DST_IPV4]);
memcpy(cfg->dst_mac, nla_data(tb[NL80211_WOWLAN_TCP_DST_MAC]),
ETH_ALEN);
if (tb[NL80211_WOWLAN_TCP_SRC_PORT])
port = nla_get_u16(tb[NL80211_WOWLAN_TCP_SRC_PORT]);
else
port = 0;
#ifdef CONFIG_INET
/* allocate a socket and port for it and use it */
err = __sock_create(wiphy_net(&rdev->wiphy), PF_INET, SOCK_STREAM,
IPPROTO_TCP, &cfg->sock, 1);
if (err) {
kfree(cfg);
return err;
}
if (inet_csk_get_port(cfg->sock->sk, port)) {
sock_release(cfg->sock);
kfree(cfg);
return -EADDRINUSE;
}
cfg->src_port = inet_sk(cfg->sock->sk)->inet_num;
#else
if (!port) {
kfree(cfg);
return -EINVAL;
}
cfg->src_port = port;
#endif
cfg->dst_port = nla_get_u16(tb[NL80211_WOWLAN_TCP_DST_PORT]);
cfg->payload_len = data_size;
cfg->payload = (u8 *)cfg + sizeof(*cfg) + tokens_size;
memcpy((void *)cfg->payload,
nla_data(tb[NL80211_WOWLAN_TCP_DATA_PAYLOAD]),
data_size);
if (seq)
cfg->payload_seq = *seq;
cfg->data_interval = nla_get_u32(tb[NL80211_WOWLAN_TCP_DATA_INTERVAL]);
cfg->wake_len = wake_size;
cfg->wake_data = (u8 *)cfg + sizeof(*cfg) + tokens_size + data_size;
memcpy((void *)cfg->wake_data,
nla_data(tb[NL80211_WOWLAN_TCP_WAKE_PAYLOAD]),
wake_size);
cfg->wake_mask = (u8 *)cfg + sizeof(*cfg) + tokens_size +
data_size + wake_size;
memcpy((void *)cfg->wake_mask,
nla_data(tb[NL80211_WOWLAN_TCP_WAKE_MASK]),
wake_mask_size);
if (tok) {
cfg->tokens_size = tokens_size;
memcpy(&cfg->payload_tok, tok, sizeof(*tok) + tokens_size);
}
trig->tcp = cfg;
return 0;
}
static int nl80211_set_wowlan(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct nlattr *tb[NUM_NL80211_WOWLAN_TRIG];
struct cfg80211_wowlan new_triggers = {};
struct cfg80211_wowlan *ntrig;
const struct wiphy_wowlan_support *wowlan = rdev->wiphy.wowlan;
int err, i;
bool prev_enabled = rdev->wiphy.wowlan_config;
if (!wowlan)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS]) {
cfg80211_rdev_free_wowlan(rdev);
rdev->wiphy.wowlan_config = NULL;
goto set_wakeup;
}
err = nla_parse(tb, MAX_NL80211_WOWLAN_TRIG,
nla_data(info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS]),
nla_len(info->attrs[NL80211_ATTR_WOWLAN_TRIGGERS]),
nl80211_wowlan_policy);
if (err)
return err;
if (tb[NL80211_WOWLAN_TRIG_ANY]) {
if (!(wowlan->flags & WIPHY_WOWLAN_ANY))
return -EINVAL;
new_triggers.any = true;
}
if (tb[NL80211_WOWLAN_TRIG_DISCONNECT]) {
if (!(wowlan->flags & WIPHY_WOWLAN_DISCONNECT))
return -EINVAL;
new_triggers.disconnect = true;
}
if (tb[NL80211_WOWLAN_TRIG_MAGIC_PKT]) {
if (!(wowlan->flags & WIPHY_WOWLAN_MAGIC_PKT))
return -EINVAL;
new_triggers.magic_pkt = true;
}
if (tb[NL80211_WOWLAN_TRIG_GTK_REKEY_SUPPORTED])
return -EINVAL;
if (tb[NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE]) {
if (!(wowlan->flags & WIPHY_WOWLAN_GTK_REKEY_FAILURE))
return -EINVAL;
new_triggers.gtk_rekey_failure = true;
}
if (tb[NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST]) {
if (!(wowlan->flags & WIPHY_WOWLAN_EAP_IDENTITY_REQ))
return -EINVAL;
new_triggers.eap_identity_req = true;
}
if (tb[NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE]) {
if (!(wowlan->flags & WIPHY_WOWLAN_4WAY_HANDSHAKE))
return -EINVAL;
new_triggers.four_way_handshake = true;
}
if (tb[NL80211_WOWLAN_TRIG_RFKILL_RELEASE]) {
if (!(wowlan->flags & WIPHY_WOWLAN_RFKILL_RELEASE))
return -EINVAL;
new_triggers.rfkill_release = true;
}
if (tb[NL80211_WOWLAN_TRIG_PKT_PATTERN]) {
struct nlattr *pat;
int n_patterns = 0;
int rem, pat_len, mask_len, pkt_offset;
struct nlattr *pat_tb[NUM_NL80211_PKTPAT];
nla_for_each_nested(pat, tb[NL80211_WOWLAN_TRIG_PKT_PATTERN],
rem)
n_patterns++;
if (n_patterns > wowlan->n_patterns)
return -EINVAL;
new_triggers.patterns = kcalloc(n_patterns,
sizeof(new_triggers.patterns[0]),
GFP_KERNEL);
if (!new_triggers.patterns)
return -ENOMEM;
new_triggers.n_patterns = n_patterns;
i = 0;
nla_for_each_nested(pat, tb[NL80211_WOWLAN_TRIG_PKT_PATTERN],
rem) {
nla_parse(pat_tb, MAX_NL80211_PKTPAT, nla_data(pat),
nla_len(pat), NULL);
err = -EINVAL;
if (!pat_tb[NL80211_PKTPAT_MASK] ||
!pat_tb[NL80211_PKTPAT_PATTERN])
goto error;
pat_len = nla_len(pat_tb[NL80211_PKTPAT_PATTERN]);
mask_len = DIV_ROUND_UP(pat_len, 8);
if (nla_len(pat_tb[NL80211_PKTPAT_MASK]) != mask_len)
goto error;
if (pat_len > wowlan->pattern_max_len ||
pat_len < wowlan->pattern_min_len)
goto error;
if (!pat_tb[NL80211_PKTPAT_OFFSET])
pkt_offset = 0;
else
pkt_offset = nla_get_u32(
pat_tb[NL80211_PKTPAT_OFFSET]);
if (pkt_offset > wowlan->max_pkt_offset)
goto error;
new_triggers.patterns[i].pkt_offset = pkt_offset;
new_triggers.patterns[i].mask =
kmalloc(mask_len + pat_len, GFP_KERNEL);
if (!new_triggers.patterns[i].mask) {
err = -ENOMEM;
goto error;
}
new_triggers.patterns[i].pattern =
new_triggers.patterns[i].mask + mask_len;
memcpy(new_triggers.patterns[i].mask,
nla_data(pat_tb[NL80211_PKTPAT_MASK]),
mask_len);
new_triggers.patterns[i].pattern_len = pat_len;
memcpy(new_triggers.patterns[i].pattern,
nla_data(pat_tb[NL80211_PKTPAT_PATTERN]),
pat_len);
i++;
}
}
if (tb[NL80211_WOWLAN_TRIG_TCP_CONNECTION]) {
err = nl80211_parse_wowlan_tcp(
rdev, tb[NL80211_WOWLAN_TRIG_TCP_CONNECTION],
&new_triggers);
if (err)
goto error;
}
ntrig = kmemdup(&new_triggers, sizeof(new_triggers), GFP_KERNEL);
if (!ntrig) {
err = -ENOMEM;
goto error;
}
cfg80211_rdev_free_wowlan(rdev);
rdev->wiphy.wowlan_config = ntrig;
set_wakeup:
if (rdev->ops->set_wakeup &&
prev_enabled != !!rdev->wiphy.wowlan_config)
rdev_set_wakeup(rdev, rdev->wiphy.wowlan_config);
return 0;
error:
for (i = 0; i < new_triggers.n_patterns; i++)
kfree(new_triggers.patterns[i].mask);
kfree(new_triggers.patterns);
if (new_triggers.tcp && new_triggers.tcp->sock)
sock_release(new_triggers.tcp->sock);
kfree(new_triggers.tcp);
return err;
}
#endif
static int nl80211_send_coalesce_rules(struct sk_buff *msg,
struct cfg80211_registered_device *rdev)
{
struct nlattr *nl_pats, *nl_pat, *nl_rule, *nl_rules;
int i, j, pat_len;
struct cfg80211_coalesce_rules *rule;
if (!rdev->coalesce->n_rules)
return 0;
nl_rules = nla_nest_start(msg, NL80211_ATTR_COALESCE_RULE);
if (!nl_rules)
return -ENOBUFS;
for (i = 0; i < rdev->coalesce->n_rules; i++) {
nl_rule = nla_nest_start(msg, i + 1);
if (!nl_rule)
return -ENOBUFS;
rule = &rdev->coalesce->rules[i];
if (nla_put_u32(msg, NL80211_ATTR_COALESCE_RULE_DELAY,
rule->delay))
return -ENOBUFS;
if (nla_put_u32(msg, NL80211_ATTR_COALESCE_RULE_CONDITION,
rule->condition))
return -ENOBUFS;
nl_pats = nla_nest_start(msg,
NL80211_ATTR_COALESCE_RULE_PKT_PATTERN);
if (!nl_pats)
return -ENOBUFS;
for (j = 0; j < rule->n_patterns; j++) {
nl_pat = nla_nest_start(msg, j + 1);
if (!nl_pat)
return -ENOBUFS;
pat_len = rule->patterns[j].pattern_len;
if (nla_put(msg, NL80211_PKTPAT_MASK,
DIV_ROUND_UP(pat_len, 8),
rule->patterns[j].mask) ||
nla_put(msg, NL80211_PKTPAT_PATTERN, pat_len,
rule->patterns[j].pattern) ||
nla_put_u32(msg, NL80211_PKTPAT_OFFSET,
rule->patterns[j].pkt_offset))
return -ENOBUFS;
nla_nest_end(msg, nl_pat);
}
nla_nest_end(msg, nl_pats);
nla_nest_end(msg, nl_rule);
}
nla_nest_end(msg, nl_rules);
return 0;
}
static int nl80211_get_coalesce(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct sk_buff *msg;
void *hdr;
if (!rdev->wiphy.coalesce)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_COALESCE);
if (!hdr)
goto nla_put_failure;
if (rdev->coalesce && nl80211_send_coalesce_rules(msg, rdev))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
nlmsg_free(msg);
return -ENOBUFS;
}
void cfg80211_rdev_free_coalesce(struct cfg80211_registered_device *rdev)
{
struct cfg80211_coalesce *coalesce = rdev->coalesce;
int i, j;
struct cfg80211_coalesce_rules *rule;
if (!coalesce)
return;
for (i = 0; i < coalesce->n_rules; i++) {
rule = &coalesce->rules[i];
for (j = 0; j < rule->n_patterns; j++)
kfree(rule->patterns[j].mask);
kfree(rule->patterns);
}
kfree(coalesce->rules);
kfree(coalesce);
rdev->coalesce = NULL;
}
static int nl80211_parse_coalesce_rule(struct cfg80211_registered_device *rdev,
struct nlattr *rule,
struct cfg80211_coalesce_rules *new_rule)
{
int err, i;
const struct wiphy_coalesce_support *coalesce = rdev->wiphy.coalesce;
struct nlattr *tb[NUM_NL80211_ATTR_COALESCE_RULE], *pat;
int rem, pat_len, mask_len, pkt_offset, n_patterns = 0;
struct nlattr *pat_tb[NUM_NL80211_PKTPAT];
err = nla_parse(tb, NL80211_ATTR_COALESCE_RULE_MAX, nla_data(rule),
nla_len(rule), nl80211_coalesce_policy);
if (err)
return err;
if (tb[NL80211_ATTR_COALESCE_RULE_DELAY])
new_rule->delay =
nla_get_u32(tb[NL80211_ATTR_COALESCE_RULE_DELAY]);
if (new_rule->delay > coalesce->max_delay)
return -EINVAL;
if (tb[NL80211_ATTR_COALESCE_RULE_CONDITION])
new_rule->condition =
nla_get_u32(tb[NL80211_ATTR_COALESCE_RULE_CONDITION]);
if (new_rule->condition != NL80211_COALESCE_CONDITION_MATCH &&
new_rule->condition != NL80211_COALESCE_CONDITION_NO_MATCH)
return -EINVAL;
if (!tb[NL80211_ATTR_COALESCE_RULE_PKT_PATTERN])
return -EINVAL;
nla_for_each_nested(pat, tb[NL80211_ATTR_COALESCE_RULE_PKT_PATTERN],
rem)
n_patterns++;
if (n_patterns > coalesce->n_patterns)
return -EINVAL;
new_rule->patterns = kcalloc(n_patterns, sizeof(new_rule->patterns[0]),
GFP_KERNEL);
if (!new_rule->patterns)
return -ENOMEM;
new_rule->n_patterns = n_patterns;
i = 0;
nla_for_each_nested(pat, tb[NL80211_ATTR_COALESCE_RULE_PKT_PATTERN],
rem) {
nla_parse(pat_tb, MAX_NL80211_PKTPAT, nla_data(pat),
nla_len(pat), NULL);
if (!pat_tb[NL80211_PKTPAT_MASK] ||
!pat_tb[NL80211_PKTPAT_PATTERN])
return -EINVAL;
pat_len = nla_len(pat_tb[NL80211_PKTPAT_PATTERN]);
mask_len = DIV_ROUND_UP(pat_len, 8);
if (nla_len(pat_tb[NL80211_PKTPAT_MASK]) != mask_len)
return -EINVAL;
if (pat_len > coalesce->pattern_max_len ||
pat_len < coalesce->pattern_min_len)
return -EINVAL;
if (!pat_tb[NL80211_PKTPAT_OFFSET])
pkt_offset = 0;
else
pkt_offset = nla_get_u32(pat_tb[NL80211_PKTPAT_OFFSET]);
if (pkt_offset > coalesce->max_pkt_offset)
return -EINVAL;
new_rule->patterns[i].pkt_offset = pkt_offset;
new_rule->patterns[i].mask =
kmalloc(mask_len + pat_len, GFP_KERNEL);
if (!new_rule->patterns[i].mask)
return -ENOMEM;
new_rule->patterns[i].pattern =
new_rule->patterns[i].mask + mask_len;
memcpy(new_rule->patterns[i].mask,
nla_data(pat_tb[NL80211_PKTPAT_MASK]), mask_len);
new_rule->patterns[i].pattern_len = pat_len;
memcpy(new_rule->patterns[i].pattern,
nla_data(pat_tb[NL80211_PKTPAT_PATTERN]), pat_len);
i++;
}
return 0;
}
static int nl80211_set_coalesce(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
const struct wiphy_coalesce_support *coalesce = rdev->wiphy.coalesce;
struct cfg80211_coalesce new_coalesce = {};
struct cfg80211_coalesce *n_coalesce;
int err, rem_rule, n_rules = 0, i, j;
struct nlattr *rule;
struct cfg80211_coalesce_rules *tmp_rule;
if (!rdev->wiphy.coalesce || !rdev->ops->set_coalesce)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_COALESCE_RULE]) {
cfg80211_rdev_free_coalesce(rdev);
rdev->ops->set_coalesce(&rdev->wiphy, NULL);
return 0;
}
nla_for_each_nested(rule, info->attrs[NL80211_ATTR_COALESCE_RULE],
rem_rule)
n_rules++;
if (n_rules > coalesce->n_rules)
return -EINVAL;
new_coalesce.rules = kcalloc(n_rules, sizeof(new_coalesce.rules[0]),
GFP_KERNEL);
if (!new_coalesce.rules)
return -ENOMEM;
new_coalesce.n_rules = n_rules;
i = 0;
nla_for_each_nested(rule, info->attrs[NL80211_ATTR_COALESCE_RULE],
rem_rule) {
err = nl80211_parse_coalesce_rule(rdev, rule,
&new_coalesce.rules[i]);
if (err)
goto error;
i++;
}
err = rdev->ops->set_coalesce(&rdev->wiphy, &new_coalesce);
if (err)
goto error;
n_coalesce = kmemdup(&new_coalesce, sizeof(new_coalesce), GFP_KERNEL);
if (!n_coalesce) {
err = -ENOMEM;
goto error;
}
cfg80211_rdev_free_coalesce(rdev);
rdev->coalesce = n_coalesce;
return 0;
error:
for (i = 0; i < new_coalesce.n_rules; i++) {
tmp_rule = &new_coalesce.rules[i];
for (j = 0; j < tmp_rule->n_patterns; j++)
kfree(tmp_rule->patterns[j].mask);
kfree(tmp_rule->patterns);
}
kfree(new_coalesce.rules);
return err;
}
static int nl80211_set_rekey_data(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct nlattr *tb[NUM_NL80211_REKEY_DATA];
struct cfg80211_gtk_rekey_data rekey_data;
int err;
if (!info->attrs[NL80211_ATTR_REKEY_DATA])
return -EINVAL;
err = nla_parse(tb, MAX_NL80211_REKEY_DATA,
nla_data(info->attrs[NL80211_ATTR_REKEY_DATA]),
nla_len(info->attrs[NL80211_ATTR_REKEY_DATA]),
nl80211_rekey_policy);
if (err)
return err;
if (nla_len(tb[NL80211_REKEY_DATA_REPLAY_CTR]) != NL80211_REPLAY_CTR_LEN)
return -ERANGE;
if (nla_len(tb[NL80211_REKEY_DATA_KEK]) != NL80211_KEK_LEN)
return -ERANGE;
if (nla_len(tb[NL80211_REKEY_DATA_KCK]) != NL80211_KCK_LEN)
return -ERANGE;
memcpy(rekey_data.kek, nla_data(tb[NL80211_REKEY_DATA_KEK]),
NL80211_KEK_LEN);
memcpy(rekey_data.kck, nla_data(tb[NL80211_REKEY_DATA_KCK]),
NL80211_KCK_LEN);
memcpy(rekey_data.replay_ctr,
nla_data(tb[NL80211_REKEY_DATA_REPLAY_CTR]),
NL80211_REPLAY_CTR_LEN);
wdev_lock(wdev);
if (!wdev->current_bss) {
err = -ENOTCONN;
goto out;
}
if (!rdev->ops->set_rekey_data) {
err = -EOPNOTSUPP;
goto out;
}
err = rdev_set_rekey_data(rdev, dev, &rekey_data);
out:
wdev_unlock(wdev);
return err;
}
static int nl80211_register_unexpected_frame(struct sk_buff *skb,
struct genl_info *info)
{
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
if (wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO)
return -EINVAL;
if (wdev->ap_unexpected_nlportid)
return -EBUSY;
wdev->ap_unexpected_nlportid = info->snd_portid;
return 0;
}
static int nl80211_probe_client(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct net_device *dev = info->user_ptr[1];
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct sk_buff *msg;
void *hdr;
const u8 *addr;
u64 cookie;
int err;
if (wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_MAC])
return -EINVAL;
if (!rdev->ops->probe_client)
return -EOPNOTSUPP;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_PROBE_CLIENT);
if (!hdr) {
err = -ENOBUFS;
goto free_msg;
}
addr = nla_data(info->attrs[NL80211_ATTR_MAC]);
err = rdev_probe_client(rdev, dev, addr, &cookie);
if (err)
goto free_msg;
if (nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
err = -ENOBUFS;
free_msg:
nlmsg_free(msg);
return err;
}
static int nl80211_register_beacons(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct cfg80211_beacon_registration *reg, *nreg;
int rv;
if (!(rdev->wiphy.flags & WIPHY_FLAG_REPORTS_OBSS))
return -EOPNOTSUPP;
nreg = kzalloc(sizeof(*nreg), GFP_KERNEL);
if (!nreg)
return -ENOMEM;
/* First, check if already registered. */
spin_lock_bh(&rdev->beacon_registrations_lock);
list_for_each_entry(reg, &rdev->beacon_registrations, list) {
if (reg->nlportid == info->snd_portid) {
rv = -EALREADY;
goto out_err;
}
}
/* Add it to the list */
nreg->nlportid = info->snd_portid;
list_add(&nreg->list, &rdev->beacon_registrations);
spin_unlock_bh(&rdev->beacon_registrations_lock);
return 0;
out_err:
spin_unlock_bh(&rdev->beacon_registrations_lock);
kfree(nreg);
return rv;
}
static int nl80211_start_p2p_device(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
int err;
if (!rdev->ops->start_p2p_device)
return -EOPNOTSUPP;
if (wdev->iftype != NL80211_IFTYPE_P2P_DEVICE)
return -EOPNOTSUPP;
if (wdev->p2p_started)
return 0;
err = cfg80211_can_add_interface(rdev, wdev->iftype);
if (err)
return err;
err = rdev_start_p2p_device(rdev, wdev);
if (err)
return err;
wdev->p2p_started = true;
rdev->opencount++;
return 0;
}
static int nl80211_stop_p2p_device(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
if (wdev->iftype != NL80211_IFTYPE_P2P_DEVICE)
return -EOPNOTSUPP;
if (!rdev->ops->stop_p2p_device)
return -EOPNOTSUPP;
cfg80211_stop_p2p_device(rdev, wdev);
return 0;
}
static int nl80211_get_protocol_features(struct sk_buff *skb,
struct genl_info *info)
{
void *hdr;
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, info->snd_portid, info->snd_seq, 0,
NL80211_CMD_GET_PROTOCOL_FEATURES);
if (!hdr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_PROTOCOL_FEATURES,
NL80211_PROTOCOL_FEATURE_SPLIT_WIPHY_DUMP))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_reply(msg, info);
nla_put_failure:
kfree_skb(msg);
return -ENOBUFS;
}
static int nl80211_update_ft_ies(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct cfg80211_update_ft_ies_params ft_params;
struct net_device *dev = info->user_ptr[1];
if (!rdev->ops->update_ft_ies)
return -EOPNOTSUPP;
if (!info->attrs[NL80211_ATTR_MDID] ||
!is_valid_ie_attr(info->attrs[NL80211_ATTR_IE]))
return -EINVAL;
memset(&ft_params, 0, sizeof(ft_params));
ft_params.md = nla_get_u16(info->attrs[NL80211_ATTR_MDID]);
ft_params.ie = nla_data(info->attrs[NL80211_ATTR_IE]);
ft_params.ie_len = nla_len(info->attrs[NL80211_ATTR_IE]);
return rdev_update_ft_ies(rdev, dev, &ft_params);
}
static int nl80211_crit_protocol_start(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
enum nl80211_crit_proto_id proto = NL80211_CRIT_PROTO_UNSPEC;
u16 duration;
int ret;
if (!rdev->ops->crit_proto_start)
return -EOPNOTSUPP;
if (WARN_ON(!rdev->ops->crit_proto_stop))
return -EINVAL;
if (rdev->crit_proto_nlportid)
return -EBUSY;
/* determine protocol if provided */
if (info->attrs[NL80211_ATTR_CRIT_PROT_ID])
proto = nla_get_u16(info->attrs[NL80211_ATTR_CRIT_PROT_ID]);
if (proto >= NUM_NL80211_CRIT_PROTO)
return -EINVAL;
/* timeout must be provided */
if (!info->attrs[NL80211_ATTR_MAX_CRIT_PROT_DURATION])
return -EINVAL;
duration =
nla_get_u16(info->attrs[NL80211_ATTR_MAX_CRIT_PROT_DURATION]);
if (duration > NL80211_CRIT_PROTO_MAX_DURATION)
return -ERANGE;
ret = rdev_crit_proto_start(rdev, wdev, proto, duration);
if (!ret)
rdev->crit_proto_nlportid = info->snd_portid;
return ret;
}
static int nl80211_crit_protocol_stop(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev = info->user_ptr[1];
if (!rdev->ops->crit_proto_stop)
return -EOPNOTSUPP;
if (rdev->crit_proto_nlportid) {
rdev->crit_proto_nlportid = 0;
rdev_crit_proto_stop(rdev, wdev);
}
return 0;
}
static int nl80211_vendor_cmd(struct sk_buff *skb, struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct wireless_dev *wdev =
__cfg80211_wdev_from_attrs(genl_info_net(info), info->attrs);
int i, err;
u32 vid, subcmd;
if (!rdev->wiphy.vendor_commands)
return -EOPNOTSUPP;
if (IS_ERR(wdev)) {
err = PTR_ERR(wdev);
if (err != -EINVAL)
return err;
wdev = NULL;
} else if (wdev->wiphy != &rdev->wiphy) {
return -EINVAL;
}
if (!info->attrs[NL80211_ATTR_VENDOR_ID] ||
!info->attrs[NL80211_ATTR_VENDOR_SUBCMD])
return -EINVAL;
vid = nla_get_u32(info->attrs[NL80211_ATTR_VENDOR_ID]);
subcmd = nla_get_u32(info->attrs[NL80211_ATTR_VENDOR_SUBCMD]);
for (i = 0; i < rdev->wiphy.n_vendor_commands; i++) {
const struct wiphy_vendor_command *vcmd;
void *data = NULL;
int len = 0;
vcmd = &rdev->wiphy.vendor_commands[i];
if (vcmd->info.vendor_id != vid || vcmd->info.subcmd != subcmd)
continue;
if (vcmd->flags & (WIPHY_VENDOR_CMD_NEED_WDEV |
WIPHY_VENDOR_CMD_NEED_NETDEV)) {
if (!wdev)
return -EINVAL;
if (vcmd->flags & WIPHY_VENDOR_CMD_NEED_NETDEV &&
!wdev->netdev)
return -EINVAL;
if (vcmd->flags & WIPHY_VENDOR_CMD_NEED_RUNNING) {
if (wdev->netdev &&
!netif_running(wdev->netdev))
return -ENETDOWN;
if (!wdev->netdev && !wdev->p2p_started)
return -ENETDOWN;
}
} else {
wdev = NULL;
}
if (info->attrs[NL80211_ATTR_VENDOR_DATA]) {
data = nla_data(info->attrs[NL80211_ATTR_VENDOR_DATA]);
len = nla_len(info->attrs[NL80211_ATTR_VENDOR_DATA]);
}
rdev->cur_cmd_info = info;
err = rdev->wiphy.vendor_commands[i].doit(&rdev->wiphy, wdev,
data, len);
rdev->cur_cmd_info = NULL;
return err;
}
return -EOPNOTSUPP;
}
struct sk_buff *__cfg80211_alloc_reply_skb(struct wiphy *wiphy,
enum nl80211_commands cmd,
enum nl80211_attrs attr,
int approxlen)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
if (WARN_ON(!rdev->cur_cmd_info))
return NULL;
return __cfg80211_alloc_vendor_skb(rdev, approxlen,
rdev->cur_cmd_info->snd_portid,
rdev->cur_cmd_info->snd_seq,
cmd, attr, NULL, GFP_KERNEL);
}
EXPORT_SYMBOL(__cfg80211_alloc_reply_skb);
int cfg80211_vendor_cmd_reply(struct sk_buff *skb)
{
struct cfg80211_registered_device *rdev = ((void **)skb->cb)[0];
void *hdr = ((void **)skb->cb)[1];
struct nlattr *data = ((void **)skb->cb)[2];
if (WARN_ON(!rdev->cur_cmd_info)) {
kfree_skb(skb);
return -EINVAL;
}
nla_nest_end(skb, data);
genlmsg_end(skb, hdr);
return genlmsg_reply(skb, rdev->cur_cmd_info);
}
EXPORT_SYMBOL_GPL(cfg80211_vendor_cmd_reply);
static int nl80211_set_qos_map(struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev = info->user_ptr[0];
struct cfg80211_qos_map *qos_map = NULL;
struct net_device *dev = info->user_ptr[1];
u8 *pos, len, num_des, des_len, des;
int ret;
if (!rdev->ops->set_qos_map)
return -EOPNOTSUPP;
if (info->attrs[NL80211_ATTR_QOS_MAP]) {
pos = nla_data(info->attrs[NL80211_ATTR_QOS_MAP]);
len = nla_len(info->attrs[NL80211_ATTR_QOS_MAP]);
if (len % 2 || len < IEEE80211_QOS_MAP_LEN_MIN ||
len > IEEE80211_QOS_MAP_LEN_MAX)
return -EINVAL;
qos_map = kzalloc(sizeof(struct cfg80211_qos_map), GFP_KERNEL);
if (!qos_map)
return -ENOMEM;
num_des = (len - IEEE80211_QOS_MAP_LEN_MIN) >> 1;
if (num_des) {
des_len = num_des *
sizeof(struct cfg80211_dscp_exception);
memcpy(qos_map->dscp_exception, pos, des_len);
qos_map->num_des = num_des;
for (des = 0; des < num_des; des++) {
if (qos_map->dscp_exception[des].up > 7) {
kfree(qos_map);
return -EINVAL;
}
}
pos += des_len;
}
memcpy(qos_map->up, pos, IEEE80211_QOS_MAP_LEN_MIN);
}
wdev_lock(dev->ieee80211_ptr);
ret = nl80211_key_allowed(dev->ieee80211_ptr);
if (!ret)
ret = rdev_set_qos_map(rdev, dev, qos_map);
wdev_unlock(dev->ieee80211_ptr);
kfree(qos_map);
return ret;
}
#define NL80211_FLAG_NEED_WIPHY 0x01
#define NL80211_FLAG_NEED_NETDEV 0x02
#define NL80211_FLAG_NEED_RTNL 0x04
#define NL80211_FLAG_CHECK_NETDEV_UP 0x08
#define NL80211_FLAG_NEED_NETDEV_UP (NL80211_FLAG_NEED_NETDEV |\
NL80211_FLAG_CHECK_NETDEV_UP)
#define NL80211_FLAG_NEED_WDEV 0x10
/* If a netdev is associated, it must be UP, P2P must be started */
#define NL80211_FLAG_NEED_WDEV_UP (NL80211_FLAG_NEED_WDEV |\
NL80211_FLAG_CHECK_NETDEV_UP)
static int nl80211_pre_doit(const struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
struct cfg80211_registered_device *rdev;
struct wireless_dev *wdev;
struct net_device *dev;
bool rtnl = ops->internal_flags & NL80211_FLAG_NEED_RTNL;
if (rtnl)
rtnl_lock();
if (ops->internal_flags & NL80211_FLAG_NEED_WIPHY) {
rdev = cfg80211_get_dev_from_info(genl_info_net(info), info);
if (IS_ERR(rdev)) {
if (rtnl)
rtnl_unlock();
return PTR_ERR(rdev);
}
info->user_ptr[0] = rdev;
} else if (ops->internal_flags & NL80211_FLAG_NEED_NETDEV ||
ops->internal_flags & NL80211_FLAG_NEED_WDEV) {
ASSERT_RTNL();
wdev = __cfg80211_wdev_from_attrs(genl_info_net(info),
info->attrs);
if (IS_ERR(wdev)) {
if (rtnl)
rtnl_unlock();
return PTR_ERR(wdev);
}
dev = wdev->netdev;
rdev = wiphy_to_dev(wdev->wiphy);
if (ops->internal_flags & NL80211_FLAG_NEED_NETDEV) {
if (!dev) {
if (rtnl)
rtnl_unlock();
return -EINVAL;
}
info->user_ptr[1] = dev;
} else {
info->user_ptr[1] = wdev;
}
if (dev) {
if (ops->internal_flags & NL80211_FLAG_CHECK_NETDEV_UP &&
!netif_running(dev)) {
if (rtnl)
rtnl_unlock();
return -ENETDOWN;
}
dev_hold(dev);
} else if (ops->internal_flags & NL80211_FLAG_CHECK_NETDEV_UP) {
if (!wdev->p2p_started) {
if (rtnl)
rtnl_unlock();
return -ENETDOWN;
}
}
info->user_ptr[0] = rdev;
}
return 0;
}
static void nl80211_post_doit(const struct genl_ops *ops, struct sk_buff *skb,
struct genl_info *info)
{
if (info->user_ptr[1]) {
if (ops->internal_flags & NL80211_FLAG_NEED_WDEV) {
struct wireless_dev *wdev = info->user_ptr[1];
if (wdev->netdev)
dev_put(wdev->netdev);
} else {
dev_put(info->user_ptr[1]);
}
}
if (ops->internal_flags & NL80211_FLAG_NEED_RTNL)
rtnl_unlock();
}
static const struct genl_ops nl80211_ops[] = {
{
.cmd = NL80211_CMD_GET_WIPHY,
.doit = nl80211_get_wiphy,
.dumpit = nl80211_dump_wiphy,
.done = nl80211_dump_wiphy_done,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WIPHY,
.doit = nl80211_set_wiphy,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_INTERFACE,
.doit = nl80211_get_interface,
.dumpit = nl80211_dump_interface,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_WDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_INTERFACE,
.doit = nl80211_set_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_INTERFACE,
.doit = nl80211_new_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_INTERFACE,
.doit = nl80211_del_interface,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_KEY,
.doit = nl80211_get_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_KEY,
.doit = nl80211_set_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_KEY,
.doit = nl80211_new_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_KEY,
.doit = nl80211_del_key,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_BEACON,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_set_beacon,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_START_AP,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_start_ap,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_STOP_AP,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.doit = nl80211_stop_ap,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_STATION,
.doit = nl80211_get_station,
.dumpit = nl80211_dump_station,
.policy = nl80211_policy,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_STATION,
.doit = nl80211_set_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_STATION,
.doit = nl80211_new_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_STATION,
.doit = nl80211_del_station,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_MPATH,
.doit = nl80211_get_mpath,
.dumpit = nl80211_dump_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MPATH,
.doit = nl80211_set_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_NEW_MPATH,
.doit = nl80211_new_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_MPATH,
.doit = nl80211_del_mpath,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_BSS,
.doit = nl80211_set_bss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_REG,
.doit = nl80211_get_reg,
.policy = nl80211_policy,
.internal_flags = NL80211_FLAG_NEED_RTNL,
/* can be retrieved by unprivileged users */
},
{
.cmd = NL80211_CMD_SET_REG,
.doit = nl80211_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REQ_SET_REG,
.doit = nl80211_req_set_reg,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
},
{
.cmd = NL80211_CMD_GET_MESH_CONFIG,
.doit = nl80211_get_mesh_config,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MESH_CONFIG,
.doit = nl80211_update_mesh_config,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_TRIGGER_SCAN,
.doit = nl80211_trigger_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_SCAN,
.policy = nl80211_policy,
.dumpit = nl80211_dump_scan,
},
{
.cmd = NL80211_CMD_START_SCHED_SCAN,
.doit = nl80211_start_sched_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_STOP_SCHED_SCAN,
.doit = nl80211_stop_sched_scan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_AUTHENTICATE,
.doit = nl80211_authenticate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_ASSOCIATE,
.doit = nl80211_associate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEAUTHENTICATE,
.doit = nl80211_deauthenticate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DISASSOCIATE,
.doit = nl80211_disassociate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_JOIN_IBSS,
.doit = nl80211_join_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_LEAVE_IBSS,
.doit = nl80211_leave_ibss,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
#ifdef CONFIG_NL80211_TESTMODE
{
.cmd = NL80211_CMD_TESTMODE,
.doit = nl80211_testmode_do,
.dumpit = nl80211_testmode_dump,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
#endif
{
.cmd = NL80211_CMD_CONNECT,
.doit = nl80211_connect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DISCONNECT,
.doit = nl80211_disconnect,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WIPHY_NETNS,
.doit = nl80211_wiphy_netns,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_SURVEY,
.policy = nl80211_policy,
.dumpit = nl80211_dump_survey,
},
{
.cmd = NL80211_CMD_SET_PMKSA,
.doit = nl80211_setdel_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_DEL_PMKSA,
.doit = nl80211_setdel_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FLUSH_PMKSA,
.doit = nl80211_flush_pmksa,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REMAIN_ON_CHANNEL,
.doit = nl80211_remain_on_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL,
.doit = nl80211_cancel_remain_on_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_TX_BITRATE_MASK,
.doit = nl80211_set_tx_bitrate_mask,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REGISTER_FRAME,
.doit = nl80211_register_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FRAME,
.doit = nl80211_tx_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_FRAME_WAIT_CANCEL,
.doit = nl80211_tx_mgmt_cancel_wait,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_POWER_SAVE,
.doit = nl80211_set_power_save,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_POWER_SAVE,
.doit = nl80211_get_power_save,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_CQM,
.doit = nl80211_set_cqm,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_CHANNEL,
.doit = nl80211_set_channel,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WDS_PEER,
.doit = nl80211_set_wds_peer,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_JOIN_MESH,
.doit = nl80211_join_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_LEAVE_MESH,
.doit = nl80211_leave_mesh,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
#ifdef CONFIG_PM
{
.cmd = NL80211_CMD_GET_WOWLAN,
.doit = nl80211_get_wowlan,
.policy = nl80211_policy,
/* can be retrieved by unprivileged users */
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_WOWLAN,
.doit = nl80211_set_wowlan,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
#endif
{
.cmd = NL80211_CMD_SET_REKEY_OFFLOAD,
.doit = nl80211_set_rekey_data,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_TDLS_MGMT,
.doit = nl80211_tdls_mgmt,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_TDLS_OPER,
.doit = nl80211_tdls_oper,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_UNEXPECTED_FRAME,
.doit = nl80211_register_unexpected_frame,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_PROBE_CLIENT,
.doit = nl80211_probe_client,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_REGISTER_BEACONS,
.doit = nl80211_register_beacons,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_NOACK_MAP,
.doit = nl80211_set_noack_map,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_START_P2P_DEVICE,
.doit = nl80211_start_p2p_device,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_STOP_P2P_DEVICE,
.doit = nl80211_stop_p2p_device,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MCAST_RATE,
.doit = nl80211_set_mcast_rate,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_MAC_ACL,
.doit = nl80211_set_mac_acl,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_RADAR_DETECT,
.doit = nl80211_start_radar_detection,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_PROTOCOL_FEATURES,
.doit = nl80211_get_protocol_features,
.policy = nl80211_policy,
},
{
.cmd = NL80211_CMD_UPDATE_FT_IES,
.doit = nl80211_update_ft_ies,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_CRIT_PROTOCOL_START,
.doit = nl80211_crit_protocol_start,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_CRIT_PROTOCOL_STOP,
.doit = nl80211_crit_protocol_stop,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_GET_COALESCE,
.doit = nl80211_get_coalesce,
.policy = nl80211_policy,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_COALESCE,
.doit = nl80211_set_coalesce,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_CHANNEL_SWITCH,
.doit = nl80211_channel_switch,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_VENDOR,
.doit = nl80211_vendor_cmd,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_WIPHY |
NL80211_FLAG_NEED_RTNL,
},
{
.cmd = NL80211_CMD_SET_QOS_MAP,
.doit = nl80211_set_qos_map,
.policy = nl80211_policy,
.flags = GENL_ADMIN_PERM,
.internal_flags = NL80211_FLAG_NEED_NETDEV_UP |
NL80211_FLAG_NEED_RTNL,
},
};
/* notification functions */
void nl80211_notify_dev_rename(struct cfg80211_registered_device *rdev)
{
struct sk_buff *msg;
struct nl80211_dump_wiphy_state state = {};
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_wiphy(rdev, msg, 0, 0, 0, &state) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_CONFIG, GFP_KERNEL);
}
static int nl80211_add_scan_req(struct sk_buff *msg,
struct cfg80211_registered_device *rdev)
{
struct cfg80211_scan_request *req = rdev->scan_req;
struct nlattr *nest;
int i;
if (WARN_ON(!req))
return 0;
nest = nla_nest_start(msg, NL80211_ATTR_SCAN_SSIDS);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_ssids; i++) {
if (nla_put(msg, i, req->ssids[i].ssid_len, req->ssids[i].ssid))
goto nla_put_failure;
}
nla_nest_end(msg, nest);
nest = nla_nest_start(msg, NL80211_ATTR_SCAN_FREQUENCIES);
if (!nest)
goto nla_put_failure;
for (i = 0; i < req->n_channels; i++) {
if (nla_put_u32(msg, i, req->channels[i]->center_freq))
goto nla_put_failure;
}
nla_nest_end(msg, nest);
if (req->ie &&
nla_put(msg, NL80211_ATTR_IE, req->ie_len, req->ie))
goto nla_put_failure;
if (req->flags &&
nla_put_u32(msg, NL80211_ATTR_SCAN_FLAGS, req->flags))
goto nla_put_failure;
return 0;
nla_put_failure:
return -ENOBUFS;
}
static int nl80211_send_scan_msg(struct sk_buff *msg,
struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev,
u32 portid, u32 seq, int flags,
u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, portid, seq, flags, cmd);
if (!hdr)
return -1;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
(wdev->netdev && nla_put_u32(msg, NL80211_ATTR_IFINDEX,
wdev->netdev->ifindex)) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto nla_put_failure;
/* ignore errors and send incomplete event anyway */
nl80211_add_scan_req(msg, rdev);
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
static int
nl80211_send_sched_scan_msg(struct sk_buff *msg,
struct cfg80211_registered_device *rdev,
struct net_device *netdev,
u32 portid, u32 seq, int flags, u32 cmd)
{
void *hdr;
hdr = nl80211hdr_put(msg, portid, seq, flags, cmd);
if (!hdr)
return -1;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex))
goto nla_put_failure;
return genlmsg_end(msg, hdr);
nla_put_failure:
genlmsg_cancel(msg, hdr);
return -EMSGSIZE;
}
void nl80211_send_scan_start(struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_scan_msg(msg, rdev, wdev, 0, 0, 0,
NL80211_CMD_TRIGGER_SCAN) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_SCAN, GFP_KERNEL);
}
struct sk_buff *nl80211_build_scan_msg(struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev, bool aborted)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return NULL;
if (nl80211_send_scan_msg(msg, rdev, wdev, 0, 0, 0,
aborted ? NL80211_CMD_SCAN_ABORTED :
NL80211_CMD_NEW_SCAN_RESULTS) < 0) {
nlmsg_free(msg);
return NULL;
}
return msg;
}
void nl80211_send_scan_result(struct cfg80211_registered_device *rdev,
struct sk_buff *msg)
{
if (!msg)
return;
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_SCAN, GFP_KERNEL);
}
void nl80211_send_sched_scan_results(struct cfg80211_registered_device *rdev,
struct net_device *netdev)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_sched_scan_msg(msg, rdev, netdev, 0, 0, 0,
NL80211_CMD_SCHED_SCAN_RESULTS) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_SCAN, GFP_KERNEL);
}
void nl80211_send_sched_scan(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u32 cmd)
{
struct sk_buff *msg;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
if (nl80211_send_sched_scan_msg(msg, rdev, netdev, 0, 0, 0, cmd) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_SCAN, GFP_KERNEL);
}
/*
* This can happen on global regulatory changes or device specific settings
* based on custom world regulatory domains.
*/
void nl80211_send_reg_change_event(struct regulatory_request *request)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_REG_CHANGE);
if (!hdr) {
nlmsg_free(msg);
return;
}
/* Userspace can always count this one always being set */
if (nla_put_u8(msg, NL80211_ATTR_REG_INITIATOR, request->initiator))
goto nla_put_failure;
if (request->alpha2[0] == '0' && request->alpha2[1] == '0') {
if (nla_put_u8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_WORLD))
goto nla_put_failure;
} else if (request->alpha2[0] == '9' && request->alpha2[1] == '9') {
if (nla_put_u8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_CUSTOM_WORLD))
goto nla_put_failure;
} else if ((request->alpha2[0] == '9' && request->alpha2[1] == '8') ||
request->intersect) {
if (nla_put_u8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_INTERSECTION))
goto nla_put_failure;
} else {
if (nla_put_u8(msg, NL80211_ATTR_REG_TYPE,
NL80211_REGDOM_TYPE_COUNTRY) ||
nla_put_string(msg, NL80211_ATTR_REG_ALPHA2,
request->alpha2))
goto nla_put_failure;
}
if (request->wiphy_idx != WIPHY_IDX_INVALID &&
nla_put_u32(msg, NL80211_ATTR_WIPHY, request->wiphy_idx))
goto nla_put_failure;
genlmsg_end(msg, hdr);
rcu_read_lock();
genlmsg_multicast_allns(&nl80211_fam, msg, 0,
NL80211_MCGRP_REGULATORY, GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void nl80211_send_mlme_event(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
const u8 *buf, size_t len,
enum nl80211_commands cmd, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put(msg, NL80211_ATTR_FRAME, len, buf))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_rx_auth(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_AUTHENTICATE, gfp);
}
void nl80211_send_rx_assoc(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_ASSOCIATE, gfp);
}
void nl80211_send_deauth(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_DEAUTHENTICATE, gfp);
}
void nl80211_send_disassoc(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *buf,
size_t len, gfp_t gfp)
{
nl80211_send_mlme_event(rdev, netdev, buf, len,
NL80211_CMD_DISASSOCIATE, gfp);
}
void cfg80211_rx_unprot_mlme_mgmt(struct net_device *dev, const u8 *buf,
size_t len)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
const struct ieee80211_mgmt *mgmt = (void *)buf;
u32 cmd;
if (WARN_ON(len < 2))
return;
if (ieee80211_is_deauth(mgmt->frame_control))
cmd = NL80211_CMD_UNPROT_DEAUTHENTICATE;
else
cmd = NL80211_CMD_UNPROT_DISASSOCIATE;
trace_cfg80211_rx_unprot_mlme_mgmt(dev, buf, len);
nl80211_send_mlme_event(rdev, dev, buf, len, cmd, GFP_ATOMIC);
}
EXPORT_SYMBOL(cfg80211_rx_unprot_mlme_mgmt);
static void nl80211_send_mlme_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, int cmd,
const u8 *addr, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put_flag(msg, NL80211_ATTR_TIMED_OUT) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, addr))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_auth_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
nl80211_send_mlme_timeout(rdev, netdev, NL80211_CMD_AUTHENTICATE,
addr, gfp);
}
void nl80211_send_assoc_timeout(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
gfp_t gfp)
{
nl80211_send_mlme_timeout(rdev, netdev, NL80211_CMD_ASSOCIATE,
addr, gfp);
}
void nl80211_send_connect_result(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len,
u16 status, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CONNECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
(bssid && nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid)) ||
nla_put_u16(msg, NL80211_ATTR_STATUS_CODE, status) ||
(req_ie &&
nla_put(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie)) ||
(resp_ie &&
nla_put(msg, NL80211_ATTR_RESP_IE, resp_ie_len, resp_ie)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_roamed(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *req_ie, size_t req_ie_len,
const u8 *resp_ie, size_t resp_ie_len, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_ROAM);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid) ||
(req_ie &&
nla_put(msg, NL80211_ATTR_REQ_IE, req_ie_len, req_ie)) ||
(resp_ie &&
nla_put(msg, NL80211_ATTR_RESP_IE, resp_ie_len, resp_ie)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_disconnected(struct cfg80211_registered_device *rdev,
struct net_device *netdev, u16 reason,
const u8 *ie, size_t ie_len, bool from_ap)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_DISCONNECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
(from_ap && reason &&
nla_put_u16(msg, NL80211_ATTR_REASON_CODE, reason)) ||
(from_ap &&
nla_put_flag(msg, NL80211_ATTR_DISCONNECTED_BY_AP)) ||
(ie && nla_put(msg, NL80211_ATTR_IE, ie_len, ie)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, GFP_KERNEL);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_ibss_bssid(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_JOIN_IBSS);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_notify_new_peer_candidate(struct net_device *dev, const u8 *addr,
const u8* ie, u8 ie_len, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_MESH_POINT))
return;
trace_cfg80211_notify_new_peer_candidate(dev, addr);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NEW_PEER_CANDIDATE);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, addr) ||
(ie_len && ie &&
nla_put(msg, NL80211_ATTR_IE, ie_len , ie)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_notify_new_peer_candidate);
void nl80211_michael_mic_failure(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *addr,
enum nl80211_key_type key_type, int key_id,
const u8 *tsc, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_MICHAEL_MIC_FAILURE);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
(addr && nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, addr)) ||
nla_put_u32(msg, NL80211_ATTR_KEY_TYPE, key_type) ||
(key_id != -1 &&
nla_put_u8(msg, NL80211_ATTR_KEY_IDX, key_id)) ||
(tsc && nla_put(msg, NL80211_ATTR_KEY_SEQ, 6, tsc)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void nl80211_send_beacon_hint_event(struct wiphy *wiphy,
struct ieee80211_channel *channel_before,
struct ieee80211_channel *channel_after)
{
struct sk_buff *msg;
void *hdr;
struct nlattr *nl_freq;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_REG_BEACON_HINT);
if (!hdr) {
nlmsg_free(msg);
return;
}
/*
* Since we are applying the beacon hint to a wiphy we know its
* wiphy_idx is valid
*/
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, get_wiphy_idx(wiphy)))
goto nla_put_failure;
/* Before */
nl_freq = nla_nest_start(msg, NL80211_ATTR_FREQ_BEFORE);
if (!nl_freq)
goto nla_put_failure;
if (nl80211_msg_put_channel(msg, channel_before, false))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
/* After */
nl_freq = nla_nest_start(msg, NL80211_ATTR_FREQ_AFTER);
if (!nl_freq)
goto nla_put_failure;
if (nl80211_msg_put_channel(msg, channel_after, false))
goto nla_put_failure;
nla_nest_end(msg, nl_freq);
genlmsg_end(msg, hdr);
rcu_read_lock();
genlmsg_multicast_allns(&nl80211_fam, msg, 0,
NL80211_MCGRP_REGULATORY, GFP_ATOMIC);
rcu_read_unlock();
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
static void nl80211_send_remain_on_chan_event(
int cmd, struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev, u64 cookie,
struct ieee80211_channel *chan,
unsigned int duration, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
(wdev->netdev && nla_put_u32(msg, NL80211_ATTR_IFINDEX,
wdev->netdev->ifindex)) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_FREQ, chan->center_freq) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_CHANNEL_TYPE,
NL80211_CHAN_NO_HT) ||
nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie))
goto nla_put_failure;
if (cmd == NL80211_CMD_REMAIN_ON_CHANNEL &&
nla_put_u32(msg, NL80211_ATTR_DURATION, duration))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_ready_on_channel(struct wireless_dev *wdev, u64 cookie,
struct ieee80211_channel *chan,
unsigned int duration, gfp_t gfp)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
trace_cfg80211_ready_on_channel(wdev, cookie, chan, duration);
nl80211_send_remain_on_chan_event(NL80211_CMD_REMAIN_ON_CHANNEL,
rdev, wdev, cookie, chan,
duration, gfp);
}
EXPORT_SYMBOL(cfg80211_ready_on_channel);
void cfg80211_remain_on_channel_expired(struct wireless_dev *wdev, u64 cookie,
struct ieee80211_channel *chan,
gfp_t gfp)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
trace_cfg80211_ready_on_channel_expired(wdev, cookie, chan);
nl80211_send_remain_on_chan_event(NL80211_CMD_CANCEL_REMAIN_ON_CHANNEL,
rdev, wdev, cookie, chan, 0, gfp);
}
EXPORT_SYMBOL(cfg80211_remain_on_channel_expired);
void cfg80211_new_sta(struct net_device *dev, const u8 *mac_addr,
struct station_info *sinfo, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
trace_cfg80211_new_sta(dev, mac_addr, sinfo);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
if (nl80211_send_station(msg, 0, 0, 0,
rdev, dev, mac_addr, sinfo) < 0) {
nlmsg_free(msg);
return;
}
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
}
EXPORT_SYMBOL(cfg80211_new_sta);
void cfg80211_del_sta(struct net_device *dev, const u8 *mac_addr, gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
trace_cfg80211_del_sta(dev, mac_addr);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_DEL_STATION);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_del_sta);
void cfg80211_conn_failed(struct net_device *dev, const u8 *mac_addr,
enum nl80211_connect_failed_reason reason,
gfp_t gfp)
{
struct wiphy *wiphy = dev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CONN_FAILED);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, mac_addr) ||
nla_put_u32(msg, NL80211_ATTR_CONN_FAILED_REASON, reason))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_conn_failed);
static bool __nl80211_unexpected_frame(struct net_device *dev, u8 cmd,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
u32 nlportid = ACCESS_ONCE(wdev->ap_unexpected_nlportid);
if (!nlportid)
return false;
msg = nlmsg_new(100, gfp);
if (!msg)
return true;
hdr = nl80211hdr_put(msg, 0, 0, 0, cmd);
if (!hdr) {
nlmsg_free(msg);
return true;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, addr))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlportid);
return true;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
return true;
}
bool cfg80211_rx_spurious_frame(struct net_device *dev,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
bool ret;
trace_cfg80211_rx_spurious_frame(dev, addr);
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO)) {
trace_cfg80211_return_bool(false);
return false;
}
ret = __nl80211_unexpected_frame(dev, NL80211_CMD_UNEXPECTED_FRAME,
addr, gfp);
trace_cfg80211_return_bool(ret);
return ret;
}
EXPORT_SYMBOL(cfg80211_rx_spurious_frame);
bool cfg80211_rx_unexpected_4addr_frame(struct net_device *dev,
const u8 *addr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
bool ret;
trace_cfg80211_rx_unexpected_4addr_frame(dev, addr);
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO &&
wdev->iftype != NL80211_IFTYPE_AP_VLAN)) {
trace_cfg80211_return_bool(false);
return false;
}
ret = __nl80211_unexpected_frame(dev,
NL80211_CMD_UNEXPECTED_4ADDR_FRAME,
addr, gfp);
trace_cfg80211_return_bool(ret);
return ret;
}
EXPORT_SYMBOL(cfg80211_rx_unexpected_4addr_frame);
int nl80211_send_mgmt(struct cfg80211_registered_device *rdev,
struct wireless_dev *wdev, u32 nlportid,
int freq, int sig_dbm,
const u8 *buf, size_t len, u32 flags, gfp_t gfp)
{
struct net_device *netdev = wdev->netdev;
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return -ENOMEM;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME);
if (!hdr) {
nlmsg_free(msg);
return -ENOMEM;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
(netdev && nla_put_u32(msg, NL80211_ATTR_IFINDEX,
netdev->ifindex)) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)) ||
nla_put_u32(msg, NL80211_ATTR_WIPHY_FREQ, freq) ||
(sig_dbm &&
nla_put_u32(msg, NL80211_ATTR_RX_SIGNAL_DBM, sig_dbm)) ||
nla_put(msg, NL80211_ATTR_FRAME, len, buf) ||
(flags &&
nla_put_u32(msg, NL80211_ATTR_RXMGMT_FLAGS, flags)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
return genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlportid);
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
return -ENOBUFS;
}
void cfg80211_mgmt_tx_status(struct wireless_dev *wdev, u64 cookie,
const u8 *buf, size_t len, bool ack, gfp_t gfp)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct net_device *netdev = wdev->netdev;
struct sk_buff *msg;
void *hdr;
trace_cfg80211_mgmt_tx_status(wdev, cookie, ack);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME_TX_STATUS);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
(netdev && nla_put_u32(msg, NL80211_ATTR_IFINDEX,
netdev->ifindex)) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)) ||
nla_put(msg, NL80211_ATTR_FRAME, len, buf) ||
nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie) ||
(ack && nla_put_flag(msg, NL80211_ATTR_ACK)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_mgmt_tx_status);
void cfg80211_cqm_rssi_notify(struct net_device *dev,
enum nl80211_cqm_rssi_threshold_event rssi_event,
gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
trace_cfg80211_cqm_rssi_notify(dev, rssi_event);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex))
goto nla_put_failure;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_CQM_RSSI_THRESHOLD_EVENT,
rssi_event))
goto nla_put_failure;
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_cqm_rssi_notify);
static void nl80211_gtk_rekey_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev, const u8 *bssid,
const u8 *replay_ctr, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *rekey_attr;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_SET_REKEY_OFFLOAD);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, bssid))
goto nla_put_failure;
rekey_attr = nla_nest_start(msg, NL80211_ATTR_REKEY_DATA);
if (!rekey_attr)
goto nla_put_failure;
if (nla_put(msg, NL80211_REKEY_DATA_REPLAY_CTR,
NL80211_REPLAY_CTR_LEN, replay_ctr))
goto nla_put_failure;
nla_nest_end(msg, rekey_attr);
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_gtk_rekey_notify(struct net_device *dev, const u8 *bssid,
const u8 *replay_ctr, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
trace_cfg80211_gtk_rekey_notify(dev, bssid);
nl80211_gtk_rekey_notify(rdev, dev, bssid, replay_ctr, gfp);
}
EXPORT_SYMBOL(cfg80211_gtk_rekey_notify);
static void
nl80211_pmksa_candidate_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev, int index,
const u8 *bssid, bool preauth, gfp_t gfp)
{
struct sk_buff *msg;
struct nlattr *attr;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_PMKSA_CANDIDATE);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex))
goto nla_put_failure;
attr = nla_nest_start(msg, NL80211_ATTR_PMKSA_CANDIDATE);
if (!attr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_PMKSA_CANDIDATE_INDEX, index) ||
nla_put(msg, NL80211_PMKSA_CANDIDATE_BSSID, ETH_ALEN, bssid) ||
(preauth &&
nla_put_flag(msg, NL80211_PMKSA_CANDIDATE_PREAUTH)))
goto nla_put_failure;
nla_nest_end(msg, attr);
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_pmksa_candidate_notify(struct net_device *dev, int index,
const u8 *bssid, bool preauth, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
trace_cfg80211_pmksa_candidate_notify(dev, index, bssid, preauth);
nl80211_pmksa_candidate_notify(rdev, dev, index, bssid, preauth, gfp);
}
EXPORT_SYMBOL(cfg80211_pmksa_candidate_notify);
static void nl80211_ch_switch_notify(struct cfg80211_registered_device *rdev,
struct net_device *netdev,
struct cfg80211_chan_def *chandef,
gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CH_SWITCH_NOTIFY);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex))
goto nla_put_failure;
if (nl80211_send_chandef(msg, chandef))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_ch_switch_notify(struct net_device *dev,
struct cfg80211_chan_def *chandef)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
ASSERT_WDEV_LOCK(wdev);
trace_cfg80211_ch_switch_notify(dev, chandef);
if (WARN_ON(wdev->iftype != NL80211_IFTYPE_AP &&
wdev->iftype != NL80211_IFTYPE_P2P_GO &&
wdev->iftype != NL80211_IFTYPE_ADHOC &&
wdev->iftype != NL80211_IFTYPE_MESH_POINT))
return;
wdev->chandef = *chandef;
wdev->preset_chandef = *chandef;
nl80211_ch_switch_notify(rdev, dev, chandef, GFP_KERNEL);
}
EXPORT_SYMBOL(cfg80211_ch_switch_notify);
void cfg80211_cqm_txe_notify(struct net_device *dev,
const u8 *peer, u32 num_packets,
u32 rate, u32 intvl, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
msg = nlmsg_new(NLMSG_GOODSIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, peer))
goto nla_put_failure;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_CQM_TXE_PKTS, num_packets))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_CQM_TXE_RATE, rate))
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_CQM_TXE_INTVL, intvl))
goto nla_put_failure;
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_cqm_txe_notify);
void
nl80211_radar_notify(struct cfg80211_registered_device *rdev,
const struct cfg80211_chan_def *chandef,
enum nl80211_radar_event event,
struct net_device *netdev, gfp_t gfp)
{
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_RADAR_DETECT);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx))
goto nla_put_failure;
/* NOP and radar events don't need a netdev parameter */
if (netdev) {
struct wireless_dev *wdev = netdev->ieee80211_ptr;
if (nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto nla_put_failure;
}
if (nla_put_u32(msg, NL80211_ATTR_RADAR_EVENT, event))
goto nla_put_failure;
if (nl80211_send_chandef(msg, chandef))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
void cfg80211_cqm_pktloss_notify(struct net_device *dev,
const u8 *peer, u32 num_packets, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
struct nlattr *pinfoattr;
void *hdr;
trace_cfg80211_cqm_pktloss_notify(dev, peer, num_packets);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_NOTIFY_CQM);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, peer))
goto nla_put_failure;
pinfoattr = nla_nest_start(msg, NL80211_ATTR_CQM);
if (!pinfoattr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_CQM_PKT_LOSS_EVENT, num_packets))
goto nla_put_failure;
nla_nest_end(msg, pinfoattr);
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_cqm_pktloss_notify);
void cfg80211_probe_status(struct net_device *dev, const u8 *addr,
u64 cookie, bool acked, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
trace_cfg80211_probe_status(dev, addr, cookie, acked);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_PROBE_CLIENT);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, addr) ||
nla_put_u64(msg, NL80211_ATTR_COOKIE, cookie) ||
(acked && nla_put_flag(msg, NL80211_ATTR_ACK)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_probe_status);
void cfg80211_report_obss_beacon(struct wiphy *wiphy,
const u8 *frame, size_t len,
int freq, int sig_dbm)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
struct cfg80211_beacon_registration *reg;
trace_cfg80211_report_obss_beacon(wiphy, frame, len, freq, sig_dbm);
spin_lock_bh(&rdev->beacon_registrations_lock);
list_for_each_entry(reg, &rdev->beacon_registrations, list) {
msg = nlmsg_new(len + 100, GFP_ATOMIC);
if (!msg) {
spin_unlock_bh(&rdev->beacon_registrations_lock);
return;
}
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FRAME);
if (!hdr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
(freq &&
nla_put_u32(msg, NL80211_ATTR_WIPHY_FREQ, freq)) ||
(sig_dbm &&
nla_put_u32(msg, NL80211_ATTR_RX_SIGNAL_DBM, sig_dbm)) ||
nla_put(msg, NL80211_ATTR_FRAME, len, frame))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, reg->nlportid);
}
spin_unlock_bh(&rdev->beacon_registrations_lock);
return;
nla_put_failure:
spin_unlock_bh(&rdev->beacon_registrations_lock);
if (hdr)
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_report_obss_beacon);
#ifdef CONFIG_PM
void cfg80211_report_wowlan_wakeup(struct wireless_dev *wdev,
struct cfg80211_wowlan_wakeup *wakeup,
gfp_t gfp)
{
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
int size = 200;
trace_cfg80211_report_wowlan_wakeup(wdev->wiphy, wdev, wakeup);
if (wakeup)
size += wakeup->packet_present_len;
msg = nlmsg_new(size, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_SET_WOWLAN);
if (!hdr)
goto free_msg;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto free_msg;
if (wdev->netdev && nla_put_u32(msg, NL80211_ATTR_IFINDEX,
wdev->netdev->ifindex))
goto free_msg;
if (wakeup) {
struct nlattr *reasons;
reasons = nla_nest_start(msg, NL80211_ATTR_WOWLAN_TRIGGERS);
if (!reasons)
goto free_msg;
if (wakeup->disconnect &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_DISCONNECT))
goto free_msg;
if (wakeup->magic_pkt &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_MAGIC_PKT))
goto free_msg;
if (wakeup->gtk_rekey_failure &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_GTK_REKEY_FAILURE))
goto free_msg;
if (wakeup->eap_identity_req &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_EAP_IDENT_REQUEST))
goto free_msg;
if (wakeup->four_way_handshake &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_4WAY_HANDSHAKE))
goto free_msg;
if (wakeup->rfkill_release &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_RFKILL_RELEASE))
goto free_msg;
if (wakeup->pattern_idx >= 0 &&
nla_put_u32(msg, NL80211_WOWLAN_TRIG_PKT_PATTERN,
wakeup->pattern_idx))
goto free_msg;
if (wakeup->tcp_match &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_WAKEUP_TCP_MATCH))
goto free_msg;
if (wakeup->tcp_connlost &&
nla_put_flag(msg, NL80211_WOWLAN_TRIG_WAKEUP_TCP_CONNLOST))
goto free_msg;
if (wakeup->tcp_nomoretokens &&
nla_put_flag(msg,
NL80211_WOWLAN_TRIG_WAKEUP_TCP_NOMORETOKENS))
goto free_msg;
if (wakeup->packet) {
u32 pkt_attr = NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211;
u32 len_attr = NL80211_WOWLAN_TRIG_WAKEUP_PKT_80211_LEN;
if (!wakeup->packet_80211) {
pkt_attr =
NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023;
len_attr =
NL80211_WOWLAN_TRIG_WAKEUP_PKT_8023_LEN;
}
if (wakeup->packet_len &&
nla_put_u32(msg, len_attr, wakeup->packet_len))
goto free_msg;
if (nla_put(msg, pkt_attr, wakeup->packet_present_len,
wakeup->packet))
goto free_msg;
}
nla_nest_end(msg, reasons);
}
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
free_msg:
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_report_wowlan_wakeup);
#endif
void cfg80211_tdls_oper_request(struct net_device *dev, const u8 *peer,
enum nl80211_tdls_operation oper,
u16 reason_code, gfp_t gfp)
{
struct wireless_dev *wdev = dev->ieee80211_ptr;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wdev->wiphy);
struct sk_buff *msg;
void *hdr;
trace_cfg80211_tdls_oper_request(wdev->wiphy, dev, peer, oper,
reason_code);
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_TDLS_OPER);
if (!hdr) {
nlmsg_free(msg);
return;
}
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, dev->ifindex) ||
nla_put_u8(msg, NL80211_ATTR_TDLS_OPERATION, oper) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, peer) ||
(reason_code > 0 &&
nla_put_u16(msg, NL80211_ATTR_REASON_CODE, reason_code)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, gfp);
return;
nla_put_failure:
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_tdls_oper_request);
static int nl80211_netlink_notify(struct notifier_block * nb,
unsigned long state,
void *_notify)
{
struct netlink_notify *notify = _notify;
struct cfg80211_registered_device *rdev;
struct wireless_dev *wdev;
struct cfg80211_beacon_registration *reg, *tmp;
if (state != NETLINK_URELEASE)
return NOTIFY_DONE;
rcu_read_lock();
list_for_each_entry_rcu(rdev, &cfg80211_rdev_list, list) {
list_for_each_entry_rcu(wdev, &rdev->wdev_list, list)
cfg80211_mlme_unregister_socket(wdev, notify->portid);
spin_lock_bh(&rdev->beacon_registrations_lock);
list_for_each_entry_safe(reg, tmp, &rdev->beacon_registrations,
list) {
if (reg->nlportid == notify->portid) {
list_del(®->list);
kfree(reg);
break;
}
}
spin_unlock_bh(&rdev->beacon_registrations_lock);
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static struct notifier_block nl80211_netlink_notifier = {
.notifier_call = nl80211_netlink_notify,
};
void cfg80211_ft_event(struct net_device *netdev,
struct cfg80211_ft_event_params *ft_event)
{
struct wiphy *wiphy = netdev->ieee80211_ptr->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
trace_cfg80211_ft_event(wiphy, netdev, ft_event);
if (!ft_event->target_ap)
return;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_FT_EVENT);
if (!hdr)
goto out;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, netdev->ifindex) ||
nla_put(msg, NL80211_ATTR_MAC, ETH_ALEN, ft_event->target_ap))
goto out;
if (ft_event->ies &&
nla_put(msg, NL80211_ATTR_IE, ft_event->ies_len, ft_event->ies))
goto out;
if (ft_event->ric_ies &&
nla_put(msg, NL80211_ATTR_IE_RIC, ft_event->ric_ies_len,
ft_event->ric_ies))
goto out;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(&rdev->wiphy), msg, 0,
NL80211_MCGRP_MLME, GFP_KERNEL);
return;
out:
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_ft_event);
void cfg80211_crit_proto_stopped(struct wireless_dev *wdev, gfp_t gfp)
{
struct cfg80211_registered_device *rdev;
struct sk_buff *msg;
void *hdr;
u32 nlportid;
rdev = wiphy_to_dev(wdev->wiphy);
if (!rdev->crit_proto_nlportid)
return;
nlportid = rdev->crit_proto_nlportid;
rdev->crit_proto_nlportid = 0;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, gfp);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_CRIT_PROTOCOL_STOP);
if (!hdr)
goto nla_put_failure;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto nla_put_failure;
genlmsg_end(msg, hdr);
genlmsg_unicast(wiphy_net(&rdev->wiphy), msg, nlportid);
return;
nla_put_failure:
if (hdr)
genlmsg_cancel(msg, hdr);
nlmsg_free(msg);
}
EXPORT_SYMBOL(cfg80211_crit_proto_stopped);
void nl80211_send_ap_stopped(struct wireless_dev *wdev)
{
struct wiphy *wiphy = wdev->wiphy;
struct cfg80211_registered_device *rdev = wiphy_to_dev(wiphy);
struct sk_buff *msg;
void *hdr;
msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
if (!msg)
return;
hdr = nl80211hdr_put(msg, 0, 0, 0, NL80211_CMD_STOP_AP);
if (!hdr)
goto out;
if (nla_put_u32(msg, NL80211_ATTR_WIPHY, rdev->wiphy_idx) ||
nla_put_u32(msg, NL80211_ATTR_IFINDEX, wdev->netdev->ifindex) ||
nla_put_u64(msg, NL80211_ATTR_WDEV, wdev_id(wdev)))
goto out;
genlmsg_end(msg, hdr);
genlmsg_multicast_netns(&nl80211_fam, wiphy_net(wiphy), msg, 0,
NL80211_MCGRP_MLME, GFP_KERNEL);
return;
out:
nlmsg_free(msg);
}
/* initialisation/exit functions */
int nl80211_init(void)
{
int err;
err = genl_register_family_with_ops_groups(&nl80211_fam, nl80211_ops,
nl80211_mcgrps);
if (err)
return err;
err = netlink_register_notifier(&nl80211_netlink_notifier);
if (err)
goto err_out;
return 0;
err_out:
genl_unregister_family(&nl80211_fam);
return err;
}
void nl80211_exit(void)
{
netlink_unregister_notifier(&nl80211_netlink_notifier);
genl_unregister_family(&nl80211_fam);
}
| gpl-2.0 |
MattCrystal/jewel-jb | drivers/mfd/pm8xxx-irq.c | 303 | 12761 | /*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#define pr_fmt(fmt) "%s: " fmt, __func__
#include <linux/export.h>
#include <linux/err.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/mfd/pm8xxx/core.h>
#include <linux/mfd/pm8xxx/irq.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#define SSBI_REG_ADDR_IRQ_ROOT(base) (base + 0)
#define SSBI_REG_ADDR_IRQ_M_STATUS1(base) (base + 1)
#define SSBI_REG_ADDR_IRQ_M_STATUS2(base) (base + 2)
#define SSBI_REG_ADDR_IRQ_M_STATUS3(base) (base + 3)
#define SSBI_REG_ADDR_IRQ_M_STATUS4(base) (base + 4)
#define SSBI_REG_ADDR_IRQ_BLK_SEL(base) (base + 5)
#define SSBI_REG_ADDR_IRQ_IT_STATUS(base) (base + 6)
#define SSBI_REG_ADDR_IRQ_CONFIG(base) (base + 7)
#define SSBI_REG_ADDR_IRQ_RT_STATUS(base) (base + 8)
#define PM_IRQF_LVL_SEL 0x01
#define PM_IRQF_MASK_FE 0x02
#define PM_IRQF_MASK_RE 0x04
#define PM_IRQF_CLR 0x08
#define PM_IRQF_BITS_MASK 0x70
#define PM_IRQF_BITS_SHIFT 4
#define PM_IRQF_WRITE 0x80
#define PM_IRQF_MASK_ALL (PM_IRQF_MASK_FE | \
PM_IRQF_MASK_RE)
#define MAX_PM_IRQ 256
struct pm_irq_chip {
struct device *dev;
spinlock_t pm_irq_lock;
unsigned int base_addr;
unsigned int devirq;
unsigned int irq_base;
unsigned int num_irqs;
unsigned int num_blocks;
unsigned int num_masters;
u8 config[0];
};
struct pm_irq_wake_state
{
u8 wake_enable[MAX_PM_IRQ];
u16 count_wakeable;
};
struct pm_irq_wake_state pm8xxx_wake_state;
static int pm8xxx_read_root_irq(const struct pm_irq_chip *chip, u8 *rp)
{
return pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_ROOT(chip->base_addr), rp);
}
static int pm8xxx_read_master_irq(const struct pm_irq_chip *chip, u8 m, u8 *bp)
{
return pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_M_STATUS1(chip->base_addr) + m, bp);
}
static int pm8xxx_read_block_irq(struct pm_irq_chip *chip, u8 bp, u8 *ip)
{
int rc;
spin_lock(&chip->pm_irq_lock);
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_BLK_SEL(chip->base_addr), bp);
if (rc) {
pr_err("Failed Selecting Block %d rc=%d\n", bp, rc);
goto bail;
}
rc = pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_IT_STATUS(chip->base_addr), ip);
if (rc)
pr_err("Failed Reading Status rc=%d\n", rc);
bail:
spin_unlock(&chip->pm_irq_lock);
return rc;
}
static int pm8xxx_read_config_irq(struct pm_irq_chip *chip, u8 bp, u8 cp, u8 *r)
{
int rc;
spin_lock(&chip->pm_irq_lock);
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_BLK_SEL(chip->base_addr), bp);
if (rc) {
pr_err("Failed Selecting Block %d rc=%d\n", bp, rc);
goto bail;
}
cp &= ~PM_IRQF_WRITE;
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_CONFIG(chip->base_addr), cp);
if (rc)
pr_err("Failed Configuring IRQ rc=%d\n", rc);
rc = pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_CONFIG(chip->base_addr), r);
if (rc)
pr_err("Failed reading IRQ rc=%d\n", rc);
bail:
spin_unlock(&chip->pm_irq_lock);
return rc;
}
static int pm8xxx_write_config_irq(struct pm_irq_chip *chip, u8 bp, u8 cp)
{
int rc;
spin_lock(&chip->pm_irq_lock);
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_BLK_SEL(chip->base_addr), bp);
if (rc) {
pr_err("Failed Selecting Block %d rc=%d\n", bp, rc);
goto bail;
}
cp |= PM_IRQF_WRITE;
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_CONFIG(chip->base_addr), cp);
if (rc)
pr_err("Failed Configuring IRQ rc=%d\n", rc);
bail:
spin_unlock(&chip->pm_irq_lock);
return rc;
}
static int pm8xxx_irq_block_handler(struct pm_irq_chip *chip, int block)
{
int pmirq, irq, i, ret = 0;
u8 bits;
ret = pm8xxx_read_block_irq(chip, block, &bits);
if (ret) {
pr_err("Failed reading %d block ret=%d", block, ret);
return ret;
}
if (!bits) {
pr_err("block bit set in master but no irqs: %d", block);
return 0;
}
for (i = 0; i < 8; i++) {
if (bits & (1 << i)) {
pmirq = block * 8 + i;
irq = pmirq + chip->irq_base;
generic_handle_irq(irq);
}
}
return 0;
}
static int pm8xxx_irq_master_handler(struct pm_irq_chip *chip, int master)
{
u8 blockbits;
int block_number, i, ret = 0;
ret = pm8xxx_read_master_irq(chip, master, &blockbits);
if (ret) {
pr_err("Failed to read master %d ret=%d\n", master, ret);
return ret;
}
if (!blockbits) {
pr_err("master bit set in root but no blocks: %d", master);
return 0;
}
for (i = 0; i < 8; i++)
if (blockbits & (1 << i)) {
block_number = master * 8 + i;
ret |= pm8xxx_irq_block_handler(chip, block_number);
}
return ret;
}
static irqreturn_t pm8xxx_irq_handler(int irq, void *data)
{
struct pm_irq_chip *chip = data;
u8 root;
int i, ret, masters = 0;
ret = pm8xxx_read_root_irq(chip, &root);
if (ret) {
pr_err("Can't read root status ret=%d\n", ret);
return IRQ_HANDLED;
}
masters = root >> 1;
for (i = 0; i < chip->num_masters; i++)
if (masters & (1 << i))
pm8xxx_irq_master_handler(chip, i);
return IRQ_HANDLED;
}
static void pm8xxx_irq_mask(struct irq_data *d)
{
struct pm_irq_chip *chip = irq_data_get_irq_chip_data(d);
unsigned int pmirq = d->irq - chip->irq_base;
int master, irq_bit;
u8 block, config;
block = pmirq / 8;
master = block / 8;
irq_bit = pmirq % 8;
if (chip->config[pmirq] == 0) {
pr_warn("masking rogue irq=%d pmirq=%d\n", d->irq, pmirq);
chip->config[pmirq] = irq_bit << PM_IRQF_BITS_SHIFT;
}
config = chip->config[pmirq] | PM_IRQF_MASK_ALL;
pm8xxx_write_config_irq(chip, block, config);
}
static void pm8xxx_irq_mask_ack(struct irq_data *d)
{
struct pm_irq_chip *chip = irq_data_get_irq_chip_data(d);
unsigned int pmirq = d->irq - chip->irq_base;
int master, irq_bit;
u8 block, config;
block = pmirq / 8;
master = block / 8;
irq_bit = pmirq % 8;
if (chip->config[pmirq] == 0) {
pr_warn("mask acking rogue irq=%d pmirq=%d\n", d->irq, pmirq);
chip->config[pmirq] = irq_bit << PM_IRQF_BITS_SHIFT;
}
config = chip->config[pmirq] | PM_IRQF_MASK_ALL | PM_IRQF_CLR;
pm8xxx_write_config_irq(chip, block, config);
}
static void pm8xxx_irq_unmask(struct irq_data *d)
{
struct pm_irq_chip *chip = irq_data_get_irq_chip_data(d);
unsigned int pmirq = d->irq - chip->irq_base;
int master, irq_bit;
u8 block, config, hw_conf;
block = pmirq / 8;
master = block / 8;
irq_bit = pmirq % 8;
config = chip->config[pmirq];
pm8xxx_read_config_irq(chip, block, config, &hw_conf);
if ((hw_conf & PM_IRQF_MASK_ALL) == PM_IRQF_MASK_ALL)
pm8xxx_write_config_irq(chip, block, config);
}
static int pm8xxx_irq_set_type(struct irq_data *d, unsigned int flow_type)
{
struct pm_irq_chip *chip = irq_data_get_irq_chip_data(d);
unsigned int pmirq = d->irq - chip->irq_base;
int master, irq_bit;
u8 block, config;
block = pmirq / 8;
master = block / 8;
irq_bit = pmirq % 8;
chip->config[pmirq] = (irq_bit << PM_IRQF_BITS_SHIFT)
| PM_IRQF_MASK_ALL;
if (flow_type & (IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING)) {
if (flow_type & IRQF_TRIGGER_RISING)
chip->config[pmirq] &= ~PM_IRQF_MASK_RE;
if (flow_type & IRQF_TRIGGER_FALLING)
chip->config[pmirq] &= ~PM_IRQF_MASK_FE;
} else {
chip->config[pmirq] |= PM_IRQF_LVL_SEL;
if (flow_type & IRQF_TRIGGER_HIGH)
chip->config[pmirq] &= ~PM_IRQF_MASK_RE;
else
chip->config[pmirq] &= ~PM_IRQF_MASK_FE;
}
chip->config[pmirq] |= PM_IRQF_WRITE;
config = chip->config[pmirq] | PM_IRQF_CLR;
return pm8xxx_write_config_irq(chip, block, config);
}
static int pm8xxx_irq_set_wake(struct irq_data *d, unsigned int on)
{
struct pm_irq_chip *chip;
unsigned int irq;
chip = irq_data_get_irq_chip_data(d);
irq = d->irq - chip->irq_base;
if (on) {
if (!pm8xxx_wake_state.wake_enable[irq]) {
pm8xxx_wake_state.wake_enable[irq] = 1;
pm8xxx_wake_state.count_wakeable++;
}
} else {
if (pm8xxx_wake_state.wake_enable[irq]) {
pm8xxx_wake_state.wake_enable[irq] = 0;
pm8xxx_wake_state.count_wakeable--;
}
}
return 0;
}
static int pm8xxx_irq_read_line(struct irq_data *d)
{
struct pm_irq_chip *chip = irq_data_get_irq_chip_data(d);
return pm8xxx_get_irq_stat(chip, d->irq);
}
static struct irq_chip pm8xxx_irq_chip = {
.name = "pm8xxx",
.irq_mask = pm8xxx_irq_mask,
.irq_mask_ack = pm8xxx_irq_mask_ack,
.irq_unmask = pm8xxx_irq_unmask,
.irq_set_type = pm8xxx_irq_set_type,
.irq_set_wake = pm8xxx_irq_set_wake,
.irq_read_line = pm8xxx_irq_read_line,
.flags = IRQCHIP_MASK_ON_SUSPEND,
};
int pm8xxx_get_irq_stat(struct pm_irq_chip *chip, int irq)
{
int pmirq, rc;
u8 block, bits, bit;
unsigned long flags;
if (chip == NULL || irq < chip->irq_base ||
irq >= chip->irq_base + chip->num_irqs)
return -EINVAL;
pmirq = irq - chip->irq_base;
block = pmirq / 8;
bit = pmirq % 8;
spin_lock_irqsave(&chip->pm_irq_lock, flags);
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_BLK_SEL(chip->base_addr), block);
if (rc) {
pr_err("Failed Selecting block irq=%d pmirq=%d blk=%d rc=%d\n",
irq, pmirq, block, rc);
goto bail_out;
}
rc = pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_RT_STATUS(chip->base_addr), &bits);
if (rc) {
pr_err("Failed Configuring irq=%d pmirq=%d blk=%d rc=%d\n",
irq, pmirq, block, rc);
goto bail_out;
}
rc = (bits & (1 << bit)) ? 1 : 0;
bail_out:
spin_unlock_irqrestore(&chip->pm_irq_lock, flags);
return rc;
}
EXPORT_SYMBOL_GPL(pm8xxx_get_irq_stat);
int pm8xxx_get_irq_it_stat(struct pm_irq_chip *chip, int irq)
{
int pmirq, rc;
u8 block, bits, bit;
if (chip == NULL || irq < chip->irq_base ||
irq >= chip->irq_base + chip->num_irqs)
return -EINVAL;
pmirq = irq - chip->irq_base;
block = pmirq / 8;
bit = pmirq % 8;
rc = pm8xxx_writeb(chip->dev,
SSBI_REG_ADDR_IRQ_BLK_SEL(chip->base_addr), block);
if (rc) {
pr_err("Failed Selecting block irq=%d pmirq=%d blk=%d rc=%d\n",
irq, pmirq, block, rc);
goto bail_out;
}
rc = pm8xxx_readb(chip->dev,
SSBI_REG_ADDR_IRQ_IT_STATUS(chip->base_addr), &bits);
if (rc) {
pr_err("Failed Configuring irq=%d pmirq=%d blk=%d rc=%d\n",
irq, pmirq, block, rc);
goto bail_out;
}
rc = (bits & (1 << bit)) ? 1 : 0;
bail_out:
return rc;
}
EXPORT_SYMBOL_GPL(pm8xxx_get_irq_it_stat);
int pm8xxx_get_irq_wake_stat(struct pm_irq_chip *chip, int irq)
{
if (chip == NULL || irq < chip->irq_base ||
irq >= chip->irq_base + chip->num_irqs)
return -EINVAL;
return pm8xxx_wake_state.wake_enable[(irq-chip->irq_base)];
}
EXPORT_SYMBOL_GPL(pm8xxx_get_irq_wake_stat);
int pm8xxx_get_irq_base(struct pm_irq_chip *chip)
{
if (chip == NULL)
return -EINVAL;
return chip->irq_base;
}
EXPORT_SYMBOL_GPL(pm8xxx_get_irq_base);
struct pm_irq_chip * __devinit pm8xxx_irq_init(struct device *dev,
const struct pm8xxx_irq_platform_data *pdata)
{
struct pm_irq_chip *chip;
int devirq, rc;
unsigned int pmirq;
if (!pdata) {
pr_err("No platform data\n");
return ERR_PTR(-EINVAL);
}
devirq = pdata->devirq;
if (devirq < 0) {
pr_err("missing devirq\n");
rc = devirq;
return ERR_PTR(-EINVAL);
}
chip = kzalloc(sizeof(struct pm_irq_chip)
+ sizeof(u8) * pdata->irq_cdata.nirqs, GFP_KERNEL);
if (!chip) {
pr_err("Cannot alloc pm_irq_chip struct\n");
return ERR_PTR(-EINVAL);
}
memset((void*)&pm8xxx_wake_state.wake_enable[0],0,sizeof(u8)*MAX_PM_IRQ);
pm8xxx_wake_state.count_wakeable = 0;
chip->dev = dev;
chip->devirq = devirq;
chip->irq_base = pdata->irq_base;
chip->num_irqs = pdata->irq_cdata.nirqs;
chip->base_addr = pdata->irq_cdata.base_addr;
chip->num_blocks = DIV_ROUND_UP(chip->num_irqs, 8);
chip->num_masters = DIV_ROUND_UP(chip->num_blocks, 8);
spin_lock_init(&chip->pm_irq_lock);
for (pmirq = 0; pmirq < chip->num_irqs; pmirq++) {
irq_set_chip_and_handler(chip->irq_base + pmirq,
&pm8xxx_irq_chip,
handle_level_irq);
irq_set_chip_data(chip->irq_base + pmirq, chip);
#ifdef CONFIG_ARM
set_irq_flags(chip->irq_base + pmirq, IRQF_VALID);
#else
irq_set_noprobe(chip->irq_base + pmirq);
#endif
}
if (devirq != 0) {
rc = request_irq(devirq, pm8xxx_irq_handler,
pdata->irq_trigger_flag,
"pm8xxx_usr_irq", chip);
if (rc) {
pr_err("failed to request_irq for %d rc=%d\n",
devirq, rc);
} else {
irq_set_irq_wake(devirq, 1);
}
}
return chip;
}
int pm8xxx_irq_exit(struct pm_irq_chip *chip)
{
irq_set_chained_handler(chip->devirq, NULL);
kfree(chip);
return 0;
}
| gpl-2.0 |
sirgatez/Android-Froyo-Kernel-Source-v2.6.32.9 | drivers/leds/leds-wm831x-status.c | 559 | 7935 | /*
* LED driver for WM831x status LEDs
*
* Copyright(C) 2009 Wolfson Microelectronics PLC.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/leds.h>
#include <linux/err.h>
#include <linux/mfd/wm831x/core.h>
#include <linux/mfd/wm831x/pdata.h>
#include <linux/mfd/wm831x/status.h>
struct wm831x_status {
struct led_classdev cdev;
struct wm831x *wm831x;
struct work_struct work;
struct mutex mutex;
spinlock_t value_lock;
int reg; /* Control register */
int reg_val; /* Control register value */
int blink;
int blink_time;
int blink_cyc;
int src;
enum led_brightness brightness;
};
#define to_wm831x_status(led_cdev) \
container_of(led_cdev, struct wm831x_status, cdev)
static void wm831x_status_work(struct work_struct *work)
{
struct wm831x_status *led = container_of(work, struct wm831x_status,
work);
unsigned long flags;
mutex_lock(&led->mutex);
led->reg_val &= ~(WM831X_LED_SRC_MASK | WM831X_LED_MODE_MASK |
WM831X_LED_DUTY_CYC_MASK | WM831X_LED_DUR_MASK);
spin_lock_irqsave(&led->value_lock, flags);
led->reg_val |= led->src << WM831X_LED_SRC_SHIFT;
if (led->blink) {
led->reg_val |= 2 << WM831X_LED_MODE_SHIFT;
led->reg_val |= led->blink_time << WM831X_LED_DUR_SHIFT;
led->reg_val |= led->blink_cyc;
} else {
if (led->brightness != LED_OFF)
led->reg_val |= 1 << WM831X_LED_MODE_SHIFT;
}
spin_unlock_irqrestore(&led->value_lock, flags);
wm831x_reg_write(led->wm831x, led->reg, led->reg_val);
mutex_unlock(&led->mutex);
}
static void wm831x_status_set(struct led_classdev *led_cdev,
enum led_brightness value)
{
struct wm831x_status *led = to_wm831x_status(led_cdev);
unsigned long flags;
spin_lock_irqsave(&led->value_lock, flags);
led->brightness = value;
if (value == LED_OFF)
led->blink = 0;
schedule_work(&led->work);
spin_unlock_irqrestore(&led->value_lock, flags);
}
static int wm831x_status_blink_set(struct led_classdev *led_cdev,
unsigned long *delay_on,
unsigned long *delay_off)
{
struct wm831x_status *led = to_wm831x_status(led_cdev);
unsigned long flags;
int ret = 0;
/* Pick some defaults if we've not been given times */
if (*delay_on == 0 && *delay_off == 0) {
*delay_on = 250;
*delay_off = 250;
}
spin_lock_irqsave(&led->value_lock, flags);
/* We only have a limited selection of settings, see if we can
* support the configuration we're being given */
switch (*delay_on) {
case 1000:
led->blink_time = 0;
break;
case 250:
led->blink_time = 1;
break;
case 125:
led->blink_time = 2;
break;
case 62:
case 63:
/* Actually 62.5ms */
led->blink_time = 3;
break;
default:
ret = -EINVAL;
break;
}
if (ret == 0) {
switch (*delay_off / *delay_on) {
case 1:
led->blink_cyc = 0;
break;
case 3:
led->blink_cyc = 1;
break;
case 4:
led->blink_cyc = 2;
break;
case 8:
led->blink_cyc = 3;
break;
default:
ret = -EINVAL;
break;
}
}
if (ret == 0)
led->blink = 1;
else
led->blink = 0;
/* Always update; if we fail turn off blinking since we expect
* a software fallback. */
schedule_work(&led->work);
spin_unlock_irqrestore(&led->value_lock, flags);
return ret;
}
static const char *led_src_texts[] = {
"otp",
"power",
"charger",
"soft",
};
static ssize_t wm831x_status_src_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct wm831x_status *led = to_wm831x_status(led_cdev);
int i;
ssize_t ret = 0;
mutex_lock(&led->mutex);
for (i = 0; i < ARRAY_SIZE(led_src_texts); i++)
if (i == led->src)
ret += sprintf(&buf[ret], "[%s] ", led_src_texts[i]);
else
ret += sprintf(&buf[ret], "%s ", led_src_texts[i]);
mutex_unlock(&led->mutex);
ret += sprintf(&buf[ret], "\n");
return ret;
}
static ssize_t wm831x_status_src_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct led_classdev *led_cdev = dev_get_drvdata(dev);
struct wm831x_status *led = to_wm831x_status(led_cdev);
char name[20];
int i;
size_t len;
name[sizeof(name) - 1] = '\0';
strncpy(name, buf, sizeof(name) - 1);
len = strlen(name);
if (len && name[len - 1] == '\n')
name[len - 1] = '\0';
for (i = 0; i < ARRAY_SIZE(led_src_texts); i++) {
if (!strcmp(name, led_src_texts[i])) {
mutex_lock(&led->mutex);
led->src = i;
schedule_work(&led->work);
mutex_unlock(&led->mutex);
}
}
return size;
}
static DEVICE_ATTR(src, 0644, wm831x_status_src_show, wm831x_status_src_store);
static int wm831x_status_probe(struct platform_device *pdev)
{
struct wm831x *wm831x = dev_get_drvdata(pdev->dev.parent);
struct wm831x_pdata *chip_pdata;
struct wm831x_status_pdata pdata;
struct wm831x_status *drvdata;
struct resource *res;
int id = pdev->id % ARRAY_SIZE(chip_pdata->status);
int ret;
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (res == NULL) {
dev_err(&pdev->dev, "No I/O resource\n");
ret = -EINVAL;
goto err;
}
drvdata = kzalloc(sizeof(struct wm831x_status), GFP_KERNEL);
if (!drvdata)
return -ENOMEM;
dev_set_drvdata(&pdev->dev, drvdata);
drvdata->wm831x = wm831x;
drvdata->reg = res->start;
if (wm831x->dev->platform_data)
chip_pdata = wm831x->dev->platform_data;
else
chip_pdata = NULL;
memset(&pdata, 0, sizeof(pdata));
if (chip_pdata && chip_pdata->status[id])
memcpy(&pdata, chip_pdata->status[id], sizeof(pdata));
else
pdata.name = dev_name(&pdev->dev);
mutex_init(&drvdata->mutex);
INIT_WORK(&drvdata->work, wm831x_status_work);
spin_lock_init(&drvdata->value_lock);
/* We cache the configuration register and read startup values
* from it. */
drvdata->reg_val = wm831x_reg_read(wm831x, drvdata->reg);
if (drvdata->reg_val & WM831X_LED_MODE_MASK)
drvdata->brightness = LED_FULL;
else
drvdata->brightness = LED_OFF;
/* Set a default source if configured, otherwise leave the
* current hardware setting.
*/
if (pdata.default_src == WM831X_STATUS_PRESERVE) {
drvdata->src = drvdata->reg_val;
drvdata->src &= WM831X_LED_SRC_MASK;
drvdata->src >>= WM831X_LED_SRC_SHIFT;
} else {
drvdata->src = pdata.default_src - 1;
}
drvdata->cdev.name = pdata.name;
drvdata->cdev.default_trigger = pdata.default_trigger;
drvdata->cdev.brightness_set = wm831x_status_set;
drvdata->cdev.blink_set = wm831x_status_blink_set;
ret = led_classdev_register(wm831x->dev, &drvdata->cdev);
if (ret < 0) {
dev_err(&pdev->dev, "Failed to register LED: %d\n", ret);
goto err_led;
}
ret = device_create_file(drvdata->cdev.dev, &dev_attr_src);
if (ret != 0)
dev_err(&pdev->dev,
"No source control for LED: %d\n", ret);
return 0;
err_led:
led_classdev_unregister(&drvdata->cdev);
kfree(drvdata);
err:
return ret;
}
static int wm831x_status_remove(struct platform_device *pdev)
{
struct wm831x_status *drvdata = platform_get_drvdata(pdev);
device_remove_file(drvdata->cdev.dev, &dev_attr_src);
led_classdev_unregister(&drvdata->cdev);
kfree(drvdata);
return 0;
}
static struct platform_driver wm831x_status_driver = {
.driver = {
.name = "wm831x-status",
.owner = THIS_MODULE,
},
.probe = wm831x_status_probe,
.remove = wm831x_status_remove,
};
static int __devinit wm831x_status_init(void)
{
return platform_driver_register(&wm831x_status_driver);
}
module_init(wm831x_status_init);
static void wm831x_status_exit(void)
{
platform_driver_unregister(&wm831x_status_driver);
}
module_exit(wm831x_status_exit);
MODULE_AUTHOR("Mark Brown <broonie@opensource.wolfsonmicro.com>");
MODULE_DESCRIPTION("WM831x status LED driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:wm831x-status");
| gpl-2.0 |
ztemt/Z9Max_NX510J_V1_kernel | drivers/net/wireless/rt2x00/rt2x00firmware.c | 2351 | 3393 | /*
Copyright (C) 2004 - 2009 Ivo van Doorn <IvDoorn@gmail.com>
Copyright (C) 2004 - 2009 Gertjan van Wingerde <gwingerde@gmail.com>
<http://rt2x00.serialmonkey.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the
Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/*
Module: rt2x00lib
Abstract: rt2x00 firmware loading routines.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include "rt2x00.h"
#include "rt2x00lib.h"
static int rt2x00lib_request_firmware(struct rt2x00_dev *rt2x00dev)
{
struct device *device = wiphy_dev(rt2x00dev->hw->wiphy);
const struct firmware *fw;
char *fw_name;
int retval;
/*
* Read correct firmware from harddisk.
*/
fw_name = rt2x00dev->ops->lib->get_firmware_name(rt2x00dev);
if (!fw_name) {
rt2x00_err(rt2x00dev,
"Invalid firmware filename\n"
"Please file bug report to %s\n", DRV_PROJECT);
return -EINVAL;
}
rt2x00_info(rt2x00dev, "Loading firmware file '%s'\n", fw_name);
retval = request_firmware(&fw, fw_name, device);
if (retval) {
rt2x00_err(rt2x00dev, "Failed to request Firmware\n");
return retval;
}
if (!fw || !fw->size || !fw->data) {
rt2x00_err(rt2x00dev, "Failed to read Firmware\n");
release_firmware(fw);
return -ENOENT;
}
rt2x00_info(rt2x00dev, "Firmware detected - version: %d.%d\n",
fw->data[fw->size - 4], fw->data[fw->size - 3]);
snprintf(rt2x00dev->hw->wiphy->fw_version,
sizeof(rt2x00dev->hw->wiphy->fw_version), "%d.%d",
fw->data[fw->size - 4], fw->data[fw->size - 3]);
retval = rt2x00dev->ops->lib->check_firmware(rt2x00dev, fw->data, fw->size);
switch (retval) {
case FW_OK:
break;
case FW_BAD_CRC:
rt2x00_err(rt2x00dev, "Firmware checksum error\n");
goto exit;
case FW_BAD_LENGTH:
rt2x00_err(rt2x00dev, "Invalid firmware file length (len=%zu)\n",
fw->size);
goto exit;
case FW_BAD_VERSION:
rt2x00_err(rt2x00dev, "Current firmware does not support detected chipset\n");
goto exit;
}
rt2x00dev->fw = fw;
return 0;
exit:
release_firmware(fw);
return -ENOENT;
}
int rt2x00lib_load_firmware(struct rt2x00_dev *rt2x00dev)
{
int retval;
if (!test_bit(REQUIRE_FIRMWARE, &rt2x00dev->cap_flags))
return 0;
if (!rt2x00dev->fw) {
retval = rt2x00lib_request_firmware(rt2x00dev);
if (retval)
return retval;
}
/*
* Send firmware to the device.
*/
retval = rt2x00dev->ops->lib->load_firmware(rt2x00dev,
rt2x00dev->fw->data,
rt2x00dev->fw->size);
/*
* When the firmware is uploaded to the hardware the LED
* association status might have been triggered, for correct
* LED handling it should now be reset.
*/
rt2x00leds_led_assoc(rt2x00dev, false);
return retval;
}
void rt2x00lib_free_firmware(struct rt2x00_dev *rt2x00dev)
{
release_firmware(rt2x00dev->fw);
rt2x00dev->fw = NULL;
}
| gpl-2.0 |
mozzwald/linux-sunxi-marsboard-a20 | drivers/acpi/thermal.c | 4655 | 30075 | /*
* acpi_thermal.c - ACPI Thermal Zone Driver ($Revision: 41 $)
*
* Copyright (C) 2001, 2002 Andy Grover <andrew.grover@intel.com>
* Copyright (C) 2001, 2002 Paul Diefenbaugh <paul.s.diefenbaugh@intel.com>
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* This driver fully implements the ACPI thermal policy as described in the
* ACPI 2.0 Specification.
*
* TBD: 1. Implement passive cooling hysteresis.
* 2. Enhance passive cooling (CPU) states/limit interface to support
* concepts of 'multiple limiters', upper/lower limits, etc.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/dmi.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/types.h>
#include <linux/jiffies.h>
#include <linux/kmod.h>
#include <linux/reboot.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <linux/thermal.h>
#include <acpi/acpi_bus.h>
#include <acpi/acpi_drivers.h>
#define PREFIX "ACPI: "
#define ACPI_THERMAL_CLASS "thermal_zone"
#define ACPI_THERMAL_DEVICE_NAME "Thermal Zone"
#define ACPI_THERMAL_FILE_STATE "state"
#define ACPI_THERMAL_FILE_TEMPERATURE "temperature"
#define ACPI_THERMAL_FILE_TRIP_POINTS "trip_points"
#define ACPI_THERMAL_FILE_COOLING_MODE "cooling_mode"
#define ACPI_THERMAL_FILE_POLLING_FREQ "polling_frequency"
#define ACPI_THERMAL_NOTIFY_TEMPERATURE 0x80
#define ACPI_THERMAL_NOTIFY_THRESHOLDS 0x81
#define ACPI_THERMAL_NOTIFY_DEVICES 0x82
#define ACPI_THERMAL_NOTIFY_CRITICAL 0xF0
#define ACPI_THERMAL_NOTIFY_HOT 0xF1
#define ACPI_THERMAL_MODE_ACTIVE 0x00
#define ACPI_THERMAL_MAX_ACTIVE 10
#define ACPI_THERMAL_MAX_LIMIT_STR_LEN 65
#define _COMPONENT ACPI_THERMAL_COMPONENT
ACPI_MODULE_NAME("thermal");
MODULE_AUTHOR("Paul Diefenbaugh");
MODULE_DESCRIPTION("ACPI Thermal Zone Driver");
MODULE_LICENSE("GPL");
static int act;
module_param(act, int, 0644);
MODULE_PARM_DESC(act, "Disable or override all lowest active trip points.");
static int crt;
module_param(crt, int, 0644);
MODULE_PARM_DESC(crt, "Disable or lower all critical trip points.");
static int tzp;
module_param(tzp, int, 0444);
MODULE_PARM_DESC(tzp, "Thermal zone polling frequency, in 1/10 seconds.");
static int nocrt;
module_param(nocrt, int, 0);
MODULE_PARM_DESC(nocrt, "Set to take no action upon ACPI thermal zone critical trips points.");
static int off;
module_param(off, int, 0);
MODULE_PARM_DESC(off, "Set to disable ACPI thermal support.");
static int psv;
module_param(psv, int, 0644);
MODULE_PARM_DESC(psv, "Disable or override all passive trip points.");
static int acpi_thermal_add(struct acpi_device *device);
static int acpi_thermal_remove(struct acpi_device *device, int type);
static int acpi_thermal_resume(struct acpi_device *device);
static void acpi_thermal_notify(struct acpi_device *device, u32 event);
static const struct acpi_device_id thermal_device_ids[] = {
{ACPI_THERMAL_HID, 0},
{"", 0},
};
MODULE_DEVICE_TABLE(acpi, thermal_device_ids);
static struct acpi_driver acpi_thermal_driver = {
.name = "thermal",
.class = ACPI_THERMAL_CLASS,
.ids = thermal_device_ids,
.ops = {
.add = acpi_thermal_add,
.remove = acpi_thermal_remove,
.resume = acpi_thermal_resume,
.notify = acpi_thermal_notify,
},
};
struct acpi_thermal_state {
u8 critical:1;
u8 hot:1;
u8 passive:1;
u8 active:1;
u8 reserved:4;
int active_index;
};
struct acpi_thermal_state_flags {
u8 valid:1;
u8 enabled:1;
u8 reserved:6;
};
struct acpi_thermal_critical {
struct acpi_thermal_state_flags flags;
unsigned long temperature;
};
struct acpi_thermal_hot {
struct acpi_thermal_state_flags flags;
unsigned long temperature;
};
struct acpi_thermal_passive {
struct acpi_thermal_state_flags flags;
unsigned long temperature;
unsigned long tc1;
unsigned long tc2;
unsigned long tsp;
struct acpi_handle_list devices;
};
struct acpi_thermal_active {
struct acpi_thermal_state_flags flags;
unsigned long temperature;
struct acpi_handle_list devices;
};
struct acpi_thermal_trips {
struct acpi_thermal_critical critical;
struct acpi_thermal_hot hot;
struct acpi_thermal_passive passive;
struct acpi_thermal_active active[ACPI_THERMAL_MAX_ACTIVE];
};
struct acpi_thermal_flags {
u8 cooling_mode:1; /* _SCP */
u8 devices:1; /* _TZD */
u8 reserved:6;
};
struct acpi_thermal {
struct acpi_device * device;
acpi_bus_id name;
unsigned long temperature;
unsigned long last_temperature;
unsigned long polling_frequency;
volatile u8 zombie;
struct acpi_thermal_flags flags;
struct acpi_thermal_state state;
struct acpi_thermal_trips trips;
struct acpi_handle_list devices;
struct thermal_zone_device *thermal_zone;
int tz_enabled;
int kelvin_offset;
struct mutex lock;
};
/* --------------------------------------------------------------------------
Thermal Zone Management
-------------------------------------------------------------------------- */
static int acpi_thermal_get_temperature(struct acpi_thermal *tz)
{
acpi_status status = AE_OK;
unsigned long long tmp;
if (!tz)
return -EINVAL;
tz->last_temperature = tz->temperature;
status = acpi_evaluate_integer(tz->device->handle, "_TMP", NULL, &tmp);
if (ACPI_FAILURE(status))
return -ENODEV;
tz->temperature = tmp;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Temperature is %lu dK\n",
tz->temperature));
return 0;
}
static int acpi_thermal_get_polling_frequency(struct acpi_thermal *tz)
{
acpi_status status = AE_OK;
unsigned long long tmp;
if (!tz)
return -EINVAL;
status = acpi_evaluate_integer(tz->device->handle, "_TZP", NULL, &tmp);
if (ACPI_FAILURE(status))
return -ENODEV;
tz->polling_frequency = tmp;
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "Polling frequency is %lu dS\n",
tz->polling_frequency));
return 0;
}
static int acpi_thermal_set_cooling_mode(struct acpi_thermal *tz, int mode)
{
acpi_status status = AE_OK;
union acpi_object arg0 = { ACPI_TYPE_INTEGER };
struct acpi_object_list arg_list = { 1, &arg0 };
acpi_handle handle = NULL;
if (!tz)
return -EINVAL;
status = acpi_get_handle(tz->device->handle, "_SCP", &handle);
if (ACPI_FAILURE(status)) {
ACPI_DEBUG_PRINT((ACPI_DB_INFO, "_SCP not present\n"));
return -ENODEV;
}
arg0.integer.value = mode;
status = acpi_evaluate_object(handle, NULL, &arg_list, NULL);
if (ACPI_FAILURE(status))
return -ENODEV;
return 0;
}
#define ACPI_TRIPS_CRITICAL 0x01
#define ACPI_TRIPS_HOT 0x02
#define ACPI_TRIPS_PASSIVE 0x04
#define ACPI_TRIPS_ACTIVE 0x08
#define ACPI_TRIPS_DEVICES 0x10
#define ACPI_TRIPS_REFRESH_THRESHOLDS (ACPI_TRIPS_PASSIVE | ACPI_TRIPS_ACTIVE)
#define ACPI_TRIPS_REFRESH_DEVICES ACPI_TRIPS_DEVICES
#define ACPI_TRIPS_INIT (ACPI_TRIPS_CRITICAL | ACPI_TRIPS_HOT | \
ACPI_TRIPS_PASSIVE | ACPI_TRIPS_ACTIVE | \
ACPI_TRIPS_DEVICES)
/*
* This exception is thrown out in two cases:
* 1.An invalid trip point becomes invalid or a valid trip point becomes invalid
* when re-evaluating the AML code.
* 2.TODO: Devices listed in _PSL, _ALx, _TZD may change.
* We need to re-bind the cooling devices of a thermal zone when this occurs.
*/
#define ACPI_THERMAL_TRIPS_EXCEPTION(flags, str) \
do { \
if (flags != ACPI_TRIPS_INIT) \
ACPI_EXCEPTION((AE_INFO, AE_ERROR, \
"ACPI thermal trip point %s changed\n" \
"Please send acpidump to linux-acpi@vger.kernel.org\n", str)); \
} while (0)
static int acpi_thermal_trips_update(struct acpi_thermal *tz, int flag)
{
acpi_status status = AE_OK;
unsigned long long tmp;
struct acpi_handle_list devices;
int valid = 0;
int i;
/* Critical Shutdown */
if (flag & ACPI_TRIPS_CRITICAL) {
status = acpi_evaluate_integer(tz->device->handle,
"_CRT", NULL, &tmp);
tz->trips.critical.temperature = tmp;
/*
* Treat freezing temperatures as invalid as well; some
* BIOSes return really low values and cause reboots at startup.
* Below zero (Celsius) values clearly aren't right for sure..
* ... so lets discard those as invalid.
*/
if (ACPI_FAILURE(status)) {
tz->trips.critical.flags.valid = 0;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"No critical threshold\n"));
} else if (tmp <= 2732) {
printk(KERN_WARNING FW_BUG "Invalid critical threshold "
"(%llu)\n", tmp);
tz->trips.critical.flags.valid = 0;
} else {
tz->trips.critical.flags.valid = 1;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Found critical threshold [%lu]\n",
tz->trips.critical.temperature));
}
if (tz->trips.critical.flags.valid == 1) {
if (crt == -1) {
tz->trips.critical.flags.valid = 0;
} else if (crt > 0) {
unsigned long crt_k = CELSIUS_TO_KELVIN(crt);
/*
* Allow override critical threshold
*/
if (crt_k > tz->trips.critical.temperature)
printk(KERN_WARNING PREFIX
"Critical threshold %d C\n", crt);
tz->trips.critical.temperature = crt_k;
}
}
}
/* Critical Sleep (optional) */
if (flag & ACPI_TRIPS_HOT) {
status = acpi_evaluate_integer(tz->device->handle,
"_HOT", NULL, &tmp);
if (ACPI_FAILURE(status)) {
tz->trips.hot.flags.valid = 0;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"No hot threshold\n"));
} else {
tz->trips.hot.temperature = tmp;
tz->trips.hot.flags.valid = 1;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Found hot threshold [%lu]\n",
tz->trips.critical.temperature));
}
}
/* Passive (optional) */
if (((flag & ACPI_TRIPS_PASSIVE) && tz->trips.passive.flags.valid) ||
(flag == ACPI_TRIPS_INIT)) {
valid = tz->trips.passive.flags.valid;
if (psv == -1) {
status = AE_SUPPORT;
} else if (psv > 0) {
tmp = CELSIUS_TO_KELVIN(psv);
status = AE_OK;
} else {
status = acpi_evaluate_integer(tz->device->handle,
"_PSV", NULL, &tmp);
}
if (ACPI_FAILURE(status))
tz->trips.passive.flags.valid = 0;
else {
tz->trips.passive.temperature = tmp;
tz->trips.passive.flags.valid = 1;
if (flag == ACPI_TRIPS_INIT) {
status = acpi_evaluate_integer(
tz->device->handle, "_TC1",
NULL, &tmp);
if (ACPI_FAILURE(status))
tz->trips.passive.flags.valid = 0;
else
tz->trips.passive.tc1 = tmp;
status = acpi_evaluate_integer(
tz->device->handle, "_TC2",
NULL, &tmp);
if (ACPI_FAILURE(status))
tz->trips.passive.flags.valid = 0;
else
tz->trips.passive.tc2 = tmp;
status = acpi_evaluate_integer(
tz->device->handle, "_TSP",
NULL, &tmp);
if (ACPI_FAILURE(status))
tz->trips.passive.flags.valid = 0;
else
tz->trips.passive.tsp = tmp;
}
}
}
if ((flag & ACPI_TRIPS_DEVICES) && tz->trips.passive.flags.valid) {
memset(&devices, 0, sizeof(struct acpi_handle_list));
status = acpi_evaluate_reference(tz->device->handle, "_PSL",
NULL, &devices);
if (ACPI_FAILURE(status)) {
printk(KERN_WARNING PREFIX
"Invalid passive threshold\n");
tz->trips.passive.flags.valid = 0;
}
else
tz->trips.passive.flags.valid = 1;
if (memcmp(&tz->trips.passive.devices, &devices,
sizeof(struct acpi_handle_list))) {
memcpy(&tz->trips.passive.devices, &devices,
sizeof(struct acpi_handle_list));
ACPI_THERMAL_TRIPS_EXCEPTION(flag, "device");
}
}
if ((flag & ACPI_TRIPS_PASSIVE) || (flag & ACPI_TRIPS_DEVICES)) {
if (valid != tz->trips.passive.flags.valid)
ACPI_THERMAL_TRIPS_EXCEPTION(flag, "state");
}
/* Active (optional) */
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE; i++) {
char name[5] = { '_', 'A', 'C', ('0' + i), '\0' };
valid = tz->trips.active[i].flags.valid;
if (act == -1)
break; /* disable all active trip points */
if ((flag == ACPI_TRIPS_INIT) || ((flag & ACPI_TRIPS_ACTIVE) &&
tz->trips.active[i].flags.valid)) {
status = acpi_evaluate_integer(tz->device->handle,
name, NULL, &tmp);
if (ACPI_FAILURE(status)) {
tz->trips.active[i].flags.valid = 0;
if (i == 0)
break;
if (act <= 0)
break;
if (i == 1)
tz->trips.active[0].temperature =
CELSIUS_TO_KELVIN(act);
else
/*
* Don't allow override higher than
* the next higher trip point
*/
tz->trips.active[i - 1].temperature =
(tz->trips.active[i - 2].temperature <
CELSIUS_TO_KELVIN(act) ?
tz->trips.active[i - 2].temperature :
CELSIUS_TO_KELVIN(act));
break;
} else {
tz->trips.active[i].temperature = tmp;
tz->trips.active[i].flags.valid = 1;
}
}
name[2] = 'L';
if ((flag & ACPI_TRIPS_DEVICES) && tz->trips.active[i].flags.valid ) {
memset(&devices, 0, sizeof(struct acpi_handle_list));
status = acpi_evaluate_reference(tz->device->handle,
name, NULL, &devices);
if (ACPI_FAILURE(status)) {
printk(KERN_WARNING PREFIX
"Invalid active%d threshold\n", i);
tz->trips.active[i].flags.valid = 0;
}
else
tz->trips.active[i].flags.valid = 1;
if (memcmp(&tz->trips.active[i].devices, &devices,
sizeof(struct acpi_handle_list))) {
memcpy(&tz->trips.active[i].devices, &devices,
sizeof(struct acpi_handle_list));
ACPI_THERMAL_TRIPS_EXCEPTION(flag, "device");
}
}
if ((flag & ACPI_TRIPS_ACTIVE) || (flag & ACPI_TRIPS_DEVICES))
if (valid != tz->trips.active[i].flags.valid)
ACPI_THERMAL_TRIPS_EXCEPTION(flag, "state");
if (!tz->trips.active[i].flags.valid)
break;
}
if (flag & ACPI_TRIPS_DEVICES) {
memset(&devices, 0, sizeof(struct acpi_handle_list));
status = acpi_evaluate_reference(tz->device->handle, "_TZD",
NULL, &devices);
if (memcmp(&tz->devices, &devices,
sizeof(struct acpi_handle_list))) {
memcpy(&tz->devices, &devices,
sizeof(struct acpi_handle_list));
ACPI_THERMAL_TRIPS_EXCEPTION(flag, "device");
}
}
return 0;
}
static int acpi_thermal_get_trip_points(struct acpi_thermal *tz)
{
int i, valid, ret = acpi_thermal_trips_update(tz, ACPI_TRIPS_INIT);
if (ret)
return ret;
valid = tz->trips.critical.flags.valid |
tz->trips.hot.flags.valid |
tz->trips.passive.flags.valid;
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE; i++)
valid |= tz->trips.active[i].flags.valid;
if (!valid) {
printk(KERN_WARNING FW_BUG "No valid trip found\n");
return -ENODEV;
}
return 0;
}
static void acpi_thermal_check(void *data)
{
struct acpi_thermal *tz = data;
thermal_zone_device_update(tz->thermal_zone);
}
/* sys I/F for generic thermal sysfs support */
#define KELVIN_TO_MILLICELSIUS(t, off) (((t) - (off)) * 100)
static int thermal_get_temp(struct thermal_zone_device *thermal,
unsigned long *temp)
{
struct acpi_thermal *tz = thermal->devdata;
int result;
if (!tz)
return -EINVAL;
result = acpi_thermal_get_temperature(tz);
if (result)
return result;
*temp = KELVIN_TO_MILLICELSIUS(tz->temperature, tz->kelvin_offset);
return 0;
}
static const char enabled[] = "kernel";
static const char disabled[] = "user";
static int thermal_get_mode(struct thermal_zone_device *thermal,
enum thermal_device_mode *mode)
{
struct acpi_thermal *tz = thermal->devdata;
if (!tz)
return -EINVAL;
*mode = tz->tz_enabled ? THERMAL_DEVICE_ENABLED :
THERMAL_DEVICE_DISABLED;
return 0;
}
static int thermal_set_mode(struct thermal_zone_device *thermal,
enum thermal_device_mode mode)
{
struct acpi_thermal *tz = thermal->devdata;
int enable;
if (!tz)
return -EINVAL;
/*
* enable/disable thermal management from ACPI thermal driver
*/
if (mode == THERMAL_DEVICE_ENABLED)
enable = 1;
else if (mode == THERMAL_DEVICE_DISABLED)
enable = 0;
else
return -EINVAL;
if (enable != tz->tz_enabled) {
tz->tz_enabled = enable;
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"%s ACPI thermal control\n",
tz->tz_enabled ? enabled : disabled));
acpi_thermal_check(tz);
}
return 0;
}
static int thermal_get_trip_type(struct thermal_zone_device *thermal,
int trip, enum thermal_trip_type *type)
{
struct acpi_thermal *tz = thermal->devdata;
int i;
if (!tz || trip < 0)
return -EINVAL;
if (tz->trips.critical.flags.valid) {
if (!trip) {
*type = THERMAL_TRIP_CRITICAL;
return 0;
}
trip--;
}
if (tz->trips.hot.flags.valid) {
if (!trip) {
*type = THERMAL_TRIP_HOT;
return 0;
}
trip--;
}
if (tz->trips.passive.flags.valid) {
if (!trip) {
*type = THERMAL_TRIP_PASSIVE;
return 0;
}
trip--;
}
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE &&
tz->trips.active[i].flags.valid; i++) {
if (!trip) {
*type = THERMAL_TRIP_ACTIVE;
return 0;
}
trip--;
}
return -EINVAL;
}
static int thermal_get_trip_temp(struct thermal_zone_device *thermal,
int trip, unsigned long *temp)
{
struct acpi_thermal *tz = thermal->devdata;
int i;
if (!tz || trip < 0)
return -EINVAL;
if (tz->trips.critical.flags.valid) {
if (!trip) {
*temp = KELVIN_TO_MILLICELSIUS(
tz->trips.critical.temperature,
tz->kelvin_offset);
return 0;
}
trip--;
}
if (tz->trips.hot.flags.valid) {
if (!trip) {
*temp = KELVIN_TO_MILLICELSIUS(
tz->trips.hot.temperature,
tz->kelvin_offset);
return 0;
}
trip--;
}
if (tz->trips.passive.flags.valid) {
if (!trip) {
*temp = KELVIN_TO_MILLICELSIUS(
tz->trips.passive.temperature,
tz->kelvin_offset);
return 0;
}
trip--;
}
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE &&
tz->trips.active[i].flags.valid; i++) {
if (!trip) {
*temp = KELVIN_TO_MILLICELSIUS(
tz->trips.active[i].temperature,
tz->kelvin_offset);
return 0;
}
trip--;
}
return -EINVAL;
}
static int thermal_get_crit_temp(struct thermal_zone_device *thermal,
unsigned long *temperature) {
struct acpi_thermal *tz = thermal->devdata;
if (tz->trips.critical.flags.valid) {
*temperature = KELVIN_TO_MILLICELSIUS(
tz->trips.critical.temperature,
tz->kelvin_offset);
return 0;
} else
return -EINVAL;
}
static int thermal_notify(struct thermal_zone_device *thermal, int trip,
enum thermal_trip_type trip_type)
{
u8 type = 0;
struct acpi_thermal *tz = thermal->devdata;
if (trip_type == THERMAL_TRIP_CRITICAL)
type = ACPI_THERMAL_NOTIFY_CRITICAL;
else if (trip_type == THERMAL_TRIP_HOT)
type = ACPI_THERMAL_NOTIFY_HOT;
else
return 0;
acpi_bus_generate_proc_event(tz->device, type, 1);
acpi_bus_generate_netlink_event(tz->device->pnp.device_class,
dev_name(&tz->device->dev), type, 1);
if (trip_type == THERMAL_TRIP_CRITICAL && nocrt)
return 1;
return 0;
}
typedef int (*cb)(struct thermal_zone_device *, int,
struct thermal_cooling_device *);
static int acpi_thermal_cooling_device_cb(struct thermal_zone_device *thermal,
struct thermal_cooling_device *cdev,
cb action)
{
struct acpi_device *device = cdev->devdata;
struct acpi_thermal *tz = thermal->devdata;
struct acpi_device *dev;
acpi_status status;
acpi_handle handle;
int i;
int j;
int trip = -1;
int result = 0;
if (tz->trips.critical.flags.valid)
trip++;
if (tz->trips.hot.flags.valid)
trip++;
if (tz->trips.passive.flags.valid) {
trip++;
for (i = 0; i < tz->trips.passive.devices.count;
i++) {
handle = tz->trips.passive.devices.handles[i];
status = acpi_bus_get_device(handle, &dev);
if (ACPI_SUCCESS(status) && (dev == device)) {
result = action(thermal, trip, cdev);
if (result)
goto failed;
}
}
}
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE; i++) {
if (!tz->trips.active[i].flags.valid)
break;
trip++;
for (j = 0;
j < tz->trips.active[i].devices.count;
j++) {
handle = tz->trips.active[i].devices.handles[j];
status = acpi_bus_get_device(handle, &dev);
if (ACPI_SUCCESS(status) && (dev == device)) {
result = action(thermal, trip, cdev);
if (result)
goto failed;
}
}
}
for (i = 0; i < tz->devices.count; i++) {
handle = tz->devices.handles[i];
status = acpi_bus_get_device(handle, &dev);
if (ACPI_SUCCESS(status) && (dev == device)) {
result = action(thermal, -1, cdev);
if (result)
goto failed;
}
}
failed:
return result;
}
static int
acpi_thermal_bind_cooling_device(struct thermal_zone_device *thermal,
struct thermal_cooling_device *cdev)
{
return acpi_thermal_cooling_device_cb(thermal, cdev,
thermal_zone_bind_cooling_device);
}
static int
acpi_thermal_unbind_cooling_device(struct thermal_zone_device *thermal,
struct thermal_cooling_device *cdev)
{
return acpi_thermal_cooling_device_cb(thermal, cdev,
thermal_zone_unbind_cooling_device);
}
static const struct thermal_zone_device_ops acpi_thermal_zone_ops = {
.bind = acpi_thermal_bind_cooling_device,
.unbind = acpi_thermal_unbind_cooling_device,
.get_temp = thermal_get_temp,
.get_mode = thermal_get_mode,
.set_mode = thermal_set_mode,
.get_trip_type = thermal_get_trip_type,
.get_trip_temp = thermal_get_trip_temp,
.get_crit_temp = thermal_get_crit_temp,
.notify = thermal_notify,
};
static int acpi_thermal_register_thermal_zone(struct acpi_thermal *tz)
{
int trips = 0;
int result;
acpi_status status;
int i;
if (tz->trips.critical.flags.valid)
trips++;
if (tz->trips.hot.flags.valid)
trips++;
if (tz->trips.passive.flags.valid)
trips++;
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE &&
tz->trips.active[i].flags.valid; i++, trips++);
if (tz->trips.passive.flags.valid)
tz->thermal_zone =
thermal_zone_device_register("acpitz", trips, tz,
&acpi_thermal_zone_ops,
tz->trips.passive.tc1,
tz->trips.passive.tc2,
tz->trips.passive.tsp*100,
tz->polling_frequency*100);
else
tz->thermal_zone =
thermal_zone_device_register("acpitz", trips, tz,
&acpi_thermal_zone_ops,
0, 0, 0,
tz->polling_frequency*100);
if (IS_ERR(tz->thermal_zone))
return -ENODEV;
result = sysfs_create_link(&tz->device->dev.kobj,
&tz->thermal_zone->device.kobj, "thermal_zone");
if (result)
return result;
result = sysfs_create_link(&tz->thermal_zone->device.kobj,
&tz->device->dev.kobj, "device");
if (result)
return result;
status = acpi_attach_data(tz->device->handle,
acpi_bus_private_data_handler,
tz->thermal_zone);
if (ACPI_FAILURE(status)) {
printk(KERN_ERR PREFIX
"Error attaching device data\n");
return -ENODEV;
}
tz->tz_enabled = 1;
dev_info(&tz->device->dev, "registered as thermal_zone%d\n",
tz->thermal_zone->id);
return 0;
}
static void acpi_thermal_unregister_thermal_zone(struct acpi_thermal *tz)
{
sysfs_remove_link(&tz->device->dev.kobj, "thermal_zone");
sysfs_remove_link(&tz->thermal_zone->device.kobj, "device");
thermal_zone_device_unregister(tz->thermal_zone);
tz->thermal_zone = NULL;
acpi_detach_data(tz->device->handle, acpi_bus_private_data_handler);
}
/* --------------------------------------------------------------------------
Driver Interface
-------------------------------------------------------------------------- */
static void acpi_thermal_notify(struct acpi_device *device, u32 event)
{
struct acpi_thermal *tz = acpi_driver_data(device);
if (!tz)
return;
switch (event) {
case ACPI_THERMAL_NOTIFY_TEMPERATURE:
acpi_thermal_check(tz);
break;
case ACPI_THERMAL_NOTIFY_THRESHOLDS:
acpi_thermal_trips_update(tz, ACPI_TRIPS_REFRESH_THRESHOLDS);
acpi_thermal_check(tz);
acpi_bus_generate_proc_event(device, event, 0);
acpi_bus_generate_netlink_event(device->pnp.device_class,
dev_name(&device->dev), event, 0);
break;
case ACPI_THERMAL_NOTIFY_DEVICES:
acpi_thermal_trips_update(tz, ACPI_TRIPS_REFRESH_DEVICES);
acpi_thermal_check(tz);
acpi_bus_generate_proc_event(device, event, 0);
acpi_bus_generate_netlink_event(device->pnp.device_class,
dev_name(&device->dev), event, 0);
break;
default:
ACPI_DEBUG_PRINT((ACPI_DB_INFO,
"Unsupported event [0x%x]\n", event));
break;
}
}
static int acpi_thermal_get_info(struct acpi_thermal *tz)
{
int result = 0;
if (!tz)
return -EINVAL;
/* Get trip points [_CRT, _PSV, etc.] (required) */
result = acpi_thermal_get_trip_points(tz);
if (result)
return result;
/* Get temperature [_TMP] (required) */
result = acpi_thermal_get_temperature(tz);
if (result)
return result;
/* Set the cooling mode [_SCP] to active cooling (default) */
result = acpi_thermal_set_cooling_mode(tz, ACPI_THERMAL_MODE_ACTIVE);
if (!result)
tz->flags.cooling_mode = 1;
/* Get default polling frequency [_TZP] (optional) */
if (tzp)
tz->polling_frequency = tzp;
else
acpi_thermal_get_polling_frequency(tz);
return 0;
}
/*
* The exact offset between Kelvin and degree Celsius is 273.15. However ACPI
* handles temperature values with a single decimal place. As a consequence,
* some implementations use an offset of 273.1 and others use an offset of
* 273.2. Try to find out which one is being used, to present the most
* accurate and visually appealing number.
*
* The heuristic below should work for all ACPI thermal zones which have a
* critical trip point with a value being a multiple of 0.5 degree Celsius.
*/
static void acpi_thermal_guess_offset(struct acpi_thermal *tz)
{
if (tz->trips.critical.flags.valid &&
(tz->trips.critical.temperature % 5) == 1)
tz->kelvin_offset = 2731;
else
tz->kelvin_offset = 2732;
}
static int acpi_thermal_add(struct acpi_device *device)
{
int result = 0;
struct acpi_thermal *tz = NULL;
if (!device)
return -EINVAL;
tz = kzalloc(sizeof(struct acpi_thermal), GFP_KERNEL);
if (!tz)
return -ENOMEM;
tz->device = device;
strcpy(tz->name, device->pnp.bus_id);
strcpy(acpi_device_name(device), ACPI_THERMAL_DEVICE_NAME);
strcpy(acpi_device_class(device), ACPI_THERMAL_CLASS);
device->driver_data = tz;
mutex_init(&tz->lock);
result = acpi_thermal_get_info(tz);
if (result)
goto free_memory;
acpi_thermal_guess_offset(tz);
result = acpi_thermal_register_thermal_zone(tz);
if (result)
goto free_memory;
printk(KERN_INFO PREFIX "%s [%s] (%ld C)\n",
acpi_device_name(device), acpi_device_bid(device),
KELVIN_TO_CELSIUS(tz->temperature));
goto end;
free_memory:
kfree(tz);
end:
return result;
}
static int acpi_thermal_remove(struct acpi_device *device, int type)
{
struct acpi_thermal *tz = NULL;
if (!device || !acpi_driver_data(device))
return -EINVAL;
tz = acpi_driver_data(device);
acpi_thermal_unregister_thermal_zone(tz);
mutex_destroy(&tz->lock);
kfree(tz);
return 0;
}
static int acpi_thermal_resume(struct acpi_device *device)
{
struct acpi_thermal *tz = NULL;
int i, j, power_state, result;
if (!device || !acpi_driver_data(device))
return -EINVAL;
tz = acpi_driver_data(device);
for (i = 0; i < ACPI_THERMAL_MAX_ACTIVE; i++) {
if (!(&tz->trips.active[i]))
break;
if (!tz->trips.active[i].flags.valid)
break;
tz->trips.active[i].flags.enabled = 1;
for (j = 0; j < tz->trips.active[i].devices.count; j++) {
result = acpi_bus_update_power(
tz->trips.active[i].devices.handles[j],
&power_state);
if (result || (power_state != ACPI_STATE_D0)) {
tz->trips.active[i].flags.enabled = 0;
break;
}
}
tz->state.active |= tz->trips.active[i].flags.enabled;
}
acpi_thermal_check(tz);
return AE_OK;
}
static int thermal_act(const struct dmi_system_id *d) {
if (act == 0) {
printk(KERN_NOTICE "ACPI: %s detected: "
"disabling all active thermal trip points\n", d->ident);
act = -1;
}
return 0;
}
static int thermal_nocrt(const struct dmi_system_id *d) {
printk(KERN_NOTICE "ACPI: %s detected: "
"disabling all critical thermal trip point actions.\n", d->ident);
nocrt = 1;
return 0;
}
static int thermal_tzp(const struct dmi_system_id *d) {
if (tzp == 0) {
printk(KERN_NOTICE "ACPI: %s detected: "
"enabling thermal zone polling\n", d->ident);
tzp = 300; /* 300 dS = 30 Seconds */
}
return 0;
}
static int thermal_psv(const struct dmi_system_id *d) {
if (psv == 0) {
printk(KERN_NOTICE "ACPI: %s detected: "
"disabling all passive thermal trip points\n", d->ident);
psv = -1;
}
return 0;
}
static struct dmi_system_id thermal_dmi_table[] __initdata = {
/*
* Award BIOS on this AOpen makes thermal control almost worthless.
* http://bugzilla.kernel.org/show_bug.cgi?id=8842
*/
{
.callback = thermal_act,
.ident = "AOpen i915GMm-HFS",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "AOpen"),
DMI_MATCH(DMI_BOARD_NAME, "i915GMm-HFS"),
},
},
{
.callback = thermal_psv,
.ident = "AOpen i915GMm-HFS",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "AOpen"),
DMI_MATCH(DMI_BOARD_NAME, "i915GMm-HFS"),
},
},
{
.callback = thermal_tzp,
.ident = "AOpen i915GMm-HFS",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "AOpen"),
DMI_MATCH(DMI_BOARD_NAME, "i915GMm-HFS"),
},
},
{
.callback = thermal_nocrt,
.ident = "Gigabyte GA-7ZX",
.matches = {
DMI_MATCH(DMI_BOARD_VENDOR, "Gigabyte Technology Co., Ltd."),
DMI_MATCH(DMI_BOARD_NAME, "7ZX"),
},
},
{}
};
static int __init acpi_thermal_init(void)
{
int result = 0;
dmi_check_system(thermal_dmi_table);
if (off) {
printk(KERN_NOTICE "ACPI: thermal control disabled\n");
return -ENODEV;
}
result = acpi_bus_register_driver(&acpi_thermal_driver);
if (result < 0)
return -ENODEV;
return 0;
}
static void __exit acpi_thermal_exit(void)
{
acpi_bus_unregister_driver(&acpi_thermal_driver);
return;
}
module_init(acpi_thermal_init);
module_exit(acpi_thermal_exit);
| gpl-2.0 |
tbalden/android_kernel_htc_m7-sense4.2 | arch/arm/plat-mxc/devices/platform-ahci-imx.c | 4911 | 3935 | /*
* Copyright (C) 2011 Freescale Semiconductor, Inc. All Rights Reserved.
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <asm/sizes.h>
#include <mach/hardware.h>
#include <mach/devices-common.h>
#define imx_ahci_imx_data_entry_single(soc, _devid) \
{ \
.devid = _devid, \
.iobase = soc ## _SATA_BASE_ADDR, \
.irq = soc ## _INT_SATA, \
}
#ifdef CONFIG_SOC_IMX53
const struct imx_ahci_imx_data imx53_ahci_imx_data __initconst =
imx_ahci_imx_data_entry_single(MX53, "imx53-ahci");
#endif
enum {
HOST_CAP = 0x00,
HOST_CAP_SSS = (1 << 27), /* Staggered Spin-up */
HOST_PORTS_IMPL = 0x0c,
HOST_TIMER1MS = 0xe0, /* Timer 1-ms */
};
static struct clk *sata_clk, *sata_ref_clk;
/* AHCI module Initialization, if return 0, initialization is successful. */
static int imx_sata_init(struct device *dev, void __iomem *addr)
{
u32 tmpdata;
int ret = 0;
struct clk *clk;
sata_clk = clk_get(dev, "ahci");
if (IS_ERR(sata_clk)) {
dev_err(dev, "no sata clock.\n");
return PTR_ERR(sata_clk);
}
ret = clk_prepare_enable(sata_clk);
if (ret) {
dev_err(dev, "can't prepare/enable sata clock.\n");
goto put_sata_clk;
}
/* Get the AHCI SATA PHY CLK */
sata_ref_clk = clk_get(dev, "ahci_phy");
if (IS_ERR(sata_ref_clk)) {
dev_err(dev, "no sata ref clock.\n");
ret = PTR_ERR(sata_ref_clk);
goto release_sata_clk;
}
ret = clk_prepare_enable(sata_ref_clk);
if (ret) {
dev_err(dev, "can't prepare/enable sata ref clock.\n");
goto put_sata_ref_clk;
}
/* Get the AHB clock rate, and configure the TIMER1MS reg later */
clk = clk_get(dev, "ahci_dma");
if (IS_ERR(clk)) {
dev_err(dev, "no dma clock.\n");
ret = PTR_ERR(clk);
goto release_sata_ref_clk;
}
tmpdata = clk_get_rate(clk) / 1000;
clk_put(clk);
writel(tmpdata, addr + HOST_TIMER1MS);
tmpdata = readl(addr + HOST_CAP);
if (!(tmpdata & HOST_CAP_SSS)) {
tmpdata |= HOST_CAP_SSS;
writel(tmpdata, addr + HOST_CAP);
}
if (!(readl(addr + HOST_PORTS_IMPL) & 0x1))
writel((readl(addr + HOST_PORTS_IMPL) | 0x1),
addr + HOST_PORTS_IMPL);
return 0;
release_sata_ref_clk:
clk_disable_unprepare(sata_ref_clk);
put_sata_ref_clk:
clk_put(sata_ref_clk);
release_sata_clk:
clk_disable_unprepare(sata_clk);
put_sata_clk:
clk_put(sata_clk);
return ret;
}
static void imx_sata_exit(struct device *dev)
{
clk_disable_unprepare(sata_ref_clk);
clk_put(sata_ref_clk);
clk_disable_unprepare(sata_clk);
clk_put(sata_clk);
}
struct platform_device *__init imx_add_ahci_imx(
const struct imx_ahci_imx_data *data,
const struct ahci_platform_data *pdata)
{
struct resource res[] = {
{
.start = data->iobase,
.end = data->iobase + SZ_4K - 1,
.flags = IORESOURCE_MEM,
}, {
.start = data->irq,
.end = data->irq,
.flags = IORESOURCE_IRQ,
},
};
return imx_add_platform_device_dmamask(data->devid, 0,
res, ARRAY_SIZE(res),
pdata, sizeof(*pdata), DMA_BIT_MASK(32));
}
struct platform_device *__init imx53_add_ahci_imx(void)
{
struct ahci_platform_data pdata = {
.init = imx_sata_init,
.exit = imx_sata_exit,
};
return imx_add_ahci_imx(&imx53_ahci_imx_data, &pdata);
}
| gpl-2.0 |
agat63/AGAT_GB27_kernel | drivers/input/serio/maceps2.c | 5167 | 5569 | /*
* SGI O2 MACE PS2 controller driver for linux
*
* Copyright (C) 2002 Vivien Chappelier
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/serio.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <linux/err.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/system.h>
#include <asm/ip32/mace.h>
#include <asm/ip32/ip32_ints.h>
MODULE_AUTHOR("Vivien Chappelier <vivien.chappelier@linux-mips.org");
MODULE_DESCRIPTION("SGI O2 MACE PS2 controller driver");
MODULE_LICENSE("GPL");
#define MACE_PS2_TIMEOUT 10000 /* in 50us unit */
#define PS2_STATUS_CLOCK_SIGNAL BIT(0) /* external clock signal */
#define PS2_STATUS_CLOCK_INHIBIT BIT(1) /* clken output signal */
#define PS2_STATUS_TX_INPROGRESS BIT(2) /* transmission in progress */
#define PS2_STATUS_TX_EMPTY BIT(3) /* empty transmit buffer */
#define PS2_STATUS_RX_FULL BIT(4) /* full receive buffer */
#define PS2_STATUS_RX_INPROGRESS BIT(5) /* reception in progress */
#define PS2_STATUS_ERROR_PARITY BIT(6) /* parity error */
#define PS2_STATUS_ERROR_FRAMING BIT(7) /* framing error */
#define PS2_CONTROL_TX_CLOCK_DISABLE BIT(0) /* inhibit clock signal after TX */
#define PS2_CONTROL_TX_ENABLE BIT(1) /* transmit enable */
#define PS2_CONTROL_TX_INT_ENABLE BIT(2) /* enable transmit interrupt */
#define PS2_CONTROL_RX_INT_ENABLE BIT(3) /* enable receive interrupt */
#define PS2_CONTROL_RX_CLOCK_ENABLE BIT(4) /* pause reception if set to 0 */
#define PS2_CONTROL_RESET BIT(5) /* reset */
struct maceps2_data {
struct mace_ps2port *port;
int irq;
};
static struct maceps2_data port_data[2];
static struct serio *maceps2_port[2];
static struct platform_device *maceps2_device;
static int maceps2_write(struct serio *dev, unsigned char val)
{
struct mace_ps2port *port = ((struct maceps2_data *)dev->port_data)->port;
unsigned int timeout = MACE_PS2_TIMEOUT;
do {
if (port->status & PS2_STATUS_TX_EMPTY) {
port->tx = val;
return 0;
}
udelay(50);
} while (timeout--);
return -1;
}
static irqreturn_t maceps2_interrupt(int irq, void *dev_id)
{
struct serio *dev = dev_id;
struct mace_ps2port *port = ((struct maceps2_data *)dev->port_data)->port;
unsigned long byte;
if (port->status & PS2_STATUS_RX_FULL) {
byte = port->rx;
serio_interrupt(dev, byte & 0xff, 0);
}
return IRQ_HANDLED;
}
static int maceps2_open(struct serio *dev)
{
struct maceps2_data *data = (struct maceps2_data *)dev->port_data;
if (request_irq(data->irq, maceps2_interrupt, 0, "PS2 port", dev)) {
printk(KERN_ERR "Could not allocate PS/2 IRQ\n");
return -EBUSY;
}
/* Reset port */
data->port->control = PS2_CONTROL_TX_CLOCK_DISABLE | PS2_CONTROL_RESET;
udelay(100);
/* Enable interrupts */
data->port->control = PS2_CONTROL_RX_CLOCK_ENABLE |
PS2_CONTROL_TX_ENABLE |
PS2_CONTROL_RX_INT_ENABLE;
return 0;
}
static void maceps2_close(struct serio *dev)
{
struct maceps2_data *data = (struct maceps2_data *)dev->port_data;
data->port->control = PS2_CONTROL_TX_CLOCK_DISABLE | PS2_CONTROL_RESET;
udelay(100);
free_irq(data->irq, dev);
}
static struct serio * __devinit maceps2_allocate_port(int idx)
{
struct serio *serio;
serio = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (serio) {
serio->id.type = SERIO_8042;
serio->write = maceps2_write;
serio->open = maceps2_open;
serio->close = maceps2_close;
snprintf(serio->name, sizeof(serio->name), "MACE PS/2 port%d", idx);
snprintf(serio->phys, sizeof(serio->phys), "mace/serio%d", idx);
serio->port_data = &port_data[idx];
serio->dev.parent = &maceps2_device->dev;
}
return serio;
}
static int __devinit maceps2_probe(struct platform_device *dev)
{
maceps2_port[0] = maceps2_allocate_port(0);
maceps2_port[1] = maceps2_allocate_port(1);
if (!maceps2_port[0] || !maceps2_port[1]) {
kfree(maceps2_port[0]);
kfree(maceps2_port[1]);
return -ENOMEM;
}
serio_register_port(maceps2_port[0]);
serio_register_port(maceps2_port[1]);
return 0;
}
static int __devexit maceps2_remove(struct platform_device *dev)
{
serio_unregister_port(maceps2_port[0]);
serio_unregister_port(maceps2_port[1]);
return 0;
}
static struct platform_driver maceps2_driver = {
.driver = {
.name = "maceps2",
.owner = THIS_MODULE,
},
.probe = maceps2_probe,
.remove = __devexit_p(maceps2_remove),
};
static int __init maceps2_init(void)
{
int error;
error = platform_driver_register(&maceps2_driver);
if (error)
return error;
maceps2_device = platform_device_alloc("maceps2", -1);
if (!maceps2_device) {
error = -ENOMEM;
goto err_unregister_driver;
}
port_data[0].port = &mace->perif.ps2.keyb;
port_data[0].irq = MACEISA_KEYB_IRQ;
port_data[1].port = &mace->perif.ps2.mouse;
port_data[1].irq = MACEISA_MOUSE_IRQ;
error = platform_device_add(maceps2_device);
if (error)
goto err_free_device;
return 0;
err_free_device:
platform_device_put(maceps2_device);
err_unregister_driver:
platform_driver_unregister(&maceps2_driver);
return error;
}
static void __exit maceps2_exit(void)
{
platform_device_unregister(maceps2_device);
platform_driver_unregister(&maceps2_driver);
}
module_init(maceps2_init);
module_exit(maceps2_exit);
| gpl-2.0 |
ollie27/android_kernel_samsung_aries | lib/audit.c | 10799 | 1232 | #include <linux/init.h>
#include <linux/types.h>
#include <linux/audit.h>
#include <asm/unistd.h>
static unsigned dir_class[] = {
#include <asm-generic/audit_dir_write.h>
~0U
};
static unsigned read_class[] = {
#include <asm-generic/audit_read.h>
~0U
};
static unsigned write_class[] = {
#include <asm-generic/audit_write.h>
~0U
};
static unsigned chattr_class[] = {
#include <asm-generic/audit_change_attr.h>
~0U
};
static unsigned signal_class[] = {
#include <asm-generic/audit_signal.h>
~0U
};
int audit_classify_arch(int arch)
{
return 0;
}
int audit_classify_syscall(int abi, unsigned syscall)
{
switch(syscall) {
#ifdef __NR_open
case __NR_open:
return 2;
#endif
#ifdef __NR_openat
case __NR_openat:
return 3;
#endif
#ifdef __NR_socketcall
case __NR_socketcall:
return 4;
#endif
case __NR_execve:
return 5;
default:
return 0;
}
}
static int __init audit_classes_init(void)
{
audit_register_class(AUDIT_CLASS_WRITE, write_class);
audit_register_class(AUDIT_CLASS_READ, read_class);
audit_register_class(AUDIT_CLASS_DIR_WRITE, dir_class);
audit_register_class(AUDIT_CLASS_CHATTR, chattr_class);
audit_register_class(AUDIT_CLASS_SIGNAL, signal_class);
return 0;
}
__initcall(audit_classes_init);
| gpl-2.0 |
BytecodeMe/BCM-M7 | drivers/video/msm/mdp_dma_s.c | 48 | 4271 | /* Copyright (c) 2008-2009, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/time.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/hrtimer.h>
#include <mach/hardware.h>
#include <linux/io.h>
#include <asm/system.h>
#include <asm/mach-types.h>
#include <linux/semaphore.h>
#include <linux/spinlock.h>
#include <linux/fb.h>
#include "mdp.h"
#include "msm_fb.h"
static void mdp_dma_s_update_lcd(struct msm_fb_data_type *mfd)
{
MDPIBUF *iBuf = &mfd->ibuf;
int mddi_dest = FALSE;
uint32 outBpp = iBuf->bpp;
uint32 dma_s_cfg_reg;
uint8 *src;
struct msm_fb_panel_data *pdata =
(struct msm_fb_panel_data *)mfd->pdev->dev.platform_data;
dma_s_cfg_reg = DMA_PACK_TIGHT | DMA_PACK_ALIGN_LSB |
DMA_OUT_SEL_AHB | DMA_IBUF_NONCONTIGUOUS;
if (mfd->fb_imgType == MDP_BGR_565)
dma_s_cfg_reg |= DMA_PACK_PATTERN_BGR;
else
dma_s_cfg_reg |= DMA_PACK_PATTERN_RGB;
if (outBpp == 4)
dma_s_cfg_reg |= DMA_IBUF_C3ALPHA_EN;
if (outBpp == 2)
dma_s_cfg_reg |= DMA_IBUF_FORMAT_RGB565;
if (mfd->panel_info.pdest != DISPLAY_2) {
printk(KERN_ERR "error: non-secondary type through dma_s!\n");
return;
}
if (mfd->panel_info.type == MDDI_PANEL ||
mfd->panel_info.type == EXT_MDDI_PANEL) {
dma_s_cfg_reg |= DMA_OUT_SEL_MDDI;
mddi_dest = TRUE;
} else {
dma_s_cfg_reg |= DMA_AHBM_LCD_SEL_SECONDARY;
outp32(MDP_EBI2_LCD1, mfd->data_port_phys);
}
src = (uint8 *) iBuf->buf;
src += (iBuf->dma_x + iBuf->dma_y * iBuf->ibuf_width) * outBpp;
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE);
if (mfd->panel_info.type == MDDI_PANEL) {
MDP_OUTP(MDP_BASE + 0xa0004,
(iBuf->dma_h << 16 | iBuf->dma_w));
MDP_OUTP(MDP_BASE + 0xa0008, src);
MDP_OUTP(MDP_BASE + 0xa000c,
iBuf->ibuf_width * outBpp);
} else {
MDP_OUTP(MDP_BASE + 0xb0004,
(iBuf->dma_h << 16 | iBuf->dma_w));
MDP_OUTP(MDP_BASE + 0xb0008, src);
MDP_OUTP(MDP_BASE + 0xb000c,
iBuf->ibuf_width * outBpp);
}
if (mfd->panel_info.bpp == 18) {
dma_s_cfg_reg |= DMA_DSTC0G_6BITS |
DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS;
} else {
dma_s_cfg_reg |= DMA_DSTC0G_6BITS |
DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS;
}
if (mddi_dest) {
if (mfd->panel_info.type == MDDI_PANEL) {
MDP_OUTP(MDP_BASE + 0xa0010,
(iBuf->dma_y << 16) | iBuf->dma_x);
MDP_OUTP(MDP_BASE + 0x00090, 1);
} else {
MDP_OUTP(MDP_BASE + 0xb0010,
(iBuf->dma_y << 16) | iBuf->dma_x);
MDP_OUTP(MDP_BASE + 0x00090, 2);
}
MDP_OUTP(MDP_BASE + 0x00094,
(MDDI_VDO_PACKET_DESC << 16) |
mfd->panel_info.mddi.vdopkt);
} else {
pdata->set_rect(iBuf->dma_x, iBuf->dma_y, iBuf->dma_w,
iBuf->dma_h);
}
if (mfd->panel_info.type == MDDI_PANEL)
MDP_OUTP(MDP_BASE + 0xa0000, dma_s_cfg_reg);
else
MDP_OUTP(MDP_BASE + 0xb0000, dma_s_cfg_reg);
mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE);
if (mfd->panel_info.type == MDDI_PANEL)
mdp_pipe_kickoff(MDP_DMA_S_TERM, mfd);
else
mdp_pipe_kickoff(MDP_DMA_E_TERM, mfd);
}
void mdp_dma_s_update(struct msm_fb_data_type *mfd)
{
down(&mfd->dma->mutex);
if ((mfd) && (!mfd->dma->busy) && (mfd->panel_power_on)) {
down(&mfd->sem);
mdp_enable_irq(MDP_DMA_S_TERM);
if (mfd->panel_info.type == MDDI_PANEL)
mdp_enable_irq(MDP_DMA_S_TERM);
else
mdp_enable_irq(MDP_DMA_E_TERM);
mfd->dma->busy = TRUE;
INIT_COMPLETION(mfd->dma->comp);
mfd->ibuf_flushed = TRUE;
mdp_dma_s_update_lcd(mfd);
up(&mfd->sem);
wait_for_completion_killable(&mfd->dma->comp);
if (mfd->panel_info.type == MDDI_PANEL)
mdp_disable_irq(MDP_DMA_S_TERM);
else
mdp_disable_irq(MDP_DMA_E_TERM);
if (mfd->pan_waiting) {
mfd->pan_waiting = FALSE;
complete(&mfd->pan_comp);
}
}
up(&mfd->dma->mutex);
}
| gpl-2.0 |
lsigithub/axxia_yocto_linux_4.1_pull | arch/s390/mm/hugetlbpage.c | 48 | 6908 | /*
* IBM System z Huge TLB Page Support for Kernel.
*
* Copyright IBM Corp. 2007,2016
* Author(s): Gerald Schaefer <gerald.schaefer@de.ibm.com>
*/
#define KMSG_COMPONENT "hugetlb"
#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
#include <linux/mm.h>
#include <linux/hugetlb.h>
/*
* If the bit selected by single-bit bitmask "a" is set within "x", move
* it to the position indicated by single-bit bitmask "b".
*/
#define move_set_bit(x, a, b) (((x) & (a)) >> ilog2(a) << ilog2(b))
static inline unsigned long __pte_to_rste(pte_t pte)
{
unsigned long rste;
/*
* Convert encoding pte bits pmd / pud bits
* lIR.uswrdy.p dy..R...I...wr
* empty 010.000000.0 -> 00..0...1...00
* prot-none, clean, old 111.000000.1 -> 00..1...1...00
* prot-none, clean, young 111.000001.1 -> 01..1...1...00
* prot-none, dirty, old 111.000010.1 -> 10..1...1...00
* prot-none, dirty, young 111.000011.1 -> 11..1...1...00
* read-only, clean, old 111.000100.1 -> 00..1...1...01
* read-only, clean, young 101.000101.1 -> 01..1...0...01
* read-only, dirty, old 111.000110.1 -> 10..1...1...01
* read-only, dirty, young 101.000111.1 -> 11..1...0...01
* read-write, clean, old 111.001100.1 -> 00..1...1...11
* read-write, clean, young 101.001101.1 -> 01..1...0...11
* read-write, dirty, old 110.001110.1 -> 10..0...1...11
* read-write, dirty, young 100.001111.1 -> 11..0...0...11
* HW-bits: R read-only, I invalid
* SW-bits: p present, y young, d dirty, r read, w write, s special,
* u unused, l large
*/
if (pte_present(pte)) {
rste = pte_val(pte) & PAGE_MASK;
rste |= move_set_bit(pte_val(pte), _PAGE_READ,
_SEGMENT_ENTRY_READ);
rste |= move_set_bit(pte_val(pte), _PAGE_WRITE,
_SEGMENT_ENTRY_WRITE);
rste |= move_set_bit(pte_val(pte), _PAGE_INVALID,
_SEGMENT_ENTRY_INVALID);
rste |= move_set_bit(pte_val(pte), _PAGE_PROTECT,
_SEGMENT_ENTRY_PROTECT);
rste |= move_set_bit(pte_val(pte), _PAGE_DIRTY,
_SEGMENT_ENTRY_DIRTY);
rste |= move_set_bit(pte_val(pte), _PAGE_YOUNG,
_SEGMENT_ENTRY_YOUNG);
#ifdef CONFIG_MEM_SOFT_DIRTY
rste |= move_set_bit(pte_val(pte), _PAGE_SOFT_DIRTY,
_SEGMENT_ENTRY_SOFT_DIRTY);
#endif
rste |= move_set_bit(pte_val(pte), _PAGE_NOEXEC,
_SEGMENT_ENTRY_NOEXEC);
} else
rste = _SEGMENT_ENTRY_EMPTY;
return rste;
}
static inline pte_t __rste_to_pte(unsigned long rste)
{
int present;
pte_t pte;
if ((rste & _REGION_ENTRY_TYPE_MASK) == _REGION_ENTRY_TYPE_R3)
present = pud_present(__pud(rste));
else
present = pmd_present(__pmd(rste));
/*
* Convert encoding pmd / pud bits pte bits
* dy..R...I...wr lIR.uswrdy.p
* empty 00..0...1...00 -> 010.000000.0
* prot-none, clean, old 00..1...1...00 -> 111.000000.1
* prot-none, clean, young 01..1...1...00 -> 111.000001.1
* prot-none, dirty, old 10..1...1...00 -> 111.000010.1
* prot-none, dirty, young 11..1...1...00 -> 111.000011.1
* read-only, clean, old 00..1...1...01 -> 111.000100.1
* read-only, clean, young 01..1...0...01 -> 101.000101.1
* read-only, dirty, old 10..1...1...01 -> 111.000110.1
* read-only, dirty, young 11..1...0...01 -> 101.000111.1
* read-write, clean, old 00..1...1...11 -> 111.001100.1
* read-write, clean, young 01..1...0...11 -> 101.001101.1
* read-write, dirty, old 10..0...1...11 -> 110.001110.1
* read-write, dirty, young 11..0...0...11 -> 100.001111.1
* HW-bits: R read-only, I invalid
* SW-bits: p present, y young, d dirty, r read, w write, s special,
* u unused, l large
*/
if (present) {
pte_val(pte) = rste & _SEGMENT_ENTRY_ORIGIN_LARGE;
pte_val(pte) |= _PAGE_LARGE | _PAGE_PRESENT;
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_READ,
_PAGE_READ);
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_WRITE,
_PAGE_WRITE);
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_INVALID,
_PAGE_INVALID);
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_PROTECT,
_PAGE_PROTECT);
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_DIRTY,
_PAGE_DIRTY);
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_YOUNG,
_PAGE_YOUNG);
#ifdef CONFIG_MEM_SOFT_DIRTY
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_SOFT_DIRTY,
_PAGE_DIRTY);
#endif
pte_val(pte) |= move_set_bit(rste, _SEGMENT_ENTRY_NOEXEC,
_PAGE_NOEXEC);
} else
pte_val(pte) = _PAGE_INVALID;
return pte;
}
void set_huge_pte_at(struct mm_struct *mm, unsigned long addr,
pte_t *ptep, pte_t pte)
{
unsigned long rste;
rste = __pte_to_rste(pte);
if (!MACHINE_HAS_NX)
rste &= ~_SEGMENT_ENTRY_NOEXEC;
/* Set correct table type for 2G hugepages */
if ((pte_val(*ptep) & _REGION_ENTRY_TYPE_MASK) == _REGION_ENTRY_TYPE_R3)
rste |= _REGION_ENTRY_TYPE_R3 | _REGION3_ENTRY_LARGE;
else
rste |= _SEGMENT_ENTRY_LARGE;
pte_val(*ptep) = rste;
}
pte_t huge_ptep_get(pte_t *ptep)
{
return __rste_to_pte(pte_val(*ptep));
}
pte_t huge_ptep_get_and_clear(struct mm_struct *mm,
unsigned long addr, pte_t *ptep)
{
pte_t pte = huge_ptep_get(ptep);
pmd_t *pmdp = (pmd_t *) ptep;
pud_t *pudp = (pud_t *) ptep;
if ((pte_val(*ptep) & _REGION_ENTRY_TYPE_MASK) == _REGION_ENTRY_TYPE_R3)
pudp_xchg_direct(mm, addr, pudp, __pud(_REGION3_ENTRY_EMPTY));
else
pmdp_xchg_direct(mm, addr, pmdp, __pmd(_SEGMENT_ENTRY_EMPTY));
return pte;
}
pte_t *huge_pte_alloc(struct mm_struct *mm,
unsigned long addr, unsigned long sz)
{
pgd_t *pgdp;
pud_t *pudp;
pmd_t *pmdp = NULL;
pgdp = pgd_offset(mm, addr);
pudp = pud_alloc(mm, pgdp, addr);
if (pudp) {
if (sz == PUD_SIZE)
return (pte_t *) pudp;
else if (sz == PMD_SIZE)
pmdp = pmd_alloc(mm, pudp, addr);
}
return (pte_t *) pmdp;
}
pte_t *huge_pte_offset(struct mm_struct *mm, unsigned long addr)
{
pgd_t *pgdp;
pud_t *pudp;
pmd_t *pmdp = NULL;
pgdp = pgd_offset(mm, addr);
if (pgd_present(*pgdp)) {
pudp = pud_offset(pgdp, addr);
if (pud_present(*pudp)) {
if (pud_large(*pudp))
return (pte_t *) pudp;
pmdp = pmd_offset(pudp, addr);
}
}
return (pte_t *) pmdp;
}
int pmd_huge(pmd_t pmd)
{
return pmd_large(pmd);
}
int pud_huge(pud_t pud)
{
return pud_large(pud);
}
struct page *
follow_huge_pud(struct mm_struct *mm, unsigned long address,
pud_t *pud, int flags)
{
if (flags & FOLL_GET)
return NULL;
return pud_page(*pud) + ((address & ~PUD_MASK) >> PAGE_SHIFT);
}
static __init int setup_hugepagesz(char *opt)
{
unsigned long size;
char *string = opt;
size = memparse(opt, &opt);
if (MACHINE_HAS_EDAT1 && size == PMD_SIZE) {
hugetlb_add_hstate(PMD_SHIFT - PAGE_SHIFT);
} else if (MACHINE_HAS_EDAT2 && size == PUD_SIZE) {
hugetlb_add_hstate(PUD_SHIFT - PAGE_SHIFT);
} else {
hugetlb_bad_size();
pr_err("hugepagesz= specifies an unsupported page size %s\n",
string);
return 0;
}
return 1;
}
__setup("hugepagesz=", setup_hugepagesz);
| gpl-2.0 |
fulcrum7/mq107-kernel | drivers/media/video/stk-webcam.c | 48 | 36140 | /*
* stk-webcam.c : Driver for Syntek 1125 USB webcam controller
*
* Copyright (C) 2006 Nicolas VIVIEN
* Copyright 2007-2008 Jaime Velasco Juan <jsagarribay@gmail.com>
*
* Some parts are inspired from cafe_ccic.c
* Copyright 2006-2007 Jonathan Corbet
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/usb.h>
#include <linux/mm.h>
#include <linux/vmalloc.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include "stk-webcam.h"
static int hflip = 1;
module_param(hflip, bool, 0444);
MODULE_PARM_DESC(hflip, "Horizontal image flip (mirror). Defaults to 1");
static int vflip = 1;
module_param(vflip, bool, 0444);
MODULE_PARM_DESC(vflip, "Vertical image flip. Defaults to 1");
static int debug;
module_param(debug, int, 0444);
MODULE_PARM_DESC(debug, "Debug v4l ioctls. Defaults to 0");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jaime Velasco Juan <jsagarribay@gmail.com> and Nicolas VIVIEN");
MODULE_DESCRIPTION("Syntek DC1125 webcam driver");
/* Some cameras have audio interfaces, we aren't interested in those */
static struct usb_device_id stkwebcam_table[] = {
{ USB_DEVICE_AND_INTERFACE_INFO(0x174f, 0xa311, 0xff, 0xff, 0xff) },
{ USB_DEVICE_AND_INTERFACE_INFO(0x05e1, 0x0501, 0xff, 0xff, 0xff) },
{ }
};
MODULE_DEVICE_TABLE(usb, stkwebcam_table);
/*
* Basic stuff
*/
int stk_camera_write_reg(struct stk_camera *dev, u16 index, u8 value)
{
struct usb_device *udev = dev->udev;
int ret;
ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
0x01,
USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
value,
index,
NULL,
0,
500);
if (ret < 0)
return ret;
else
return 0;
}
int stk_camera_read_reg(struct stk_camera *dev, u16 index, int *value)
{
struct usb_device *udev = dev->udev;
int ret;
ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0),
0x00,
USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
0x00,
index,
(u8 *) value,
sizeof(u8),
500);
if (ret < 0)
return ret;
else
return 0;
}
static int stk_start_stream(struct stk_camera *dev)
{
int value;
int i, ret;
int value_116, value_117;
if (!is_present(dev))
return -ENODEV;
if (!is_memallocd(dev) || !is_initialised(dev)) {
STK_ERROR("FIXME: Buffers are not allocated\n");
return -EFAULT;
}
ret = usb_set_interface(dev->udev, 0, 5);
if (ret < 0)
STK_ERROR("usb_set_interface failed !\n");
if (stk_sensor_wakeup(dev))
STK_ERROR("error awaking the sensor\n");
stk_camera_read_reg(dev, 0x0116, &value_116);
stk_camera_read_reg(dev, 0x0117, &value_117);
stk_camera_write_reg(dev, 0x0116, 0x0000);
stk_camera_write_reg(dev, 0x0117, 0x0000);
stk_camera_read_reg(dev, 0x0100, &value);
stk_camera_write_reg(dev, 0x0100, value | 0x80);
stk_camera_write_reg(dev, 0x0116, value_116);
stk_camera_write_reg(dev, 0x0117, value_117);
for (i = 0; i < MAX_ISO_BUFS; i++) {
if (dev->isobufs[i].urb) {
ret = usb_submit_urb(dev->isobufs[i].urb, GFP_KERNEL);
atomic_inc(&dev->urbs_used);
if (ret)
return ret;
}
}
set_streaming(dev);
return 0;
}
static int stk_stop_stream(struct stk_camera *dev)
{
int value;
int i;
if (is_present(dev)) {
stk_camera_read_reg(dev, 0x0100, &value);
stk_camera_write_reg(dev, 0x0100, value & ~0x80);
if (dev->isobufs != NULL) {
for (i = 0; i < MAX_ISO_BUFS; i++) {
if (dev->isobufs[i].urb)
usb_kill_urb(dev->isobufs[i].urb);
}
}
unset_streaming(dev);
if (usb_set_interface(dev->udev, 0, 0))
STK_ERROR("usb_set_interface failed !\n");
if (stk_sensor_sleep(dev))
STK_ERROR("error suspending the sensor\n");
}
return 0;
}
/*
* This seems to be the shortest init sequence we
* must do in order to find the sensor
* Bit 5 of reg. 0x0000 here is important, when reset to 0 the sensor
* is also reset. Maybe powers down it?
* Rest of values don't make a difference
*/
static struct regval stk1125_initvals[] = {
/*TODO: What means this sequence? */
{0x0000, 0x24},
{0x0100, 0x21},
{0x0002, 0x68},
{0x0003, 0x80},
{0x0005, 0x00},
{0x0007, 0x03},
{0x000d, 0x00},
{0x000f, 0x02},
{0x0300, 0x12},
{0x0350, 0x41},
{0x0351, 0x00},
{0x0352, 0x00},
{0x0353, 0x00},
{0x0018, 0x10},
{0x0019, 0x00},
{0x001b, 0x0e},
{0x001c, 0x46},
{0x0300, 0x80},
{0x001a, 0x04},
{0x0110, 0x00},
{0x0111, 0x00},
{0x0112, 0x00},
{0x0113, 0x00},
{0xffff, 0xff},
};
static int stk_initialise(struct stk_camera *dev)
{
struct regval *rv;
int ret;
if (!is_present(dev))
return -ENODEV;
if (is_initialised(dev))
return 0;
rv = stk1125_initvals;
while (rv->reg != 0xffff) {
ret = stk_camera_write_reg(dev, rv->reg, rv->val);
if (ret)
return ret;
rv++;
}
if (stk_sensor_init(dev) == 0) {
set_initialised(dev);
return 0;
} else
return -1;
}
#ifdef CONFIG_VIDEO_V4L1_COMPAT
/* sysfs functions */
/*FIXME cleanup this */
static ssize_t show_brightness(struct device *class,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
return sprintf(buf, "%X\n", dev->vsettings.brightness);
}
static ssize_t store_brightness(struct device *class,
struct device_attribute *attr, const char *buf, size_t count)
{
char *endp;
unsigned long value;
int ret;
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
value = simple_strtoul(buf, &endp, 16);
dev->vsettings.brightness = (int) value;
ret = stk_sensor_set_brightness(dev, value >> 8);
if (ret)
return ret;
else
return count;
}
static ssize_t show_hflip(struct device *class,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
return sprintf(buf, "%d\n", dev->vsettings.hflip);
}
static ssize_t store_hflip(struct device *class,
struct device_attribute *attr, const char *buf, size_t count)
{
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
if (strncmp(buf, "1", 1) == 0)
dev->vsettings.hflip = 1;
else if (strncmp(buf, "0", 1) == 0)
dev->vsettings.hflip = 0;
else
return -EINVAL;
return strlen(buf);
}
static ssize_t show_vflip(struct device *class,
struct device_attribute *attr, char *buf)
{
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
return sprintf(buf, "%d\n", dev->vsettings.vflip);
}
static ssize_t store_vflip(struct device *class,
struct device_attribute *attr, const char *buf, size_t count)
{
struct video_device *vdev = to_video_device(class);
struct stk_camera *dev = vdev_to_camera(vdev);
if (strncmp(buf, "1", 1) == 0)
dev->vsettings.vflip = 1;
else if (strncmp(buf, "0", 1) == 0)
dev->vsettings.vflip = 0;
else
return -EINVAL;
return strlen(buf);
}
static DEVICE_ATTR(brightness, S_IRUGO | S_IWUGO,
show_brightness, store_brightness);
static DEVICE_ATTR(hflip, S_IRUGO | S_IWUGO, show_hflip, store_hflip);
static DEVICE_ATTR(vflip, S_IRUGO | S_IWUGO, show_vflip, store_vflip);
static int stk_create_sysfs_files(struct video_device *vdev)
{
int ret;
ret = device_create_file(&vdev->dev, &dev_attr_brightness);
ret += device_create_file(&vdev->dev, &dev_attr_hflip);
ret += device_create_file(&vdev->dev, &dev_attr_vflip);
if (ret)
STK_WARNING("Could not create sysfs files\n");
return ret;
}
static void stk_remove_sysfs_files(struct video_device *vdev)
{
device_remove_file(&vdev->dev, &dev_attr_brightness);
device_remove_file(&vdev->dev, &dev_attr_hflip);
device_remove_file(&vdev->dev, &dev_attr_vflip);
}
#else
#define stk_create_sysfs_files(a)
#define stk_remove_sysfs_files(a)
#endif
/* *********************************************** */
/*
* This function is called as an URB transfert is complete (Isochronous pipe).
* So, the traitement is done in interrupt time, so it has be fast, not crash,
* and not stall. Neat.
*/
static void stk_isoc_handler(struct urb *urb)
{
int i;
int ret;
int framelen;
unsigned long flags;
unsigned char *fill = NULL;
unsigned char *iso_buf = NULL;
struct stk_camera *dev;
struct stk_sio_buffer *fb;
dev = (struct stk_camera *) urb->context;
if (dev == NULL) {
STK_ERROR("isoc_handler called with NULL device !\n");
return;
}
if (urb->status == -ENOENT || urb->status == -ECONNRESET
|| urb->status == -ESHUTDOWN) {
atomic_dec(&dev->urbs_used);
return;
}
spin_lock_irqsave(&dev->spinlock, flags);
if (urb->status != -EINPROGRESS && urb->status != 0) {
STK_ERROR("isoc_handler: urb->status == %d\n", urb->status);
goto resubmit;
}
if (list_empty(&dev->sio_avail)) {
/*FIXME Stop streaming after a while */
(void) (printk_ratelimit() &&
STK_ERROR("isoc_handler without available buffer!\n"));
goto resubmit;
}
fb = list_first_entry(&dev->sio_avail,
struct stk_sio_buffer, list);
fill = fb->buffer + fb->v4lbuf.bytesused;
for (i = 0; i < urb->number_of_packets; i++) {
if (urb->iso_frame_desc[i].status != 0) {
if (urb->iso_frame_desc[i].status != -EXDEV)
STK_ERROR("Frame %d has error %d\n", i,
urb->iso_frame_desc[i].status);
continue;
}
framelen = urb->iso_frame_desc[i].actual_length;
iso_buf = urb->transfer_buffer + urb->iso_frame_desc[i].offset;
if (framelen <= 4)
continue; /* no data */
/*
* we found something informational from there
* the isoc frames have to type of headers
* type1: 00 xx 00 00 or 20 xx 00 00
* type2: 80 xx 00 00 00 00 00 00 or a0 xx 00 00 00 00 00 00
* xx is a sequencer which has never been seen over 0x3f
* imho data written down looks like bayer, i see similarities
* after every 640 bytes
*/
if (*iso_buf & 0x80) {
framelen -= 8;
iso_buf += 8;
/* This marks a new frame */
if (fb->v4lbuf.bytesused != 0
&& fb->v4lbuf.bytesused != dev->frame_size) {
(void) (printk_ratelimit() &&
STK_ERROR("frame %d, "
"bytesused=%d, skipping\n",
i, fb->v4lbuf.bytesused));
fb->v4lbuf.bytesused = 0;
fill = fb->buffer;
} else if (fb->v4lbuf.bytesused == dev->frame_size) {
if (list_is_singular(&dev->sio_avail)) {
/* Always reuse the last buffer */
fb->v4lbuf.bytesused = 0;
fill = fb->buffer;
} else {
list_move_tail(dev->sio_avail.next,
&dev->sio_full);
wake_up(&dev->wait_frame);
fb = list_first_entry(&dev->sio_avail,
struct stk_sio_buffer, list);
fb->v4lbuf.bytesused = 0;
fill = fb->buffer;
}
}
} else {
framelen -= 4;
iso_buf += 4;
}
/* Our buffer is full !!! */
if (framelen + fb->v4lbuf.bytesused > dev->frame_size) {
(void) (printk_ratelimit() &&
STK_ERROR("Frame buffer overflow, lost sync\n"));
/*FIXME Do something here? */
continue;
}
spin_unlock_irqrestore(&dev->spinlock, flags);
memcpy(fill, iso_buf, framelen);
spin_lock_irqsave(&dev->spinlock, flags);
fill += framelen;
/* New size of our buffer */
fb->v4lbuf.bytesused += framelen;
}
resubmit:
spin_unlock_irqrestore(&dev->spinlock, flags);
urb->dev = dev->udev;
ret = usb_submit_urb(urb, GFP_ATOMIC);
if (ret != 0) {
STK_ERROR("Error (%d) re-submitting urb in stk_isoc_handler.\n",
ret);
}
}
/* -------------------------------------------- */
static int stk_prepare_iso(struct stk_camera *dev)
{
void *kbuf;
int i, j;
struct urb *urb;
struct usb_device *udev;
if (dev == NULL)
return -ENXIO;
udev = dev->udev;
if (dev->isobufs)
STK_ERROR("isobufs already allocated. Bad\n");
else
dev->isobufs = kzalloc(MAX_ISO_BUFS * sizeof(*dev->isobufs),
GFP_KERNEL);
if (dev->isobufs == NULL) {
STK_ERROR("Unable to allocate iso buffers\n");
return -ENOMEM;
}
for (i = 0; i < MAX_ISO_BUFS; i++) {
if (dev->isobufs[i].data == NULL) {
kbuf = kzalloc(ISO_BUFFER_SIZE, GFP_KERNEL);
if (kbuf == NULL) {
STK_ERROR("Failed to allocate iso buffer %d\n",
i);
goto isobufs_out;
}
dev->isobufs[i].data = kbuf;
} else
STK_ERROR("isobuf data already allocated\n");
if (dev->isobufs[i].urb == NULL) {
urb = usb_alloc_urb(ISO_FRAMES_PER_DESC, GFP_KERNEL);
if (urb == NULL) {
STK_ERROR("Failed to allocate URB %d\n", i);
goto isobufs_out;
}
dev->isobufs[i].urb = urb;
} else {
STK_ERROR("Killing URB\n");
usb_kill_urb(dev->isobufs[i].urb);
urb = dev->isobufs[i].urb;
}
urb->interval = 1;
urb->dev = udev;
urb->pipe = usb_rcvisocpipe(udev, dev->isoc_ep);
urb->transfer_flags = URB_ISO_ASAP;
urb->transfer_buffer = dev->isobufs[i].data;
urb->transfer_buffer_length = ISO_BUFFER_SIZE;
urb->complete = stk_isoc_handler;
urb->context = dev;
urb->start_frame = 0;
urb->number_of_packets = ISO_FRAMES_PER_DESC;
for (j = 0; j < ISO_FRAMES_PER_DESC; j++) {
urb->iso_frame_desc[j].offset = j * ISO_MAX_FRAME_SIZE;
urb->iso_frame_desc[j].length = ISO_MAX_FRAME_SIZE;
}
}
set_memallocd(dev);
return 0;
isobufs_out:
for (i = 0; i < MAX_ISO_BUFS && dev->isobufs[i].data; i++)
kfree(dev->isobufs[i].data);
for (i = 0; i < MAX_ISO_BUFS && dev->isobufs[i].urb; i++)
usb_free_urb(dev->isobufs[i].urb);
kfree(dev->isobufs);
dev->isobufs = NULL;
return -ENOMEM;
}
static void stk_clean_iso(struct stk_camera *dev)
{
int i;
if (dev == NULL || dev->isobufs == NULL)
return;
for (i = 0; i < MAX_ISO_BUFS; i++) {
struct urb *urb;
urb = dev->isobufs[i].urb;
if (urb) {
if (atomic_read(&dev->urbs_used) && is_present(dev))
usb_kill_urb(urb);
usb_free_urb(urb);
}
kfree(dev->isobufs[i].data);
}
kfree(dev->isobufs);
dev->isobufs = NULL;
unset_memallocd(dev);
}
static int stk_setup_siobuf(struct stk_camera *dev, int index)
{
struct stk_sio_buffer *buf = dev->sio_bufs + index;
INIT_LIST_HEAD(&buf->list);
buf->v4lbuf.length = PAGE_ALIGN(dev->frame_size);
buf->buffer = vmalloc_user(buf->v4lbuf.length);
if (buf->buffer == NULL)
return -ENOMEM;
buf->mapcount = 0;
buf->dev = dev;
buf->v4lbuf.index = index;
buf->v4lbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf->v4lbuf.field = V4L2_FIELD_NONE;
buf->v4lbuf.memory = V4L2_MEMORY_MMAP;
buf->v4lbuf.m.offset = 2*index*buf->v4lbuf.length;
return 0;
}
static int stk_free_sio_buffers(struct stk_camera *dev)
{
int i;
int nbufs;
unsigned long flags;
if (dev->n_sbufs == 0 || dev->sio_bufs == NULL)
return 0;
/*
* If any buffers are mapped, we cannot free them at all.
*/
for (i = 0; i < dev->n_sbufs; i++) {
if (dev->sio_bufs[i].mapcount > 0)
return -EBUSY;
}
/*
* OK, let's do it.
*/
spin_lock_irqsave(&dev->spinlock, flags);
INIT_LIST_HEAD(&dev->sio_avail);
INIT_LIST_HEAD(&dev->sio_full);
nbufs = dev->n_sbufs;
dev->n_sbufs = 0;
spin_unlock_irqrestore(&dev->spinlock, flags);
for (i = 0; i < nbufs; i++) {
if (dev->sio_bufs[i].buffer != NULL)
vfree(dev->sio_bufs[i].buffer);
}
kfree(dev->sio_bufs);
dev->sio_bufs = NULL;
return 0;
}
static int stk_prepare_sio_buffers(struct stk_camera *dev, unsigned n_sbufs)
{
int i;
if (dev->sio_bufs != NULL)
STK_ERROR("sio_bufs already allocated\n");
else {
dev->sio_bufs = kzalloc(n_sbufs * sizeof(struct stk_sio_buffer),
GFP_KERNEL);
if (dev->sio_bufs == NULL)
return -ENOMEM;
for (i = 0; i < n_sbufs; i++) {
if (stk_setup_siobuf(dev, i))
return (dev->n_sbufs > 1)? 0 : -ENOMEM;
dev->n_sbufs = i+1;
}
}
return 0;
}
static int stk_allocate_buffers(struct stk_camera *dev, unsigned n_sbufs)
{
int err;
err = stk_prepare_iso(dev);
if (err) {
stk_clean_iso(dev);
return err;
}
err = stk_prepare_sio_buffers(dev, n_sbufs);
if (err) {
stk_free_sio_buffers(dev);
return err;
}
return 0;
}
static void stk_free_buffers(struct stk_camera *dev)
{
stk_clean_iso(dev);
stk_free_sio_buffers(dev);
}
/* -------------------------------------------- */
/* v4l file operations */
static int v4l_stk_open(struct file *fp)
{
struct stk_camera *dev;
struct video_device *vdev;
vdev = video_devdata(fp);
dev = vdev_to_camera(vdev);
if (dev == NULL || !is_present(dev)) {
return -ENXIO;
}
fp->private_data = dev;
usb_autopm_get_interface(dev->interface);
return 0;
}
static int v4l_stk_release(struct file *fp)
{
struct stk_camera *dev = fp->private_data;
if (dev->owner == fp) {
stk_stop_stream(dev);
stk_free_buffers(dev);
dev->owner = NULL;
}
if(is_present(dev))
usb_autopm_put_interface(dev->interface);
return 0;
}
static ssize_t v4l_stk_read(struct file *fp, char __user *buf,
size_t count, loff_t *f_pos)
{
int i;
int ret;
unsigned long flags;
struct stk_sio_buffer *sbuf;
struct stk_camera *dev = fp->private_data;
if (!is_present(dev))
return -EIO;
if (dev->owner && dev->owner != fp)
return -EBUSY;
dev->owner = fp;
if (!is_streaming(dev)) {
if (stk_initialise(dev)
|| stk_allocate_buffers(dev, 3)
|| stk_start_stream(dev))
return -ENOMEM;
spin_lock_irqsave(&dev->spinlock, flags);
for (i = 0; i < dev->n_sbufs; i++) {
list_add_tail(&dev->sio_bufs[i].list, &dev->sio_avail);
dev->sio_bufs[i].v4lbuf.flags = V4L2_BUF_FLAG_QUEUED;
}
spin_unlock_irqrestore(&dev->spinlock, flags);
}
if (*f_pos == 0) {
if (fp->f_flags & O_NONBLOCK && list_empty(&dev->sio_full))
return -EWOULDBLOCK;
ret = wait_event_interruptible(dev->wait_frame,
!list_empty(&dev->sio_full) || !is_present(dev));
if (ret)
return ret;
if (!is_present(dev))
return -EIO;
}
if (count + *f_pos > dev->frame_size)
count = dev->frame_size - *f_pos;
spin_lock_irqsave(&dev->spinlock, flags);
if (list_empty(&dev->sio_full)) {
spin_unlock_irqrestore(&dev->spinlock, flags);
STK_ERROR("BUG: No siobufs ready\n");
return 0;
}
sbuf = list_first_entry(&dev->sio_full, struct stk_sio_buffer, list);
spin_unlock_irqrestore(&dev->spinlock, flags);
if (copy_to_user(buf, sbuf->buffer + *f_pos, count))
return -EFAULT;
*f_pos += count;
if (*f_pos >= dev->frame_size) {
*f_pos = 0;
spin_lock_irqsave(&dev->spinlock, flags);
list_move_tail(&sbuf->list, &dev->sio_avail);
spin_unlock_irqrestore(&dev->spinlock, flags);
}
return count;
}
static unsigned int v4l_stk_poll(struct file *fp, poll_table *wait)
{
struct stk_camera *dev = fp->private_data;
poll_wait(fp, &dev->wait_frame, wait);
if (!is_present(dev))
return POLLERR;
if (!list_empty(&dev->sio_full))
return (POLLIN | POLLRDNORM);
return 0;
}
static void stk_v4l_vm_open(struct vm_area_struct *vma)
{
struct stk_sio_buffer *sbuf = vma->vm_private_data;
sbuf->mapcount++;
}
static void stk_v4l_vm_close(struct vm_area_struct *vma)
{
struct stk_sio_buffer *sbuf = vma->vm_private_data;
sbuf->mapcount--;
if (sbuf->mapcount == 0)
sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_MAPPED;
}
static const struct vm_operations_struct stk_v4l_vm_ops = {
.open = stk_v4l_vm_open,
.close = stk_v4l_vm_close
};
static int v4l_stk_mmap(struct file *fp, struct vm_area_struct *vma)
{
unsigned int i;
int ret;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
struct stk_camera *dev = fp->private_data;
struct stk_sio_buffer *sbuf = NULL;
if (!(vma->vm_flags & VM_WRITE) || !(vma->vm_flags & VM_SHARED))
return -EINVAL;
for (i = 0; i < dev->n_sbufs; i++) {
if (dev->sio_bufs[i].v4lbuf.m.offset == offset) {
sbuf = dev->sio_bufs + i;
break;
}
}
if (sbuf == NULL)
return -EINVAL;
ret = remap_vmalloc_range(vma, sbuf->buffer, 0);
if (ret)
return ret;
vma->vm_flags |= VM_DONTEXPAND;
vma->vm_private_data = sbuf;
vma->vm_ops = &stk_v4l_vm_ops;
sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_MAPPED;
stk_v4l_vm_open(vma);
return 0;
}
/* v4l ioctl handlers */
static int stk_vidioc_querycap(struct file *filp,
void *priv, struct v4l2_capability *cap)
{
strcpy(cap->driver, "stk");
strcpy(cap->card, "stk");
cap->version = DRIVER_VERSION_NUM;
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE
| V4L2_CAP_READWRITE | V4L2_CAP_STREAMING;
return 0;
}
static int stk_vidioc_enum_input(struct file *filp,
void *priv, struct v4l2_input *input)
{
if (input->index != 0)
return -EINVAL;
strcpy(input->name, "Syntek USB Camera");
input->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int stk_vidioc_g_input(struct file *filp, void *priv, unsigned int *i)
{
*i = 0;
return 0;
}
static int stk_vidioc_s_input(struct file *filp, void *priv, unsigned int i)
{
if (i != 0)
return -EINVAL;
else
return 0;
}
/* from vivi.c */
static int stk_vidioc_s_std(struct file *filp, void *priv, v4l2_std_id *a)
{
return 0;
}
/* List of all V4Lv2 controls supported by the driver */
static struct v4l2_queryctrl stk_controls[] = {
{
.id = V4L2_CID_BRIGHTNESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Brightness",
.minimum = 0,
.maximum = 0xffff,
.step = 0x0100,
.default_value = 0x6000,
},
/*TODO: get more controls to work */
};
static int stk_vidioc_queryctrl(struct file *filp,
void *priv, struct v4l2_queryctrl *c)
{
int i;
int nbr;
nbr = ARRAY_SIZE(stk_controls);
for (i = 0; i < nbr; i++) {
if (stk_controls[i].id == c->id) {
memcpy(c, &stk_controls[i],
sizeof(struct v4l2_queryctrl));
return 0;
}
}
return -EINVAL;
}
static int stk_vidioc_g_ctrl(struct file *filp,
void *priv, struct v4l2_control *c)
{
struct stk_camera *dev = priv;
switch (c->id) {
case V4L2_CID_BRIGHTNESS:
c->value = dev->vsettings.brightness;
break;
default:
return -EINVAL;
}
return 0;
}
static int stk_vidioc_s_ctrl(struct file *filp,
void *priv, struct v4l2_control *c)
{
struct stk_camera *dev = priv;
switch (c->id) {
case V4L2_CID_BRIGHTNESS:
dev->vsettings.brightness = c->value;
return stk_sensor_set_brightness(dev, c->value >> 8);
default:
return -EINVAL;
}
return 0;
}
static int stk_vidioc_enum_fmt_vid_cap(struct file *filp,
void *priv, struct v4l2_fmtdesc *fmtd)
{
switch (fmtd->index) {
case 0:
fmtd->pixelformat = V4L2_PIX_FMT_RGB565;
strcpy(fmtd->description, "r5g6b5");
break;
case 1:
fmtd->pixelformat = V4L2_PIX_FMT_RGB565X;
strcpy(fmtd->description, "r5g6b5BE");
break;
case 2:
fmtd->pixelformat = V4L2_PIX_FMT_UYVY;
strcpy(fmtd->description, "yuv4:2:2");
break;
case 3:
fmtd->pixelformat = V4L2_PIX_FMT_SBGGR8;
strcpy(fmtd->description, "Raw bayer");
break;
case 4:
fmtd->pixelformat = V4L2_PIX_FMT_YUYV;
strcpy(fmtd->description, "yuv4:2:2");
break;
default:
return -EINVAL;
}
return 0;
}
static struct stk_size {
unsigned w;
unsigned h;
enum stk_mode m;
} stk_sizes[] = {
{ .w = 1280, .h = 1024, .m = MODE_SXGA, },
{ .w = 640, .h = 480, .m = MODE_VGA, },
{ .w = 352, .h = 288, .m = MODE_CIF, },
{ .w = 320, .h = 240, .m = MODE_QVGA, },
{ .w = 176, .h = 144, .m = MODE_QCIF, },
};
static int stk_vidioc_g_fmt_vid_cap(struct file *filp,
void *priv, struct v4l2_format *f)
{
struct v4l2_pix_format *pix_format = &f->fmt.pix;
struct stk_camera *dev = priv;
int i;
for (i = 0; i < ARRAY_SIZE(stk_sizes)
&& stk_sizes[i].m != dev->vsettings.mode;
i++);
if (i == ARRAY_SIZE(stk_sizes)) {
STK_ERROR("ERROR: mode invalid\n");
return -EINVAL;
}
pix_format->width = stk_sizes[i].w;
pix_format->height = stk_sizes[i].h;
pix_format->field = V4L2_FIELD_NONE;
pix_format->colorspace = V4L2_COLORSPACE_SRGB;
pix_format->pixelformat = dev->vsettings.palette;
if (dev->vsettings.palette == V4L2_PIX_FMT_SBGGR8)
pix_format->bytesperline = pix_format->width;
else
pix_format->bytesperline = 2 * pix_format->width;
pix_format->sizeimage = pix_format->bytesperline
* pix_format->height;
return 0;
}
static int stk_vidioc_try_fmt_vid_cap(struct file *filp,
void *priv, struct v4l2_format *fmtd)
{
int i;
switch (fmtd->fmt.pix.pixelformat) {
case V4L2_PIX_FMT_RGB565:
case V4L2_PIX_FMT_RGB565X:
case V4L2_PIX_FMT_UYVY:
case V4L2_PIX_FMT_YUYV:
case V4L2_PIX_FMT_SBGGR8:
break;
default:
return -EINVAL;
}
for (i = 1; i < ARRAY_SIZE(stk_sizes); i++) {
if (fmtd->fmt.pix.width > stk_sizes[i].w)
break;
}
if (i == ARRAY_SIZE(stk_sizes)
|| (abs(fmtd->fmt.pix.width - stk_sizes[i-1].w)
< abs(fmtd->fmt.pix.width - stk_sizes[i].w))) {
fmtd->fmt.pix.height = stk_sizes[i-1].h;
fmtd->fmt.pix.width = stk_sizes[i-1].w;
fmtd->fmt.pix.priv = i - 1;
} else {
fmtd->fmt.pix.height = stk_sizes[i].h;
fmtd->fmt.pix.width = stk_sizes[i].w;
fmtd->fmt.pix.priv = i;
}
fmtd->fmt.pix.field = V4L2_FIELD_NONE;
fmtd->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
if (fmtd->fmt.pix.pixelformat == V4L2_PIX_FMT_SBGGR8)
fmtd->fmt.pix.bytesperline = fmtd->fmt.pix.width;
else
fmtd->fmt.pix.bytesperline = 2 * fmtd->fmt.pix.width;
fmtd->fmt.pix.sizeimage = fmtd->fmt.pix.bytesperline
* fmtd->fmt.pix.height;
return 0;
}
static int stk_setup_format(struct stk_camera *dev)
{
int i = 0;
int depth;
if (dev->vsettings.palette == V4L2_PIX_FMT_SBGGR8)
depth = 1;
else
depth = 2;
while (i < ARRAY_SIZE(stk_sizes) &&
stk_sizes[i].m != dev->vsettings.mode)
i++;
if (i == ARRAY_SIZE(stk_sizes)) {
STK_ERROR("Something is broken in %s\n", __func__);
return -EFAULT;
}
/* This registers controls some timings, not sure of what. */
stk_camera_write_reg(dev, 0x001b, 0x0e);
if (dev->vsettings.mode == MODE_SXGA)
stk_camera_write_reg(dev, 0x001c, 0x0e);
else
stk_camera_write_reg(dev, 0x001c, 0x46);
/*
* Registers 0x0115 0x0114 are the size of each line (bytes),
* regs 0x0117 0x0116 are the heigth of the image.
*/
stk_camera_write_reg(dev, 0x0115,
((stk_sizes[i].w * depth) >> 8) & 0xff);
stk_camera_write_reg(dev, 0x0114,
(stk_sizes[i].w * depth) & 0xff);
stk_camera_write_reg(dev, 0x0117,
(stk_sizes[i].h >> 8) & 0xff);
stk_camera_write_reg(dev, 0x0116,
stk_sizes[i].h & 0xff);
return stk_sensor_configure(dev);
}
static int stk_vidioc_s_fmt_vid_cap(struct file *filp,
void *priv, struct v4l2_format *fmtd)
{
int ret;
struct stk_camera *dev = priv;
if (dev == NULL)
return -ENODEV;
if (!is_present(dev))
return -ENODEV;
if (is_streaming(dev))
return -EBUSY;
if (dev->owner && dev->owner != filp)
return -EBUSY;
ret = stk_vidioc_try_fmt_vid_cap(filp, priv, fmtd);
if (ret)
return ret;
dev->owner = filp;
dev->vsettings.palette = fmtd->fmt.pix.pixelformat;
stk_free_buffers(dev);
dev->frame_size = fmtd->fmt.pix.sizeimage;
dev->vsettings.mode = stk_sizes[fmtd->fmt.pix.priv].m;
stk_initialise(dev);
return stk_setup_format(dev);
}
static int stk_vidioc_reqbufs(struct file *filp,
void *priv, struct v4l2_requestbuffers *rb)
{
struct stk_camera *dev = priv;
if (dev == NULL)
return -ENODEV;
if (rb->memory != V4L2_MEMORY_MMAP)
return -EINVAL;
if (is_streaming(dev)
|| (dev->owner && dev->owner != filp))
return -EBUSY;
dev->owner = filp;
/*FIXME If they ask for zero, we must stop streaming and free */
if (rb->count < 3)
rb->count = 3;
/* Arbitrary limit */
else if (rb->count > 5)
rb->count = 5;
stk_allocate_buffers(dev, rb->count);
rb->count = dev->n_sbufs;
return 0;
}
static int stk_vidioc_querybuf(struct file *filp,
void *priv, struct v4l2_buffer *buf)
{
struct stk_camera *dev = priv;
struct stk_sio_buffer *sbuf;
if (buf->index >= dev->n_sbufs)
return -EINVAL;
sbuf = dev->sio_bufs + buf->index;
*buf = sbuf->v4lbuf;
return 0;
}
static int stk_vidioc_qbuf(struct file *filp,
void *priv, struct v4l2_buffer *buf)
{
struct stk_camera *dev = priv;
struct stk_sio_buffer *sbuf;
unsigned long flags;
if (buf->memory != V4L2_MEMORY_MMAP)
return -EINVAL;
if (buf->index >= dev->n_sbufs)
return -EINVAL;
sbuf = dev->sio_bufs + buf->index;
if (sbuf->v4lbuf.flags & V4L2_BUF_FLAG_QUEUED)
return 0;
sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_QUEUED;
sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_DONE;
spin_lock_irqsave(&dev->spinlock, flags);
list_add_tail(&sbuf->list, &dev->sio_avail);
*buf = sbuf->v4lbuf;
spin_unlock_irqrestore(&dev->spinlock, flags);
return 0;
}
static int stk_vidioc_dqbuf(struct file *filp,
void *priv, struct v4l2_buffer *buf)
{
struct stk_camera *dev = priv;
struct stk_sio_buffer *sbuf;
unsigned long flags;
int ret;
if (!is_streaming(dev))
return -EINVAL;
if (filp->f_flags & O_NONBLOCK && list_empty(&dev->sio_full))
return -EWOULDBLOCK;
ret = wait_event_interruptible(dev->wait_frame,
!list_empty(&dev->sio_full) || !is_present(dev));
if (ret)
return ret;
if (!is_present(dev))
return -EIO;
spin_lock_irqsave(&dev->spinlock, flags);
sbuf = list_first_entry(&dev->sio_full, struct stk_sio_buffer, list);
list_del_init(&sbuf->list);
spin_unlock_irqrestore(&dev->spinlock, flags);
sbuf->v4lbuf.flags &= ~V4L2_BUF_FLAG_QUEUED;
sbuf->v4lbuf.flags |= V4L2_BUF_FLAG_DONE;
sbuf->v4lbuf.sequence = ++dev->sequence;
do_gettimeofday(&sbuf->v4lbuf.timestamp);
*buf = sbuf->v4lbuf;
return 0;
}
static int stk_vidioc_streamon(struct file *filp,
void *priv, enum v4l2_buf_type type)
{
struct stk_camera *dev = priv;
if (is_streaming(dev))
return 0;
if (dev->sio_bufs == NULL)
return -EINVAL;
dev->sequence = 0;
return stk_start_stream(dev);
}
static int stk_vidioc_streamoff(struct file *filp,
void *priv, enum v4l2_buf_type type)
{
struct stk_camera *dev = priv;
unsigned long flags;
int i;
stk_stop_stream(dev);
spin_lock_irqsave(&dev->spinlock, flags);
INIT_LIST_HEAD(&dev->sio_avail);
INIT_LIST_HEAD(&dev->sio_full);
for (i = 0; i < dev->n_sbufs; i++) {
INIT_LIST_HEAD(&dev->sio_bufs[i].list);
dev->sio_bufs[i].v4lbuf.flags = 0;
}
spin_unlock_irqrestore(&dev->spinlock, flags);
return 0;
}
static int stk_vidioc_g_parm(struct file *filp,
void *priv, struct v4l2_streamparm *sp)
{
/*FIXME This is not correct */
sp->parm.capture.timeperframe.numerator = 1;
sp->parm.capture.timeperframe.denominator = 30;
sp->parm.capture.readbuffers = 2;
return 0;
}
static int stk_vidioc_enum_framesizes(struct file *filp,
void *priv, struct v4l2_frmsizeenum *frms)
{
if (frms->index >= ARRAY_SIZE(stk_sizes))
return -EINVAL;
switch (frms->pixel_format) {
case V4L2_PIX_FMT_RGB565:
case V4L2_PIX_FMT_RGB565X:
case V4L2_PIX_FMT_UYVY:
case V4L2_PIX_FMT_YUYV:
case V4L2_PIX_FMT_SBGGR8:
frms->type = V4L2_FRMSIZE_TYPE_DISCRETE;
frms->discrete.width = stk_sizes[frms->index].w;
frms->discrete.height = stk_sizes[frms->index].h;
return 0;
default: return -EINVAL;
}
}
static struct v4l2_file_operations v4l_stk_fops = {
.owner = THIS_MODULE,
.open = v4l_stk_open,
.release = v4l_stk_release,
.read = v4l_stk_read,
.poll = v4l_stk_poll,
.mmap = v4l_stk_mmap,
.ioctl = video_ioctl2,
};
static const struct v4l2_ioctl_ops v4l_stk_ioctl_ops = {
.vidioc_querycap = stk_vidioc_querycap,
.vidioc_enum_fmt_vid_cap = stk_vidioc_enum_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = stk_vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = stk_vidioc_s_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = stk_vidioc_g_fmt_vid_cap,
.vidioc_enum_input = stk_vidioc_enum_input,
.vidioc_s_input = stk_vidioc_s_input,
.vidioc_g_input = stk_vidioc_g_input,
.vidioc_s_std = stk_vidioc_s_std,
.vidioc_reqbufs = stk_vidioc_reqbufs,
.vidioc_querybuf = stk_vidioc_querybuf,
.vidioc_qbuf = stk_vidioc_qbuf,
.vidioc_dqbuf = stk_vidioc_dqbuf,
.vidioc_streamon = stk_vidioc_streamon,
.vidioc_streamoff = stk_vidioc_streamoff,
.vidioc_queryctrl = stk_vidioc_queryctrl,
.vidioc_g_ctrl = stk_vidioc_g_ctrl,
.vidioc_s_ctrl = stk_vidioc_s_ctrl,
.vidioc_g_parm = stk_vidioc_g_parm,
.vidioc_enum_framesizes = stk_vidioc_enum_framesizes,
};
static void stk_v4l_dev_release(struct video_device *vd)
{
struct stk_camera *dev = vdev_to_camera(vd);
if (dev->sio_bufs != NULL || dev->isobufs != NULL)
STK_ERROR("We are leaking memory\n");
usb_put_intf(dev->interface);
kfree(dev);
}
static struct video_device stk_v4l_data = {
.name = "stkwebcam",
.tvnorms = V4L2_STD_UNKNOWN,
.current_norm = V4L2_STD_UNKNOWN,
.fops = &v4l_stk_fops,
.ioctl_ops = &v4l_stk_ioctl_ops,
.release = stk_v4l_dev_release,
};
static int stk_register_video_device(struct stk_camera *dev)
{
int err;
dev->vdev = stk_v4l_data;
dev->vdev.debug = debug;
dev->vdev.parent = &dev->interface->dev;
err = video_register_device(&dev->vdev, VFL_TYPE_GRABBER, -1);
if (err)
STK_ERROR("v4l registration failed\n");
else
STK_INFO("Syntek USB2.0 Camera is now controlling device %s\n",
video_device_node_name(&dev->vdev));
return err;
}
/* USB Stuff */
static int stk_camera_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
int i;
int err = 0;
struct stk_camera *dev = NULL;
struct usb_device *udev = interface_to_usbdev(interface);
struct usb_host_interface *iface_desc;
struct usb_endpoint_descriptor *endpoint;
dev = kzalloc(sizeof(struct stk_camera), GFP_KERNEL);
if (dev == NULL) {
STK_ERROR("Out of memory !\n");
return -ENOMEM;
}
spin_lock_init(&dev->spinlock);
init_waitqueue_head(&dev->wait_frame);
dev->udev = udev;
dev->interface = interface;
usb_get_intf(interface);
dev->vsettings.vflip = vflip;
dev->vsettings.hflip = hflip;
dev->n_sbufs = 0;
set_present(dev);
/* Set up the endpoint information
* use only the first isoc-in endpoint
* for the current alternate setting */
iface_desc = interface->cur_altsetting;
for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
endpoint = &iface_desc->endpoint[i].desc;
if (!dev->isoc_ep
&& usb_endpoint_is_isoc_in(endpoint)) {
/* we found an isoc in endpoint */
dev->isoc_ep = usb_endpoint_num(endpoint);
break;
}
}
if (!dev->isoc_ep) {
STK_ERROR("Could not find isoc-in endpoint");
err = -ENODEV;
goto error;
}
dev->vsettings.brightness = 0x7fff;
dev->vsettings.palette = V4L2_PIX_FMT_RGB565;
dev->vsettings.mode = MODE_VGA;
dev->frame_size = 640 * 480 * 2;
INIT_LIST_HEAD(&dev->sio_avail);
INIT_LIST_HEAD(&dev->sio_full);
usb_set_intfdata(interface, dev);
err = stk_register_video_device(dev);
if (err) {
goto error;
}
stk_create_sysfs_files(&dev->vdev);
return 0;
error:
kfree(dev);
return err;
}
static void stk_camera_disconnect(struct usb_interface *interface)
{
struct stk_camera *dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
unset_present(dev);
wake_up_interruptible(&dev->wait_frame);
stk_remove_sysfs_files(&dev->vdev);
STK_INFO("Syntek USB2.0 Camera release resources device %s\n",
video_device_node_name(&dev->vdev));
video_unregister_device(&dev->vdev);
}
#ifdef CONFIG_PM
static int stk_camera_suspend(struct usb_interface *intf, pm_message_t message)
{
struct stk_camera *dev = usb_get_intfdata(intf);
if (is_streaming(dev)) {
stk_stop_stream(dev);
/* yes, this is ugly */
set_streaming(dev);
}
return 0;
}
static int stk_camera_resume(struct usb_interface *intf)
{
struct stk_camera *dev = usb_get_intfdata(intf);
if (!is_initialised(dev))
return 0;
unset_initialised(dev);
stk_initialise(dev);
stk_setup_format(dev);
if (is_streaming(dev))
stk_start_stream(dev);
return 0;
}
#endif
static struct usb_driver stk_camera_driver = {
.name = "stkwebcam",
.probe = stk_camera_probe,
.disconnect = stk_camera_disconnect,
.id_table = stkwebcam_table,
#ifdef CONFIG_PM
.suspend = stk_camera_suspend,
.resume = stk_camera_resume,
#endif
};
static int __init stk_camera_init(void)
{
int result;
result = usb_register(&stk_camera_driver);
if (result)
STK_ERROR("usb_register failed ! Error number %d\n", result);
return result;
}
static void __exit stk_camera_exit(void)
{
usb_deregister(&stk_camera_driver);
}
module_init(stk_camera_init);
module_exit(stk_camera_exit);
| gpl-2.0 |
sadven/Meisie-Kernel | drivers/net/wireless/rtlwifi/usb.c | 304 | 31016 | /******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
*****************************************************************************/
#include "wifi.h"
#include "core.h"
#include "usb.h"
#include "base.h"
#include "ps.h"
#include "rtl8192c/fw_common.h"
#include <linux/export.h>
#define REALTEK_USB_VENQT_READ 0xC0
#define REALTEK_USB_VENQT_WRITE 0x40
#define REALTEK_USB_VENQT_CMD_REQ 0x05
#define REALTEK_USB_VENQT_CMD_IDX 0x00
#define MAX_USBCTRL_VENDORREQ_TIMES 10
static void usbctrl_async_callback(struct urb *urb)
{
if (urb) {
/* free dr */
kfree(urb->setup_packet);
/* free databuf */
kfree(urb->transfer_buffer);
}
}
static int _usbctrl_vendorreq_async_write(struct usb_device *udev, u8 request,
u16 value, u16 index, void *pdata,
u16 len)
{
int rc;
unsigned int pipe;
u8 reqtype;
struct usb_ctrlrequest *dr;
struct urb *urb;
const u16 databuf_maxlen = REALTEK_USB_VENQT_MAX_BUF_SIZE;
u8 *databuf;
if (WARN_ON_ONCE(len > databuf_maxlen))
len = databuf_maxlen;
pipe = usb_sndctrlpipe(udev, 0); /* write_out */
reqtype = REALTEK_USB_VENQT_WRITE;
dr = kmalloc(sizeof(*dr), GFP_ATOMIC);
if (!dr)
return -ENOMEM;
databuf = kmalloc(databuf_maxlen, GFP_ATOMIC);
if (!databuf) {
kfree(dr);
return -ENOMEM;
}
urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!urb) {
kfree(databuf);
kfree(dr);
return -ENOMEM;
}
dr->bRequestType = reqtype;
dr->bRequest = request;
dr->wValue = cpu_to_le16(value);
dr->wIndex = cpu_to_le16(index);
dr->wLength = cpu_to_le16(len);
/* data are already in little-endian order */
memcpy(databuf, pdata, len);
usb_fill_control_urb(urb, udev, pipe,
(unsigned char *)dr, databuf, len,
usbctrl_async_callback, NULL);
rc = usb_submit_urb(urb, GFP_ATOMIC);
if (rc < 0) {
kfree(databuf);
kfree(dr);
}
usb_free_urb(urb);
return rc;
}
static int _usbctrl_vendorreq_sync_read(struct usb_device *udev, u8 request,
u16 value, u16 index, void *pdata,
u16 len)
{
unsigned int pipe;
int status;
u8 reqtype;
int vendorreq_times = 0;
static int count;
pipe = usb_rcvctrlpipe(udev, 0); /* read_in */
reqtype = REALTEK_USB_VENQT_READ;
do {
status = usb_control_msg(udev, pipe, request, reqtype, value,
index, pdata, len, 0); /*max. timeout*/
if (status < 0) {
/* firmware download is checksumed, don't retry */
if ((value >= FW_8192C_START_ADDRESS &&
value <= FW_8192C_END_ADDRESS))
break;
} else {
break;
}
} while (++vendorreq_times < MAX_USBCTRL_VENDORREQ_TIMES);
if (status < 0 && count++ < 4)
pr_err("reg 0x%x, usbctrl_vendorreq TimeOut! status:0x%x value=0x%x\n",
value, status, *(u32 *)pdata);
return status;
}
static u32 _usb_read_sync(struct rtl_priv *rtlpriv, u32 addr, u16 len)
{
struct device *dev = rtlpriv->io.dev;
struct usb_device *udev = to_usb_device(dev);
u8 request;
u16 wvalue;
u16 index;
__le32 *data;
unsigned long flags;
spin_lock_irqsave(&rtlpriv->locks.usb_lock, flags);
if (++rtlpriv->usb_data_index >= RTL_USB_MAX_RX_COUNT)
rtlpriv->usb_data_index = 0;
data = &rtlpriv->usb_data[rtlpriv->usb_data_index];
spin_unlock_irqrestore(&rtlpriv->locks.usb_lock, flags);
request = REALTEK_USB_VENQT_CMD_REQ;
index = REALTEK_USB_VENQT_CMD_IDX; /* n/a */
wvalue = (u16)addr;
_usbctrl_vendorreq_sync_read(udev, request, wvalue, index, data, len);
return le32_to_cpu(*data);
}
static u8 _usb_read8_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return (u8)_usb_read_sync(rtlpriv, addr, 1);
}
static u16 _usb_read16_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return (u16)_usb_read_sync(rtlpriv, addr, 2);
}
static u32 _usb_read32_sync(struct rtl_priv *rtlpriv, u32 addr)
{
return _usb_read_sync(rtlpriv, addr, 4);
}
static void _usb_write_async(struct usb_device *udev, u32 addr, u32 val,
u16 len)
{
u8 request;
u16 wvalue;
u16 index;
__le32 data;
request = REALTEK_USB_VENQT_CMD_REQ;
index = REALTEK_USB_VENQT_CMD_IDX; /* n/a */
wvalue = (u16)(addr&0x0000ffff);
data = cpu_to_le32(val);
_usbctrl_vendorreq_async_write(udev, request, wvalue, index, &data,
len);
}
static void _usb_write8_async(struct rtl_priv *rtlpriv, u32 addr, u8 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 1);
}
static void _usb_write16_async(struct rtl_priv *rtlpriv, u32 addr, u16 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 2);
}
static void _usb_write32_async(struct rtl_priv *rtlpriv, u32 addr, u32 val)
{
struct device *dev = rtlpriv->io.dev;
_usb_write_async(to_usb_device(dev), addr, val, 4);
}
static void _usb_writeN_sync(struct rtl_priv *rtlpriv, u32 addr, void *data,
u16 len)
{
struct device *dev = rtlpriv->io.dev;
struct usb_device *udev = to_usb_device(dev);
u8 request = REALTEK_USB_VENQT_CMD_REQ;
u8 reqtype = REALTEK_USB_VENQT_WRITE;
u16 wvalue;
u16 index = REALTEK_USB_VENQT_CMD_IDX;
int pipe = usb_sndctrlpipe(udev, 0); /* write_out */
u8 *buffer;
wvalue = (u16)(addr & 0x0000ffff);
buffer = kmemdup(data, len, GFP_ATOMIC);
if (!buffer)
return;
usb_control_msg(udev, pipe, request, reqtype, wvalue,
index, buffer, len, 50);
kfree(buffer);
}
static void _rtl_usb_io_handler_init(struct device *dev,
struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->io.dev = dev;
mutex_init(&rtlpriv->io.bb_mutex);
rtlpriv->io.write8_async = _usb_write8_async;
rtlpriv->io.write16_async = _usb_write16_async;
rtlpriv->io.write32_async = _usb_write32_async;
rtlpriv->io.read8_sync = _usb_read8_sync;
rtlpriv->io.read16_sync = _usb_read16_sync;
rtlpriv->io.read32_sync = _usb_read32_sync;
rtlpriv->io.writeN_sync = _usb_writeN_sync;
}
static void _rtl_usb_io_handler_release(struct ieee80211_hw *hw)
{
struct rtl_priv __maybe_unused *rtlpriv = rtl_priv(hw);
mutex_destroy(&rtlpriv->io.bb_mutex);
}
/**
*
* Default aggregation handler. Do nothing and just return the oldest skb.
*/
static struct sk_buff *_none_usb_tx_aggregate_hdl(struct ieee80211_hw *hw,
struct sk_buff_head *list)
{
return skb_dequeue(list);
}
#define IS_HIGH_SPEED_USB(udev) \
((USB_SPEED_HIGH == (udev)->speed) ? true : false)
static int _rtl_usb_init_tx(struct ieee80211_hw *hw)
{
u32 i;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
rtlusb->max_bulk_out_size = IS_HIGH_SPEED_USB(rtlusb->udev)
? USB_HIGH_SPEED_BULK_SIZE
: USB_FULL_SPEED_BULK_SIZE;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG, "USB Max Bulk-out Size=%d\n",
rtlusb->max_bulk_out_size);
for (i = 0; i < __RTL_TXQ_NUM; i++) {
u32 ep_num = rtlusb->ep_map.ep_mapping[i];
if (!ep_num) {
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"Invalid endpoint map setting!\n");
return -EINVAL;
}
}
rtlusb->usb_tx_post_hdl =
rtlpriv->cfg->usb_interface_cfg->usb_tx_post_hdl;
rtlusb->usb_tx_cleanup =
rtlpriv->cfg->usb_interface_cfg->usb_tx_cleanup;
rtlusb->usb_tx_aggregate_hdl =
(rtlpriv->cfg->usb_interface_cfg->usb_tx_aggregate_hdl)
? rtlpriv->cfg->usb_interface_cfg->usb_tx_aggregate_hdl
: &_none_usb_tx_aggregate_hdl;
init_usb_anchor(&rtlusb->tx_submitted);
for (i = 0; i < RTL_USB_MAX_EP_NUM; i++) {
skb_queue_head_init(&rtlusb->tx_skb_queue[i]);
init_usb_anchor(&rtlusb->tx_pending[i]);
}
return 0;
}
static void _rtl_rx_work(unsigned long param);
static int _rtl_usb_init_rx(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
rtlusb->rx_max_size = rtlpriv->cfg->usb_interface_cfg->rx_max_size;
rtlusb->rx_urb_num = rtlpriv->cfg->usb_interface_cfg->rx_urb_num;
rtlusb->in_ep = rtlpriv->cfg->usb_interface_cfg->in_ep_num;
rtlusb->usb_rx_hdl = rtlpriv->cfg->usb_interface_cfg->usb_rx_hdl;
rtlusb->usb_rx_segregate_hdl =
rtlpriv->cfg->usb_interface_cfg->usb_rx_segregate_hdl;
pr_info("rx_max_size %d, rx_urb_num %d, in_ep %d\n",
rtlusb->rx_max_size, rtlusb->rx_urb_num, rtlusb->in_ep);
init_usb_anchor(&rtlusb->rx_submitted);
init_usb_anchor(&rtlusb->rx_cleanup_urbs);
skb_queue_head_init(&rtlusb->rx_queue);
rtlusb->rx_work_tasklet.func = _rtl_rx_work;
rtlusb->rx_work_tasklet.data = (unsigned long)rtlusb;
return 0;
}
static int _rtl_usb_init(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb_priv *usb_priv = rtl_usbpriv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(usb_priv);
int err;
u8 epidx;
struct usb_interface *usb_intf = rtlusb->intf;
u8 epnums = usb_intf->cur_altsetting->desc.bNumEndpoints;
rtlusb->out_ep_nums = rtlusb->in_ep_nums = 0;
for (epidx = 0; epidx < epnums; epidx++) {
struct usb_endpoint_descriptor *pep_desc;
pep_desc = &usb_intf->cur_altsetting->endpoint[epidx].desc;
if (usb_endpoint_dir_in(pep_desc))
rtlusb->in_ep_nums++;
else if (usb_endpoint_dir_out(pep_desc))
rtlusb->out_ep_nums++;
RT_TRACE(rtlpriv, COMP_INIT, DBG_DMESG,
"USB EP(0x%02x), MaxPacketSize=%d, Interval=%d\n",
pep_desc->bEndpointAddress, pep_desc->wMaxPacketSize,
pep_desc->bInterval);
}
if (rtlusb->in_ep_nums < rtlpriv->cfg->usb_interface_cfg->in_ep_num) {
pr_err("Too few input end points found\n");
return -EINVAL;
}
if (rtlusb->out_ep_nums == 0) {
pr_err("No output end points found\n");
return -EINVAL;
}
/* usb endpoint mapping */
err = rtlpriv->cfg->usb_interface_cfg->usb_endpoint_mapping(hw);
rtlusb->usb_mq_to_hwq = rtlpriv->cfg->usb_interface_cfg->usb_mq_to_hwq;
_rtl_usb_init_tx(hw);
_rtl_usb_init_rx(hw);
return err;
}
static void rtl_usb_init_sw(struct ieee80211_hw *hw)
{
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
rtlhal->hw = hw;
ppsc->inactiveps = false;
ppsc->leisure_ps = false;
ppsc->fwctrl_lps = false;
ppsc->reg_fwctrl_lps = 3;
ppsc->reg_max_lps_awakeintvl = 5;
ppsc->fwctrl_psmode = FW_PS_DTIM_MODE;
/* IBSS */
mac->beacon_interval = 100;
/* AMPDU */
mac->min_space_cfg = 0;
mac->max_mss_density = 0;
/* set sane AMPDU defaults */
mac->current_ampdu_density = 7;
mac->current_ampdu_factor = 3;
/* QOS */
rtlusb->acm_method = eAcmWay2_SW;
/* IRQ */
/* HIMR - turn all on */
rtlusb->irq_mask[0] = 0xFFFFFFFF;
/* HIMR_EX - turn all on */
rtlusb->irq_mask[1] = 0xFFFFFFFF;
rtlusb->disableHWSM = true;
}
static void _rtl_rx_completed(struct urb *urb);
static int _rtl_prep_rx_urb(struct ieee80211_hw *hw, struct rtl_usb *rtlusb,
struct urb *urb, gfp_t gfp_mask)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
void *buf;
buf = usb_alloc_coherent(rtlusb->udev, rtlusb->rx_max_size, gfp_mask,
&urb->transfer_dma);
if (!buf) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to usb_alloc_coherent!!\n");
return -ENOMEM;
}
usb_fill_bulk_urb(urb, rtlusb->udev,
usb_rcvbulkpipe(rtlusb->udev, rtlusb->in_ep),
buf, rtlusb->rx_max_size, _rtl_rx_completed, rtlusb);
urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
return 0;
}
static void _rtl_usb_rx_process_agg(struct ieee80211_hw *hw,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 *rxdesc = skb->data;
struct ieee80211_hdr *hdr;
bool unicast = false;
__le16 fc;
struct ieee80211_rx_status rx_status = {0};
struct rtl_stats stats = {
.signal = 0,
.noise = -98,
.rate = 0,
};
skb_pull(skb, RTL_RX_DESC_SIZE);
rtlpriv->cfg->ops->query_rx_desc(hw, &stats, &rx_status, rxdesc, skb);
skb_pull(skb, (stats.rx_drvinfo_size + stats.rx_bufshift));
hdr = (struct ieee80211_hdr *)(skb->data);
fc = hdr->frame_control;
if (!stats.crc) {
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
if (is_broadcast_ether_addr(hdr->addr1)) {
/*TODO*/;
} else if (is_multicast_ether_addr(hdr->addr1)) {
/*TODO*/
} else {
unicast = true;
rtlpriv->stats.rxbytesunicast += skb->len;
}
rtl_is_special_data(hw, skb, false);
if (ieee80211_is_data(fc)) {
rtlpriv->cfg->ops->led_control(hw, LED_CTL_RX);
if (unicast)
rtlpriv->link_info.num_rx_inperiod++;
}
}
}
static void _rtl_usb_rx_process_noagg(struct ieee80211_hw *hw,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 *rxdesc = skb->data;
struct ieee80211_hdr *hdr;
bool unicast = false;
__le16 fc;
struct ieee80211_rx_status rx_status = {0};
struct rtl_stats stats = {
.signal = 0,
.noise = -98,
.rate = 0,
};
skb_pull(skb, RTL_RX_DESC_SIZE);
rtlpriv->cfg->ops->query_rx_desc(hw, &stats, &rx_status, rxdesc, skb);
skb_pull(skb, (stats.rx_drvinfo_size + stats.rx_bufshift));
hdr = (struct ieee80211_hdr *)(skb->data);
fc = hdr->frame_control;
if (!stats.crc) {
memcpy(IEEE80211_SKB_RXCB(skb), &rx_status, sizeof(rx_status));
if (is_broadcast_ether_addr(hdr->addr1)) {
/*TODO*/;
} else if (is_multicast_ether_addr(hdr->addr1)) {
/*TODO*/
} else {
unicast = true;
rtlpriv->stats.rxbytesunicast += skb->len;
}
rtl_is_special_data(hw, skb, false);
if (ieee80211_is_data(fc)) {
rtlpriv->cfg->ops->led_control(hw, LED_CTL_RX);
if (unicast)
rtlpriv->link_info.num_rx_inperiod++;
}
/* static bcn for roaming */
rtl_beacon_statistic(hw, skb);
if (likely(rtl_action_proc(hw, skb, false)))
ieee80211_rx(hw, skb);
else
dev_kfree_skb_any(skb);
}
}
static void _rtl_rx_pre_process(struct ieee80211_hw *hw, struct sk_buff *skb)
{
struct sk_buff *_skb;
struct sk_buff_head rx_queue;
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
skb_queue_head_init(&rx_queue);
if (rtlusb->usb_rx_segregate_hdl)
rtlusb->usb_rx_segregate_hdl(hw, skb, &rx_queue);
WARN_ON(skb_queue_empty(&rx_queue));
while (!skb_queue_empty(&rx_queue)) {
_skb = skb_dequeue(&rx_queue);
_rtl_usb_rx_process_agg(hw, _skb);
ieee80211_rx(hw, _skb);
}
}
#define __RX_SKB_MAX_QUEUED 32
static void _rtl_rx_work(unsigned long param)
{
struct rtl_usb *rtlusb = (struct rtl_usb *)param;
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
struct sk_buff *skb;
while ((skb = skb_dequeue(&rtlusb->rx_queue))) {
if (unlikely(IS_USB_STOP(rtlusb))) {
dev_kfree_skb_any(skb);
continue;
}
if (likely(!rtlusb->usb_rx_segregate_hdl)) {
_rtl_usb_rx_process_noagg(hw, skb);
} else {
/* TO DO */
_rtl_rx_pre_process(hw, skb);
pr_err("rx agg not supported\n");
}
}
}
static unsigned int _rtl_rx_get_padding(struct ieee80211_hdr *hdr,
unsigned int len)
{
unsigned int padding = 0;
/* make function no-op when possible */
if (NET_IP_ALIGN == 0 || len < sizeof(*hdr))
return 0;
/* alignment calculation as in lbtf_rx() / carl9170_rx_copy_data() */
/* TODO: deduplicate common code, define helper function instead? */
if (ieee80211_is_data_qos(hdr->frame_control)) {
u8 *qc = ieee80211_get_qos_ctl(hdr);
padding ^= NET_IP_ALIGN;
/* Input might be invalid, avoid accessing memory outside
* the buffer.
*/
if ((unsigned long)qc - (unsigned long)hdr < len &&
*qc & IEEE80211_QOS_CTL_A_MSDU_PRESENT)
padding ^= NET_IP_ALIGN;
}
if (ieee80211_has_a4(hdr->frame_control))
padding ^= NET_IP_ALIGN;
return padding;
}
#define __RADIO_TAP_SIZE_RSV 32
static void _rtl_rx_completed(struct urb *_urb)
{
struct rtl_usb *rtlusb = (struct rtl_usb *)_urb->context;
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
struct rtl_priv *rtlpriv = rtl_priv(hw);
int err = 0;
if (unlikely(IS_USB_STOP(rtlusb)))
goto free;
if (likely(0 == _urb->status)) {
unsigned int padding;
struct sk_buff *skb;
unsigned int qlen;
unsigned int size = _urb->actual_length;
struct ieee80211_hdr *hdr;
if (size < RTL_RX_DESC_SIZE + sizeof(struct ieee80211_hdr)) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Too short packet from bulk IN! (len: %d)\n",
size);
goto resubmit;
}
qlen = skb_queue_len(&rtlusb->rx_queue);
if (qlen >= __RX_SKB_MAX_QUEUED) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Pending RX skbuff queue full! (qlen: %d)\n",
qlen);
goto resubmit;
}
hdr = (void *)(_urb->transfer_buffer + RTL_RX_DESC_SIZE);
padding = _rtl_rx_get_padding(hdr, size - RTL_RX_DESC_SIZE);
skb = dev_alloc_skb(size + __RADIO_TAP_SIZE_RSV + padding);
if (!skb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Can't allocate skb for bulk IN!\n");
goto resubmit;
}
_rtl_install_trx_info(rtlusb, skb, rtlusb->in_ep);
/* Make sure the payload data is 4 byte aligned. */
skb_reserve(skb, padding);
/* reserve some space for mac80211's radiotap */
skb_reserve(skb, __RADIO_TAP_SIZE_RSV);
memcpy(skb_put(skb, size), _urb->transfer_buffer, size);
skb_queue_tail(&rtlusb->rx_queue, skb);
tasklet_schedule(&rtlusb->rx_work_tasklet);
goto resubmit;
}
switch (_urb->status) {
/* disconnect */
case -ENOENT:
case -ECONNRESET:
case -ENODEV:
case -ESHUTDOWN:
goto free;
default:
break;
}
resubmit:
usb_anchor_urb(_urb, &rtlusb->rx_submitted);
err = usb_submit_urb(_urb, GFP_ATOMIC);
if (unlikely(err)) {
usb_unanchor_urb(_urb);
goto free;
}
return;
free:
/* On some architectures, usb_free_coherent must not be called from
* hardirq context. Queue urb to cleanup list.
*/
usb_anchor_urb(_urb, &rtlusb->rx_cleanup_urbs);
}
#undef __RADIO_TAP_SIZE_RSV
static void _rtl_usb_cleanup_rx(struct ieee80211_hw *hw)
{
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct urb *urb;
usb_kill_anchored_urbs(&rtlusb->rx_submitted);
tasklet_kill(&rtlusb->rx_work_tasklet);
skb_queue_purge(&rtlusb->rx_queue);
while ((urb = usb_get_from_anchor(&rtlusb->rx_cleanup_urbs))) {
usb_free_coherent(urb->dev, urb->transfer_buffer_length,
urb->transfer_buffer, urb->transfer_dma);
usb_free_urb(urb);
}
}
static int _rtl_usb_receive(struct ieee80211_hw *hw)
{
struct urb *urb;
int err;
int i;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
WARN_ON(0 == rtlusb->rx_urb_num);
/* 1600 == 1514 + max WLAN header + rtk info */
WARN_ON(rtlusb->rx_max_size < 1600);
for (i = 0; i < rtlusb->rx_urb_num; i++) {
err = -ENOMEM;
urb = usb_alloc_urb(0, GFP_KERNEL);
if (!urb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to alloc URB!!\n");
goto err_out;
}
err = _rtl_prep_rx_urb(hw, rtlusb, urb, GFP_KERNEL);
if (err < 0) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to prep_rx_urb!!\n");
usb_free_urb(urb);
goto err_out;
}
usb_anchor_urb(urb, &rtlusb->rx_submitted);
err = usb_submit_urb(urb, GFP_KERNEL);
if (err)
goto err_out;
usb_free_urb(urb);
}
return 0;
err_out:
usb_kill_anchored_urbs(&rtlusb->rx_submitted);
_rtl_usb_cleanup_rx(hw);
return err;
}
static int rtl_usb_start(struct ieee80211_hw *hw)
{
int err;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
err = rtlpriv->cfg->ops->hw_init(hw);
if (!err) {
rtl_init_rx_config(hw);
/* Enable software */
SET_USB_START(rtlusb);
/* should after adapter start and interrupt enable. */
set_hal_start(rtlhal);
/* Start bulk IN */
err = _rtl_usb_receive(hw);
}
return err;
}
/**
*
*
*/
/*======================= tx =========================================*/
static void rtl_usb_cleanup(struct ieee80211_hw *hw)
{
u32 i;
struct sk_buff *_skb;
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct ieee80211_tx_info *txinfo;
SET_USB_STOP(rtlusb);
/* clean up rx stuff. */
_rtl_usb_cleanup_rx(hw);
/* clean up tx stuff */
for (i = 0; i < RTL_USB_MAX_EP_NUM; i++) {
while ((_skb = skb_dequeue(&rtlusb->tx_skb_queue[i]))) {
rtlusb->usb_tx_cleanup(hw, _skb);
txinfo = IEEE80211_SKB_CB(_skb);
ieee80211_tx_info_clear_status(txinfo);
txinfo->flags |= IEEE80211_TX_STAT_ACK;
ieee80211_tx_status_irqsafe(hw, _skb);
}
usb_kill_anchored_urbs(&rtlusb->tx_pending[i]);
}
usb_kill_anchored_urbs(&rtlusb->tx_submitted);
}
/**
*
* We may add some struct into struct rtl_usb later. Do deinit here.
*
*/
static void rtl_usb_deinit(struct ieee80211_hw *hw)
{
rtl_usb_cleanup(hw);
}
static void rtl_usb_stop(struct ieee80211_hw *hw)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
/* should after adapter start and interrupt enable. */
set_hal_stop(rtlhal);
cancel_work_sync(&rtlpriv->works.fill_h2c_cmd);
/* Enable software */
SET_USB_STOP(rtlusb);
rtl_usb_deinit(hw);
rtlpriv->cfg->ops->hw_disable(hw);
}
static void _rtl_submit_tx_urb(struct ieee80211_hw *hw, struct urb *_urb)
{
int err;
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
usb_anchor_urb(_urb, &rtlusb->tx_submitted);
err = usb_submit_urb(_urb, GFP_ATOMIC);
if (err < 0) {
struct sk_buff *skb;
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Failed to submit urb\n");
usb_unanchor_urb(_urb);
skb = (struct sk_buff *)_urb->context;
kfree_skb(skb);
}
usb_free_urb(_urb);
}
static int _usb_tx_post(struct ieee80211_hw *hw, struct urb *urb,
struct sk_buff *skb)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct ieee80211_tx_info *txinfo;
rtlusb->usb_tx_post_hdl(hw, urb, skb);
skb_pull(skb, RTL_TX_HEADER_SIZE);
txinfo = IEEE80211_SKB_CB(skb);
ieee80211_tx_info_clear_status(txinfo);
txinfo->flags |= IEEE80211_TX_STAT_ACK;
if (urb->status) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Urb has error status 0x%X\n", urb->status);
goto out;
}
/* TODO: statistics */
out:
ieee80211_tx_status_irqsafe(hw, skb);
return urb->status;
}
static void _rtl_tx_complete(struct urb *urb)
{
struct sk_buff *skb = (struct sk_buff *)urb->context;
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl_usb *rtlusb = (struct rtl_usb *)info->rate_driver_data[0];
struct ieee80211_hw *hw = usb_get_intfdata(rtlusb->intf);
int err;
if (unlikely(IS_USB_STOP(rtlusb)))
return;
err = _usb_tx_post(hw, urb, skb);
if (err) {
/* Ignore error and keep issuiing other urbs */
return;
}
}
static struct urb *_rtl_usb_tx_urb_setup(struct ieee80211_hw *hw,
struct sk_buff *skb, u32 ep_num)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct urb *_urb;
WARN_ON(NULL == skb);
_urb = usb_alloc_urb(0, GFP_ATOMIC);
if (!_urb) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"Can't allocate URB for bulk out!\n");
kfree_skb(skb);
return NULL;
}
_rtl_install_trx_info(rtlusb, skb, ep_num);
usb_fill_bulk_urb(_urb, rtlusb->udev, usb_sndbulkpipe(rtlusb->udev,
ep_num), skb->data, skb->len, _rtl_tx_complete, skb);
_urb->transfer_flags |= URB_ZERO_PACKET;
return _urb;
}
static void _rtl_usb_transmit(struct ieee80211_hw *hw, struct sk_buff *skb,
enum rtl_txq qnum)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
u32 ep_num;
struct urb *_urb = NULL;
struct sk_buff *_skb = NULL;
WARN_ON(NULL == rtlusb->usb_tx_aggregate_hdl);
if (unlikely(IS_USB_STOP(rtlusb))) {
RT_TRACE(rtlpriv, COMP_USB, DBG_EMERG,
"USB device is stopping...\n");
kfree_skb(skb);
return;
}
ep_num = rtlusb->ep_map.ep_mapping[qnum];
_skb = skb;
_urb = _rtl_usb_tx_urb_setup(hw, _skb, ep_num);
if (unlikely(!_urb)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't allocate urb. Drop skb!\n");
kfree_skb(skb);
return;
}
_rtl_submit_tx_urb(hw, _urb);
}
static void _rtl_usb_tx_preprocess(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb,
u16 hw_queue)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *mac = rtl_mac(rtl_priv(hw));
struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
struct rtl_tx_desc *pdesc = NULL;
struct rtl_tcb_desc tcb_desc;
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
u8 *pda_addr = hdr->addr1;
/* ssn */
u8 *qc = NULL;
u8 tid = 0;
u16 seq_number = 0;
memset(&tcb_desc, 0, sizeof(struct rtl_tcb_desc));
if (ieee80211_is_auth(fc)) {
RT_TRACE(rtlpriv, COMP_SEND, DBG_DMESG, "MAC80211_LINKING\n");
rtl_ips_nic_on(hw);
}
if (rtlpriv->psc.sw_ps_enabled) {
if (ieee80211_is_data(fc) && !ieee80211_is_nullfunc(fc) &&
!ieee80211_has_pm(fc))
hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_PM);
}
rtl_action_proc(hw, skb, true);
if (is_multicast_ether_addr(pda_addr))
rtlpriv->stats.txbytesmulticast += skb->len;
else if (is_broadcast_ether_addr(pda_addr))
rtlpriv->stats.txbytesbroadcast += skb->len;
else
rtlpriv->stats.txbytesunicast += skb->len;
if (ieee80211_is_data_qos(fc)) {
qc = ieee80211_get_qos_ctl(hdr);
tid = qc[0] & IEEE80211_QOS_CTL_TID_MASK;
seq_number = (le16_to_cpu(hdr->seq_ctrl) &
IEEE80211_SCTL_SEQ) >> 4;
seq_number += 1;
seq_number <<= 4;
}
rtlpriv->cfg->ops->fill_tx_desc(hw, hdr, (u8 *)pdesc, info, sta, skb,
hw_queue, &tcb_desc);
if (!ieee80211_has_morefrags(hdr->frame_control)) {
if (qc)
mac->tids[tid].seq_number = seq_number;
}
if (ieee80211_is_data(fc))
rtlpriv->cfg->ops->led_control(hw, LED_CTL_TX);
}
static int rtl_usb_tx(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb,
struct rtl_tcb_desc *dummy)
{
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
struct rtl_hal *rtlhal = rtl_hal(rtl_priv(hw));
struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)(skb->data);
__le16 fc = hdr->frame_control;
u16 hw_queue;
if (unlikely(is_hal_stop(rtlhal)))
goto err_free;
hw_queue = rtlusb->usb_mq_to_hwq(fc, skb_get_queue_mapping(skb));
_rtl_usb_tx_preprocess(hw, sta, skb, hw_queue);
_rtl_usb_transmit(hw, skb, hw_queue);
return NETDEV_TX_OK;
err_free:
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
static bool rtl_usb_tx_chk_waitq_insert(struct ieee80211_hw *hw,
struct ieee80211_sta *sta,
struct sk_buff *skb)
{
return false;
}
static void rtl_fill_h2c_cmd_work_callback(struct work_struct *work)
{
struct rtl_works *rtlworks =
container_of(work, struct rtl_works, fill_h2c_cmd);
struct ieee80211_hw *hw = rtlworks->hw;
struct rtl_priv *rtlpriv = rtl_priv(hw);
rtlpriv->cfg->ops->fill_h2c_cmd(hw, H2C_RA_MASK, 5, rtlpriv->rate_mask);
}
static struct rtl_intf_ops rtl_usb_ops = {
.adapter_start = rtl_usb_start,
.adapter_stop = rtl_usb_stop,
.adapter_tx = rtl_usb_tx,
.waitq_insert = rtl_usb_tx_chk_waitq_insert,
};
int rtl_usb_probe(struct usb_interface *intf,
const struct usb_device_id *id,
struct rtl_hal_cfg *rtl_hal_cfg)
{
int err;
struct ieee80211_hw *hw = NULL;
struct rtl_priv *rtlpriv = NULL;
struct usb_device *udev;
struct rtl_usb_priv *usb_priv;
hw = ieee80211_alloc_hw(sizeof(struct rtl_priv) +
sizeof(struct rtl_usb_priv), &rtl_ops);
if (!hw) {
RT_ASSERT(false, "ieee80211 alloc failed\n");
return -ENOMEM;
}
rtlpriv = hw->priv;
rtlpriv->usb_data = kzalloc(RTL_USB_MAX_RX_COUNT * sizeof(u32),
GFP_KERNEL);
if (!rtlpriv->usb_data)
return -ENOMEM;
/* this spin lock must be initialized early */
spin_lock_init(&rtlpriv->locks.usb_lock);
INIT_WORK(&rtlpriv->works.fill_h2c_cmd,
rtl_fill_h2c_cmd_work_callback);
INIT_WORK(&rtlpriv->works.lps_change_work,
rtl_lps_change_work_callback);
rtlpriv->usb_data_index = 0;
init_completion(&rtlpriv->firmware_loading_complete);
SET_IEEE80211_DEV(hw, &intf->dev);
udev = interface_to_usbdev(intf);
usb_get_dev(udev);
usb_priv = rtl_usbpriv(hw);
memset(usb_priv, 0, sizeof(*usb_priv));
usb_priv->dev.intf = intf;
usb_priv->dev.udev = udev;
usb_set_intfdata(intf, hw);
/* init cfg & intf_ops */
rtlpriv->rtlhal.interface = INTF_USB;
rtlpriv->cfg = rtl_hal_cfg;
rtlpriv->intf_ops = &rtl_usb_ops;
rtl_dbgp_flag_init(hw);
/* Init IO handler */
_rtl_usb_io_handler_init(&udev->dev, hw);
rtlpriv->cfg->ops->read_chip_version(hw);
/*like read eeprom and so on */
rtlpriv->cfg->ops->read_eeprom_info(hw);
err = _rtl_usb_init(hw);
if (err)
goto error_out;
rtl_usb_init_sw(hw);
/* Init mac80211 sw */
err = rtl_init_core(hw);
if (err) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"Can't allocate sw for mac80211\n");
goto error_out;
}
if (rtlpriv->cfg->ops->init_sw_vars(hw)) {
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, "Can't init_sw_vars\n");
goto error_out;
}
rtlpriv->cfg->ops->init_sw_leds(hw);
return 0;
error_out:
rtl_deinit_core(hw);
_rtl_usb_io_handler_release(hw);
usb_put_dev(udev);
complete(&rtlpriv->firmware_loading_complete);
return -ENODEV;
}
EXPORT_SYMBOL(rtl_usb_probe);
void rtl_usb_disconnect(struct usb_interface *intf)
{
struct ieee80211_hw *hw = usb_get_intfdata(intf);
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_mac *rtlmac = rtl_mac(rtl_priv(hw));
struct rtl_usb *rtlusb = rtl_usbdev(rtl_usbpriv(hw));
if (unlikely(!rtlpriv))
return;
/* just in case driver is removed before firmware callback */
wait_for_completion(&rtlpriv->firmware_loading_complete);
/*ieee80211_unregister_hw will call ops_stop */
if (rtlmac->mac80211_registered == 1) {
ieee80211_unregister_hw(hw);
rtlmac->mac80211_registered = 0;
} else {
rtl_deinit_deferred_work(hw);
rtlpriv->intf_ops->adapter_stop(hw);
}
/*deinit rfkill */
/* rtl_deinit_rfkill(hw); */
rtl_usb_deinit(hw);
rtl_deinit_core(hw);
kfree(rtlpriv->usb_data);
rtlpriv->cfg->ops->deinit_sw_leds(hw);
rtlpriv->cfg->ops->deinit_sw_vars(hw);
_rtl_usb_io_handler_release(hw);
usb_put_dev(rtlusb->udev);
usb_set_intfdata(intf, NULL);
ieee80211_free_hw(hw);
}
EXPORT_SYMBOL(rtl_usb_disconnect);
int rtl_usb_suspend(struct usb_interface *pusb_intf, pm_message_t message)
{
return 0;
}
EXPORT_SYMBOL(rtl_usb_suspend);
int rtl_usb_resume(struct usb_interface *pusb_intf)
{
return 0;
}
EXPORT_SYMBOL(rtl_usb_resume);
| gpl-2.0 |
kangtastic/kgb | drivers/media/video/em28xx/em28xx-cards.c | 560 | 90886 | /*
em28xx-cards.c - driver for Empia EM2800/EM2820/2840 USB
video capture devices
Copyright (C) 2005 Ludovico Cavedon <cavedon@sssup.it>
Markus Rechberger <mrechberger@gmail.com>
Mauro Carvalho Chehab <mchehab@infradead.org>
Sascha Sommer <saschasommer@freenet.de>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/usb.h>
#include <media/tuner.h>
#include <media/msp3400.h>
#include <media/saa7115.h>
#include <media/tvp5150.h>
#include <media/tvaudio.h>
#include <media/i2c-addr.h>
#include <media/tveeprom.h>
#include <media/v4l2-common.h>
#include <media/v4l2-chip-ident.h>
#include "em28xx.h"
#define DRIVER_NAME "em28xx"
static int tuner = -1;
module_param(tuner, int, 0444);
MODULE_PARM_DESC(tuner, "tuner type");
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir, "disable infrared remote support");
static unsigned int disable_usb_speed_check;
module_param(disable_usb_speed_check, int, 0444);
MODULE_PARM_DESC(disable_usb_speed_check,
"override min bandwidth requirement of 480M bps");
static unsigned int card[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = UNSET };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
/* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS */
static unsigned long em28xx_devused;
struct em28xx_hash_table {
unsigned long hash;
unsigned int model;
unsigned int tuner;
};
/*
* Reset sequences for analog/digital modes
*/
/* Reset for the most [analog] boards */
static struct em28xx_reg_seq default_analog[] = {
{EM28XX_R08_GPIO, 0x6d, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Reset for the most [digital] boards */
static struct em28xx_reg_seq default_digital[] = {
{EM28XX_R08_GPIO, 0x6e, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Board Hauppauge WinTV HVR 900 analog */
static struct em28xx_reg_seq hauppauge_wintv_hvr_900_analog[] = {
{EM28XX_R08_GPIO, 0x2d, ~EM_GPIO_4, 10},
{0x05, 0xff, 0x10, 10},
{ -1, -1, -1, -1},
};
/* Board Hauppauge WinTV HVR 900 digital */
static struct em28xx_reg_seq hauppauge_wintv_hvr_900_digital[] = {
{EM28XX_R08_GPIO, 0x2e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x04, 0x0f, 10},
{EM2880_R04_GPO, 0x0c, 0x0f, 10},
{ -1, -1, -1, -1},
};
/* Boards - EM2880 MSI DIGIVOX AD and EM2880_BOARD_MSI_DIGIVOX_AD_II */
static struct em28xx_reg_seq em2880_msi_digivox_ad_analog[] = {
{EM28XX_R08_GPIO, 0x69, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Boards - EM2880 MSI DIGIVOX AD and EM2880_BOARD_MSI_DIGIVOX_AD_II */
/* Board - EM2870 Kworld 355u
Analog - No input analog */
/* Board - EM2882 Kworld 315U digital */
static struct em28xx_reg_seq em2882_kworld_315u_digital[] = {
{EM28XX_R08_GPIO, 0xff, 0xff, 10},
{EM28XX_R08_GPIO, 0xfe, 0xff, 10},
{EM2880_R04_GPO, 0x04, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{EM28XX_R08_GPIO, 0x7e, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq em2882_kworld_315u_tuner_gpio[] = {
{EM2880_R04_GPO, 0x08, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq kworld_330u_analog[] = {
{EM28XX_R08_GPIO, 0x6d, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x00, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq kworld_330u_digital[] = {
{EM28XX_R08_GPIO, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{ -1, -1, -1, -1},
};
/* Evga inDtube
GPIO0 - Enable digital power (s5h1409) - low to enable
GPIO1 - Enable analog power (tvp5150/emp202) - low to enable
GPIO4 - xc3028 reset
GOP3 - s5h1409 reset
*/
static struct em28xx_reg_seq evga_indtube_analog[] = {
{EM28XX_R08_GPIO, 0x79, 0xff, 60},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq evga_indtube_digital[] = {
{EM28XX_R08_GPIO, 0x7a, 0xff, 1},
{EM2880_R04_GPO, 0x04, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 1},
{ -1, -1, -1, -1},
};
/* Pinnacle Hybrid Pro eb1a:2881 */
static struct em28xx_reg_seq pinnacle_hybrid_pro_analog[] = {
{EM28XX_R08_GPIO, 0xfd, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq pinnacle_hybrid_pro_digital[] = {
{EM28XX_R08_GPIO, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x04, 0xff, 100},/* zl10353 reset */
{EM2880_R04_GPO, 0x0c, 0xff, 1},
{ -1, -1, -1, -1},
};
/* eb1a:2868 Reddo DVB-C USB TV Box
GPIO4 - CU1216L NIM
Other GPIOs seems to be don't care. */
static struct em28xx_reg_seq reddo_dvb_c_usb_box[] = {
{EM28XX_R08_GPIO, 0xfe, 0xff, 10},
{EM28XX_R08_GPIO, 0xde, 0xff, 10},
{EM28XX_R08_GPIO, 0xfe, 0xff, 10},
{EM28XX_R08_GPIO, 0xff, 0xff, 10},
{EM28XX_R08_GPIO, 0x7f, 0xff, 10},
{EM28XX_R08_GPIO, 0x6f, 0xff, 10},
{EM28XX_R08_GPIO, 0xff, 0xff, 10},
{-1, -1, -1, -1},
};
/* Callback for the most boards */
static struct em28xx_reg_seq default_tuner_gpio[] = {
{EM28XX_R08_GPIO, EM_GPIO_4, EM_GPIO_4, 10},
{EM28XX_R08_GPIO, 0, EM_GPIO_4, 10},
{EM28XX_R08_GPIO, EM_GPIO_4, EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Mute/unmute */
static struct em28xx_reg_seq compro_unmute_tv_gpio[] = {
{EM28XX_R08_GPIO, 5, 7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq compro_unmute_svid_gpio[] = {
{EM28XX_R08_GPIO, 4, 7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq compro_mute_gpio[] = {
{EM28XX_R08_GPIO, 6, 7, 10},
{ -1, -1, -1, -1},
};
/* Terratec AV350 */
static struct em28xx_reg_seq terratec_av350_mute_gpio[] = {
{EM28XX_R08_GPIO, 0xff, 0x7f, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_av350_unmute_gpio[] = {
{EM28XX_R08_GPIO, 0xff, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq silvercrest_reg_seq[] = {
{EM28XX_R08_GPIO, 0xff, 0xff, 10},
{EM28XX_R08_GPIO, 0x01, 0xf7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq vc211a_enable[] = {
{EM28XX_R08_GPIO, 0xff, 0x07, 10},
{EM28XX_R08_GPIO, 0xff, 0x0f, 10},
{EM28XX_R08_GPIO, 0xff, 0x0b, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq dikom_dk300_digital[] = {
{EM28XX_R08_GPIO, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{ -1, -1, -1, -1},
};
/*
* Board definitions
*/
struct em28xx_board em28xx_boards[] = {
[EM2750_BOARD_UNKNOWN] = {
.name = "EM2710/EM2750/EM2751 webcam grabber",
.xclk = EM28XX_XCLK_FREQUENCY_20MHZ,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = silvercrest_reg_seq,
} },
},
[EM2800_BOARD_UNKNOWN] = {
.name = "Unknown EM2800 video grabber",
.is_em2800 = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_UNKNOWN] = {
.name = "Unknown EM2750/28xx video grabber",
.tuner_type = TUNER_ABSENT,
.is_webcam = 1, /* To enable sensor probe */
},
[EM2750_BOARD_DLCW_130] = {
/* Beijing Huaqi Information Digital Technology Co., Ltd */
.name = "Huaqi DLCW-130",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.xclk = EM28XX_XCLK_FREQUENCY_48MHZ,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2820_BOARD_KWORLD_PVRTV2800RF] = {
.name = "Kworld PVR TV 2800 RF",
.tuner_type = TUNER_TEMIC_PAL,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_GADMEI_TVR200] = {
.name = "Gadmei TVR200",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_TERRATEC_CINERGY_250] = {
.name = "Terratec Cinergy 250 USB",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.has_ir_i2c = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_USB_2] = {
.name = "Pinnacle PCTV USB 2",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.has_ir_i2c = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_HAUPPAUGE_WINTV_USB_2] = {
.name = "Hauppauge WinTV USB 2",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.decoder = EM28XX_TVP5150,
.has_msp34xx = 1,
.has_ir_i2c = 1,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = MSP_INPUT_DEFAULT,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
MSP_DSP_IN_SCART, MSP_DSP_IN_SCART),
} },
},
[EM2820_BOARD_DLINK_USB_TV] = {
.name = "D-Link DUB-T210 TV Tuner",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_HERCULES_SMART_TV_USB2] = {
.name = "Hercules Smart TV USB 2.0",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_USB_2_FM1216ME] = {
.name = "Pinnacle PCTV USB 2 (Philips FM1216ME)",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_GADMEI_UTV310] = {
.name = "Gadmei UTV310",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_LEADTEK_WINFAST_USBII_DELUXE] = {
.name = "Leadtek Winfast USB II Deluxe",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.has_ir_i2c = 1,
.tvaudio_addr = 0x58,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT2_ACTIVE |
TDA9887_QSS,
.decoder = EM28XX_SAA711X,
.adecoder = EM28XX_TVAUDIO,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE4,
.amux = EM28XX_AMUX_AUX,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE5,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
.radio = {
.type = EM28XX_RADIO,
.amux = EM28XX_AMUX_AUX,
}
},
[EM2820_BOARD_VIDEOLOGY_20K14XUSB] = {
.name = "Videology 20K14XUSB USB2.0",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2820_BOARD_SILVERCREST_WEBCAM] = {
.name = "Silvercrest Webcam 1.3mpix",
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = silvercrest_reg_seq,
} },
},
[EM2821_BOARD_SUPERCOMP_USB_2] = {
.name = "Supercomp USB 2.0 TV",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2821_BOARD_USBGEAR_VD204] = {
.name = "Usbgear VD204v9",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_NETGMBH_CAM] = {
/* Beijing Huaqi Information Digital Technology Co., Ltd */
.name = "NetGMBH Cam",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2860_BOARD_TYPHOON_DVD_MAKER] = {
.name = "Typhoon DVD Maker",
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT, /* Capture only device */
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_GADMEI_UTV330] = {
.name = "Gadmei UTV330",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_GADMEI_UTV330PLUS] = {
.name = "Gadmei UTV330+",
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.ir_codes = RC_MAP_GADMEI_RM008Z,
.decoder = EM28XX_SAA711X,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Cinergy A Hybrid XS",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2861_BOARD_KWORLD_PVRTV_300U] = {
.name = "KWorld PVRTV 300U",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_YAKUMO_MOVIE_MIXER] = {
.name = "Yakumo MovieMixer",
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_TVP5150_REFERENCE_DESIGN] = {
.name = "EM2860/TVP5150 Reference Design",
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_PLEXTOR_PX_TV100U] = {
.name = "Plextor ConvertX PX-TV100U",
.tuner_type = TUNER_TNF_5335MF,
.xclk = EM28XX_XCLK_I2S_MSB_TIMING |
EM28XX_XCLK_FREQUENCY_12MHZ,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.has_msp34xx = 1,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
} },
},
/* Those boards with em2870 are DVB Only*/
[EM2870_BOARD_TERRATEC_XS] = {
.name = "Terratec Cinergy T XS",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
},
[EM2870_BOARD_TERRATEC_XS_MT2060] = {
.name = "Terratec Cinergy T XS (MT2060)",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* MT2060 */
},
[EM2870_BOARD_KWORLD_350U] = {
.name = "Kworld 350 U DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
},
[EM2870_BOARD_KWORLD_355U] = {
.name = "Kworld 355 U DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
},
[EM2870_BOARD_PINNACLE_PCTV_DVB] = {
.name = "Pinnacle PCTV DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* MT2060 */
/* djh - I have serious doubts this is right... */
.xclk = EM28XX_XCLK_IR_RC5_MODE |
EM28XX_XCLK_FREQUENCY_10MHZ,
},
[EM2870_BOARD_COMPRO_VIDEOMATE] = {
.name = "Compro, VideoMate U3",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* MT2060 */
},
[EM2880_BOARD_TERRATEC_HYBRID_XS_FR] = {
.name = "Terratec Hybrid XS Secam",
.has_msp34xx = 1,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = default_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900] = {
.name = "Hauppauge WinTV HVR 900",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_HAUPPAUGE_NEW,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2] = {
.name = "Hauppauge WinTV HVR 900 (R2)",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.ir_codes = RC_MAP_HAUPPAUGE_NEW,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850] = {
.name = "Hauppauge WinTV HVR 850",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_HAUPPAUGE_NEW,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950] = {
.name = "Hauppauge WinTV HVR 950",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_RC5_HAUPPAUGE_NEW,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_PINNACLE_PCTV_HD_PRO] = {
.name = "Pinnacle PCTV HD Pro Stick",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600] = {
.name = "AMD ATI TV Wonder HD 600",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_ATI_TV_WONDER_HD_600,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Hybrid XS",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = default_digital,
.ir_codes = RC_MAP_TERRATEC_CINERGY_XS,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
/* maybe there's a reason behind it why Terratec sells the Hybrid XS
as Prodigy XS with a different PID, let's keep it separated for now
maybe we'll need it lateron */
[EM2880_BOARD_TERRATEC_PRODIGY_XS] = {
.name = "Terratec Prodigy XS",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2820_BOARD_MSI_VOX_USB_2] = {
.name = "MSI VOX USB 2.0",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.max_range_640_480 = 1,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE4,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_TERRATEC_CINERGY_200] = {
.name = "Terratec Cinergy 200 USB",
.is_em2800 = 1,
.has_ir_i2c = 1,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_GRABBEEX_USB2800] = {
.name = "eMPIA Technology, Inc. GrabBeeX+ Video Encoder",
.is_em2800 = 1,
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT, /* capture only board */
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_VC211A] = {
.name = "Actionmaster/LinXcel/Digitus VC211A",
.is_em2800 = 1,
.tuner_type = TUNER_ABSENT, /* Capture-only board */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = vc211a_enable,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = vc211a_enable,
} },
},
[EM2800_BOARD_LEADTEK_WINFAST_USBII] = {
.name = "Leadtek Winfast USB II",
.is_em2800 = 1,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_KWORLD_USB2800] = {
.name = "Kworld USB2800",
.is_em2800 = 1,
.tuner_type = TUNER_PHILIPS_FCV1236D,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_DVC_90] = {
.name = "Pinnacle Dazzle DVC 90/100/101/107 / Kaiser Baas Video to DVD maker "
"/ Kworld DVD Maker 2",
.tuner_type = TUNER_ABSENT, /* capture only board */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_VGEAR_POCKETTV] = {
.name = "V-Gear PocketTV",
.is_em2800 = 1,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PROLINK_PLAYTV_BOX4_USB2] = {
.name = "Pixelview PlayTV Box 4 USB 2.0",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_YMEC_TVF_5533MF,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.aout = EM28XX_AOUT_MONO | /* I2S */
EM28XX_AOUT_MASTER, /* Line out pin */
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PROLINK_PLAYTV_USB2] = {
.name = "SIIG AVTuner-PVR / Pixelview Prolink PlayTV USB 2.0",
.has_snapshot_button = 1,
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_YMEC_TVF_5533MF,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.aout = EM28XX_AOUT_MONO | /* I2S */
EM28XX_AOUT_MASTER, /* Line out pin */
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_SAA711X_REFERENCE_DESIGN] = {
.name = "EM2860/SAA711X Reference Design",
.has_snapshot_button = 1,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
} },
},
[EM2880_BOARD_MSI_DIGIVOX_AD] = {
.name = "MSI DigiVox A/D",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
} },
},
[EM2880_BOARD_MSI_DIGIVOX_AD_II] = {
.name = "MSI DigiVox A/D II",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
} },
},
[EM2880_BOARD_KWORLD_DVB_305U] = {
.name = "KWorld DVB-T 305U",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2880_BOARD_KWORLD_DVB_310U] = {
.name = "KWorld DVB-T 310U",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.has_dvb = 1,
.dvb_gpio = default_digital,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, { /* S-video has not been tested yet */
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2882_BOARD_KWORLD_ATSC_315U] = {
.name = "KWorld ATSC 315U HDTV TV Box",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_THOMSON_DTT761X,
.tuner_gpio = em2882_kworld_315u_tuner_gpio,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.has_dvb = 1,
.dvb_gpio = em2882_kworld_315u_digital,
.ir_codes = RC_MAP_KWORLD_315U,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE,
/* Analog mode - still not ready */
/*.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2882_kworld_315u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2882_kworld_315u_analog1,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2882_kworld_315u_analog1,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
} }, */
},
[EM2880_BOARD_EMPIRE_DUAL_TV] = {
.name = "Empire dual TV",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.has_dvb = 1,
.dvb_gpio = default_digital,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2881_BOARD_DNT_DA2_HYBRID] = {
.name = "DNT DA2 Hybrid",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2881_BOARD_PINNACLE_HYBRID_PRO] = {
.name = "Pinnacle Hybrid Pro",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = pinnacle_hybrid_pro_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
} },
},
[EM2882_BOARD_PINNACLE_HYBRID_PRO] = {
.name = "Pinnacle Hybrid Pro (2)",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2882_BOARD_KWORLD_VS_DVBT] = {
.name = "Kworld VS-DVB-T 323UR",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = kworld_330u_digital,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.ir_codes = RC_MAP_KWORLD_315U,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2882_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Hybrid XS (em2882)",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_TERRATEC_CINERGY_XS,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2882_BOARD_DIKOM_DK300] = {
.name = "Dikom DK300",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = dikom_dk300_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
} },
},
[EM2883_BOARD_KWORLD_HYBRID_330U] = {
.name = "Kworld PlusTV HD Hybrid 330",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = kworld_330u_digital,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_EEPROM_ON_BOARD |
EM28XX_I2C_EEPROM_KEY_VALID,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = kworld_330u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = kworld_330u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = kworld_330u_analog,
} },
},
[EM2820_BOARD_COMPRO_VIDEOMATE_FORYOU] = {
.name = "Compro VideoMate ForYou/Stereo",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tvaudio_addr = 0xb0,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.adecoder = EM28XX_TVAUDIO,
.mute_gpio = compro_mute_gpio,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = compro_unmute_tv_gpio,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = compro_unmute_svid_gpio,
} },
},
[EM2860_BOARD_KAIOMY_TVNPC_U2] = {
.name = "Kaiomy TVnPC U2",
.vchannels = 3,
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.tuner_gpio = default_tuner_gpio,
.ir_codes = RC_MAP_KAIOMY,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
.radio = {
.type = EM28XX_RADIO,
.amux = EM28XX_AMUX_LINE_IN,
}
},
[EM2860_BOARD_EASYCAP] = {
.name = "Easy Cap Capture DC-60",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_IODATA_GVMVP_SZ] = {
.name = "IO-DATA GV-MVP/SZ",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tuner_gpio = default_tuner_gpio,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, { /* Composite has not been tested yet */
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_VIDEO,
}, { /* S-video has not been tested yet */
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2860_BOARD_TERRATEC_GRABBY] = {
.name = "Terratec Grabby",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO2,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_VIDEO2,
} },
},
[EM2860_BOARD_TERRATEC_AV350] = {
.name = "Terratec AV350",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_TVP5150,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.mute_gpio = terratec_av350_mute_gpio,
.input = { {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AUDIO_SRC_LINE,
.gpio = terratec_av350_unmute_gpio,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AUDIO_SRC_LINE,
.gpio = terratec_av350_unmute_gpio,
} },
},
[EM2882_BOARD_EVGA_INDTUBE] = {
.name = "Evga inDtube",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = evga_indtube_digital,
.ir_codes = RC_MAP_EVGA_INDTUBE,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = evga_indtube_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE1,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = evga_indtube_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = evga_indtube_analog,
} },
},
/* eb1a:2868 Empia EM2870 + Philips CU1216L NIM (Philips TDA10023 +
Infineon TUA6034) */
[EM2870_BOARD_REDDO_DVB_C_USB_BOX] = {
.name = "Reddo DVB-C USB TV Box",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = reddo_dvb_c_usb_box,
.has_dvb = 1,
},
};
const unsigned int em28xx_bcount = ARRAY_SIZE(em28xx_boards);
/* table of devices that work with this driver */
struct usb_device_id em28xx_id_table[] = {
{ USB_DEVICE(0xeb1a, 0x2750),
.driver_info = EM2750_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2751),
.driver_info = EM2750_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2800),
.driver_info = EM2800_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2710),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2820),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2821),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2860),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2861),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2862),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2863),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2870),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2881),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2883),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2868),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0xe300),
.driver_info = EM2861_BOARD_KWORLD_PVRTV_300U },
{ USB_DEVICE(0xeb1a, 0xe303),
.driver_info = EM2860_BOARD_KAIOMY_TVNPC_U2 },
{ USB_DEVICE(0xeb1a, 0xe305),
.driver_info = EM2880_BOARD_KWORLD_DVB_305U },
{ USB_DEVICE(0xeb1a, 0xe310),
.driver_info = EM2880_BOARD_MSI_DIGIVOX_AD },
{ USB_DEVICE(0xeb1a, 0xa313),
.driver_info = EM2882_BOARD_KWORLD_ATSC_315U },
{ USB_DEVICE(0xeb1a, 0xa316),
.driver_info = EM2883_BOARD_KWORLD_HYBRID_330U },
{ USB_DEVICE(0xeb1a, 0xe320),
.driver_info = EM2880_BOARD_MSI_DIGIVOX_AD_II },
{ USB_DEVICE(0xeb1a, 0xe323),
.driver_info = EM2882_BOARD_KWORLD_VS_DVBT },
{ USB_DEVICE(0xeb1a, 0xe350),
.driver_info = EM2870_BOARD_KWORLD_350U },
{ USB_DEVICE(0xeb1a, 0xe355),
.driver_info = EM2870_BOARD_KWORLD_355U },
{ USB_DEVICE(0xeb1a, 0x2801),
.driver_info = EM2800_BOARD_GRABBEEX_USB2800 },
{ USB_DEVICE(0xeb1a, 0xe357),
.driver_info = EM2870_BOARD_KWORLD_355U },
{ USB_DEVICE(0x1b80, 0xe302),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 }, /* Kaiser Baas Video to DVD maker */
{ USB_DEVICE(0x1b80, 0xe304),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 }, /* Kworld DVD Maker 2 */
{ USB_DEVICE(0x0ccd, 0x0036),
.driver_info = EM2820_BOARD_TERRATEC_CINERGY_250 },
{ USB_DEVICE(0x0ccd, 0x004c),
.driver_info = EM2880_BOARD_TERRATEC_HYBRID_XS_FR },
{ USB_DEVICE(0x0ccd, 0x004f),
.driver_info = EM2860_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x005e),
.driver_info = EM2882_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x0042),
.driver_info = EM2880_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x0043),
.driver_info = EM2870_BOARD_TERRATEC_XS },
{ USB_DEVICE(0x0ccd, 0x0047),
.driver_info = EM2880_BOARD_TERRATEC_PRODIGY_XS },
{ USB_DEVICE(0x0ccd, 0x0084),
.driver_info = EM2860_BOARD_TERRATEC_AV350 },
{ USB_DEVICE(0x0ccd, 0x0096),
.driver_info = EM2860_BOARD_TERRATEC_GRABBY },
{ USB_DEVICE(0x185b, 0x2870),
.driver_info = EM2870_BOARD_COMPRO_VIDEOMATE },
{ USB_DEVICE(0x185b, 0x2041),
.driver_info = EM2820_BOARD_COMPRO_VIDEOMATE_FORYOU },
{ USB_DEVICE(0x2040, 0x4200),
.driver_info = EM2820_BOARD_HAUPPAUGE_WINTV_USB_2 },
{ USB_DEVICE(0x2040, 0x4201),
.driver_info = EM2820_BOARD_HAUPPAUGE_WINTV_USB_2 },
{ USB_DEVICE(0x2040, 0x6500),
.driver_info = EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900 },
{ USB_DEVICE(0x2040, 0x6502),
.driver_info = EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2 },
{ USB_DEVICE(0x2040, 0x6513), /* HCW HVR-980 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x6517), /* HP HVR-950 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x651b), /* RP HVR-950 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x651f),
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850 },
{ USB_DEVICE(0x0438, 0xb002),
.driver_info = EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600 },
{ USB_DEVICE(0x2001, 0xf112),
.driver_info = EM2820_BOARD_DLINK_USB_TV },
{ USB_DEVICE(0x2304, 0x0207),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 },
{ USB_DEVICE(0x2304, 0x0208),
.driver_info = EM2820_BOARD_PINNACLE_USB_2 },
{ USB_DEVICE(0x2304, 0x021a),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 },
{ USB_DEVICE(0x2304, 0x0226),
.driver_info = EM2882_BOARD_PINNACLE_HYBRID_PRO },
{ USB_DEVICE(0x2304, 0x0227),
.driver_info = EM2880_BOARD_PINNACLE_PCTV_HD_PRO },
{ USB_DEVICE(0x0413, 0x6023),
.driver_info = EM2800_BOARD_LEADTEK_WINFAST_USBII },
{ USB_DEVICE(0x093b, 0xa005),
.driver_info = EM2861_BOARD_PLEXTOR_PX_TV100U },
{ USB_DEVICE(0x04bb, 0x0515),
.driver_info = EM2820_BOARD_IODATA_GVMVP_SZ },
{ USB_DEVICE(0xeb1a, 0x50a6),
.driver_info = EM2860_BOARD_GADMEI_UTV330 },
{ },
};
MODULE_DEVICE_TABLE(usb, em28xx_id_table);
/*
* EEPROM hash table for devices with generic USB IDs
*/
static struct em28xx_hash_table em28xx_eeprom_hash[] = {
/* P/N: SA 60002070465 Tuner: TVF7533-MF */
{0x6ce05a8f, EM2820_BOARD_PROLINK_PLAYTV_USB2, TUNER_YMEC_TVF_5533MF},
{0x72cc5a8b, EM2820_BOARD_PROLINK_PLAYTV_BOX4_USB2, TUNER_YMEC_TVF_5533MF},
{0x966a0441, EM2880_BOARD_KWORLD_DVB_310U, TUNER_XC2028},
{0x166a0441, EM2880_BOARD_EMPIRE_DUAL_TV, TUNER_XC2028},
{0xcee44a99, EM2882_BOARD_EVGA_INDTUBE, TUNER_XC2028},
{0xb8846b20, EM2881_BOARD_PINNACLE_HYBRID_PRO, TUNER_XC2028},
{0x63f653bd, EM2870_BOARD_REDDO_DVB_C_USB_BOX, TUNER_ABSENT},
{0x4e913442, EM2882_BOARD_DIKOM_DK300, TUNER_XC2028},
};
/* I2C devicelist hash table for devices with generic USB IDs */
static struct em28xx_hash_table em28xx_i2c_hash[] = {
{0xb06a32c3, EM2800_BOARD_TERRATEC_CINERGY_200, TUNER_LG_PAL_NEW_TAPC},
{0xf51200e3, EM2800_BOARD_VGEAR_POCKETTV, TUNER_LG_PAL_NEW_TAPC},
{0x1ba50080, EM2860_BOARD_SAA711X_REFERENCE_DESIGN, TUNER_ABSENT},
{0x77800080, EM2860_BOARD_TVP5150_REFERENCE_DESIGN, TUNER_ABSENT},
{0xc51200e3, EM2820_BOARD_GADMEI_TVR200, TUNER_LG_PAL_NEW_TAPC},
{0x4ba50080, EM2861_BOARD_GADMEI_UTV330PLUS, TUNER_TNF_5335MF},
};
/* I2C possible address to saa7115, tvp5150, msp3400, tvaudio */
static unsigned short saa711x_addrs[] = {
0x4a >> 1, 0x48 >> 1, /* SAA7111, SAA7111A and SAA7113 */
0x42 >> 1, 0x40 >> 1, /* SAA7114, SAA7115 and SAA7118 */
I2C_CLIENT_END };
static unsigned short tvp5150_addrs[] = {
0xb8 >> 1,
0xba >> 1,
I2C_CLIENT_END
};
static unsigned short mt9v011_addrs[] = {
0xba >> 1,
I2C_CLIENT_END
};
static unsigned short msp3400_addrs[] = {
0x80 >> 1,
0x88 >> 1,
I2C_CLIENT_END
};
int em28xx_tuner_callback(void *ptr, int component, int command, int arg)
{
int rc = 0;
struct em28xx *dev = ptr;
if (dev->tuner_type != TUNER_XC2028)
return 0;
if (command != XC2028_TUNER_RESET)
return 0;
rc = em28xx_gpio_set(dev, dev->board.tuner_gpio);
return rc;
}
EXPORT_SYMBOL_GPL(em28xx_tuner_callback);
static inline void em28xx_set_model(struct em28xx *dev)
{
memcpy(&dev->board, &em28xx_boards[dev->model], sizeof(dev->board));
/* Those are the default values for the majority of boards
Use those values if not specified otherwise at boards entry
*/
if (!dev->board.xclk)
dev->board.xclk = EM28XX_XCLK_IR_RC5_MODE |
EM28XX_XCLK_FREQUENCY_12MHZ;
if (!dev->board.i2c_speed)
dev->board.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_100_KHZ;
}
/* FIXME: Should be replaced by a proper mt9m111 driver */
static int em28xx_initialize_mt9m111(struct em28xx *dev)
{
int i;
unsigned char regs[][3] = {
{ 0x0d, 0x00, 0x01, }, /* reset and use defaults */
{ 0x0d, 0x00, 0x00, },
{ 0x0a, 0x00, 0x21, },
{ 0x21, 0x04, 0x00, }, /* full readout speed, no row/col skipping */
};
for (i = 0; i < ARRAY_SIZE(regs); i++)
i2c_master_send(&dev->i2c_client, ®s[i][0], 3);
return 0;
}
/* FIXME: Should be replaced by a proper mt9m001 driver */
static int em28xx_initialize_mt9m001(struct em28xx *dev)
{
int i;
unsigned char regs[][3] = {
{ 0x0d, 0x00, 0x01, },
{ 0x0d, 0x00, 0x00, },
{ 0x04, 0x05, 0x00, }, /* hres = 1280 */
{ 0x03, 0x04, 0x00, }, /* vres = 1024 */
{ 0x20, 0x11, 0x00, },
{ 0x06, 0x00, 0x10, },
{ 0x2b, 0x00, 0x24, },
{ 0x2e, 0x00, 0x24, },
{ 0x35, 0x00, 0x24, },
{ 0x2d, 0x00, 0x20, },
{ 0x2c, 0x00, 0x20, },
{ 0x09, 0x0a, 0xd4, },
{ 0x35, 0x00, 0x57, },
};
for (i = 0; i < ARRAY_SIZE(regs); i++)
i2c_master_send(&dev->i2c_client, ®s[i][0], 3);
return 0;
}
/* HINT method: webcam I2C chips
*
* This method works for webcams with Micron sensors
*/
static int em28xx_hint_sensor(struct em28xx *dev)
{
int rc;
char *sensor_name;
unsigned char cmd;
__be16 version_be;
u16 version;
/* Micron sensor detection */
dev->i2c_client.addr = 0xba >> 1;
cmd = 0;
i2c_master_send(&dev->i2c_client, &cmd, 1);
rc = i2c_master_recv(&dev->i2c_client, (char *)&version_be, 2);
if (rc != 2)
return -EINVAL;
version = be16_to_cpu(version_be);
switch (version) {
case 0x8232: /* mt9v011 640x480 1.3 Mpix sensor */
case 0x8243: /* mt9v011 rev B 640x480 1.3 Mpix sensor */
dev->model = EM2820_BOARD_SILVERCREST_WEBCAM;
em28xx_set_model(dev);
sensor_name = "mt9v011";
dev->em28xx_sensor = EM28XX_MT9V011;
dev->sensor_xres = 640;
dev->sensor_yres = 480;
/*
* FIXME: mt9v011 uses I2S speed as xtal clk - at least with
* the Silvercrest cam I have here for testing - for higher
* resolutions, a high clock cause horizontal artifacts, so we
* need to use a lower xclk frequency.
* Yet, it would be possible to adjust xclk depending on the
* desired resolution, since this affects directly the
* frame rate.
*/
dev->board.xclk = EM28XX_XCLK_FREQUENCY_4_3MHZ;
dev->sensor_xtal = 4300000;
/* probably means GRGB 16 bit bayer */
dev->vinmode = 0x0d;
dev->vinctl = 0x00;
break;
case 0x143a: /* MT9M111 as found in the ECS G200 */
dev->model = EM2750_BOARD_UNKNOWN;
em28xx_set_model(dev);
sensor_name = "mt9m111";
dev->board.xclk = EM28XX_XCLK_FREQUENCY_48MHZ;
dev->em28xx_sensor = EM28XX_MT9M111;
em28xx_initialize_mt9m111(dev);
dev->sensor_xres = 640;
dev->sensor_yres = 512;
dev->vinmode = 0x0a;
dev->vinctl = 0x00;
break;
case 0x8431:
dev->model = EM2750_BOARD_UNKNOWN;
em28xx_set_model(dev);
sensor_name = "mt9m001";
dev->em28xx_sensor = EM28XX_MT9M001;
em28xx_initialize_mt9m001(dev);
dev->sensor_xres = 1280;
dev->sensor_yres = 1024;
/* probably means BGGR 16 bit bayer */
dev->vinmode = 0x0c;
dev->vinctl = 0x00;
break;
default:
printk("Unknown Micron Sensor 0x%04x\n", version);
return -EINVAL;
}
/* Setup webcam defaults */
em28xx_pre_card_setup(dev);
em28xx_errdev("Sensor is %s, using model %s entry.\n",
sensor_name, em28xx_boards[dev->model].name);
return 0;
}
/* Since em28xx_pre_card_setup() requires a proper dev->model,
* this won't work for boards with generic PCI IDs
*/
void em28xx_pre_card_setup(struct em28xx *dev)
{
/* Set the initial XCLK and I2C clock values based on the board
definition */
em28xx_write_reg(dev, EM28XX_R0F_XCLK, dev->board.xclk & 0x7f);
em28xx_write_reg(dev, EM28XX_R06_I2C_CLK, dev->board.i2c_speed);
msleep(50);
/* request some modules */
switch (dev->model) {
case EM2861_BOARD_PLEXTOR_PX_TV100U:
/* Sets the msp34xx I2S speed */
dev->i2s_speed = 2048000;
break;
case EM2861_BOARD_KWORLD_PVRTV_300U:
case EM2880_BOARD_KWORLD_DVB_305U:
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0x6d);
msleep(10);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0x7d);
msleep(10);
break;
case EM2870_BOARD_COMPRO_VIDEOMATE:
/* TODO: someone can do some cleanup here...
not everything's needed */
em28xx_write_reg(dev, EM2880_R04_GPO, 0x00);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x01);
msleep(10);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfd);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfc);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xdc);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfc);
mdelay(70);
break;
case EM2870_BOARD_TERRATEC_XS_MT2060:
/* this device needs some gpio writes to get the DVB-T
demod work */
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xde);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
mdelay(70);
break;
case EM2870_BOARD_PINNACLE_PCTV_DVB:
/* this device needs some gpio writes to get the
DVB-T demod work */
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xde);
mdelay(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
mdelay(70);
break;
case EM2820_BOARD_GADMEI_UTV310:
case EM2820_BOARD_MSI_VOX_USB_2:
/* enables audio for that devices */
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfd);
break;
case EM2882_BOARD_KWORLD_ATSC_315U:
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xff);
msleep(10);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x00);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x08);
msleep(10);
break;
case EM2860_BOARD_KAIOMY_TVNPC_U2:
em28xx_write_regs(dev, EM28XX_R0F_XCLK, "\x07", 1);
em28xx_write_regs(dev, EM28XX_R06_I2C_CLK, "\x40", 1);
em28xx_write_regs(dev, 0x0d, "\x42", 1);
em28xx_write_regs(dev, 0x08, "\xfd", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\xff", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\x7f", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\x6b", 1);
break;
case EM2860_BOARD_EASYCAP:
em28xx_write_regs(dev, 0x08, "\xf8", 1);
break;
case EM2820_BOARD_IODATA_GVMVP_SZ:
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xff);
msleep(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xf7);
msleep(10);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfe);
msleep(70);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfd);
msleep(70);
break;
}
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
/* Unlock device */
em28xx_set_mode(dev, EM28XX_SUSPEND);
}
static void em28xx_setup_xc3028(struct em28xx *dev, struct xc2028_ctrl *ctl)
{
memset(ctl, 0, sizeof(*ctl));
ctl->fname = XC2028_DEFAULT_FIRMWARE;
ctl->max_len = 64;
ctl->mts = em28xx_boards[dev->model].mts_firmware;
switch (dev->model) {
case EM2880_BOARD_EMPIRE_DUAL_TV:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900:
case EM2882_BOARD_TERRATEC_HYBRID_XS:
ctl->demod = XC3028_FE_ZARLINK456;
break;
case EM2880_BOARD_TERRATEC_HYBRID_XS:
case EM2881_BOARD_PINNACLE_HYBRID_PRO:
ctl->demod = XC3028_FE_ZARLINK456;
break;
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2:
/* djh - Not sure which demod we need here */
ctl->demod = XC3028_FE_DEFAULT;
break;
case EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600:
ctl->demod = XC3028_FE_DEFAULT;
ctl->fname = XC3028L_DEFAULT_FIRMWARE;
break;
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950:
case EM2880_BOARD_PINNACLE_PCTV_HD_PRO:
/* FIXME: Better to specify the needed IF */
ctl->demod = XC3028_FE_DEFAULT;
break;
case EM2883_BOARD_KWORLD_HYBRID_330U:
case EM2882_BOARD_DIKOM_DK300:
case EM2882_BOARD_KWORLD_VS_DVBT:
ctl->demod = XC3028_FE_CHINA;
ctl->fname = XC2028_DEFAULT_FIRMWARE;
break;
case EM2882_BOARD_EVGA_INDTUBE:
ctl->demod = XC3028_FE_CHINA;
ctl->fname = XC3028L_DEFAULT_FIRMWARE;
break;
default:
ctl->demod = XC3028_FE_OREN538;
}
}
static void em28xx_tuner_setup(struct em28xx *dev)
{
struct tuner_setup tun_setup;
struct v4l2_frequency f;
if (dev->tuner_type == TUNER_ABSENT)
return;
memset(&tun_setup, 0, sizeof(tun_setup));
tun_setup.mode_mask = T_ANALOG_TV | T_RADIO;
tun_setup.tuner_callback = em28xx_tuner_callback;
if (dev->board.radio.type) {
tun_setup.type = dev->board.radio.type;
tun_setup.addr = dev->board.radio_addr;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_type_addr, &tun_setup);
}
if ((dev->tuner_type != TUNER_ABSENT) && (dev->tuner_type)) {
tun_setup.type = dev->tuner_type;
tun_setup.addr = dev->tuner_addr;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_type_addr, &tun_setup);
}
if (dev->tda9887_conf) {
struct v4l2_priv_tun_config tda9887_cfg;
tda9887_cfg.tuner = TUNER_TDA9887;
tda9887_cfg.priv = &dev->tda9887_conf;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_config, &tda9887_cfg);
}
if (dev->tuner_type == TUNER_XC2028) {
struct v4l2_priv_tun_config xc2028_cfg;
struct xc2028_ctrl ctl;
memset(&xc2028_cfg, 0, sizeof(xc2028_cfg));
memset(&ctl, 0, sizeof(ctl));
em28xx_setup_xc3028(dev, &ctl);
xc2028_cfg.tuner = TUNER_XC2028;
xc2028_cfg.priv = &ctl;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_config, &xc2028_cfg);
}
/* configure tuner */
f.tuner = 0;
f.type = V4L2_TUNER_ANALOG_TV;
f.frequency = 9076; /* just a magic number */
dev->ctl_freq = f.frequency;
v4l2_device_call_all(&dev->v4l2_dev, 0, tuner, s_frequency, &f);
}
static int em28xx_hint_board(struct em28xx *dev)
{
int i;
/* HINT method: EEPROM
*
* This method works only for boards with eeprom.
* Uses a hash of all eeprom bytes. The hash should be
* unique for a vendor/tuner pair.
* There are a high chance that tuners for different
* video standards produce different hashes.
*/
for (i = 0; i < ARRAY_SIZE(em28xx_eeprom_hash); i++) {
if (dev->hash == em28xx_eeprom_hash[i].hash) {
dev->model = em28xx_eeprom_hash[i].model;
dev->tuner_type = em28xx_eeprom_hash[i].tuner;
em28xx_errdev("Your board has no unique USB ID.\n");
em28xx_errdev("A hint were successfully done, "
"based on eeprom hash.\n");
em28xx_errdev("This method is not 100%% failproof.\n");
em28xx_errdev("If the board were missdetected, "
"please email this log to:\n");
em28xx_errdev("\tV4L Mailing List "
" <linux-media@vger.kernel.org>\n");
em28xx_errdev("Board detected as %s\n",
em28xx_boards[dev->model].name);
return 0;
}
}
/* HINT method: I2C attached devices
*
* This method works for all boards.
* Uses a hash of i2c scanned devices.
* Devices with the same i2c attached chips will
* be considered equal.
* This method is less precise than the eeprom one.
*/
/* user did not request i2c scanning => do it now */
if (!dev->i2c_hash)
em28xx_do_i2c_scan(dev);
for (i = 0; i < ARRAY_SIZE(em28xx_i2c_hash); i++) {
if (dev->i2c_hash == em28xx_i2c_hash[i].hash) {
dev->model = em28xx_i2c_hash[i].model;
dev->tuner_type = em28xx_i2c_hash[i].tuner;
em28xx_errdev("Your board has no unique USB ID.\n");
em28xx_errdev("A hint were successfully done, "
"based on i2c devicelist hash.\n");
em28xx_errdev("This method is not 100%% failproof.\n");
em28xx_errdev("If the board were missdetected, "
"please email this log to:\n");
em28xx_errdev("\tV4L Mailing List "
" <linux-media@vger.kernel.org>\n");
em28xx_errdev("Board detected as %s\n",
em28xx_boards[dev->model].name);
return 0;
}
}
em28xx_errdev("Your board has no unique USB ID and thus need a "
"hint to be detected.\n");
em28xx_errdev("You may try to use card=<n> insmod option to "
"workaround that.\n");
em28xx_errdev("Please send an email with this log to:\n");
em28xx_errdev("\tV4L Mailing List <linux-media@vger.kernel.org>\n");
em28xx_errdev("Board eeprom hash is 0x%08lx\n", dev->hash);
em28xx_errdev("Board i2c devicelist hash is 0x%08lx\n", dev->i2c_hash);
em28xx_errdev("Here is a list of valid choices for the card=<n>"
" insmod option:\n");
for (i = 0; i < em28xx_bcount; i++) {
em28xx_errdev(" card=%d -> %s\n",
i, em28xx_boards[i].name);
}
return -1;
}
/* ----------------------------------------------------------------------- */
void em28xx_register_i2c_ir(struct em28xx *dev)
{
/* Leadtek winfast tv USBII deluxe can find a non working IR-device */
/* at address 0x18, so if that address is needed for another board in */
/* the future, please put it after 0x1f. */
struct i2c_board_info info;
const unsigned short addr_list[] = {
0x1f, 0x30, 0x47, I2C_CLIENT_END
};
if (disable_ir)
return;
memset(&info, 0, sizeof(struct i2c_board_info));
memset(&dev->init_data, 0, sizeof(dev->init_data));
strlcpy(info.type, "ir_video", I2C_NAME_SIZE);
/* detect & configure */
switch (dev->model) {
case EM2800_BOARD_TERRATEC_CINERGY_200:
case EM2820_BOARD_TERRATEC_CINERGY_250:
dev->init_data.ir_codes = RC_MAP_EM_TERRATEC;
dev->init_data.get_key = em28xx_get_key_terratec;
dev->init_data.name = "i2c IR (EM28XX Terratec)";
break;
case EM2820_BOARD_PINNACLE_USB_2:
dev->init_data.ir_codes = RC_MAP_PINNACLE_GREY;
dev->init_data.get_key = em28xx_get_key_pinnacle_usb_grey;
dev->init_data.name = "i2c IR (EM28XX Pinnacle PCTV)";
break;
case EM2820_BOARD_HAUPPAUGE_WINTV_USB_2:
dev->init_data.ir_codes = RC_MAP_RC5_HAUPPAUGE_NEW;
dev->init_data.get_key = em28xx_get_key_em_haup;
dev->init_data.name = "i2c IR (EM2840 Hauppauge)";
case EM2820_BOARD_LEADTEK_WINFAST_USBII_DELUXE:
dev->init_data.ir_codes = RC_MAP_WINFAST_USBII_DELUXE;;
dev->init_data.get_key = em28xx_get_key_winfast_usbii_deluxe;
dev->init_data.name = "i2c IR (EM2820 Winfast TV USBII Deluxe)";
break;
}
if (dev->init_data.name)
info.platform_data = &dev->init_data;
i2c_new_probed_device(&dev->i2c_adap, &info, addr_list);
}
void em28xx_card_setup(struct em28xx *dev)
{
/*
* If the device can be a webcam, seek for a sensor.
* If sensor is not found, then it isn't a webcam.
*/
if (dev->board.is_webcam) {
if (em28xx_hint_sensor(dev) < 0)
dev->board.is_webcam = 0;
else
dev->progressive = 1;
} else
em28xx_set_model(dev);
em28xx_info("Identified as %s (card=%d)\n",
dev->board.name, dev->model);
dev->tuner_type = em28xx_boards[dev->model].tuner_type;
if (em28xx_boards[dev->model].tuner_addr)
dev->tuner_addr = em28xx_boards[dev->model].tuner_addr;
if (em28xx_boards[dev->model].tda9887_conf)
dev->tda9887_conf = em28xx_boards[dev->model].tda9887_conf;
/* request some modules */
switch (dev->model) {
case EM2820_BOARD_HAUPPAUGE_WINTV_USB_2:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950:
{
struct tveeprom tv;
#if defined(CONFIG_MODULES) && defined(MODULE)
request_module("tveeprom");
#endif
/* Call first TVeeprom */
dev->i2c_client.addr = 0xa0 >> 1;
tveeprom_hauppauge_analog(&dev->i2c_client, &tv, dev->eedata);
dev->tuner_type = tv.tuner_type;
if (tv.audio_processor == V4L2_IDENT_MSPX4XX) {
dev->i2s_speed = 2048000;
dev->board.has_msp34xx = 1;
}
break;
}
case EM2882_BOARD_KWORLD_ATSC_315U:
em28xx_write_reg(dev, 0x0d, 0x42);
msleep(10);
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xfd);
msleep(10);
break;
case EM2820_BOARD_KWORLD_PVRTV2800RF:
/* GPIO enables sound on KWORLD PVR TV 2800RF */
em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xf9);
break;
case EM2820_BOARD_UNKNOWN:
case EM2800_BOARD_UNKNOWN:
/*
* The K-WORLD DVB-T 310U is detected as an MSI Digivox AD.
*
* This occurs because they share identical USB vendor and
* product IDs.
*
* What we do here is look up the EEPROM hash of the K-WORLD
* and if it is found then we decide that we do not have
* a DIGIVOX and reset the device to the K-WORLD instead.
*
* This solution is only valid if they do not share eeprom
* hash identities which has not been determined as yet.
*/
case EM2880_BOARD_MSI_DIGIVOX_AD:
if (!em28xx_hint_board(dev))
em28xx_set_model(dev);
/* In cases where we had to use a board hint, the call to
em28xx_set_mode() in em28xx_pre_card_setup() was a no-op,
so make the call now so the analog GPIOs are set properly
before probing the i2c bus. */
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
break;
/*
* The Dikom DK300 is detected as an Kworld VS-DVB-T 323UR.
*
* This occurs because they share identical USB vendor and
* product IDs.
*
* What we do here is look up the EEPROM hash of the Dikom
* and if it is found then we decide that we do not have
* a Kworld and reset the device to the Dikom instead.
*
* This solution is only valid if they do not share eeprom
* hash identities which has not been determined as yet.
*/
case EM2882_BOARD_KWORLD_VS_DVBT:
if (!em28xx_hint_board(dev))
em28xx_set_model(dev);
/* In cases where we had to use a board hint, the call to
em28xx_set_mode() in em28xx_pre_card_setup() was a no-op,
so make the call now so the analog GPIOs are set properly
before probing the i2c bus. */
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
break;
}
#if defined(CONFIG_MODULES) && defined(MODULE)
if (dev->board.has_ir_i2c && !disable_ir)
request_module("ir-kbd-i2c");
#endif
if (dev->board.has_snapshot_button)
em28xx_register_snapshot_button(dev);
if (dev->board.valid == EM28XX_BOARD_NOT_VALIDATED) {
em28xx_errdev("\n\n");
em28xx_errdev("The support for this board weren't "
"valid yet.\n");
em28xx_errdev("Please send a report of having this working\n");
em28xx_errdev("not to V4L mailing list (and/or to other "
"addresses)\n\n");
}
/* Allow override tuner type by a module parameter */
if (tuner >= 0)
dev->tuner_type = tuner;
/* request some modules */
if (dev->board.has_msp34xx)
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"msp3400", "msp3400", 0, msp3400_addrs);
if (dev->board.decoder == EM28XX_SAA711X)
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"saa7115", "saa7115_auto", 0, saa711x_addrs);
if (dev->board.decoder == EM28XX_TVP5150)
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"tvp5150", "tvp5150", 0, tvp5150_addrs);
if (dev->em28xx_sensor == EM28XX_MT9V011) {
struct v4l2_subdev *sd;
sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
&dev->i2c_adap, "mt9v011", "mt9v011", 0, mt9v011_addrs);
v4l2_subdev_call(sd, core, s_config, 0, &dev->sensor_xtal);
}
if (dev->board.adecoder == EM28XX_TVAUDIO)
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"tvaudio", "tvaudio", dev->board.tvaudio_addr, NULL);
if (dev->board.tuner_type != TUNER_ABSENT) {
int has_demod = (dev->tda9887_conf & TDA9887_PRESENT);
if (dev->board.radio.type)
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"tuner", "tuner", dev->board.radio_addr, NULL);
if (has_demod)
v4l2_i2c_new_subdev(&dev->v4l2_dev,
&dev->i2c_adap, "tuner", "tuner",
0, v4l2_i2c_tuner_addrs(ADDRS_DEMOD));
if (dev->tuner_addr == 0) {
enum v4l2_i2c_tuner_type type =
has_demod ? ADDRS_TV_WITH_DEMOD : ADDRS_TV;
struct v4l2_subdev *sd;
sd = v4l2_i2c_new_subdev(&dev->v4l2_dev,
&dev->i2c_adap, "tuner", "tuner",
0, v4l2_i2c_tuner_addrs(type));
if (sd)
dev->tuner_addr = v4l2_i2c_subdev_addr(sd);
} else {
v4l2_i2c_new_subdev(&dev->v4l2_dev, &dev->i2c_adap,
"tuner", "tuner", dev->tuner_addr, NULL);
}
}
em28xx_tuner_setup(dev);
if(!disable_ir)
em28xx_ir_init(dev);
}
#if defined(CONFIG_MODULES) && defined(MODULE)
static void request_module_async(struct work_struct *work)
{
struct em28xx *dev = container_of(work,
struct em28xx, request_module_wk);
if (dev->has_audio_class)
request_module("snd-usb-audio");
else if (dev->has_alsa_audio)
request_module("em28xx-alsa");
if (dev->board.has_dvb)
request_module("em28xx-dvb");
}
static void request_modules(struct em28xx *dev)
{
INIT_WORK(&dev->request_module_wk, request_module_async);
schedule_work(&dev->request_module_wk);
}
#else
#define request_modules(dev)
#endif /* CONFIG_MODULES */
/*
* em28xx_realease_resources()
* unregisters the v4l2,i2c and usb devices
* called when the device gets disconected or at module unload
*/
void em28xx_release_resources(struct em28xx *dev)
{
if (dev->sbutton_input_dev)
em28xx_deregister_snapshot_button(dev);
if (dev->ir)
em28xx_ir_fini(dev);
/*FIXME: I2C IR should be disconnected */
em28xx_release_analog_resources(dev);
em28xx_remove_from_devlist(dev);
em28xx_i2c_unregister(dev);
v4l2_device_unregister(&dev->v4l2_dev);
usb_put_dev(dev->udev);
/* Mark device as unused */
em28xx_devused &= ~(1 << dev->devno);
};
/*
* em28xx_init_dev()
* allocates and inits the device structs, registers i2c bus and v4l device
*/
static int em28xx_init_dev(struct em28xx **devhandle, struct usb_device *udev,
struct usb_interface *interface,
int minor)
{
struct em28xx *dev = *devhandle;
int retval;
int errCode;
dev->udev = udev;
mutex_init(&dev->ctrl_urb_lock);
spin_lock_init(&dev->slock);
init_waitqueue_head(&dev->open);
init_waitqueue_head(&dev->wait_frame);
init_waitqueue_head(&dev->wait_stream);
dev->em28xx_write_regs = em28xx_write_regs;
dev->em28xx_read_reg = em28xx_read_reg;
dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
dev->em28xx_write_regs_req = em28xx_write_regs_req;
dev->em28xx_read_reg_req = em28xx_read_reg_req;
dev->board.is_em2800 = em28xx_boards[dev->model].is_em2800;
em28xx_set_model(dev);
/* Set the default GPO/GPIO for legacy devices */
dev->reg_gpo_num = EM2880_R04_GPO;
dev->reg_gpio_num = EM28XX_R08_GPIO;
dev->wait_after_write = 5;
/* Based on the Chip ID, set the device configuration */
retval = em28xx_read_reg(dev, EM28XX_R0A_CHIPID);
if (retval > 0) {
dev->chip_id = retval;
switch (dev->chip_id) {
case CHIP_ID_EM2800:
em28xx_info("chip ID is em2800\n");
break;
case CHIP_ID_EM2710:
em28xx_info("chip ID is em2710\n");
break;
case CHIP_ID_EM2750:
em28xx_info("chip ID is em2750\n");
break;
case CHIP_ID_EM2820:
em28xx_info("chip ID is em2820 (or em2710)\n");
break;
case CHIP_ID_EM2840:
em28xx_info("chip ID is em2840\n");
break;
case CHIP_ID_EM2860:
em28xx_info("chip ID is em2860\n");
break;
case CHIP_ID_EM2870:
em28xx_info("chip ID is em2870\n");
dev->wait_after_write = 0;
break;
case CHIP_ID_EM2874:
em28xx_info("chip ID is em2874\n");
dev->reg_gpio_num = EM2874_R80_GPIO;
dev->wait_after_write = 0;
break;
case CHIP_ID_EM2883:
em28xx_info("chip ID is em2882/em2883\n");
dev->wait_after_write = 0;
break;
default:
em28xx_info("em28xx chip ID = %d\n", dev->chip_id);
}
}
/* Prepopulate cached GPO register content */
retval = em28xx_read_reg(dev, dev->reg_gpo_num);
if (retval >= 0)
dev->reg_gpo = retval;
em28xx_pre_card_setup(dev);
if (!dev->board.is_em2800) {
/* Sets I2C speed to 100 KHz */
retval = em28xx_write_reg(dev, EM28XX_R06_I2C_CLK, 0x40);
if (retval < 0) {
em28xx_errdev("%s: em28xx_write_regs_req failed!"
" retval [%d]\n",
__func__, retval);
return retval;
}
}
retval = v4l2_device_register(&interface->dev, &dev->v4l2_dev);
if (retval < 0) {
em28xx_errdev("Call to v4l2_device_register() failed!\n");
return retval;
}
/* register i2c bus */
errCode = em28xx_i2c_register(dev);
if (errCode < 0) {
v4l2_device_unregister(&dev->v4l2_dev);
em28xx_errdev("%s: em28xx_i2c_register - errCode [%d]!\n",
__func__, errCode);
return errCode;
}
/*
* Default format, used for tvp5150 or saa711x output formats
*/
dev->vinmode = 0x10;
dev->vinctl = EM28XX_VINCTRL_INTERLACED |
EM28XX_VINCTRL_CCIR656_ENABLE;
/* Do board specific init and eeprom reading */
em28xx_card_setup(dev);
/* Configure audio */
errCode = em28xx_audio_setup(dev);
if (errCode < 0) {
v4l2_device_unregister(&dev->v4l2_dev);
em28xx_errdev("%s: Error while setting audio - errCode [%d]!\n",
__func__, errCode);
}
/* wake i2c devices */
em28xx_wake_i2c(dev);
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
INIT_LIST_HEAD(&dev->vidq.queued);
INIT_LIST_HEAD(&dev->vbiq.active);
INIT_LIST_HEAD(&dev->vbiq.queued);
if (dev->board.has_msp34xx) {
/* Send a reset to other chips via gpio */
errCode = em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xf7);
if (errCode < 0) {
em28xx_errdev("%s: em28xx_write_regs_req - "
"msp34xx(1) failed! errCode [%d]\n",
__func__, errCode);
return errCode;
}
msleep(3);
errCode = em28xx_write_reg(dev, EM28XX_R08_GPIO, 0xff);
if (errCode < 0) {
em28xx_errdev("%s: em28xx_write_regs_req - "
"msp34xx(2) failed! errCode [%d]\n",
__func__, errCode);
return errCode;
}
msleep(3);
}
em28xx_add_into_devlist(dev);
retval = em28xx_register_analog_devices(dev);
if (retval < 0) {
em28xx_release_resources(dev);
goto fail_reg_devices;
}
em28xx_init_extension(dev);
/* Save some power by putting tuner to sleep */
v4l2_device_call_all(&dev->v4l2_dev, 0, core, s_power, 0);
return 0;
fail_reg_devices:
return retval;
}
/*
* em28xx_usb_probe()
* checks for supported devices
*/
static int em28xx_usb_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
const struct usb_endpoint_descriptor *endpoint;
struct usb_device *udev;
struct usb_interface *uif;
struct em28xx *dev = NULL;
int retval;
int i, nr, ifnum, isoc_pipe;
char *speed;
char descr[255] = "";
udev = usb_get_dev(interface_to_usbdev(interface));
ifnum = interface->altsetting[0].desc.bInterfaceNumber;
/* Check to see next free device and mark as used */
nr = find_first_zero_bit(&em28xx_devused, EM28XX_MAXBOARDS);
em28xx_devused |= 1<<nr;
/* Don't register audio interfaces */
if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
em28xx_err(DRIVER_NAME " audio device (%04x:%04x): "
"interface %i, class %i\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
interface->altsetting[0].desc.bInterfaceClass);
em28xx_devused &= ~(1<<nr);
retval = -ENODEV;
goto err;
}
endpoint = &interface->cur_altsetting->endpoint[0].desc;
/* check if the device has the iso in endpoint at the correct place */
if (usb_endpoint_xfer_isoc(endpoint)
&&
(interface->altsetting[1].endpoint[0].desc.wMaxPacketSize == 940)) {
/* It's a newer em2874/em2875 device */
isoc_pipe = 0;
} else {
int check_interface = 1;
isoc_pipe = 1;
endpoint = &interface->cur_altsetting->endpoint[1].desc;
if (!usb_endpoint_xfer_isoc(endpoint))
check_interface = 0;
if (usb_endpoint_dir_out(endpoint))
check_interface = 0;
if (!check_interface) {
em28xx_err(DRIVER_NAME " video device (%04x:%04x): "
"interface %i, class %i found.\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
interface->altsetting[0].desc.bInterfaceClass);
em28xx_err(DRIVER_NAME " This is an anciliary "
"interface not used by the driver\n");
em28xx_devused &= ~(1<<nr);
retval = -ENODEV;
goto err;
}
}
switch (udev->speed) {
case USB_SPEED_LOW:
speed = "1.5";
break;
case USB_SPEED_UNKNOWN:
case USB_SPEED_FULL:
speed = "12";
break;
case USB_SPEED_HIGH:
speed = "480";
break;
default:
speed = "unknown";
}
if (udev->manufacturer)
strlcpy(descr, udev->manufacturer, sizeof(descr));
if (udev->product) {
if (*descr)
strlcat(descr, " ", sizeof(descr));
strlcat(descr, udev->product, sizeof(descr));
}
if (*descr)
strlcat(descr, " ", sizeof(descr));
printk(DRIVER_NAME ": New device %s@ %s Mbps "
"(%04x:%04x, interface %d, class %d)\n",
descr,
speed,
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
interface->altsetting->desc.bInterfaceNumber);
/*
* Make sure we have 480 Mbps of bandwidth, otherwise things like
* video stream wouldn't likely work, since 12 Mbps is generally
* not enough even for most Digital TV streams.
*/
if (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {
printk(DRIVER_NAME ": Device initialization failed.\n");
printk(DRIVER_NAME ": Device must be connected to a high-speed"
" USB 2.0 port.\n");
em28xx_devused &= ~(1<<nr);
retval = -ENODEV;
goto err;
}
if (nr >= EM28XX_MAXBOARDS) {
printk(DRIVER_NAME ": Supports only %i em28xx boards.\n",
EM28XX_MAXBOARDS);
em28xx_devused &= ~(1<<nr);
retval = -ENOMEM;
goto err;
}
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
em28xx_err(DRIVER_NAME ": out of memory!\n");
em28xx_devused &= ~(1<<nr);
retval = -ENOMEM;
goto err;
}
snprintf(dev->name, 29, "em28xx #%d", nr);
dev->devno = nr;
dev->model = id->driver_info;
dev->alt = -1;
/* Checks if audio is provided by some interface */
for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
uif = udev->config->interface[i];
if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
dev->has_audio_class = 1;
break;
}
}
/* compute alternate max packet sizes */
uif = udev->actconfig->interface[0];
dev->num_alt = uif->num_altsetting;
dev->alt_max_pkt_size = kmalloc(32 * dev->num_alt, GFP_KERNEL);
if (dev->alt_max_pkt_size == NULL) {
em28xx_errdev("out of memory!\n");
em28xx_devused &= ~(1<<nr);
kfree(dev);
retval = -ENOMEM;
goto err;
}
for (i = 0; i < dev->num_alt ; i++) {
u16 tmp = le16_to_cpu(uif->altsetting[i].endpoint[isoc_pipe].desc.wMaxPacketSize);
dev->alt_max_pkt_size[i] =
(tmp & 0x07ff) * (((tmp & 0x1800) >> 11) + 1);
}
if ((card[nr] >= 0) && (card[nr] < em28xx_bcount))
dev->model = card[nr];
/* allocate device struct */
mutex_init(&dev->lock);
mutex_lock(&dev->lock);
retval = em28xx_init_dev(&dev, udev, interface, nr);
if (retval) {
em28xx_devused &= ~(1<<dev->devno);
mutex_unlock(&dev->lock);
kfree(dev);
goto err;
}
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev);
request_modules(dev);
/* Should be the last thing to do, to avoid newer udev's to
open the device before fully initializing it
*/
mutex_unlock(&dev->lock);
return 0;
err:
return retval;
}
/*
* em28xx_usb_disconnect()
* called when the device gets diconencted
* video device will be unregistered on v4l2_close in case it is still open
*/
static void em28xx_usb_disconnect(struct usb_interface *interface)
{
struct em28xx *dev;
dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
if (!dev)
return;
em28xx_info("disconnecting %s\n", dev->vdev->name);
/* wait until all current v4l2 io is finished then deallocate
resources */
mutex_lock(&dev->lock);
wake_up_interruptible_all(&dev->open);
v4l2_device_disconnect(&dev->v4l2_dev);
if (dev->users) {
em28xx_warn
("device %s is open! Deregistration and memory "
"deallocation are deferred on close.\n",
video_device_node_name(dev->vdev));
dev->state |= DEV_MISCONFIGURED;
em28xx_uninit_isoc(dev);
dev->state |= DEV_DISCONNECTED;
wake_up_interruptible(&dev->wait_frame);
wake_up_interruptible(&dev->wait_stream);
} else {
dev->state |= DEV_DISCONNECTED;
em28xx_release_resources(dev);
}
em28xx_close_extension(dev);
mutex_unlock(&dev->lock);
if (!dev->users) {
kfree(dev->alt_max_pkt_size);
kfree(dev);
}
}
static struct usb_driver em28xx_usb_driver = {
.name = "em28xx",
.probe = em28xx_usb_probe,
.disconnect = em28xx_usb_disconnect,
.id_table = em28xx_id_table,
};
static int __init em28xx_module_init(void)
{
int result;
/* register this driver with the USB subsystem */
result = usb_register(&em28xx_usb_driver);
if (result)
em28xx_err(DRIVER_NAME
" usb_register failed. Error number %d.\n", result);
printk(KERN_INFO DRIVER_NAME " driver loaded\n");
return result;
}
static void __exit em28xx_module_exit(void)
{
/* deregister this driver with the USB subsystem */
usb_deregister(&em28xx_usb_driver);
}
module_init(em28xx_module_init);
module_exit(em28xx_module_exit);
| gpl-2.0 |
royorbs3/Leviathan-V1-Kernel-G925T | drivers/media/platform/exynos4-is/fimc-lite-reg.c | 2096 | 8590 | /*
* Register interface file for EXYNOS FIMC-LITE (camera interface) driver
*
* Copyright (C) 2012 Samsung Electronics Co., Ltd.
* Sylwester Nawrocki <s.nawrocki@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/io.h>
#include <linux/delay.h>
#include <media/s5p_fimc.h>
#include "fimc-lite-reg.h"
#include "fimc-lite.h"
#include "fimc-core.h"
#define FLITE_RESET_TIMEOUT 50 /* in ms */
void flite_hw_reset(struct fimc_lite *dev)
{
unsigned long end = jiffies + msecs_to_jiffies(FLITE_RESET_TIMEOUT);
u32 cfg;
cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
cfg |= FLITE_REG_CIGCTRL_SWRST_REQ;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
while (time_is_after_jiffies(end)) {
cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
if (cfg & FLITE_REG_CIGCTRL_SWRST_RDY)
break;
usleep_range(1000, 5000);
}
cfg |= FLITE_REG_CIGCTRL_SWRST;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
}
void flite_hw_clear_pending_irq(struct fimc_lite *dev)
{
u32 cfg = readl(dev->regs + FLITE_REG_CISTATUS);
cfg &= ~FLITE_REG_CISTATUS_IRQ_CAM;
writel(cfg, dev->regs + FLITE_REG_CISTATUS);
}
u32 flite_hw_get_interrupt_source(struct fimc_lite *dev)
{
u32 intsrc = readl(dev->regs + FLITE_REG_CISTATUS);
return intsrc & FLITE_REG_CISTATUS_IRQ_MASK;
}
void flite_hw_clear_last_capture_end(struct fimc_lite *dev)
{
u32 cfg = readl(dev->regs + FLITE_REG_CISTATUS2);
cfg &= ~FLITE_REG_CISTATUS2_LASTCAPEND;
writel(cfg, dev->regs + FLITE_REG_CISTATUS2);
}
void flite_hw_set_interrupt_mask(struct fimc_lite *dev)
{
u32 cfg, intsrc;
/* Select interrupts to be enabled for each output mode */
if (atomic_read(&dev->out_path) == FIMC_IO_DMA) {
intsrc = FLITE_REG_CIGCTRL_IRQ_OVFEN |
FLITE_REG_CIGCTRL_IRQ_LASTEN |
FLITE_REG_CIGCTRL_IRQ_STARTEN;
} else {
/* An output to the FIMC-IS */
intsrc = FLITE_REG_CIGCTRL_IRQ_OVFEN |
FLITE_REG_CIGCTRL_IRQ_LASTEN;
}
cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
cfg |= FLITE_REG_CIGCTRL_IRQ_DISABLE_MASK;
cfg &= ~intsrc;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
}
void flite_hw_capture_start(struct fimc_lite *dev)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIIMGCPT);
cfg |= FLITE_REG_CIIMGCPT_IMGCPTEN;
writel(cfg, dev->regs + FLITE_REG_CIIMGCPT);
}
void flite_hw_capture_stop(struct fimc_lite *dev)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIIMGCPT);
cfg &= ~FLITE_REG_CIIMGCPT_IMGCPTEN;
writel(cfg, dev->regs + FLITE_REG_CIIMGCPT);
}
/*
* Test pattern (color bars) enable/disable. External sensor
* pixel clock must be active for the test pattern to work.
*/
void flite_hw_set_test_pattern(struct fimc_lite *dev, bool on)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
if (on)
cfg |= FLITE_REG_CIGCTRL_TEST_PATTERN_COLORBAR;
else
cfg &= ~FLITE_REG_CIGCTRL_TEST_PATTERN_COLORBAR;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
}
static const u32 src_pixfmt_map[8][3] = {
{ V4L2_MBUS_FMT_YUYV8_2X8, FLITE_REG_CISRCSIZE_ORDER422_IN_YCBYCR,
FLITE_REG_CIGCTRL_YUV422_1P },
{ V4L2_MBUS_FMT_YVYU8_2X8, FLITE_REG_CISRCSIZE_ORDER422_IN_YCRYCB,
FLITE_REG_CIGCTRL_YUV422_1P },
{ V4L2_MBUS_FMT_UYVY8_2X8, FLITE_REG_CISRCSIZE_ORDER422_IN_CBYCRY,
FLITE_REG_CIGCTRL_YUV422_1P },
{ V4L2_MBUS_FMT_VYUY8_2X8, FLITE_REG_CISRCSIZE_ORDER422_IN_CRYCBY,
FLITE_REG_CIGCTRL_YUV422_1P },
{ V4L2_MBUS_FMT_SGRBG8_1X8, 0, FLITE_REG_CIGCTRL_RAW8 },
{ V4L2_MBUS_FMT_SGRBG10_1X10, 0, FLITE_REG_CIGCTRL_RAW10 },
{ V4L2_MBUS_FMT_SGRBG12_1X12, 0, FLITE_REG_CIGCTRL_RAW12 },
{ V4L2_MBUS_FMT_JPEG_1X8, 0, FLITE_REG_CIGCTRL_USER(1) },
};
/* Set camera input pixel format and resolution */
void flite_hw_set_source_format(struct fimc_lite *dev, struct flite_frame *f)
{
enum v4l2_mbus_pixelcode pixelcode = f->fmt->mbus_code;
int i = ARRAY_SIZE(src_pixfmt_map);
u32 cfg;
while (--i >= 0) {
if (src_pixfmt_map[i][0] == pixelcode)
break;
}
if (i == 0 && src_pixfmt_map[i][0] != pixelcode) {
v4l2_err(&dev->vfd,
"Unsupported pixel code, falling back to %#08x\n",
src_pixfmt_map[i][0]);
}
cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
cfg &= ~FLITE_REG_CIGCTRL_FMT_MASK;
cfg |= src_pixfmt_map[i][2];
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
cfg = readl(dev->regs + FLITE_REG_CISRCSIZE);
cfg &= ~(FLITE_REG_CISRCSIZE_ORDER422_MASK |
FLITE_REG_CISRCSIZE_SIZE_CAM_MASK);
cfg |= (f->f_width << 16) | f->f_height;
cfg |= src_pixfmt_map[i][1];
writel(cfg, dev->regs + FLITE_REG_CISRCSIZE);
}
/* Set the camera host input window offsets (cropping) */
void flite_hw_set_window_offset(struct fimc_lite *dev, struct flite_frame *f)
{
u32 hoff2, voff2;
u32 cfg;
cfg = readl(dev->regs + FLITE_REG_CIWDOFST);
cfg &= ~FLITE_REG_CIWDOFST_OFST_MASK;
cfg |= (f->rect.left << 16) | f->rect.top;
cfg |= FLITE_REG_CIWDOFST_WINOFSEN;
writel(cfg, dev->regs + FLITE_REG_CIWDOFST);
hoff2 = f->f_width - f->rect.width - f->rect.left;
voff2 = f->f_height - f->rect.height - f->rect.top;
cfg = (hoff2 << 16) | voff2;
writel(cfg, dev->regs + FLITE_REG_CIWDOFST2);
}
/* Select camera port (A, B) */
static void flite_hw_set_camera_port(struct fimc_lite *dev, int id)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIGENERAL);
if (id == 0)
cfg &= ~FLITE_REG_CIGENERAL_CAM_B;
else
cfg |= FLITE_REG_CIGENERAL_CAM_B;
writel(cfg, dev->regs + FLITE_REG_CIGENERAL);
}
/* Select serial or parallel bus, camera port (A,B) and set signals polarity */
void flite_hw_set_camera_bus(struct fimc_lite *dev,
struct fimc_source_info *si)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
unsigned int flags = si->flags;
if (si->sensor_bus_type != FIMC_BUS_TYPE_MIPI_CSI2) {
cfg &= ~(FLITE_REG_CIGCTRL_SELCAM_MIPI |
FLITE_REG_CIGCTRL_INVPOLPCLK |
FLITE_REG_CIGCTRL_INVPOLVSYNC |
FLITE_REG_CIGCTRL_INVPOLHREF);
if (flags & V4L2_MBUS_PCLK_SAMPLE_FALLING)
cfg |= FLITE_REG_CIGCTRL_INVPOLPCLK;
if (flags & V4L2_MBUS_VSYNC_ACTIVE_LOW)
cfg |= FLITE_REG_CIGCTRL_INVPOLVSYNC;
if (flags & V4L2_MBUS_HSYNC_ACTIVE_LOW)
cfg |= FLITE_REG_CIGCTRL_INVPOLHREF;
} else {
cfg |= FLITE_REG_CIGCTRL_SELCAM_MIPI;
}
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
flite_hw_set_camera_port(dev, si->mux_id);
}
static void flite_hw_set_out_order(struct fimc_lite *dev, struct flite_frame *f)
{
static const u32 pixcode[4][2] = {
{ V4L2_MBUS_FMT_YUYV8_2X8, FLITE_REG_CIODMAFMT_YCBYCR },
{ V4L2_MBUS_FMT_YVYU8_2X8, FLITE_REG_CIODMAFMT_YCRYCB },
{ V4L2_MBUS_FMT_UYVY8_2X8, FLITE_REG_CIODMAFMT_CBYCRY },
{ V4L2_MBUS_FMT_VYUY8_2X8, FLITE_REG_CIODMAFMT_CRYCBY },
};
u32 cfg = readl(dev->regs + FLITE_REG_CIODMAFMT);
int i = ARRAY_SIZE(pixcode);
while (--i >= 0)
if (pixcode[i][0] == f->fmt->mbus_code)
break;
cfg &= ~FLITE_REG_CIODMAFMT_YCBCR_ORDER_MASK;
writel(cfg | pixcode[i][1], dev->regs + FLITE_REG_CIODMAFMT);
}
void flite_hw_set_dma_window(struct fimc_lite *dev, struct flite_frame *f)
{
u32 cfg;
/* Maximum output pixel size */
cfg = readl(dev->regs + FLITE_REG_CIOCAN);
cfg &= ~FLITE_REG_CIOCAN_MASK;
cfg = (f->f_height << 16) | f->f_width;
writel(cfg, dev->regs + FLITE_REG_CIOCAN);
/* DMA offsets */
cfg = readl(dev->regs + FLITE_REG_CIOOFF);
cfg &= ~FLITE_REG_CIOOFF_MASK;
cfg |= (f->rect.top << 16) | f->rect.left;
writel(cfg, dev->regs + FLITE_REG_CIOOFF);
}
/* Enable/disable output DMA, set output pixel size and offsets (composition) */
void flite_hw_set_output_dma(struct fimc_lite *dev, struct flite_frame *f,
bool enable)
{
u32 cfg = readl(dev->regs + FLITE_REG_CIGCTRL);
if (!enable) {
cfg |= FLITE_REG_CIGCTRL_ODMA_DISABLE;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
return;
}
cfg &= ~FLITE_REG_CIGCTRL_ODMA_DISABLE;
writel(cfg, dev->regs + FLITE_REG_CIGCTRL);
flite_hw_set_out_order(dev, f);
flite_hw_set_dma_window(dev, f);
}
void flite_hw_dump_regs(struct fimc_lite *dev, const char *label)
{
struct {
u32 offset;
const char * const name;
} registers[] = {
{ 0x00, "CISRCSIZE" },
{ 0x04, "CIGCTRL" },
{ 0x08, "CIIMGCPT" },
{ 0x0c, "CICPTSEQ" },
{ 0x10, "CIWDOFST" },
{ 0x14, "CIWDOFST2" },
{ 0x18, "CIODMAFMT" },
{ 0x20, "CIOCAN" },
{ 0x24, "CIOOFF" },
{ 0x30, "CIOSA" },
{ 0x40, "CISTATUS" },
{ 0x44, "CISTATUS2" },
{ 0xf0, "CITHOLD" },
{ 0xfc, "CIGENERAL" },
};
u32 i;
v4l2_info(&dev->subdev, "--- %s ---\n", label);
for (i = 0; i < ARRAY_SIZE(registers); i++) {
u32 cfg = readl(dev->regs + registers[i].offset);
v4l2_info(&dev->subdev, "%9s: 0x%08x\n",
registers[i].name, cfg);
}
}
| gpl-2.0 |
profglavcho/test | drivers/media/platform/exynos4-is/fimc-core.c | 2096 | 32588 | /*
* Samsung S5P/EXYNOS4 SoC series FIMC (CAMIF) driver
*
* Copyright (C) 2010-2012 Samsung Electronics Co., Ltd.
* Sylwester Nawrocki <s.nawrocki@samsung.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 2 of the License,
* or (at your option) any later version.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/errno.h>
#include <linux/bug.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/list.h>
#include <linux/mfd/syscon.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/of_device.h>
#include <linux/slab.h>
#include <linux/clk.h>
#include <media/v4l2-ioctl.h>
#include <media/videobuf2-core.h>
#include <media/videobuf2-dma-contig.h>
#include "fimc-core.h"
#include "fimc-reg.h"
#include "media-dev.h"
static char *fimc_clocks[MAX_FIMC_CLOCKS] = {
"sclk_fimc", "fimc"
};
static struct fimc_fmt fimc_formats[] = {
{
.name = "RGB565",
.fourcc = V4L2_PIX_FMT_RGB565,
.depth = { 16 },
.color = FIMC_FMT_RGB565,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "BGR666",
.fourcc = V4L2_PIX_FMT_BGR666,
.depth = { 32 },
.color = FIMC_FMT_RGB666,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M,
}, {
.name = "ARGB8888, 32 bpp",
.fourcc = V4L2_PIX_FMT_RGB32,
.depth = { 32 },
.color = FIMC_FMT_RGB888,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M | FMT_HAS_ALPHA,
}, {
.name = "ARGB1555",
.fourcc = V4L2_PIX_FMT_RGB555,
.depth = { 16 },
.color = FIMC_FMT_RGB555,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "ARGB4444",
.fourcc = V4L2_PIX_FMT_RGB444,
.depth = { 16 },
.color = FIMC_FMT_RGB444,
.memplanes = 1,
.colplanes = 1,
.flags = FMT_FLAGS_M2M_OUT | FMT_HAS_ALPHA,
}, {
.name = "YUV 4:4:4",
.mbus_code = V4L2_MBUS_FMT_YUV10_1X30,
.flags = FMT_FLAGS_WRITEBACK,
}, {
.name = "YUV 4:2:2 packed, YCbYCr",
.fourcc = V4L2_PIX_FMT_YUYV,
.depth = { 16 },
.color = FIMC_FMT_YCBYCR422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YUYV8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CbYCrY",
.fourcc = V4L2_PIX_FMT_UYVY,
.depth = { 16 },
.color = FIMC_FMT_CBYCRY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_UYVY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, CrYCbY",
.fourcc = V4L2_PIX_FMT_VYUY,
.depth = { 16 },
.color = FIMC_FMT_CRYCBY422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_VYUY8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 packed, YCrYCb",
.fourcc = V4L2_PIX_FMT_YVYU,
.depth = { 16 },
.color = FIMC_FMT_YCRYCB422,
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_YVYU8_2X8,
.flags = FMT_FLAGS_M2M | FMT_FLAGS_CAM,
}, {
.name = "YUV 4:2:2 planar, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV422P,
.depth = { 12 },
.color = FIMC_FMT_YCBYCR422,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV16,
.depth = { 16 },
.color = FIMC_FMT_YCBYCR422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:2 planar, Y/CrCb",
.fourcc = V4L2_PIX_FMT_NV61,
.depth = { 16 },
.color = FIMC_FMT_YCRYCB422,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, YCbCr",
.fourcc = V4L2_PIX_FMT_YUV420,
.depth = { 12 },
.color = FIMC_FMT_YCBCR420,
.memplanes = 1,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 planar, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12,
.depth = { 12 },
.color = FIMC_FMT_YCBCR420,
.memplanes = 1,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contig. 2p, Y/CbCr",
.fourcc = V4L2_PIX_FMT_NV12M,
.color = FIMC_FMT_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contig. 3p, Y/Cb/Cr",
.fourcc = V4L2_PIX_FMT_YUV420M,
.color = FIMC_FMT_YCBCR420,
.depth = { 8, 2, 2 },
.memplanes = 3,
.colplanes = 3,
.flags = FMT_FLAGS_M2M,
}, {
.name = "YUV 4:2:0 non-contig. 2p, tiled",
.fourcc = V4L2_PIX_FMT_NV12MT,
.color = FIMC_FMT_YCBCR420,
.depth = { 8, 4 },
.memplanes = 2,
.colplanes = 2,
.flags = FMT_FLAGS_M2M,
}, {
.name = "JPEG encoded data",
.fourcc = V4L2_PIX_FMT_JPEG,
.color = FIMC_FMT_JPEG,
.depth = { 8 },
.memplanes = 1,
.colplanes = 1,
.mbus_code = V4L2_MBUS_FMT_JPEG_1X8,
.flags = FMT_FLAGS_CAM | FMT_FLAGS_COMPRESSED,
}, {
.name = "S5C73MX interleaved UYVY/JPEG",
.fourcc = V4L2_PIX_FMT_S5C_UYVY_JPG,
.color = FIMC_FMT_YUYV_JPEG,
.depth = { 8 },
.memplanes = 2,
.colplanes = 1,
.mdataplanes = 0x2, /* plane 1 holds frame meta data */
.mbus_code = V4L2_MBUS_FMT_S5C_UYVY_JPEG_1X8,
.flags = FMT_FLAGS_CAM | FMT_FLAGS_COMPRESSED,
},
};
struct fimc_fmt *fimc_get_format(unsigned int index)
{
if (index >= ARRAY_SIZE(fimc_formats))
return NULL;
return &fimc_formats[index];
}
void __fimc_vidioc_querycap(struct device *dev, struct v4l2_capability *cap,
unsigned int caps)
{
strlcpy(cap->driver, dev->driver->name, sizeof(cap->driver));
strlcpy(cap->card, dev->driver->name, sizeof(cap->card));
snprintf(cap->bus_info, sizeof(cap->bus_info),
"platform:%s", dev_name(dev));
cap->device_caps = caps;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
}
int fimc_check_scaler_ratio(struct fimc_ctx *ctx, int sw, int sh,
int dw, int dh, int rotation)
{
if (rotation == 90 || rotation == 270)
swap(dw, dh);
if (!ctx->scaler.enabled)
return (sw == dw && sh == dh) ? 0 : -EINVAL;
if ((sw >= SCALER_MAX_HRATIO * dw) || (sh >= SCALER_MAX_VRATIO * dh))
return -EINVAL;
return 0;
}
static int fimc_get_scaler_factor(u32 src, u32 tar, u32 *ratio, u32 *shift)
{
u32 sh = 6;
if (src >= 64 * tar)
return -EINVAL;
while (sh--) {
u32 tmp = 1 << sh;
if (src >= tar * tmp) {
*shift = sh, *ratio = tmp;
return 0;
}
}
*shift = 0, *ratio = 1;
return 0;
}
int fimc_set_scaler_info(struct fimc_ctx *ctx)
{
const struct fimc_variant *variant = ctx->fimc_dev->variant;
struct device *dev = &ctx->fimc_dev->pdev->dev;
struct fimc_scaler *sc = &ctx->scaler;
struct fimc_frame *s_frame = &ctx->s_frame;
struct fimc_frame *d_frame = &ctx->d_frame;
int tx, ty, sx, sy;
int ret;
if (ctx->rotation == 90 || ctx->rotation == 270) {
ty = d_frame->width;
tx = d_frame->height;
} else {
tx = d_frame->width;
ty = d_frame->height;
}
if (tx <= 0 || ty <= 0) {
dev_err(dev, "Invalid target size: %dx%d\n", tx, ty);
return -EINVAL;
}
sx = s_frame->width;
sy = s_frame->height;
if (sx <= 0 || sy <= 0) {
dev_err(dev, "Invalid source size: %dx%d\n", sx, sy);
return -EINVAL;
}
sc->real_width = sx;
sc->real_height = sy;
ret = fimc_get_scaler_factor(sx, tx, &sc->pre_hratio, &sc->hfactor);
if (ret)
return ret;
ret = fimc_get_scaler_factor(sy, ty, &sc->pre_vratio, &sc->vfactor);
if (ret)
return ret;
sc->pre_dst_width = sx / sc->pre_hratio;
sc->pre_dst_height = sy / sc->pre_vratio;
if (variant->has_mainscaler_ext) {
sc->main_hratio = (sx << 14) / (tx << sc->hfactor);
sc->main_vratio = (sy << 14) / (ty << sc->vfactor);
} else {
sc->main_hratio = (sx << 8) / (tx << sc->hfactor);
sc->main_vratio = (sy << 8) / (ty << sc->vfactor);
}
sc->scaleup_h = (tx >= sx) ? 1 : 0;
sc->scaleup_v = (ty >= sy) ? 1 : 0;
/* check to see if input and output size/format differ */
if (s_frame->fmt->color == d_frame->fmt->color
&& s_frame->width == d_frame->width
&& s_frame->height == d_frame->height)
sc->copy_mode = 1;
else
sc->copy_mode = 0;
return 0;
}
static irqreturn_t fimc_irq_handler(int irq, void *priv)
{
struct fimc_dev *fimc = priv;
struct fimc_ctx *ctx;
fimc_hw_clear_irq(fimc);
spin_lock(&fimc->slock);
if (test_and_clear_bit(ST_M2M_PEND, &fimc->state)) {
if (test_and_clear_bit(ST_M2M_SUSPENDING, &fimc->state)) {
set_bit(ST_M2M_SUSPENDED, &fimc->state);
wake_up(&fimc->irq_queue);
goto out;
}
ctx = v4l2_m2m_get_curr_priv(fimc->m2m.m2m_dev);
if (ctx != NULL) {
spin_unlock(&fimc->slock);
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_DONE);
if (ctx->state & FIMC_CTX_SHUT) {
ctx->state &= ~FIMC_CTX_SHUT;
wake_up(&fimc->irq_queue);
}
return IRQ_HANDLED;
}
} else if (test_bit(ST_CAPT_PEND, &fimc->state)) {
int last_buf = test_bit(ST_CAPT_JPEG, &fimc->state) &&
fimc->vid_cap.reqbufs_count == 1;
fimc_capture_irq_handler(fimc, !last_buf);
}
out:
spin_unlock(&fimc->slock);
return IRQ_HANDLED;
}
/* The color format (colplanes, memplanes) must be already configured. */
int fimc_prepare_addr(struct fimc_ctx *ctx, struct vb2_buffer *vb,
struct fimc_frame *frame, struct fimc_addr *paddr)
{
int ret = 0;
u32 pix_size;
if (vb == NULL || frame == NULL)
return -EINVAL;
pix_size = frame->width * frame->height;
dbg("memplanes= %d, colplanes= %d, pix_size= %d",
frame->fmt->memplanes, frame->fmt->colplanes, pix_size);
paddr->y = vb2_dma_contig_plane_dma_addr(vb, 0);
if (frame->fmt->memplanes == 1) {
switch (frame->fmt->colplanes) {
case 1:
paddr->cb = 0;
paddr->cr = 0;
break;
case 2:
/* decompose Y into Y/Cb */
paddr->cb = (u32)(paddr->y + pix_size);
paddr->cr = 0;
break;
case 3:
paddr->cb = (u32)(paddr->y + pix_size);
/* decompose Y into Y/Cb/Cr */
if (FIMC_FMT_YCBCR420 == frame->fmt->color)
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 2));
else /* 422 */
paddr->cr = (u32)(paddr->cb
+ (pix_size >> 1));
break;
default:
return -EINVAL;
}
} else if (!frame->fmt->mdataplanes) {
if (frame->fmt->memplanes >= 2)
paddr->cb = vb2_dma_contig_plane_dma_addr(vb, 1);
if (frame->fmt->memplanes == 3)
paddr->cr = vb2_dma_contig_plane_dma_addr(vb, 2);
}
dbg("PHYS_ADDR: y= 0x%X cb= 0x%X cr= 0x%X ret= %d",
paddr->y, paddr->cb, paddr->cr, ret);
return ret;
}
/* Set order for 1 and 2 plane YCBCR 4:2:2 formats. */
void fimc_set_yuv_order(struct fimc_ctx *ctx)
{
/* The one only mode supported in SoC. */
ctx->in_order_2p = FIMC_REG_CIOCTRL_ORDER422_2P_LSB_CRCB;
ctx->out_order_2p = FIMC_REG_CIOCTRL_ORDER422_2P_LSB_CRCB;
/* Set order for 1 plane input formats. */
switch (ctx->s_frame.fmt->color) {
case FIMC_FMT_YCRYCB422:
ctx->in_order_1p = FIMC_REG_MSCTRL_ORDER422_YCRYCB;
break;
case FIMC_FMT_CBYCRY422:
ctx->in_order_1p = FIMC_REG_MSCTRL_ORDER422_CBYCRY;
break;
case FIMC_FMT_CRYCBY422:
ctx->in_order_1p = FIMC_REG_MSCTRL_ORDER422_CRYCBY;
break;
case FIMC_FMT_YCBYCR422:
default:
ctx->in_order_1p = FIMC_REG_MSCTRL_ORDER422_YCBYCR;
break;
}
dbg("ctx->in_order_1p= %d", ctx->in_order_1p);
switch (ctx->d_frame.fmt->color) {
case FIMC_FMT_YCRYCB422:
ctx->out_order_1p = FIMC_REG_CIOCTRL_ORDER422_YCRYCB;
break;
case FIMC_FMT_CBYCRY422:
ctx->out_order_1p = FIMC_REG_CIOCTRL_ORDER422_CBYCRY;
break;
case FIMC_FMT_CRYCBY422:
ctx->out_order_1p = FIMC_REG_CIOCTRL_ORDER422_CRYCBY;
break;
case FIMC_FMT_YCBYCR422:
default:
ctx->out_order_1p = FIMC_REG_CIOCTRL_ORDER422_YCBYCR;
break;
}
dbg("ctx->out_order_1p= %d", ctx->out_order_1p);
}
void fimc_prepare_dma_offset(struct fimc_ctx *ctx, struct fimc_frame *f)
{
bool pix_hoff = ctx->fimc_dev->drv_data->dma_pix_hoff;
u32 i, depth = 0;
for (i = 0; i < f->fmt->colplanes; i++)
depth += f->fmt->depth[i];
f->dma_offset.y_h = f->offs_h;
if (!pix_hoff)
f->dma_offset.y_h *= (depth >> 3);
f->dma_offset.y_v = f->offs_v;
f->dma_offset.cb_h = f->offs_h;
f->dma_offset.cb_v = f->offs_v;
f->dma_offset.cr_h = f->offs_h;
f->dma_offset.cr_v = f->offs_v;
if (!pix_hoff) {
if (f->fmt->colplanes == 3) {
f->dma_offset.cb_h >>= 1;
f->dma_offset.cr_h >>= 1;
}
if (f->fmt->color == FIMC_FMT_YCBCR420) {
f->dma_offset.cb_v >>= 1;
f->dma_offset.cr_v >>= 1;
}
}
dbg("in_offset: color= %d, y_h= %d, y_v= %d",
f->fmt->color, f->dma_offset.y_h, f->dma_offset.y_v);
}
static int fimc_set_color_effect(struct fimc_ctx *ctx, enum v4l2_colorfx colorfx)
{
struct fimc_effect *effect = &ctx->effect;
switch (colorfx) {
case V4L2_COLORFX_NONE:
effect->type = FIMC_REG_CIIMGEFF_FIN_BYPASS;
break;
case V4L2_COLORFX_BW:
effect->type = FIMC_REG_CIIMGEFF_FIN_ARBITRARY;
effect->pat_cb = 128;
effect->pat_cr = 128;
break;
case V4L2_COLORFX_SEPIA:
effect->type = FIMC_REG_CIIMGEFF_FIN_ARBITRARY;
effect->pat_cb = 115;
effect->pat_cr = 145;
break;
case V4L2_COLORFX_NEGATIVE:
effect->type = FIMC_REG_CIIMGEFF_FIN_NEGATIVE;
break;
case V4L2_COLORFX_EMBOSS:
effect->type = FIMC_REG_CIIMGEFF_FIN_EMBOSSING;
break;
case V4L2_COLORFX_ART_FREEZE:
effect->type = FIMC_REG_CIIMGEFF_FIN_ARTFREEZE;
break;
case V4L2_COLORFX_SILHOUETTE:
effect->type = FIMC_REG_CIIMGEFF_FIN_SILHOUETTE;
break;
case V4L2_COLORFX_SET_CBCR:
effect->type = FIMC_REG_CIIMGEFF_FIN_ARBITRARY;
effect->pat_cb = ctx->ctrls.colorfx_cbcr->val >> 8;
effect->pat_cr = ctx->ctrls.colorfx_cbcr->val & 0xff;
break;
default:
return -EINVAL;
}
return 0;
}
/*
* V4L2 controls handling
*/
#define ctrl_to_ctx(__ctrl) \
container_of((__ctrl)->handler, struct fimc_ctx, ctrls.handler)
static int __fimc_s_ctrl(struct fimc_ctx *ctx, struct v4l2_ctrl *ctrl)
{
struct fimc_dev *fimc = ctx->fimc_dev;
const struct fimc_variant *variant = fimc->variant;
int ret = 0;
if (ctrl->flags & V4L2_CTRL_FLAG_INACTIVE)
return 0;
switch (ctrl->id) {
case V4L2_CID_HFLIP:
ctx->hflip = ctrl->val;
break;
case V4L2_CID_VFLIP:
ctx->vflip = ctrl->val;
break;
case V4L2_CID_ROTATE:
if (fimc_capture_pending(fimc)) {
ret = fimc_check_scaler_ratio(ctx, ctx->s_frame.width,
ctx->s_frame.height, ctx->d_frame.width,
ctx->d_frame.height, ctrl->val);
if (ret)
return -EINVAL;
}
if ((ctrl->val == 90 || ctrl->val == 270) &&
!variant->has_out_rot)
return -EINVAL;
ctx->rotation = ctrl->val;
break;
case V4L2_CID_ALPHA_COMPONENT:
ctx->d_frame.alpha = ctrl->val;
break;
case V4L2_CID_COLORFX:
ret = fimc_set_color_effect(ctx, ctrl->val);
if (ret)
return ret;
break;
}
ctx->state |= FIMC_PARAMS;
set_bit(ST_CAPT_APPLY_CFG, &fimc->state);
return 0;
}
static int fimc_s_ctrl(struct v4l2_ctrl *ctrl)
{
struct fimc_ctx *ctx = ctrl_to_ctx(ctrl);
unsigned long flags;
int ret;
spin_lock_irqsave(&ctx->fimc_dev->slock, flags);
ret = __fimc_s_ctrl(ctx, ctrl);
spin_unlock_irqrestore(&ctx->fimc_dev->slock, flags);
return ret;
}
static const struct v4l2_ctrl_ops fimc_ctrl_ops = {
.s_ctrl = fimc_s_ctrl,
};
int fimc_ctrls_create(struct fimc_ctx *ctx)
{
unsigned int max_alpha = fimc_get_alpha_mask(ctx->d_frame.fmt);
struct fimc_ctrls *ctrls = &ctx->ctrls;
struct v4l2_ctrl_handler *handler = &ctrls->handler;
if (ctx->ctrls.ready)
return 0;
v4l2_ctrl_handler_init(handler, 6);
ctrls->rotate = v4l2_ctrl_new_std(handler, &fimc_ctrl_ops,
V4L2_CID_ROTATE, 0, 270, 90, 0);
ctrls->hflip = v4l2_ctrl_new_std(handler, &fimc_ctrl_ops,
V4L2_CID_HFLIP, 0, 1, 1, 0);
ctrls->vflip = v4l2_ctrl_new_std(handler, &fimc_ctrl_ops,
V4L2_CID_VFLIP, 0, 1, 1, 0);
if (ctx->fimc_dev->drv_data->alpha_color)
ctrls->alpha = v4l2_ctrl_new_std(handler, &fimc_ctrl_ops,
V4L2_CID_ALPHA_COMPONENT,
0, max_alpha, 1, 0);
else
ctrls->alpha = NULL;
ctrls->colorfx = v4l2_ctrl_new_std_menu(handler, &fimc_ctrl_ops,
V4L2_CID_COLORFX, V4L2_COLORFX_SET_CBCR,
~0x983f, V4L2_COLORFX_NONE);
ctrls->colorfx_cbcr = v4l2_ctrl_new_std(handler, &fimc_ctrl_ops,
V4L2_CID_COLORFX_CBCR, 0, 0xffff, 1, 0);
ctx->effect.type = FIMC_REG_CIIMGEFF_FIN_BYPASS;
if (!handler->error) {
v4l2_ctrl_cluster(2, &ctrls->colorfx);
ctrls->ready = true;
}
return handler->error;
}
void fimc_ctrls_delete(struct fimc_ctx *ctx)
{
struct fimc_ctrls *ctrls = &ctx->ctrls;
if (ctrls->ready) {
v4l2_ctrl_handler_free(&ctrls->handler);
ctrls->ready = false;
ctrls->alpha = NULL;
}
}
void fimc_ctrls_activate(struct fimc_ctx *ctx, bool active)
{
unsigned int has_alpha = ctx->d_frame.fmt->flags & FMT_HAS_ALPHA;
struct fimc_ctrls *ctrls = &ctx->ctrls;
if (!ctrls->ready)
return;
mutex_lock(ctrls->handler.lock);
v4l2_ctrl_activate(ctrls->rotate, active);
v4l2_ctrl_activate(ctrls->hflip, active);
v4l2_ctrl_activate(ctrls->vflip, active);
v4l2_ctrl_activate(ctrls->colorfx, active);
if (ctrls->alpha)
v4l2_ctrl_activate(ctrls->alpha, active && has_alpha);
if (active) {
fimc_set_color_effect(ctx, ctrls->colorfx->cur.val);
ctx->rotation = ctrls->rotate->val;
ctx->hflip = ctrls->hflip->val;
ctx->vflip = ctrls->vflip->val;
} else {
ctx->effect.type = FIMC_REG_CIIMGEFF_FIN_BYPASS;
ctx->rotation = 0;
ctx->hflip = 0;
ctx->vflip = 0;
}
mutex_unlock(ctrls->handler.lock);
}
/* Update maximum value of the alpha color control */
void fimc_alpha_ctrl_update(struct fimc_ctx *ctx)
{
struct fimc_dev *fimc = ctx->fimc_dev;
struct v4l2_ctrl *ctrl = ctx->ctrls.alpha;
if (ctrl == NULL || !fimc->drv_data->alpha_color)
return;
v4l2_ctrl_lock(ctrl);
ctrl->maximum = fimc_get_alpha_mask(ctx->d_frame.fmt);
if (ctrl->cur.val > ctrl->maximum)
ctrl->cur.val = ctrl->maximum;
v4l2_ctrl_unlock(ctrl);
}
void __fimc_get_format(struct fimc_frame *frame, struct v4l2_format *f)
{
struct v4l2_pix_format_mplane *pixm = &f->fmt.pix_mp;
int i;
pixm->width = frame->o_width;
pixm->height = frame->o_height;
pixm->field = V4L2_FIELD_NONE;
pixm->pixelformat = frame->fmt->fourcc;
pixm->colorspace = V4L2_COLORSPACE_JPEG;
pixm->num_planes = frame->fmt->memplanes;
for (i = 0; i < pixm->num_planes; ++i) {
pixm->plane_fmt[i].bytesperline = frame->bytesperline[i];
pixm->plane_fmt[i].sizeimage = frame->payload[i];
}
}
/**
* fimc_adjust_mplane_format - adjust bytesperline/sizeimage for each plane
* @fmt: fimc pixel format description (input)
* @width: requested pixel width
* @height: requested pixel height
* @pix: multi-plane format to adjust
*/
void fimc_adjust_mplane_format(struct fimc_fmt *fmt, u32 width, u32 height,
struct v4l2_pix_format_mplane *pix)
{
u32 bytesperline = 0;
int i;
pix->colorspace = V4L2_COLORSPACE_JPEG;
pix->field = V4L2_FIELD_NONE;
pix->num_planes = fmt->memplanes;
pix->pixelformat = fmt->fourcc;
pix->height = height;
pix->width = width;
for (i = 0; i < pix->num_planes; ++i) {
struct v4l2_plane_pix_format *plane_fmt = &pix->plane_fmt[i];
u32 bpl = plane_fmt->bytesperline;
if (fmt->colplanes > 1 && (bpl == 0 || bpl < pix->width))
bpl = pix->width; /* Planar */
if (fmt->colplanes == 1 && /* Packed */
(bpl == 0 || ((bpl * 8) / fmt->depth[i]) < pix->width))
bpl = (pix->width * fmt->depth[0]) / 8;
/*
* Currently bytesperline for each plane is same, except
* V4L2_PIX_FMT_YUV420M format. This calculation may need
* to be changed when other multi-planar formats are added
* to the fimc_formats[] array.
*/
if (i == 0)
bytesperline = bpl;
else if (i == 1 && fmt->memplanes == 3)
bytesperline /= 2;
plane_fmt->bytesperline = bytesperline;
plane_fmt->sizeimage = max((pix->width * pix->height *
fmt->depth[i]) / 8, plane_fmt->sizeimage);
}
}
/**
* fimc_find_format - lookup fimc color format by fourcc or media bus format
* @pixelformat: fourcc to match, ignored if null
* @mbus_code: media bus code to match, ignored if null
* @mask: the color flags to match
* @index: offset in the fimc_formats array, ignored if negative
*/
struct fimc_fmt *fimc_find_format(const u32 *pixelformat, const u32 *mbus_code,
unsigned int mask, int index)
{
struct fimc_fmt *fmt, *def_fmt = NULL;
unsigned int i;
int id = 0;
if (index >= (int)ARRAY_SIZE(fimc_formats))
return NULL;
for (i = 0; i < ARRAY_SIZE(fimc_formats); ++i) {
fmt = &fimc_formats[i];
if (!(fmt->flags & mask))
continue;
if (pixelformat && fmt->fourcc == *pixelformat)
return fmt;
if (mbus_code && fmt->mbus_code == *mbus_code)
return fmt;
if (index == id)
def_fmt = fmt;
id++;
}
return def_fmt;
}
static void fimc_clk_put(struct fimc_dev *fimc)
{
int i;
for (i = 0; i < MAX_FIMC_CLOCKS; i++) {
if (IS_ERR(fimc->clock[i]))
continue;
clk_unprepare(fimc->clock[i]);
clk_put(fimc->clock[i]);
fimc->clock[i] = ERR_PTR(-EINVAL);
}
}
static int fimc_clk_get(struct fimc_dev *fimc)
{
int i, ret;
for (i = 0; i < MAX_FIMC_CLOCKS; i++)
fimc->clock[i] = ERR_PTR(-EINVAL);
for (i = 0; i < MAX_FIMC_CLOCKS; i++) {
fimc->clock[i] = clk_get(&fimc->pdev->dev, fimc_clocks[i]);
if (IS_ERR(fimc->clock[i])) {
ret = PTR_ERR(fimc->clock[i]);
goto err;
}
ret = clk_prepare(fimc->clock[i]);
if (ret < 0) {
clk_put(fimc->clock[i]);
fimc->clock[i] = ERR_PTR(-EINVAL);
goto err;
}
}
return 0;
err:
fimc_clk_put(fimc);
dev_err(&fimc->pdev->dev, "failed to get clock: %s\n",
fimc_clocks[i]);
return -ENXIO;
}
static int fimc_m2m_suspend(struct fimc_dev *fimc)
{
unsigned long flags;
int timeout;
spin_lock_irqsave(&fimc->slock, flags);
if (!fimc_m2m_pending(fimc)) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
clear_bit(ST_M2M_SUSPENDED, &fimc->state);
set_bit(ST_M2M_SUSPENDING, &fimc->state);
spin_unlock_irqrestore(&fimc->slock, flags);
timeout = wait_event_timeout(fimc->irq_queue,
test_bit(ST_M2M_SUSPENDED, &fimc->state),
FIMC_SHUTDOWN_TIMEOUT);
clear_bit(ST_M2M_SUSPENDING, &fimc->state);
return timeout == 0 ? -EAGAIN : 0;
}
static int fimc_m2m_resume(struct fimc_dev *fimc)
{
struct fimc_ctx *ctx;
unsigned long flags;
spin_lock_irqsave(&fimc->slock, flags);
/* Clear for full H/W setup in first run after resume */
ctx = fimc->m2m.ctx;
fimc->m2m.ctx = NULL;
spin_unlock_irqrestore(&fimc->slock, flags);
if (test_and_clear_bit(ST_M2M_SUSPENDED, &fimc->state))
fimc_m2m_job_finish(ctx, VB2_BUF_STATE_ERROR);
return 0;
}
static const struct of_device_id fimc_of_match[];
static int fimc_parse_dt(struct fimc_dev *fimc, u32 *clk_freq)
{
struct device *dev = &fimc->pdev->dev;
struct device_node *node = dev->of_node;
const struct of_device_id *of_id;
struct fimc_variant *v;
struct fimc_pix_limit *lim;
u32 args[FIMC_PIX_LIMITS_MAX];
int ret;
if (of_property_read_bool(node, "samsung,lcd-wb"))
return -ENODEV;
v = devm_kzalloc(dev, sizeof(*v) + sizeof(*lim), GFP_KERNEL);
if (!v)
return -ENOMEM;
of_id = of_match_node(fimc_of_match, node);
if (!of_id)
return -EINVAL;
fimc->drv_data = of_id->data;
ret = of_property_read_u32_array(node, "samsung,pix-limits",
args, FIMC_PIX_LIMITS_MAX);
if (ret < 0)
return ret;
lim = (struct fimc_pix_limit *)&v[1];
lim->scaler_en_w = args[0];
lim->scaler_dis_w = args[1];
lim->out_rot_en_w = args[2];
lim->out_rot_dis_w = args[3];
v->pix_limit = lim;
ret = of_property_read_u32_array(node, "samsung,min-pix-sizes",
args, 2);
v->min_inp_pixsize = ret ? FIMC_DEF_MIN_SIZE : args[0];
v->min_out_pixsize = ret ? FIMC_DEF_MIN_SIZE : args[1];
ret = of_property_read_u32_array(node, "samsung,min-pix-alignment",
args, 2);
v->min_vsize_align = ret ? FIMC_DEF_HEIGHT_ALIGN : args[0];
v->hor_offs_align = ret ? FIMC_DEF_HOR_OFFS_ALIGN : args[1];
ret = of_property_read_u32(node, "samsung,rotators", &args[1]);
v->has_inp_rot = ret ? 1 : args[1] & 0x01;
v->has_out_rot = ret ? 1 : args[1] & 0x10;
v->has_mainscaler_ext = of_property_read_bool(node,
"samsung,mainscaler-ext");
v->has_isp_wb = of_property_read_bool(node, "samsung,isp-wb");
v->has_cam_if = of_property_read_bool(node, "samsung,cam-if");
of_property_read_u32(node, "clock-frequency", clk_freq);
fimc->id = of_alias_get_id(node, "fimc");
fimc->variant = v;
return 0;
}
static int fimc_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
u32 lclk_freq = 0;
struct fimc_dev *fimc;
struct resource *res;
int ret = 0;
fimc = devm_kzalloc(dev, sizeof(*fimc), GFP_KERNEL);
if (!fimc)
return -ENOMEM;
fimc->pdev = pdev;
if (dev->of_node) {
ret = fimc_parse_dt(fimc, &lclk_freq);
if (ret < 0)
return ret;
} else {
fimc->drv_data = fimc_get_drvdata(pdev);
fimc->id = pdev->id;
}
if (!fimc->drv_data || fimc->id >= fimc->drv_data->num_entities ||
fimc->id < 0) {
dev_err(dev, "Invalid driver data or device id (%d)\n",
fimc->id);
return -EINVAL;
}
if (!dev->of_node)
fimc->variant = fimc->drv_data->variant[fimc->id];
init_waitqueue_head(&fimc->irq_queue);
spin_lock_init(&fimc->slock);
mutex_init(&fimc->lock);
fimc->sysreg = fimc_get_sysreg_regmap(dev->of_node);
if (IS_ERR(fimc->sysreg))
return PTR_ERR(fimc->sysreg);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
fimc->regs = devm_ioremap_resource(dev, res);
if (IS_ERR(fimc->regs))
return PTR_ERR(fimc->regs);
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (res == NULL) {
dev_err(dev, "Failed to get IRQ resource\n");
return -ENXIO;
}
ret = fimc_clk_get(fimc);
if (ret)
return ret;
if (lclk_freq == 0)
lclk_freq = fimc->drv_data->lclk_frequency;
ret = clk_set_rate(fimc->clock[CLK_BUS], lclk_freq);
if (ret < 0)
return ret;
ret = clk_enable(fimc->clock[CLK_BUS]);
if (ret < 0)
return ret;
ret = devm_request_irq(dev, res->start, fimc_irq_handler,
0, dev_name(dev), fimc);
if (ret) {
dev_err(dev, "failed to install irq (%d)\n", ret);
goto err_clk;
}
ret = fimc_initialize_capture_subdev(fimc);
if (ret)
goto err_clk;
platform_set_drvdata(pdev, fimc);
pm_runtime_enable(dev);
ret = pm_runtime_get_sync(dev);
if (ret < 0)
goto err_sd;
/* Initialize contiguous memory allocator */
fimc->alloc_ctx = vb2_dma_contig_init_ctx(dev);
if (IS_ERR(fimc->alloc_ctx)) {
ret = PTR_ERR(fimc->alloc_ctx);
goto err_pm;
}
dev_dbg(dev, "FIMC.%d registered successfully\n", fimc->id);
pm_runtime_put(dev);
return 0;
err_pm:
pm_runtime_put(dev);
err_sd:
fimc_unregister_capture_subdev(fimc);
err_clk:
clk_disable(fimc->clock[CLK_BUS]);
fimc_clk_put(fimc);
return ret;
}
static int fimc_runtime_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Enable clocks and perform basic initalization */
clk_enable(fimc->clock[CLK_GATE]);
fimc_hw_reset(fimc);
/* Resume the capture or mem-to-mem device */
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_runtime_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
int ret = 0;
if (fimc_capture_busy(fimc))
ret = fimc_capture_suspend(fimc);
else
ret = fimc_m2m_suspend(fimc);
if (!ret)
clk_disable(fimc->clock[CLK_GATE]);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
return ret;
}
#ifdef CONFIG_PM_SLEEP
static int fimc_resume(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
unsigned long flags;
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
/* Do not resume if the device was idle before system suspend */
spin_lock_irqsave(&fimc->slock, flags);
if (!test_and_clear_bit(ST_LPM, &fimc->state) ||
(!fimc_m2m_active(fimc) && !fimc_capture_busy(fimc))) {
spin_unlock_irqrestore(&fimc->slock, flags);
return 0;
}
fimc_hw_reset(fimc);
spin_unlock_irqrestore(&fimc->slock, flags);
if (fimc_capture_busy(fimc))
return fimc_capture_resume(fimc);
return fimc_m2m_resume(fimc);
}
static int fimc_suspend(struct device *dev)
{
struct fimc_dev *fimc = dev_get_drvdata(dev);
dbg("fimc%d: state: 0x%lx", fimc->id, fimc->state);
if (test_and_set_bit(ST_LPM, &fimc->state))
return 0;
if (fimc_capture_busy(fimc))
return fimc_capture_suspend(fimc);
return fimc_m2m_suspend(fimc);
}
#endif /* CONFIG_PM_SLEEP */
static int fimc_remove(struct platform_device *pdev)
{
struct fimc_dev *fimc = platform_get_drvdata(pdev);
pm_runtime_disable(&pdev->dev);
pm_runtime_set_suspended(&pdev->dev);
fimc_unregister_capture_subdev(fimc);
vb2_dma_contig_cleanup_ctx(fimc->alloc_ctx);
clk_disable(fimc->clock[CLK_BUS]);
fimc_clk_put(fimc);
dev_info(&pdev->dev, "driver unloaded\n");
return 0;
}
/* Image pixel limits, similar across several FIMC HW revisions. */
static const struct fimc_pix_limit s5p_pix_limit[4] = {
[0] = {
.scaler_en_w = 3264,
.scaler_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[1] = {
.scaler_en_w = 4224,
.scaler_dis_w = 8192,
.out_rot_en_w = 1920,
.out_rot_dis_w = 4224,
},
[2] = {
.scaler_en_w = 1920,
.scaler_dis_w = 8192,
.out_rot_en_w = 1280,
.out_rot_dis_w = 1920,
},
};
static const struct fimc_variant fimc0_variant_s5p = {
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.pix_limit = &s5p_pix_limit[0],
};
static const struct fimc_variant fimc2_variant_s5p = {
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.pix_limit = &s5p_pix_limit[1],
};
static const struct fimc_variant fimc0_variant_s5pv210 = {
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.pix_limit = &s5p_pix_limit[1],
};
static const struct fimc_variant fimc1_variant_s5pv210 = {
.has_inp_rot = 1,
.has_out_rot = 1,
.has_cam_if = 1,
.has_mainscaler_ext = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 1,
.min_vsize_align = 1,
.pix_limit = &s5p_pix_limit[2],
};
static const struct fimc_variant fimc2_variant_s5pv210 = {
.has_cam_if = 1,
.min_inp_pixsize = 16,
.min_out_pixsize = 16,
.hor_offs_align = 8,
.min_vsize_align = 16,
.pix_limit = &s5p_pix_limit[2],
};
/* S5PC100 */
static const struct fimc_drvdata fimc_drvdata_s5p = {
.variant = {
[0] = &fimc0_variant_s5p,
[1] = &fimc0_variant_s5p,
[2] = &fimc2_variant_s5p,
},
.num_entities = 3,
.lclk_frequency = 133000000UL,
.out_buf_count = 4,
};
/* S5PV210, S5PC110 */
static const struct fimc_drvdata fimc_drvdata_s5pv210 = {
.variant = {
[0] = &fimc0_variant_s5pv210,
[1] = &fimc1_variant_s5pv210,
[2] = &fimc2_variant_s5pv210,
},
.num_entities = 3,
.lclk_frequency = 166000000UL,
.out_buf_count = 4,
.dma_pix_hoff = 1,
};
/* EXYNOS4210, S5PV310, S5PC210 */
static const struct fimc_drvdata fimc_drvdata_exynos4210 = {
.num_entities = 4,
.lclk_frequency = 166000000UL,
.dma_pix_hoff = 1,
.cistatus2 = 1,
.alpha_color = 1,
.out_buf_count = 32,
};
/* EXYNOS4212, EXYNOS4412 */
static const struct fimc_drvdata fimc_drvdata_exynos4x12 = {
.num_entities = 4,
.lclk_frequency = 166000000UL,
.dma_pix_hoff = 1,
.cistatus2 = 1,
.alpha_color = 1,
.out_buf_count = 32,
};
static const struct platform_device_id fimc_driver_ids[] = {
{
.name = "s5p-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5p,
}, {
.name = "s5pv210-fimc",
.driver_data = (unsigned long)&fimc_drvdata_s5pv210,
}, {
.name = "exynos4-fimc",
.driver_data = (unsigned long)&fimc_drvdata_exynos4210,
}, {
.name = "exynos4x12-fimc",
.driver_data = (unsigned long)&fimc_drvdata_exynos4x12,
},
{ },
};
static const struct of_device_id fimc_of_match[] = {
{
.compatible = "samsung,s5pv210-fimc",
.data = &fimc_drvdata_s5pv210,
}, {
.compatible = "samsung,exynos4210-fimc",
.data = &fimc_drvdata_exynos4210,
}, {
.compatible = "samsung,exynos4212-fimc",
.data = &fimc_drvdata_exynos4x12,
},
{ /* sentinel */ },
};
static const struct dev_pm_ops fimc_pm_ops = {
SET_SYSTEM_SLEEP_PM_OPS(fimc_suspend, fimc_resume)
SET_RUNTIME_PM_OPS(fimc_runtime_suspend, fimc_runtime_resume, NULL)
};
static struct platform_driver fimc_driver = {
.probe = fimc_probe,
.remove = fimc_remove,
.id_table = fimc_driver_ids,
.driver = {
.of_match_table = fimc_of_match,
.name = FIMC_DRIVER_NAME,
.owner = THIS_MODULE,
.pm = &fimc_pm_ops,
}
};
int __init fimc_register_driver(void)
{
return platform_driver_register(&fimc_driver);
}
void __exit fimc_unregister_driver(void)
{
platform_driver_unregister(&fimc_driver);
}
| gpl-2.0 |
miuihu/android_kernel_xiaomi_redmi2 | drivers/input/serio/apbps2.c | 2608 | 5809 | /*
* Copyright (C) 2013 Aeroflex Gaisler
*
* This driver supports the APBPS2 PS/2 core available in the GRLIB
* VHDL IP core library.
*
* Full documentation of the APBPS2 core can be found here:
* http://www.gaisler.com/products/grlib/grip.pdf
*
* See "Documentation/devicetree/bindings/input/ps2keyb-mouse-apbps2.txt" for
* information on open firmware properties.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* Contributors: Daniel Hellstrom <daniel@gaisler.com>
*/
#include <linux/platform_device.h>
#include <linux/of_device.h>
#include <linux/module.h>
#include <linux/serio.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/of_irq.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/io.h>
struct apbps2_regs {
u32 __iomem data; /* 0x00 */
u32 __iomem status; /* 0x04 */
u32 __iomem ctrl; /* 0x08 */
u32 __iomem reload; /* 0x0c */
};
#define APBPS2_STATUS_DR (1<<0)
#define APBPS2_STATUS_PE (1<<1)
#define APBPS2_STATUS_FE (1<<2)
#define APBPS2_STATUS_KI (1<<3)
#define APBPS2_STATUS_RF (1<<4)
#define APBPS2_STATUS_TF (1<<5)
#define APBPS2_STATUS_TCNT (0x1f<<22)
#define APBPS2_STATUS_RCNT (0x1f<<27)
#define APBPS2_CTRL_RE (1<<0)
#define APBPS2_CTRL_TE (1<<1)
#define APBPS2_CTRL_RI (1<<2)
#define APBPS2_CTRL_TI (1<<3)
struct apbps2_priv {
struct serio *io;
struct apbps2_regs *regs;
};
static int apbps2_idx;
static irqreturn_t apbps2_isr(int irq, void *dev_id)
{
struct apbps2_priv *priv = dev_id;
unsigned long status, data, rxflags;
irqreturn_t ret = IRQ_NONE;
while ((status = ioread32be(&priv->regs->status)) & APBPS2_STATUS_DR) {
data = ioread32be(&priv->regs->data);
rxflags = (status & APBPS2_STATUS_PE) ? SERIO_PARITY : 0;
rxflags |= (status & APBPS2_STATUS_FE) ? SERIO_FRAME : 0;
/* clear error bits? */
if (rxflags)
iowrite32be(0, &priv->regs->status);
serio_interrupt(priv->io, data, rxflags);
ret = IRQ_HANDLED;
}
return ret;
}
static int apbps2_write(struct serio *io, unsigned char val)
{
struct apbps2_priv *priv = io->port_data;
unsigned int tleft = 10000; /* timeout in 100ms */
/* delay until PS/2 controller has room for more chars */
while ((ioread32be(&priv->regs->status) & APBPS2_STATUS_TF) && tleft--)
udelay(10);
if ((ioread32be(&priv->regs->status) & APBPS2_STATUS_TF) == 0) {
iowrite32be(val, &priv->regs->data);
iowrite32be(APBPS2_CTRL_RE | APBPS2_CTRL_RI | APBPS2_CTRL_TE,
&priv->regs->ctrl);
return 0;
}
return -ETIMEDOUT;
}
static int apbps2_open(struct serio *io)
{
struct apbps2_priv *priv = io->port_data;
int limit;
unsigned long tmp;
/* clear error flags */
iowrite32be(0, &priv->regs->status);
/* Clear old data if available (unlikely) */
limit = 1024;
while ((ioread32be(&priv->regs->status) & APBPS2_STATUS_DR) && --limit)
tmp = ioread32be(&priv->regs->data);
/* Enable reciever and it's interrupt */
iowrite32be(APBPS2_CTRL_RE | APBPS2_CTRL_RI, &priv->regs->ctrl);
return 0;
}
static void apbps2_close(struct serio *io)
{
struct apbps2_priv *priv = io->port_data;
/* stop interrupts at PS/2 HW level */
iowrite32be(0, &priv->regs->ctrl);
}
/* Initialize one APBPS2 PS/2 core */
static int apbps2_of_probe(struct platform_device *ofdev)
{
struct apbps2_priv *priv;
int irq, err;
u32 freq_hz;
struct resource *res;
priv = devm_kzalloc(&ofdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv) {
dev_err(&ofdev->dev, "memory allocation failed\n");
return -ENOMEM;
}
/* Find Device Address */
res = platform_get_resource(ofdev, IORESOURCE_MEM, 0);
priv->regs = devm_ioremap_resource(&ofdev->dev, res);
if (IS_ERR(priv->regs))
return PTR_ERR(priv->regs);
/* Reset hardware, disable interrupt */
iowrite32be(0, &priv->regs->ctrl);
/* IRQ */
irq = irq_of_parse_and_map(ofdev->dev.of_node, 0);
err = devm_request_irq(&ofdev->dev, irq, apbps2_isr,
IRQF_SHARED, "apbps2", priv);
if (err) {
dev_err(&ofdev->dev, "request IRQ%d failed\n", irq);
return err;
}
/* Get core frequency */
if (of_property_read_u32(ofdev->dev.of_node, "freq", &freq_hz)) {
dev_err(&ofdev->dev, "unable to get core frequency\n");
return -EINVAL;
}
/* Set reload register to core freq in kHz/10 */
iowrite32be(freq_hz / 10000, &priv->regs->reload);
priv->io = kzalloc(sizeof(struct serio), GFP_KERNEL);
if (!priv->io)
return -ENOMEM;
priv->io->id.type = SERIO_8042;
priv->io->open = apbps2_open;
priv->io->close = apbps2_close;
priv->io->write = apbps2_write;
priv->io->port_data = priv;
strlcpy(priv->io->name, "APBPS2 PS/2", sizeof(priv->io->name));
snprintf(priv->io->phys, sizeof(priv->io->phys),
"apbps2_%d", apbps2_idx++);
dev_info(&ofdev->dev, "irq = %d, base = 0x%p\n", irq, priv->regs);
serio_register_port(priv->io);
platform_set_drvdata(ofdev, priv);
return 0;
}
static int apbps2_of_remove(struct platform_device *of_dev)
{
struct apbps2_priv *priv = platform_get_drvdata(of_dev);
serio_unregister_port(priv->io);
return 0;
}
static struct of_device_id apbps2_of_match[] = {
{ .name = "GAISLER_APBPS2", },
{ .name = "01_060", },
{}
};
MODULE_DEVICE_TABLE(of, apbps2_of_match);
static struct platform_driver apbps2_of_driver = {
.driver = {
.name = "grlib-apbps2",
.owner = THIS_MODULE,
.of_match_table = apbps2_of_match,
},
.probe = apbps2_of_probe,
.remove = apbps2_of_remove,
};
module_platform_driver(apbps2_of_driver);
MODULE_AUTHOR("Aeroflex Gaisler AB.");
MODULE_DESCRIPTION("GRLIB APBPS2 PS/2 serial I/O");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Krabappel2548/u8500_kernel_sources | sound/pci/ymfpci/ymfpci.c | 3632 | 11114 | /*
* The driver for the Yamaha's DS1/DS1E cards
* Copyright (c) by Jaroslav Kysela <perex@perex.cz>
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/moduleparam.h>
#include <sound/core.h>
#include <sound/ymfpci.h>
#include <sound/mpu401.h>
#include <sound/opl3.h>
#include <sound/initval.h>
MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>");
MODULE_DESCRIPTION("Yamaha DS-1 PCI");
MODULE_LICENSE("GPL");
MODULE_SUPPORTED_DEVICE("{{Yamaha,YMF724},"
"{Yamaha,YMF724F},"
"{Yamaha,YMF740},"
"{Yamaha,YMF740C},"
"{Yamaha,YMF744},"
"{Yamaha,YMF754}}");
static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-MAX */
static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* ID for this card */
static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable this card */
static long fm_port[SNDRV_CARDS];
static long mpu_port[SNDRV_CARDS];
#ifdef SUPPORT_JOYSTICK
static long joystick_port[SNDRV_CARDS];
#endif
static int rear_switch[SNDRV_CARDS];
module_param_array(index, int, NULL, 0444);
MODULE_PARM_DESC(index, "Index value for the Yamaha DS-1 PCI soundcard.");
module_param_array(id, charp, NULL, 0444);
MODULE_PARM_DESC(id, "ID string for the Yamaha DS-1 PCI soundcard.");
module_param_array(enable, bool, NULL, 0444);
MODULE_PARM_DESC(enable, "Enable Yamaha DS-1 soundcard.");
module_param_array(mpu_port, long, NULL, 0444);
MODULE_PARM_DESC(mpu_port, "MPU-401 Port.");
module_param_array(fm_port, long, NULL, 0444);
MODULE_PARM_DESC(fm_port, "FM OPL-3 Port.");
#ifdef SUPPORT_JOYSTICK
module_param_array(joystick_port, long, NULL, 0444);
MODULE_PARM_DESC(joystick_port, "Joystick port address");
#endif
module_param_array(rear_switch, bool, NULL, 0444);
MODULE_PARM_DESC(rear_switch, "Enable shared rear/line-in switch");
static DEFINE_PCI_DEVICE_TABLE(snd_ymfpci_ids) = {
{ PCI_VDEVICE(YAMAHA, 0x0004), 0, }, /* YMF724 */
{ PCI_VDEVICE(YAMAHA, 0x000d), 0, }, /* YMF724F */
{ PCI_VDEVICE(YAMAHA, 0x000a), 0, }, /* YMF740 */
{ PCI_VDEVICE(YAMAHA, 0x000c), 0, }, /* YMF740C */
{ PCI_VDEVICE(YAMAHA, 0x0010), 0, }, /* YMF744 */
{ PCI_VDEVICE(YAMAHA, 0x0012), 0, }, /* YMF754 */
{ 0, }
};
MODULE_DEVICE_TABLE(pci, snd_ymfpci_ids);
#ifdef SUPPORT_JOYSTICK
static int __devinit snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev,
int legacy_ctrl, int legacy_ctrl2)
{
struct gameport *gp;
struct resource *r = NULL;
int io_port = joystick_port[dev];
if (!io_port)
return -ENODEV;
if (chip->pci->device >= 0x0010) { /* YMF 744/754 */
if (io_port == 1) {
/* auto-detect */
if (!(io_port = pci_resource_start(chip->pci, 2)))
return -ENODEV;
}
} else {
if (io_port == 1) {
/* auto-detect */
for (io_port = 0x201; io_port <= 0x205; io_port++) {
if (io_port == 0x203)
continue;
if ((r = request_region(io_port, 1, "YMFPCI gameport")) != NULL)
break;
}
if (!r) {
printk(KERN_ERR "ymfpci: no gameport ports available\n");
return -EBUSY;
}
}
switch (io_port) {
case 0x201: legacy_ctrl2 |= 0 << 6; break;
case 0x202: legacy_ctrl2 |= 1 << 6; break;
case 0x204: legacy_ctrl2 |= 2 << 6; break;
case 0x205: legacy_ctrl2 |= 3 << 6; break;
default:
printk(KERN_ERR "ymfpci: invalid joystick port %#x", io_port);
return -EINVAL;
}
}
if (!r && !(r = request_region(io_port, 1, "YMFPCI gameport"))) {
printk(KERN_ERR "ymfpci: joystick port %#x is in use.\n", io_port);
return -EBUSY;
}
chip->gameport = gp = gameport_allocate_port();
if (!gp) {
printk(KERN_ERR "ymfpci: cannot allocate memory for gameport\n");
release_and_free_resource(r);
return -ENOMEM;
}
gameport_set_name(gp, "Yamaha YMF Gameport");
gameport_set_phys(gp, "pci%s/gameport0", pci_name(chip->pci));
gameport_set_dev_parent(gp, &chip->pci->dev);
gp->io = io_port;
gameport_set_port_data(gp, r);
if (chip->pci->device >= 0x0010) /* YMF 744/754 */
pci_write_config_word(chip->pci, PCIR_DSXG_JOYBASE, io_port);
pci_write_config_word(chip->pci, PCIR_DSXG_LEGACY, legacy_ctrl | YMFPCI_LEGACY_JPEN);
pci_write_config_word(chip->pci, PCIR_DSXG_ELEGACY, legacy_ctrl2);
gameport_register_port(chip->gameport);
return 0;
}
void snd_ymfpci_free_gameport(struct snd_ymfpci *chip)
{
if (chip->gameport) {
struct resource *r = gameport_get_port_data(chip->gameport);
gameport_unregister_port(chip->gameport);
chip->gameport = NULL;
release_and_free_resource(r);
}
}
#else
static inline int snd_ymfpci_create_gameport(struct snd_ymfpci *chip, int dev, int l, int l2) { return -ENOSYS; }
void snd_ymfpci_free_gameport(struct snd_ymfpci *chip) { }
#endif /* SUPPORT_JOYSTICK */
static int __devinit snd_card_ymfpci_probe(struct pci_dev *pci,
const struct pci_device_id *pci_id)
{
static int dev;
struct snd_card *card;
struct resource *fm_res = NULL;
struct resource *mpu_res = NULL;
struct snd_ymfpci *chip;
struct snd_opl3 *opl3;
const char *str, *model;
int err;
u16 legacy_ctrl, legacy_ctrl2, old_legacy_ctrl;
if (dev >= SNDRV_CARDS)
return -ENODEV;
if (!enable[dev]) {
dev++;
return -ENOENT;
}
err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
if (err < 0)
return err;
switch (pci_id->device) {
case 0x0004: str = "YMF724"; model = "DS-1"; break;
case 0x000d: str = "YMF724F"; model = "DS-1"; break;
case 0x000a: str = "YMF740"; model = "DS-1L"; break;
case 0x000c: str = "YMF740C"; model = "DS-1L"; break;
case 0x0010: str = "YMF744"; model = "DS-1S"; break;
case 0x0012: str = "YMF754"; model = "DS-1E"; break;
default: model = str = "???"; break;
}
legacy_ctrl = 0;
legacy_ctrl2 = 0x0800; /* SBEN = 0, SMOD = 01, LAD = 0 */
if (pci_id->device >= 0x0010) { /* YMF 744/754 */
if (fm_port[dev] == 1) {
/* auto-detect */
fm_port[dev] = pci_resource_start(pci, 1);
}
if (fm_port[dev] > 0 &&
(fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) {
legacy_ctrl |= YMFPCI_LEGACY_FMEN;
pci_write_config_word(pci, PCIR_DSXG_FMBASE, fm_port[dev]);
}
if (mpu_port[dev] == 1) {
/* auto-detect */
mpu_port[dev] = pci_resource_start(pci, 1) + 0x20;
}
if (mpu_port[dev] > 0 &&
(mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) {
legacy_ctrl |= YMFPCI_LEGACY_MEN;
pci_write_config_word(pci, PCIR_DSXG_MPU401BASE, mpu_port[dev]);
}
} else {
switch (fm_port[dev]) {
case 0x388: legacy_ctrl2 |= 0; break;
case 0x398: legacy_ctrl2 |= 1; break;
case 0x3a0: legacy_ctrl2 |= 2; break;
case 0x3a8: legacy_ctrl2 |= 3; break;
default: fm_port[dev] = 0; break;
}
if (fm_port[dev] > 0 &&
(fm_res = request_region(fm_port[dev], 4, "YMFPCI OPL3")) != NULL) {
legacy_ctrl |= YMFPCI_LEGACY_FMEN;
} else {
legacy_ctrl2 &= ~YMFPCI_LEGACY2_FMIO;
fm_port[dev] = 0;
}
switch (mpu_port[dev]) {
case 0x330: legacy_ctrl2 |= 0 << 4; break;
case 0x300: legacy_ctrl2 |= 1 << 4; break;
case 0x332: legacy_ctrl2 |= 2 << 4; break;
case 0x334: legacy_ctrl2 |= 3 << 4; break;
default: mpu_port[dev] = 0; break;
}
if (mpu_port[dev] > 0 &&
(mpu_res = request_region(mpu_port[dev], 2, "YMFPCI MPU401")) != NULL) {
legacy_ctrl |= YMFPCI_LEGACY_MEN;
} else {
legacy_ctrl2 &= ~YMFPCI_LEGACY2_MPUIO;
mpu_port[dev] = 0;
}
}
if (mpu_res) {
legacy_ctrl |= YMFPCI_LEGACY_MIEN;
legacy_ctrl2 |= YMFPCI_LEGACY2_IMOD;
}
pci_read_config_word(pci, PCIR_DSXG_LEGACY, &old_legacy_ctrl);
pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl);
pci_write_config_word(pci, PCIR_DSXG_ELEGACY, legacy_ctrl2);
if ((err = snd_ymfpci_create(card, pci,
old_legacy_ctrl,
&chip)) < 0) {
snd_card_free(card);
release_and_free_resource(mpu_res);
release_and_free_resource(fm_res);
return err;
}
chip->fm_res = fm_res;
chip->mpu_res = mpu_res;
card->private_data = chip;
strcpy(card->driver, str);
sprintf(card->shortname, "Yamaha %s (%s)", model, str);
sprintf(card->longname, "%s at 0x%lx, irq %i",
card->shortname,
chip->reg_area_phys,
chip->irq);
if ((err = snd_ymfpci_pcm(chip, 0, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ymfpci_pcm_spdif(chip, 1, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ymfpci_pcm_4ch(chip, 2, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ymfpci_pcm2(chip, 3, NULL)) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ymfpci_mixer(chip, rear_switch[dev])) < 0) {
snd_card_free(card);
return err;
}
if ((err = snd_ymfpci_timer(chip, 0)) < 0) {
snd_card_free(card);
return err;
}
if (chip->mpu_res) {
if ((err = snd_mpu401_uart_new(card, 0, MPU401_HW_YMFPCI,
mpu_port[dev],
MPU401_INFO_INTEGRATED,
pci->irq, 0, &chip->rawmidi)) < 0) {
printk(KERN_WARNING "ymfpci: cannot initialize MPU401 at 0x%lx, skipping...\n", mpu_port[dev]);
legacy_ctrl &= ~YMFPCI_LEGACY_MIEN; /* disable MPU401 irq */
pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl);
}
}
if (chip->fm_res) {
if ((err = snd_opl3_create(card,
fm_port[dev],
fm_port[dev] + 2,
OPL3_HW_OPL3, 1, &opl3)) < 0) {
printk(KERN_WARNING "ymfpci: cannot initialize FM OPL3 at 0x%lx, skipping...\n", fm_port[dev]);
legacy_ctrl &= ~YMFPCI_LEGACY_FMEN;
pci_write_config_word(pci, PCIR_DSXG_LEGACY, legacy_ctrl);
} else if ((err = snd_opl3_hwdep_new(opl3, 0, 1, NULL)) < 0) {
snd_card_free(card);
snd_printk(KERN_ERR "cannot create opl3 hwdep\n");
return err;
}
}
snd_ymfpci_create_gameport(chip, dev, legacy_ctrl, legacy_ctrl2);
if ((err = snd_card_register(card)) < 0) {
snd_card_free(card);
return err;
}
pci_set_drvdata(pci, card);
dev++;
return 0;
}
static void __devexit snd_card_ymfpci_remove(struct pci_dev *pci)
{
snd_card_free(pci_get_drvdata(pci));
pci_set_drvdata(pci, NULL);
}
static struct pci_driver driver = {
.name = "Yamaha DS-1 PCI",
.id_table = snd_ymfpci_ids,
.probe = snd_card_ymfpci_probe,
.remove = __devexit_p(snd_card_ymfpci_remove),
#ifdef CONFIG_PM
.suspend = snd_ymfpci_suspend,
.resume = snd_ymfpci_resume,
#endif
};
static int __init alsa_card_ymfpci_init(void)
{
return pci_register_driver(&driver);
}
static void __exit alsa_card_ymfpci_exit(void)
{
pci_unregister_driver(&driver);
}
module_init(alsa_card_ymfpci_init)
module_exit(alsa_card_ymfpci_exit)
| gpl-2.0 |
CyanogenMod/motorola-kernel-stingray | net/netfilter/xt_TCPOPTSTRIP.c | 4144 | 3785 | /*
* A module for stripping a specific TCP option from TCP packets.
*
* Copyright (C) 2007 Sven Schnelle <svens@bitebene.org>
* Copyright © CC Computer Consultants GmbH, 2007
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/ipv6.h>
#include <linux/tcp.h>
#include <net/ipv6.h>
#include <net/tcp.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter/xt_TCPOPTSTRIP.h>
static inline unsigned int optlen(const u_int8_t *opt, unsigned int offset)
{
/* Beware zero-length options: make finite progress */
if (opt[offset] <= TCPOPT_NOP || opt[offset+1] == 0)
return 1;
else
return opt[offset+1];
}
static unsigned int
tcpoptstrip_mangle_packet(struct sk_buff *skb,
const struct xt_tcpoptstrip_target_info *info,
unsigned int tcphoff, unsigned int minlen)
{
unsigned int optl, i, j;
struct tcphdr *tcph;
u_int16_t n, o;
u_int8_t *opt;
if (!skb_make_writable(skb, skb->len))
return NF_DROP;
tcph = (struct tcphdr *)(skb_network_header(skb) + tcphoff);
opt = (u_int8_t *)tcph;
/*
* Walk through all TCP options - if we find some option to remove,
* set all octets to %TCPOPT_NOP and adjust checksum.
*/
for (i = sizeof(struct tcphdr); i < tcp_hdrlen(skb); i += optl) {
optl = optlen(opt, i);
if (i + optl > tcp_hdrlen(skb))
break;
if (!tcpoptstrip_test_bit(info->strip_bmap, opt[i]))
continue;
for (j = 0; j < optl; ++j) {
o = opt[i+j];
n = TCPOPT_NOP;
if ((i + j) % 2 == 0) {
o <<= 8;
n <<= 8;
}
inet_proto_csum_replace2(&tcph->check, skb, htons(o),
htons(n), 0);
}
memset(opt + i, TCPOPT_NOP, optl);
}
return XT_CONTINUE;
}
static unsigned int
tcpoptstrip_tg4(struct sk_buff *skb, const struct xt_action_param *par)
{
return tcpoptstrip_mangle_packet(skb, par->targinfo, ip_hdrlen(skb),
sizeof(struct iphdr) + sizeof(struct tcphdr));
}
#if defined(CONFIG_IP6_NF_MANGLE) || defined(CONFIG_IP6_NF_MANGLE_MODULE)
static unsigned int
tcpoptstrip_tg6(struct sk_buff *skb, const struct xt_action_param *par)
{
struct ipv6hdr *ipv6h = ipv6_hdr(skb);
int tcphoff;
u_int8_t nexthdr;
nexthdr = ipv6h->nexthdr;
tcphoff = ipv6_skip_exthdr(skb, sizeof(*ipv6h), &nexthdr);
if (tcphoff < 0)
return NF_DROP;
return tcpoptstrip_mangle_packet(skb, par->targinfo, tcphoff,
sizeof(*ipv6h) + sizeof(struct tcphdr));
}
#endif
static struct xt_target tcpoptstrip_tg_reg[] __read_mostly = {
{
.name = "TCPOPTSTRIP",
.family = NFPROTO_IPV4,
.table = "mangle",
.proto = IPPROTO_TCP,
.target = tcpoptstrip_tg4,
.targetsize = sizeof(struct xt_tcpoptstrip_target_info),
.me = THIS_MODULE,
},
#if defined(CONFIG_IP6_NF_MANGLE) || defined(CONFIG_IP6_NF_MANGLE_MODULE)
{
.name = "TCPOPTSTRIP",
.family = NFPROTO_IPV6,
.table = "mangle",
.proto = IPPROTO_TCP,
.target = tcpoptstrip_tg6,
.targetsize = sizeof(struct xt_tcpoptstrip_target_info),
.me = THIS_MODULE,
},
#endif
};
static int __init tcpoptstrip_tg_init(void)
{
return xt_register_targets(tcpoptstrip_tg_reg,
ARRAY_SIZE(tcpoptstrip_tg_reg));
}
static void __exit tcpoptstrip_tg_exit(void)
{
xt_unregister_targets(tcpoptstrip_tg_reg,
ARRAY_SIZE(tcpoptstrip_tg_reg));
}
module_init(tcpoptstrip_tg_init);
module_exit(tcpoptstrip_tg_exit);
MODULE_AUTHOR("Sven Schnelle <svens@bitebene.org>, Jan Engelhardt <jengelh@medozas.de>");
MODULE_DESCRIPTION("Xtables: TCP option stripping");
MODULE_LICENSE("GPL");
MODULE_ALIAS("ipt_TCPOPTSTRIP");
MODULE_ALIAS("ip6t_TCPOPTSTRIP");
| gpl-2.0 |
Sangsub/android-samsung-2.6.35-gingerbread | drivers/usb/serial/safe_serial.c | 4144 | 11581 | /*
* Safe Encapsulated USB Serial Driver
*
* Copyright (C) 2010 Johan Hovold <jhovold@gmail.com>
* Copyright (C) 2001 Lineo
* Copyright (C) 2001 Hewlett-Packard
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* By:
* Stuart Lynne <sl@lineo.com>, Tom Rushworth <tbr@lineo.com>
*/
/*
* The encapsultaion is designed to overcome difficulties with some USB
* hardware.
*
* While the USB protocol has a CRC over the data while in transit, i.e. while
* being carried over the bus, there is no end to end protection. If the
* hardware has any problems getting the data into or out of the USB transmit
* and receive FIFO's then data can be lost.
*
* This protocol adds a two byte trailer to each USB packet to specify the
* number of bytes of valid data and a 10 bit CRC that will allow the receiver
* to verify that the entire USB packet was received without error.
*
* Because in this case the sender and receiver are the class and function
* drivers there is now end to end protection.
*
* There is an additional option that can be used to force all transmitted
* packets to be padded to the maximum packet size. This provides a work
* around for some devices which have problems with small USB packets.
*
* Assuming a packetsize of N:
*
* 0..N-2 data and optional padding
*
* N-2 bits 7-2 - number of bytes of valid data
* bits 1-0 top two bits of 10 bit CRC
* N-1 bottom 8 bits of 10 bit CRC
*
*
* | Data Length | 10 bit CRC |
* + 7 . 6 . 5 . 4 . 3 . 2 . 1 . 0 | 7 . 6 . 5 . 4 . 3 . 2 . 1 . 0 +
*
* The 10 bit CRC is computed across the sent data, followed by the trailer
* with the length set and the CRC set to zero. The CRC is then OR'd into
* the trailer.
*
* When received a 10 bit CRC is computed over the entire frame including
* the trailer and should be equal to zero.
*
* Two module parameters are used to control the encapsulation, if both are
* turned of the module works as a simple serial device with NO
* encapsulation.
*
* See linux/drivers/usbd/serial_fd for a device function driver
* implementation of this.
*
*/
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/gfp.h>
#include <linux/init.h>
#include <linux/tty.h>
#include <linux/tty_driver.h>
#include <linux/tty_flip.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/uaccess.h>
#include <linux/usb.h>
#include <linux/usb/serial.h>
#ifndef CONFIG_USB_SERIAL_SAFE_PADDED
#define CONFIG_USB_SERIAL_SAFE_PADDED 0
#endif
static int debug;
static int safe = 1;
static int padded = CONFIG_USB_SERIAL_SAFE_PADDED;
#define DRIVER_VERSION "v0.1"
#define DRIVER_AUTHOR "sl@lineo.com, tbr@lineo.com, Johan Hovold <jhovold@gmail.com>"
#define DRIVER_DESC "USB Safe Encapsulated Serial"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE("GPL");
static __u16 vendor; /* no default */
static __u16 product; /* no default */
module_param(vendor, ushort, 0);
MODULE_PARM_DESC(vendor, "User specified USB idVendor (required)");
module_param(product, ushort, 0);
MODULE_PARM_DESC(product, "User specified USB idProduct (required)");
module_param(debug, bool, S_IRUGO | S_IWUSR);
MODULE_PARM_DESC(debug, "Debug enabled or not");
module_param(safe, bool, 0);
MODULE_PARM_DESC(safe, "Turn Safe Encapsulation On/Off");
module_param(padded, bool, 0);
MODULE_PARM_DESC(padded, "Pad to full wMaxPacketSize On/Off");
#define CDC_DEVICE_CLASS 0x02
#define CDC_INTERFACE_CLASS 0x02
#define CDC_INTERFACE_SUBCLASS 0x06
#define LINEO_INTERFACE_CLASS 0xff
#define LINEO_INTERFACE_SUBCLASS_SAFENET 0x01
#define LINEO_SAFENET_CRC 0x01
#define LINEO_SAFENET_CRC_PADDED 0x02
#define LINEO_INTERFACE_SUBCLASS_SAFESERIAL 0x02
#define LINEO_SAFESERIAL_CRC 0x01
#define LINEO_SAFESERIAL_CRC_PADDED 0x02
#define MY_USB_DEVICE(vend, prod, dc, ic, isc) \
.match_flags = USB_DEVICE_ID_MATCH_DEVICE | \
USB_DEVICE_ID_MATCH_DEV_CLASS | \
USB_DEVICE_ID_MATCH_INT_CLASS | \
USB_DEVICE_ID_MATCH_INT_SUBCLASS, \
.idVendor = (vend), \
.idProduct = (prod),\
.bDeviceClass = (dc),\
.bInterfaceClass = (ic), \
.bInterfaceSubClass = (isc),
static struct usb_device_id id_table[] = {
{MY_USB_DEVICE(0x49f, 0xffff, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Itsy */
{MY_USB_DEVICE(0x3f0, 0x2101, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Calypso */
{MY_USB_DEVICE(0x4dd, 0x8001, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Iris */
{MY_USB_DEVICE(0x4dd, 0x8002, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Collie */
{MY_USB_DEVICE(0x4dd, 0x8003, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Collie */
{MY_USB_DEVICE(0x4dd, 0x8004, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Collie */
{MY_USB_DEVICE(0x5f9, 0xffff, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)}, /* Sharp tmp */
/* extra null entry for module vendor/produc parameters */
{MY_USB_DEVICE(0, 0, CDC_DEVICE_CLASS, LINEO_INTERFACE_CLASS, LINEO_INTERFACE_SUBCLASS_SAFESERIAL)},
{} /* terminating entry */
};
MODULE_DEVICE_TABLE(usb, id_table);
static struct usb_driver safe_driver = {
.name = "safe_serial",
.probe = usb_serial_probe,
.disconnect = usb_serial_disconnect,
.id_table = id_table,
.no_dynamic_id = 1,
};
static const __u16 crc10_table[256] = {
0x000, 0x233, 0x255, 0x066, 0x299, 0x0aa, 0x0cc, 0x2ff,
0x301, 0x132, 0x154, 0x367, 0x198, 0x3ab, 0x3cd, 0x1fe,
0x031, 0x202, 0x264, 0x057, 0x2a8, 0x09b, 0x0fd, 0x2ce,
0x330, 0x103, 0x165, 0x356, 0x1a9, 0x39a, 0x3fc, 0x1cf,
0x062, 0x251, 0x237, 0x004, 0x2fb, 0x0c8, 0x0ae, 0x29d,
0x363, 0x150, 0x136, 0x305, 0x1fa, 0x3c9, 0x3af, 0x19c,
0x053, 0x260, 0x206, 0x035, 0x2ca, 0x0f9, 0x09f, 0x2ac,
0x352, 0x161, 0x107, 0x334, 0x1cb, 0x3f8, 0x39e, 0x1ad,
0x0c4, 0x2f7, 0x291, 0x0a2, 0x25d, 0x06e, 0x008, 0x23b,
0x3c5, 0x1f6, 0x190, 0x3a3, 0x15c, 0x36f, 0x309, 0x13a,
0x0f5, 0x2c6, 0x2a0, 0x093, 0x26c, 0x05f, 0x039, 0x20a,
0x3f4, 0x1c7, 0x1a1, 0x392, 0x16d, 0x35e, 0x338, 0x10b,
0x0a6, 0x295, 0x2f3, 0x0c0, 0x23f, 0x00c, 0x06a, 0x259,
0x3a7, 0x194, 0x1f2, 0x3c1, 0x13e, 0x30d, 0x36b, 0x158,
0x097, 0x2a4, 0x2c2, 0x0f1, 0x20e, 0x03d, 0x05b, 0x268,
0x396, 0x1a5, 0x1c3, 0x3f0, 0x10f, 0x33c, 0x35a, 0x169,
0x188, 0x3bb, 0x3dd, 0x1ee, 0x311, 0x122, 0x144, 0x377,
0x289, 0x0ba, 0x0dc, 0x2ef, 0x010, 0x223, 0x245, 0x076,
0x1b9, 0x38a, 0x3ec, 0x1df, 0x320, 0x113, 0x175, 0x346,
0x2b8, 0x08b, 0x0ed, 0x2de, 0x021, 0x212, 0x274, 0x047,
0x1ea, 0x3d9, 0x3bf, 0x18c, 0x373, 0x140, 0x126, 0x315,
0x2eb, 0x0d8, 0x0be, 0x28d, 0x072, 0x241, 0x227, 0x014,
0x1db, 0x3e8, 0x38e, 0x1bd, 0x342, 0x171, 0x117, 0x324,
0x2da, 0x0e9, 0x08f, 0x2bc, 0x043, 0x270, 0x216, 0x025,
0x14c, 0x37f, 0x319, 0x12a, 0x3d5, 0x1e6, 0x180, 0x3b3,
0x24d, 0x07e, 0x018, 0x22b, 0x0d4, 0x2e7, 0x281, 0x0b2,
0x17d, 0x34e, 0x328, 0x11b, 0x3e4, 0x1d7, 0x1b1, 0x382,
0x27c, 0x04f, 0x029, 0x21a, 0x0e5, 0x2d6, 0x2b0, 0x083,
0x12e, 0x31d, 0x37b, 0x148, 0x3b7, 0x184, 0x1e2, 0x3d1,
0x22f, 0x01c, 0x07a, 0x249, 0x0b6, 0x285, 0x2e3, 0x0d0,
0x11f, 0x32c, 0x34a, 0x179, 0x386, 0x1b5, 0x1d3, 0x3e0,
0x21e, 0x02d, 0x04b, 0x278, 0x087, 0x2b4, 0x2d2, 0x0e1,
};
#define CRC10_INITFCS 0x000 /* Initial FCS value */
#define CRC10_GOODFCS 0x000 /* Good final FCS value */
#define CRC10_FCS(fcs, c) ((((fcs) << 8) & 0x3ff) ^ crc10_table[((fcs) >> 2) & 0xff] ^ (c))
/**
* fcs_compute10 - memcpy and calculate 10 bit CRC across buffer
* @sp: pointer to buffer
* @len: number of bytes
* @fcs: starting FCS
*
* Perform a memcpy and calculate fcs using ppp 10bit CRC algorithm. Return
* new 10 bit FCS.
*/
static __u16 __inline__ fcs_compute10(unsigned char *sp, int len, __u16 fcs)
{
for (; len-- > 0; fcs = CRC10_FCS(fcs, *sp++));
return fcs;
}
static void safe_process_read_urb(struct urb *urb)
{
struct usb_serial_port *port = urb->context;
unsigned char *data = urb->transfer_buffer;
unsigned char length = urb->actual_length;
int actual_length;
struct tty_struct *tty;
__u16 fcs;
if (!length)
return;
tty = tty_port_tty_get(&port->port);
if (!tty)
return;
if (!safe)
goto out;
fcs = fcs_compute10(data, length, CRC10_INITFCS);
if (fcs) {
dev_err(&port->dev, "%s - bad CRC %x\n", __func__, fcs);
goto err;
}
actual_length = data[length - 2] >> 2;
if (actual_length > (length - 2)) {
dev_err(&port->dev, "%s - inconsistent lengths %d:%d\n",
__func__, actual_length, length);
goto err;
}
dev_info(&urb->dev->dev, "%s - actual: %d\n", __func__, actual_length);
length = actual_length;
out:
tty_insert_flip_string(tty, data, length);
tty_flip_buffer_push(tty);
err:
tty_kref_put(tty);
}
static int safe_prepare_write_buffer(struct usb_serial_port *port,
void *dest, size_t size)
{
unsigned char *buf = dest;
int count;
int trailer_len;
int pkt_len;
__u16 fcs;
trailer_len = safe ? 2 : 0;
count = kfifo_out_locked(&port->write_fifo, buf, size - trailer_len,
&port->lock);
if (!safe)
return count;
/* pad if necessary */
if (padded) {
pkt_len = size;
memset(buf + count, '0', pkt_len - count - trailer_len);
} else {
pkt_len = count + trailer_len;
}
/* set count */
buf[pkt_len - 2] = count << 2;
buf[pkt_len - 1] = 0;
/* compute fcs and insert into trailer */
fcs = fcs_compute10(buf, pkt_len, CRC10_INITFCS);
buf[pkt_len - 2] |= fcs >> 8;
buf[pkt_len - 1] |= fcs & 0xff;
return pkt_len;
}
static int safe_startup(struct usb_serial *serial)
{
switch (serial->interface->cur_altsetting->desc.bInterfaceProtocol) {
case LINEO_SAFESERIAL_CRC:
break;
case LINEO_SAFESERIAL_CRC_PADDED:
padded = 1;
break;
default:
return -EINVAL;
}
return 0;
}
static struct usb_serial_driver safe_device = {
.driver = {
.owner = THIS_MODULE,
.name = "safe_serial",
},
.id_table = id_table,
.usb_driver = &safe_driver,
.num_ports = 1,
.process_read_urb = safe_process_read_urb,
.prepare_write_buffer = safe_prepare_write_buffer,
.attach = safe_startup,
};
static int __init safe_init(void)
{
int i, retval;
printk(KERN_INFO KBUILD_MODNAME ": " DRIVER_VERSION ":"
DRIVER_DESC "\n");
/* if we have vendor / product parameters patch them into id list */
if (vendor || product) {
printk(KERN_INFO KBUILD_MODNAME ": vendor: %x product: %x\n",
vendor, product);
for (i = 0; i < ARRAY_SIZE(id_table); i++) {
if (!id_table[i].idVendor && !id_table[i].idProduct) {
id_table[i].idVendor = vendor;
id_table[i].idProduct = product;
break;
}
}
}
retval = usb_serial_register(&safe_device);
if (retval)
goto failed_usb_serial_register;
retval = usb_register(&safe_driver);
if (retval)
goto failed_usb_register;
return 0;
failed_usb_register:
usb_serial_deregister(&safe_device);
failed_usb_serial_register:
return retval;
}
static void __exit safe_exit(void)
{
usb_deregister(&safe_driver);
usb_serial_deregister(&safe_device);
}
module_init(safe_init);
module_exit(safe_exit);
| gpl-2.0 |
kannu1994/crespo_kernel | fs/ext4/xattr_user.c | 4144 | 1630 | /*
* linux/fs/ext4/xattr_user.c
* Handler for extended user attributes.
*
* Copyright (C) 2001 by Andreas Gruenbacher, <a.gruenbacher@computer.org>
*/
#include <linux/module.h>
#include <linux/string.h>
#include <linux/fs.h>
#include "ext4_jbd2.h"
#include "ext4.h"
#include "xattr.h"
static size_t
ext4_xattr_user_list(struct dentry *dentry, char *list, size_t list_size,
const char *name, size_t name_len, int type)
{
const size_t prefix_len = XATTR_USER_PREFIX_LEN;
const size_t total_len = prefix_len + name_len + 1;
if (!test_opt(dentry->d_sb, XATTR_USER))
return 0;
if (list && total_len <= list_size) {
memcpy(list, XATTR_USER_PREFIX, prefix_len);
memcpy(list+prefix_len, name, name_len);
list[prefix_len + name_len] = '\0';
}
return total_len;
}
static int
ext4_xattr_user_get(struct dentry *dentry, const char *name,
void *buffer, size_t size, int type)
{
if (strcmp(name, "") == 0)
return -EINVAL;
if (!test_opt(dentry->d_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_get(dentry->d_inode, EXT4_XATTR_INDEX_USER,
name, buffer, size);
}
static int
ext4_xattr_user_set(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags, int type)
{
if (strcmp(name, "") == 0)
return -EINVAL;
if (!test_opt(dentry->d_sb, XATTR_USER))
return -EOPNOTSUPP;
return ext4_xattr_set(dentry->d_inode, EXT4_XATTR_INDEX_USER,
name, value, size, flags);
}
const struct xattr_handler ext4_xattr_user_handler = {
.prefix = XATTR_USER_PREFIX,
.list = ext4_xattr_user_list,
.get = ext4_xattr_user_get,
.set = ext4_xattr_user_set,
};
| gpl-2.0 |
flar2/m8-Sense-4.4.3 | arch/sparc/kernel/traps_64.c | 4400 | 76560 | /* arch/sparc64/kernel/traps.c
*
* Copyright (C) 1995,1997,2008,2009 David S. Miller (davem@davemloft.net)
* Copyright (C) 1997,1999,2000 Jakub Jelinek (jakub@redhat.com)
*/
/*
* I like traps on v9, :))))
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/linkage.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/smp.h>
#include <linux/mm.h>
#include <linux/init.h>
#include <linux/kdebug.h>
#include <linux/ftrace.h>
#include <linux/gfp.h>
#include <asm/smp.h>
#include <asm/delay.h>
#include <asm/ptrace.h>
#include <asm/oplib.h>
#include <asm/page.h>
#include <asm/pgtable.h>
#include <asm/unistd.h>
#include <asm/uaccess.h>
#include <asm/fpumacro.h>
#include <asm/lsu.h>
#include <asm/dcu.h>
#include <asm/estate.h>
#include <asm/chafsr.h>
#include <asm/sfafsr.h>
#include <asm/psrcompat.h>
#include <asm/processor.h>
#include <asm/timer.h>
#include <asm/head.h>
#include <asm/prom.h>
#include <asm/memctrl.h>
#include <asm/cacheflush.h>
#include "entry.h"
#include "kstack.h"
/* When an irrecoverable trap occurs at tl > 0, the trap entry
* code logs the trap state registers at every level in the trap
* stack. It is found at (pt_regs + sizeof(pt_regs)) and the layout
* is as follows:
*/
struct tl1_traplog {
struct {
unsigned long tstate;
unsigned long tpc;
unsigned long tnpc;
unsigned long tt;
} trapstack[4];
unsigned long tl;
};
static void dump_tl1_traplog(struct tl1_traplog *p)
{
int i, limit;
printk(KERN_EMERG "TRAPLOG: Error at trap level 0x%lx, "
"dumping track stack.\n", p->tl);
limit = (tlb_type == hypervisor) ? 2 : 4;
for (i = 0; i < limit; i++) {
printk(KERN_EMERG
"TRAPLOG: Trap level %d TSTATE[%016lx] TPC[%016lx] "
"TNPC[%016lx] TT[%lx]\n",
i + 1,
p->trapstack[i].tstate, p->trapstack[i].tpc,
p->trapstack[i].tnpc, p->trapstack[i].tt);
printk("TRAPLOG: TPC<%pS>\n", (void *) p->trapstack[i].tpc);
}
}
void bad_trap(struct pt_regs *regs, long lvl)
{
char buffer[32];
siginfo_t info;
if (notify_die(DIE_TRAP, "bad trap", regs,
0, lvl, SIGTRAP) == NOTIFY_STOP)
return;
if (lvl < 0x100) {
sprintf(buffer, "Bad hw trap %lx at tl0\n", lvl);
die_if_kernel(buffer, regs);
}
lvl -= 0x100;
if (regs->tstate & TSTATE_PRIV) {
sprintf(buffer, "Kernel bad sw trap %lx", lvl);
die_if_kernel(buffer, regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLTRP;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = lvl;
force_sig_info(SIGILL, &info, current);
}
void bad_trap_tl1(struct pt_regs *regs, long lvl)
{
char buffer[32];
if (notify_die(DIE_TRAP_TL1, "bad trap tl1", regs,
0, lvl, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sprintf (buffer, "Bad trap %lx at tl>0", lvl);
die_if_kernel (buffer, regs);
}
#ifdef CONFIG_DEBUG_BUGVERBOSE
void do_BUG(const char *file, int line)
{
bust_spinlocks(1);
printk("kernel BUG at %s:%d!\n", file, line);
}
EXPORT_SYMBOL(do_BUG);
#endif
static DEFINE_SPINLOCK(dimm_handler_lock);
static dimm_printer_t dimm_handler;
static int sprintf_dimm(int synd_code, unsigned long paddr, char *buf, int buflen)
{
unsigned long flags;
int ret = -ENODEV;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (dimm_handler) {
ret = dimm_handler(synd_code, paddr, buf, buflen);
} else if (tlb_type == spitfire) {
if (prom_getunumber(synd_code, paddr, buf, buflen) == -1)
ret = -EINVAL;
else
ret = 0;
} else
ret = -ENODEV;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
return ret;
}
int register_dimm_printer(dimm_printer_t func)
{
unsigned long flags;
int ret = 0;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (!dimm_handler)
dimm_handler = func;
else
ret = -EEXIST;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
return ret;
}
EXPORT_SYMBOL_GPL(register_dimm_printer);
void unregister_dimm_printer(dimm_printer_t func)
{
unsigned long flags;
spin_lock_irqsave(&dimm_handler_lock, flags);
if (dimm_handler == func)
dimm_handler = NULL;
spin_unlock_irqrestore(&dimm_handler_lock, flags);
}
EXPORT_SYMBOL_GPL(unregister_dimm_printer);
void spitfire_insn_access_exception(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "instruction access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
printk("spitfire_insn_access_exception: SFSR[%016lx] "
"SFAR[%016lx], going.\n", sfsr, sfar);
die_if_kernel("Iax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void spitfire_insn_access_exception_tl1(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
if (notify_die(DIE_TRAP_TL1, "instruction access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
spitfire_insn_access_exception(regs, sfsr, sfar);
}
void sun4v_insn_access_exception(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
unsigned short type = (type_ctx >> 16);
unsigned short ctx = (type_ctx & 0xffff);
siginfo_t info;
if (notify_die(DIE_TRAP, "instruction access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
printk("sun4v_insn_access_exception: ADDR[%016lx] "
"CTX[%04x] TYPE[%04x], going.\n",
addr, ctx, type);
die_if_kernel("Iax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void sun4v_insn_access_exception_tl1(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
if (notify_die(DIE_TRAP_TL1, "instruction access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sun4v_insn_access_exception(regs, addr, type_ctx);
}
void spitfire_data_access_exception(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "data access exception", regs,
0, 0x30, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
/* Test if this comes from uaccess places. */
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* Ouch, somebody is trying VM hole tricks on us... */
#ifdef DEBUG_EXCEPTIONS
printk("Exception: PC<%016lx> faddr<UNKNOWN>\n", regs->tpc);
printk("EX_TABLE: insn<%016lx> fixup<%016lx>\n",
regs->tpc, entry->fixup);
#endif
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
return;
}
/* Shit... */
printk("spitfire_data_access_exception: SFSR[%016lx] "
"SFAR[%016lx], going.\n", sfsr, sfar);
die_if_kernel("Dax", regs);
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *)sfar;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void spitfire_data_access_exception_tl1(struct pt_regs *regs, unsigned long sfsr, unsigned long sfar)
{
if (notify_die(DIE_TRAP_TL1, "data access exception tl1", regs,
0, 0x30, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
spitfire_data_access_exception(regs, sfsr, sfar);
}
void sun4v_data_access_exception(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
unsigned short type = (type_ctx >> 16);
unsigned short ctx = (type_ctx & 0xffff);
siginfo_t info;
if (notify_die(DIE_TRAP, "data access exception", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
/* Test if this comes from uaccess places. */
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* Ouch, somebody is trying VM hole tricks on us... */
#ifdef DEBUG_EXCEPTIONS
printk("Exception: PC<%016lx> faddr<UNKNOWN>\n", regs->tpc);
printk("EX_TABLE: insn<%016lx> fixup<%016lx>\n",
regs->tpc, entry->fixup);
#endif
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
return;
}
printk("sun4v_data_access_exception: ADDR[%016lx] "
"CTX[%04x] TYPE[%04x], going.\n",
addr, ctx, type);
die_if_kernel("Dax", regs);
}
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGSEGV;
info.si_errno = 0;
info.si_code = SEGV_MAPERR;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGSEGV, &info, current);
}
void sun4v_data_access_exception_tl1(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
if (notify_die(DIE_TRAP_TL1, "data access exception tl1", regs,
0, 0x8, SIGTRAP) == NOTIFY_STOP)
return;
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
sun4v_data_access_exception(regs, addr, type_ctx);
}
#ifdef CONFIG_PCI
#include "pci_impl.h"
#endif
/* When access exceptions happen, we must do this. */
static void spitfire_clean_and_reenable_l1_caches(void)
{
unsigned long va;
if (tlb_type != spitfire)
BUG();
/* Clean 'em. */
for (va = 0; va < (PAGE_SIZE << 1); va += 32) {
spitfire_put_icache_tag(va, 0x0);
spitfire_put_dcache_tag(va, 0x0);
}
/* Re-enable in LSU. */
__asm__ __volatile__("flush %%g6\n\t"
"membar #Sync\n\t"
"stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (LSU_CONTROL_IC | LSU_CONTROL_DC |
LSU_CONTROL_IM | LSU_CONTROL_DM),
"i" (ASI_LSU_CONTROL)
: "memory");
}
static void spitfire_enable_estate_errors(void)
{
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (ESTATE_ERR_ALL),
"i" (ASI_ESTATE_ERROR_EN));
}
static char ecc_syndrome_table[] = {
0x4c, 0x40, 0x41, 0x48, 0x42, 0x48, 0x48, 0x49,
0x43, 0x48, 0x48, 0x49, 0x48, 0x49, 0x49, 0x4a,
0x44, 0x48, 0x48, 0x20, 0x48, 0x39, 0x4b, 0x48,
0x48, 0x25, 0x31, 0x48, 0x28, 0x48, 0x48, 0x2c,
0x45, 0x48, 0x48, 0x21, 0x48, 0x3d, 0x04, 0x48,
0x48, 0x4b, 0x35, 0x48, 0x2d, 0x48, 0x48, 0x29,
0x48, 0x00, 0x01, 0x48, 0x0a, 0x48, 0x48, 0x4b,
0x0f, 0x48, 0x48, 0x4b, 0x48, 0x49, 0x49, 0x48,
0x46, 0x48, 0x48, 0x2a, 0x48, 0x3b, 0x27, 0x48,
0x48, 0x4b, 0x33, 0x48, 0x22, 0x48, 0x48, 0x2e,
0x48, 0x19, 0x1d, 0x48, 0x1b, 0x4a, 0x48, 0x4b,
0x1f, 0x48, 0x4a, 0x4b, 0x48, 0x4b, 0x4b, 0x48,
0x48, 0x4b, 0x24, 0x48, 0x07, 0x48, 0x48, 0x36,
0x4b, 0x48, 0x48, 0x3e, 0x48, 0x30, 0x38, 0x48,
0x49, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x16, 0x48,
0x48, 0x12, 0x4b, 0x48, 0x49, 0x48, 0x48, 0x4b,
0x47, 0x48, 0x48, 0x2f, 0x48, 0x3f, 0x4b, 0x48,
0x48, 0x06, 0x37, 0x48, 0x23, 0x48, 0x48, 0x2b,
0x48, 0x05, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x32,
0x26, 0x48, 0x48, 0x3a, 0x48, 0x34, 0x3c, 0x48,
0x48, 0x11, 0x15, 0x48, 0x13, 0x4a, 0x48, 0x4b,
0x17, 0x48, 0x4a, 0x4b, 0x48, 0x4b, 0x4b, 0x48,
0x49, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x1e, 0x48,
0x48, 0x1a, 0x4b, 0x48, 0x49, 0x48, 0x48, 0x4b,
0x48, 0x08, 0x0d, 0x48, 0x02, 0x48, 0x48, 0x49,
0x03, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x4b, 0x48,
0x49, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x10, 0x48,
0x48, 0x14, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x4b,
0x49, 0x48, 0x48, 0x49, 0x48, 0x4b, 0x18, 0x48,
0x48, 0x1c, 0x4b, 0x48, 0x4b, 0x48, 0x48, 0x4b,
0x4a, 0x0c, 0x09, 0x48, 0x0e, 0x48, 0x48, 0x4b,
0x0b, 0x48, 0x48, 0x4b, 0x48, 0x4b, 0x4b, 0x4a
};
static char *syndrome_unknown = "<Unknown>";
static void spitfire_log_udb_syndrome(unsigned long afar, unsigned long udbh, unsigned long udbl, unsigned long bit)
{
unsigned short scode;
char memmod_str[64], *p;
if (udbl & bit) {
scode = ecc_syndrome_table[udbl & 0xff];
if (sprintf_dimm(scode, afar, memmod_str, sizeof(memmod_str)) < 0)
p = syndrome_unknown;
else
p = memmod_str;
printk(KERN_WARNING "CPU[%d]: UDBL Syndrome[%x] "
"Memory Module \"%s\"\n",
smp_processor_id(), scode, p);
}
if (udbh & bit) {
scode = ecc_syndrome_table[udbh & 0xff];
if (sprintf_dimm(scode, afar, memmod_str, sizeof(memmod_str)) < 0)
p = syndrome_unknown;
else
p = memmod_str;
printk(KERN_WARNING "CPU[%d]: UDBH Syndrome[%x] "
"Memory Module \"%s\"\n",
smp_processor_id(), scode, p);
}
}
static void spitfire_cee_log(unsigned long afsr, unsigned long afar, unsigned long udbh, unsigned long udbl, int tl1, struct pt_regs *regs)
{
printk(KERN_WARNING "CPU[%d]: Correctable ECC Error "
"AFSR[%lx] AFAR[%016lx] UDBL[%lx] UDBH[%lx] TL>1[%d]\n",
smp_processor_id(), afsr, afar, udbl, udbh, tl1);
spitfire_log_udb_syndrome(afar, udbh, udbl, UDBE_CE);
/* We always log it, even if someone is listening for this
* trap.
*/
notify_die(DIE_TRAP, "Correctable ECC Error", regs,
0, TRAP_TYPE_CEE, SIGTRAP);
/* The Correctable ECC Error trap does not disable I/D caches. So
* we only have to restore the ESTATE Error Enable register.
*/
spitfire_enable_estate_errors();
}
static void spitfire_ue_log(unsigned long afsr, unsigned long afar, unsigned long udbh, unsigned long udbl, unsigned long tt, int tl1, struct pt_regs *regs)
{
siginfo_t info;
printk(KERN_WARNING "CPU[%d]: Uncorrectable Error AFSR[%lx] "
"AFAR[%lx] UDBL[%lx] UDBH[%ld] TT[%lx] TL>1[%d]\n",
smp_processor_id(), afsr, afar, udbl, udbh, tt, tl1);
/* XXX add more human friendly logging of the error status
* XXX as is implemented for cheetah
*/
spitfire_log_udb_syndrome(afar, udbh, udbl, UDBE_UE);
/* We always log it, even if someone is listening for this
* trap.
*/
notify_die(DIE_TRAP, "Uncorrectable Error", regs,
0, tt, SIGTRAP);
if (regs->tstate & TSTATE_PRIV) {
if (tl1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("UE", regs);
}
/* XXX need more intelligent processing here, such as is implemented
* XXX for cheetah errors, in fact if the E-cache still holds the
* XXX line with bad parity this will loop
*/
spitfire_clean_and_reenable_l1_caches();
spitfire_enable_estate_errors();
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_OBJERR;
info.si_addr = (void *)0;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void spitfire_access_error(struct pt_regs *regs, unsigned long status_encoded, unsigned long afar)
{
unsigned long afsr, tt, udbh, udbl;
int tl1;
afsr = (status_encoded & SFSTAT_AFSR_MASK) >> SFSTAT_AFSR_SHIFT;
tt = (status_encoded & SFSTAT_TRAP_TYPE) >> SFSTAT_TRAP_TYPE_SHIFT;
tl1 = (status_encoded & SFSTAT_TL_GT_ONE) ? 1 : 0;
udbl = (status_encoded & SFSTAT_UDBL_MASK) >> SFSTAT_UDBL_SHIFT;
udbh = (status_encoded & SFSTAT_UDBH_MASK) >> SFSTAT_UDBH_SHIFT;
#ifdef CONFIG_PCI
if (tt == TRAP_TYPE_DAE &&
pci_poke_in_progress && pci_poke_cpu == smp_processor_id()) {
spitfire_clean_and_reenable_l1_caches();
spitfire_enable_estate_errors();
pci_poke_faulted = 1;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
if (afsr & SFAFSR_UE)
spitfire_ue_log(afsr, afar, udbh, udbl, tt, tl1, regs);
if (tt == TRAP_TYPE_CEE) {
/* Handle the case where we took a CEE trap, but ACK'd
* only the UE state in the UDB error registers.
*/
if (afsr & SFAFSR_UE) {
if (udbh & UDBE_CE) {
__asm__ __volatile__(
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (udbh & UDBE_CE),
"r" (0x0), "i" (ASI_UDB_ERROR_W));
}
if (udbl & UDBE_CE) {
__asm__ __volatile__(
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (udbl & UDBE_CE),
"r" (0x18), "i" (ASI_UDB_ERROR_W));
}
}
spitfire_cee_log(afsr, afar, udbh, udbl, tl1, regs);
}
}
int cheetah_pcache_forced_on;
void cheetah_enable_pcache(void)
{
unsigned long dcr;
printk("CHEETAH: Enabling P-Cache on cpu %d.\n",
smp_processor_id());
__asm__ __volatile__("ldxa [%%g0] %1, %0"
: "=r" (dcr)
: "i" (ASI_DCU_CONTROL_REG));
dcr |= (DCU_PE | DCU_HPE | DCU_SPE | DCU_SL);
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (dcr), "i" (ASI_DCU_CONTROL_REG));
}
/* Cheetah error trap handling. */
static unsigned long ecache_flush_physbase;
static unsigned long ecache_flush_linesize;
static unsigned long ecache_flush_size;
/* This table is ordered in priority of errors and matches the
* AFAR overwrite policy as well.
*/
struct afsr_error_table {
unsigned long mask;
const char *name;
};
static const char CHAFSR_PERR_msg[] =
"System interface protocol error";
static const char CHAFSR_IERR_msg[] =
"Internal processor error";
static const char CHAFSR_ISAP_msg[] =
"System request parity error on incoming address";
static const char CHAFSR_UCU_msg[] =
"Uncorrectable E-cache ECC error for ifetch/data";
static const char CHAFSR_UCC_msg[] =
"SW Correctable E-cache ECC error for ifetch/data";
static const char CHAFSR_UE_msg[] =
"Uncorrectable system bus data ECC error for read";
static const char CHAFSR_EDU_msg[] =
"Uncorrectable E-cache ECC error for stmerge/blkld";
static const char CHAFSR_EMU_msg[] =
"Uncorrectable system bus MTAG error";
static const char CHAFSR_WDU_msg[] =
"Uncorrectable E-cache ECC error for writeback";
static const char CHAFSR_CPU_msg[] =
"Uncorrectable ECC error for copyout";
static const char CHAFSR_CE_msg[] =
"HW corrected system bus data ECC error for read";
static const char CHAFSR_EDC_msg[] =
"HW corrected E-cache ECC error for stmerge/blkld";
static const char CHAFSR_EMC_msg[] =
"HW corrected system bus MTAG ECC error";
static const char CHAFSR_WDC_msg[] =
"HW corrected E-cache ECC error for writeback";
static const char CHAFSR_CPC_msg[] =
"HW corrected ECC error for copyout";
static const char CHAFSR_TO_msg[] =
"Unmapped error from system bus";
static const char CHAFSR_BERR_msg[] =
"Bus error response from system bus";
static const char CHAFSR_IVC_msg[] =
"HW corrected system bus data ECC error for ivec read";
static const char CHAFSR_IVU_msg[] =
"Uncorrectable system bus data ECC error for ivec read";
static struct afsr_error_table __cheetah_error_table[] = {
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ CHAFSR_EMU, CHAFSR_EMU_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ CHAFSR_EMC, CHAFSR_EMC_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVC, CHAFSR_IVC_msg },
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static const char CHPAFSR_DTO_msg[] =
"System bus unmapped error for prefetch/storequeue-read";
static const char CHPAFSR_DBERR_msg[] =
"System bus error for prefetch/storequeue-read";
static const char CHPAFSR_THCE_msg[] =
"Hardware corrected E-cache Tag ECC error";
static const char CHPAFSR_TSCE_msg[] =
"SW handled correctable E-cache Tag ECC error";
static const char CHPAFSR_TUE_msg[] =
"Uncorrectable E-cache Tag ECC error";
static const char CHPAFSR_DUE_msg[] =
"System bus uncorrectable data ECC error due to prefetch/store-fill";
static struct afsr_error_table __cheetah_plus_error_table[] = {
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ CHAFSR_EMU, CHAFSR_EMU_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ CHAFSR_EMC, CHAFSR_EMC_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
{ CHPAFSR_DTO, CHPAFSR_DTO_msg },
{ CHPAFSR_DBERR, CHPAFSR_DBERR_msg },
{ CHPAFSR_THCE, CHPAFSR_THCE_msg },
{ CHPAFSR_TSCE, CHPAFSR_TSCE_msg },
{ CHPAFSR_TUE, CHPAFSR_TUE_msg },
{ CHPAFSR_DUE, CHPAFSR_DUE_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVC, CHAFSR_IVC_msg },
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static const char JPAFSR_JETO_msg[] =
"System interface protocol error, hw timeout caused";
static const char JPAFSR_SCE_msg[] =
"Parity error on system snoop results";
static const char JPAFSR_JEIC_msg[] =
"System interface protocol error, illegal command detected";
static const char JPAFSR_JEIT_msg[] =
"System interface protocol error, illegal ADTYPE detected";
static const char JPAFSR_OM_msg[] =
"Out of range memory error has occurred";
static const char JPAFSR_ETP_msg[] =
"Parity error on L2 cache tag SRAM";
static const char JPAFSR_UMS_msg[] =
"Error due to unsupported store";
static const char JPAFSR_RUE_msg[] =
"Uncorrectable ECC error from remote cache/memory";
static const char JPAFSR_RCE_msg[] =
"Correctable ECC error from remote cache/memory";
static const char JPAFSR_BP_msg[] =
"JBUS parity error on returned read data";
static const char JPAFSR_WBP_msg[] =
"JBUS parity error on data for writeback or block store";
static const char JPAFSR_FRC_msg[] =
"Foreign read to DRAM incurring correctable ECC error";
static const char JPAFSR_FRU_msg[] =
"Foreign read to DRAM incurring uncorrectable ECC error";
static struct afsr_error_table __jalapeno_error_table[] = {
{ JPAFSR_JETO, JPAFSR_JETO_msg },
{ JPAFSR_SCE, JPAFSR_SCE_msg },
{ JPAFSR_JEIC, JPAFSR_JEIC_msg },
{ JPAFSR_JEIT, JPAFSR_JEIT_msg },
{ CHAFSR_PERR, CHAFSR_PERR_msg },
{ CHAFSR_IERR, CHAFSR_IERR_msg },
{ CHAFSR_ISAP, CHAFSR_ISAP_msg },
{ CHAFSR_UCU, CHAFSR_UCU_msg },
{ CHAFSR_UCC, CHAFSR_UCC_msg },
{ CHAFSR_UE, CHAFSR_UE_msg },
{ CHAFSR_EDU, CHAFSR_EDU_msg },
{ JPAFSR_OM, JPAFSR_OM_msg },
{ CHAFSR_WDU, CHAFSR_WDU_msg },
{ CHAFSR_CPU, CHAFSR_CPU_msg },
{ CHAFSR_CE, CHAFSR_CE_msg },
{ CHAFSR_EDC, CHAFSR_EDC_msg },
{ JPAFSR_ETP, JPAFSR_ETP_msg },
{ CHAFSR_WDC, CHAFSR_WDC_msg },
{ CHAFSR_CPC, CHAFSR_CPC_msg },
{ CHAFSR_TO, CHAFSR_TO_msg },
{ CHAFSR_BERR, CHAFSR_BERR_msg },
{ JPAFSR_UMS, JPAFSR_UMS_msg },
{ JPAFSR_RUE, JPAFSR_RUE_msg },
{ JPAFSR_RCE, JPAFSR_RCE_msg },
{ JPAFSR_BP, JPAFSR_BP_msg },
{ JPAFSR_WBP, JPAFSR_WBP_msg },
{ JPAFSR_FRC, JPAFSR_FRC_msg },
{ JPAFSR_FRU, JPAFSR_FRU_msg },
/* These two do not update the AFAR. */
{ CHAFSR_IVU, CHAFSR_IVU_msg },
{ 0, NULL },
};
static struct afsr_error_table *cheetah_error_table;
static unsigned long cheetah_afsr_errors;
struct cheetah_err_info *cheetah_error_log;
static inline struct cheetah_err_info *cheetah_get_error_log(unsigned long afsr)
{
struct cheetah_err_info *p;
int cpu = smp_processor_id();
if (!cheetah_error_log)
return NULL;
p = cheetah_error_log + (cpu * 2);
if ((afsr & CHAFSR_TL1) != 0UL)
p++;
return p;
}
extern unsigned int tl0_icpe[], tl1_icpe[];
extern unsigned int tl0_dcpe[], tl1_dcpe[];
extern unsigned int tl0_fecc[], tl1_fecc[];
extern unsigned int tl0_cee[], tl1_cee[];
extern unsigned int tl0_iae[], tl1_iae[];
extern unsigned int tl0_dae[], tl1_dae[];
extern unsigned int cheetah_plus_icpe_trap_vector[], cheetah_plus_icpe_trap_vector_tl1[];
extern unsigned int cheetah_plus_dcpe_trap_vector[], cheetah_plus_dcpe_trap_vector_tl1[];
extern unsigned int cheetah_fecc_trap_vector[], cheetah_fecc_trap_vector_tl1[];
extern unsigned int cheetah_cee_trap_vector[], cheetah_cee_trap_vector_tl1[];
extern unsigned int cheetah_deferred_trap_vector[], cheetah_deferred_trap_vector_tl1[];
void __init cheetah_ecache_flush_init(void)
{
unsigned long largest_size, smallest_linesize, order, ver;
int i, sz;
/* Scan all cpu device tree nodes, note two values:
* 1) largest E-cache size
* 2) smallest E-cache line size
*/
largest_size = 0UL;
smallest_linesize = ~0UL;
for (i = 0; i < NR_CPUS; i++) {
unsigned long val;
val = cpu_data(i).ecache_size;
if (!val)
continue;
if (val > largest_size)
largest_size = val;
val = cpu_data(i).ecache_line_size;
if (val < smallest_linesize)
smallest_linesize = val;
}
if (largest_size == 0UL || smallest_linesize == ~0UL) {
prom_printf("cheetah_ecache_flush_init: Cannot probe cpu E-cache "
"parameters.\n");
prom_halt();
}
ecache_flush_size = (2 * largest_size);
ecache_flush_linesize = smallest_linesize;
ecache_flush_physbase = find_ecache_flush_span(ecache_flush_size);
if (ecache_flush_physbase == ~0UL) {
prom_printf("cheetah_ecache_flush_init: Cannot find %d byte "
"contiguous physical memory.\n",
ecache_flush_size);
prom_halt();
}
/* Now allocate error trap reporting scoreboard. */
sz = NR_CPUS * (2 * sizeof(struct cheetah_err_info));
for (order = 0; order < MAX_ORDER; order++) {
if ((PAGE_SIZE << order) >= sz)
break;
}
cheetah_error_log = (struct cheetah_err_info *)
__get_free_pages(GFP_KERNEL, order);
if (!cheetah_error_log) {
prom_printf("cheetah_ecache_flush_init: Failed to allocate "
"error logging scoreboard (%d bytes).\n", sz);
prom_halt();
}
memset(cheetah_error_log, 0, PAGE_SIZE << order);
/* Mark all AFSRs as invalid so that the trap handler will
* log new new information there.
*/
for (i = 0; i < 2 * NR_CPUS; i++)
cheetah_error_log[i].afsr = CHAFSR_INVALID;
__asm__ ("rdpr %%ver, %0" : "=r" (ver));
if ((ver >> 32) == __JALAPENO_ID ||
(ver >> 32) == __SERRANO_ID) {
cheetah_error_table = &__jalapeno_error_table[0];
cheetah_afsr_errors = JPAFSR_ERRORS;
} else if ((ver >> 32) == 0x003e0015) {
cheetah_error_table = &__cheetah_plus_error_table[0];
cheetah_afsr_errors = CHPAFSR_ERRORS;
} else {
cheetah_error_table = &__cheetah_error_table[0];
cheetah_afsr_errors = CHAFSR_ERRORS;
}
/* Now patch trap tables. */
memcpy(tl0_fecc, cheetah_fecc_trap_vector, (8 * 4));
memcpy(tl1_fecc, cheetah_fecc_trap_vector_tl1, (8 * 4));
memcpy(tl0_cee, cheetah_cee_trap_vector, (8 * 4));
memcpy(tl1_cee, cheetah_cee_trap_vector_tl1, (8 * 4));
memcpy(tl0_iae, cheetah_deferred_trap_vector, (8 * 4));
memcpy(tl1_iae, cheetah_deferred_trap_vector_tl1, (8 * 4));
memcpy(tl0_dae, cheetah_deferred_trap_vector, (8 * 4));
memcpy(tl1_dae, cheetah_deferred_trap_vector_tl1, (8 * 4));
if (tlb_type == cheetah_plus) {
memcpy(tl0_dcpe, cheetah_plus_dcpe_trap_vector, (8 * 4));
memcpy(tl1_dcpe, cheetah_plus_dcpe_trap_vector_tl1, (8 * 4));
memcpy(tl0_icpe, cheetah_plus_icpe_trap_vector, (8 * 4));
memcpy(tl1_icpe, cheetah_plus_icpe_trap_vector_tl1, (8 * 4));
}
flushi(PAGE_OFFSET);
}
static void cheetah_flush_ecache(void)
{
unsigned long flush_base = ecache_flush_physbase;
unsigned long flush_linesize = ecache_flush_linesize;
unsigned long flush_size = ecache_flush_size;
__asm__ __volatile__("1: subcc %0, %4, %0\n\t"
" bne,pt %%xcc, 1b\n\t"
" ldxa [%2 + %0] %3, %%g0\n\t"
: "=&r" (flush_size)
: "0" (flush_size), "r" (flush_base),
"i" (ASI_PHYS_USE_EC), "r" (flush_linesize));
}
static void cheetah_flush_ecache_line(unsigned long physaddr)
{
unsigned long alias;
physaddr &= ~(8UL - 1UL);
physaddr = (ecache_flush_physbase +
(physaddr & ((ecache_flush_size>>1UL) - 1UL)));
alias = physaddr + (ecache_flush_size >> 1UL);
__asm__ __volatile__("ldxa [%0] %2, %%g0\n\t"
"ldxa [%1] %2, %%g0\n\t"
"membar #Sync"
: /* no outputs */
: "r" (physaddr), "r" (alias),
"i" (ASI_PHYS_USE_EC));
}
/* Unfortunately, the diagnostic access to the I-cache tags we need to
* use to clear the thing interferes with I-cache coherency transactions.
*
* So we must only flush the I-cache when it is disabled.
*/
static void __cheetah_flush_icache(void)
{
unsigned int icache_size, icache_line_size;
unsigned long addr;
icache_size = local_cpu_data().icache_size;
icache_line_size = local_cpu_data().icache_line_size;
/* Clear the valid bits in all the tags. */
for (addr = 0; addr < icache_size; addr += icache_line_size) {
__asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (addr | (2 << 3)),
"i" (ASI_IC_TAG));
}
}
static void cheetah_flush_icache(void)
{
unsigned long dcu_save;
/* Save current DCU, disable I-cache. */
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
"or %0, %2, %%g1\n\t"
"stxa %%g1, [%%g0] %1\n\t"
"membar #Sync"
: "=r" (dcu_save)
: "i" (ASI_DCU_CONTROL_REG), "i" (DCU_IC)
: "g1");
__cheetah_flush_icache();
/* Restore DCU register */
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (dcu_save), "i" (ASI_DCU_CONTROL_REG));
}
static void cheetah_flush_dcache(void)
{
unsigned int dcache_size, dcache_line_size;
unsigned long addr;
dcache_size = local_cpu_data().dcache_size;
dcache_line_size = local_cpu_data().dcache_line_size;
for (addr = 0; addr < dcache_size; addr += dcache_line_size) {
__asm__ __volatile__("stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (addr), "i" (ASI_DCACHE_TAG));
}
}
/* In order to make the even parity correct we must do two things.
* First, we clear DC_data_parity and set DC_utag to an appropriate value.
* Next, we clear out all 32-bytes of data for that line. Data of
* all-zero + tag parity value of zero == correct parity.
*/
static void cheetah_plus_zap_dcache_parity(void)
{
unsigned int dcache_size, dcache_line_size;
unsigned long addr;
dcache_size = local_cpu_data().dcache_size;
dcache_line_size = local_cpu_data().dcache_line_size;
for (addr = 0; addr < dcache_size; addr += dcache_line_size) {
unsigned long tag = (addr >> 14);
unsigned long line;
__asm__ __volatile__("membar #Sync\n\t"
"stxa %0, [%1] %2\n\t"
"membar #Sync"
: /* no outputs */
: "r" (tag), "r" (addr),
"i" (ASI_DCACHE_UTAG));
for (line = addr; line < addr + dcache_line_size; line += 8)
__asm__ __volatile__("membar #Sync\n\t"
"stxa %%g0, [%0] %1\n\t"
"membar #Sync"
: /* no outputs */
: "r" (line),
"i" (ASI_DCACHE_DATA));
}
}
/* Conversion tables used to frob Cheetah AFSR syndrome values into
* something palatable to the memory controller driver get_unumber
* routine.
*/
#define MT0 137
#define MT1 138
#define MT2 139
#define NONE 254
#define MTC0 140
#define MTC1 141
#define MTC2 142
#define MTC3 143
#define C0 128
#define C1 129
#define C2 130
#define C3 131
#define C4 132
#define C5 133
#define C6 134
#define C7 135
#define C8 136
#define M2 144
#define M3 145
#define M4 146
#define M 147
static unsigned char cheetah_ecc_syntab[] = {
/*00*/NONE, C0, C1, M2, C2, M2, M3, 47, C3, M2, M2, 53, M2, 41, 29, M,
/*01*/C4, M, M, 50, M2, 38, 25, M2, M2, 33, 24, M2, 11, M, M2, 16,
/*02*/C5, M, M, 46, M2, 37, 19, M2, M, 31, 32, M, 7, M2, M2, 10,
/*03*/M2, 40, 13, M2, 59, M, M2, 66, M, M2, M2, 0, M2, 67, 71, M,
/*04*/C6, M, M, 43, M, 36, 18, M, M2, 49, 15, M, 63, M2, M2, 6,
/*05*/M2, 44, 28, M2, M, M2, M2, 52, 68, M2, M2, 62, M2, M3, M3, M4,
/*06*/M2, 26, 106, M2, 64, M, M2, 2, 120, M, M2, M3, M, M3, M3, M4,
/*07*/116, M2, M2, M3, M2, M3, M, M4, M2, 58, 54, M2, M, M4, M4, M3,
/*08*/C7, M2, M, 42, M, 35, 17, M2, M, 45, 14, M2, 21, M2, M2, 5,
/*09*/M, 27, M, M, 99, M, M, 3, 114, M2, M2, 20, M2, M3, M3, M,
/*0a*/M2, 23, 113, M2, 112, M2, M, 51, 95, M, M2, M3, M2, M3, M3, M2,
/*0b*/103, M, M2, M3, M2, M3, M3, M4, M2, 48, M, M, 73, M2, M, M3,
/*0c*/M2, 22, 110, M2, 109, M2, M, 9, 108, M2, M, M3, M2, M3, M3, M,
/*0d*/102, M2, M, M, M2, M3, M3, M, M2, M3, M3, M2, M, M4, M, M3,
/*0e*/98, M, M2, M3, M2, M, M3, M4, M2, M3, M3, M4, M3, M, M, M,
/*0f*/M2, M3, M3, M, M3, M, M, M, 56, M4, M, M3, M4, M, M, M,
/*10*/C8, M, M2, 39, M, 34, 105, M2, M, 30, 104, M, 101, M, M, 4,
/*11*/M, M, 100, M, 83, M, M2, 12, 87, M, M, 57, M2, M, M3, M,
/*12*/M2, 97, 82, M2, 78, M2, M2, 1, 96, M, M, M, M, M, M3, M2,
/*13*/94, M, M2, M3, M2, M, M3, M, M2, M, 79, M, 69, M, M4, M,
/*14*/M2, 93, 92, M, 91, M, M2, 8, 90, M2, M2, M, M, M, M, M4,
/*15*/89, M, M, M3, M2, M3, M3, M, M, M, M3, M2, M3, M2, M, M3,
/*16*/86, M, M2, M3, M2, M, M3, M, M2, M, M3, M, M3, M, M, M3,
/*17*/M, M, M3, M2, M3, M2, M4, M, 60, M, M2, M3, M4, M, M, M2,
/*18*/M2, 88, 85, M2, 84, M, M2, 55, 81, M2, M2, M3, M2, M3, M3, M4,
/*19*/77, M, M, M, M2, M3, M, M, M2, M3, M3, M4, M3, M2, M, M,
/*1a*/74, M, M2, M3, M, M, M3, M, M, M, M3, M, M3, M, M4, M3,
/*1b*/M2, 70, 107, M4, 65, M2, M2, M, 127, M, M, M, M2, M3, M3, M,
/*1c*/80, M2, M2, 72, M, 119, 118, M, M2, 126, 76, M, 125, M, M4, M3,
/*1d*/M2, 115, 124, M, 75, M, M, M3, 61, M, M4, M, M4, M, M, M,
/*1e*/M, 123, 122, M4, 121, M4, M, M3, 117, M2, M2, M3, M4, M3, M, M,
/*1f*/111, M, M, M, M4, M3, M3, M, M, M, M3, M, M3, M2, M, M
};
static unsigned char cheetah_mtag_syntab[] = {
NONE, MTC0,
MTC1, NONE,
MTC2, NONE,
NONE, MT0,
MTC3, NONE,
NONE, MT1,
NONE, MT2,
NONE, NONE
};
/* Return the highest priority error conditon mentioned. */
static inline unsigned long cheetah_get_hipri(unsigned long afsr)
{
unsigned long tmp = 0;
int i;
for (i = 0; cheetah_error_table[i].mask; i++) {
if ((tmp = (afsr & cheetah_error_table[i].mask)) != 0UL)
return tmp;
}
return tmp;
}
static const char *cheetah_get_string(unsigned long bit)
{
int i;
for (i = 0; cheetah_error_table[i].mask; i++) {
if ((bit & cheetah_error_table[i].mask) != 0UL)
return cheetah_error_table[i].name;
}
return "???";
}
static void cheetah_log_errors(struct pt_regs *regs, struct cheetah_err_info *info,
unsigned long afsr, unsigned long afar, int recoverable)
{
unsigned long hipri;
char unum[256];
printk("%s" "ERROR(%d): Cheetah error trap taken afsr[%016lx] afar[%016lx] TL1(%d)\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
afsr, afar,
(afsr & CHAFSR_TL1) ? 1 : 0);
printk("%s" "ERROR(%d): TPC[%lx] TNPC[%lx] O7[%lx] TSTATE[%lx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
regs->tpc, regs->tnpc, regs->u_regs[UREG_I7], regs->tstate);
printk("%s" "ERROR(%d): ",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id());
printk("TPC<%pS>\n", (void *) regs->tpc);
printk("%s" "ERROR(%d): M_SYND(%lx), E_SYND(%lx)%s%s\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(afsr & CHAFSR_M_SYNDROME) >> CHAFSR_M_SYNDROME_SHIFT,
(afsr & CHAFSR_E_SYNDROME) >> CHAFSR_E_SYNDROME_SHIFT,
(afsr & CHAFSR_ME) ? ", Multiple Errors" : "",
(afsr & CHAFSR_PRIV) ? ", Privileged" : "");
hipri = cheetah_get_hipri(afsr);
printk("%s" "ERROR(%d): Highest priority error (%016lx) \"%s\"\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
hipri, cheetah_get_string(hipri));
/* Try to get unumber if relevant. */
#define ESYND_ERRORS (CHAFSR_IVC | CHAFSR_IVU | \
CHAFSR_CPC | CHAFSR_CPU | \
CHAFSR_UE | CHAFSR_CE | \
CHAFSR_EDC | CHAFSR_EDU | \
CHAFSR_UCC | CHAFSR_UCU | \
CHAFSR_WDU | CHAFSR_WDC)
#define MSYND_ERRORS (CHAFSR_EMC | CHAFSR_EMU)
if (afsr & ESYND_ERRORS) {
int syndrome;
int ret;
syndrome = (afsr & CHAFSR_E_SYNDROME) >> CHAFSR_E_SYNDROME_SHIFT;
syndrome = cheetah_ecc_syntab[syndrome];
ret = sprintf_dimm(syndrome, afar, unum, sizeof(unum));
if (ret != -1)
printk("%s" "ERROR(%d): AFAR E-syndrome [%s]\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
smp_processor_id(), unum);
} else if (afsr & MSYND_ERRORS) {
int syndrome;
int ret;
syndrome = (afsr & CHAFSR_M_SYNDROME) >> CHAFSR_M_SYNDROME_SHIFT;
syndrome = cheetah_mtag_syntab[syndrome];
ret = sprintf_dimm(syndrome, afar, unum, sizeof(unum));
if (ret != -1)
printk("%s" "ERROR(%d): AFAR M-syndrome [%s]\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
smp_processor_id(), unum);
}
/* Now dump the cache snapshots. */
printk("%s" "ERROR(%d): D-cache idx[%x] tag[%016llx] utag[%016llx] stag[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->dcache_index,
info->dcache_tag,
info->dcache_utag,
info->dcache_stag);
printk("%s" "ERROR(%d): D-cache data0[%016llx] data1[%016llx] data2[%016llx] data3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->dcache_data[0],
info->dcache_data[1],
info->dcache_data[2],
info->dcache_data[3]);
printk("%s" "ERROR(%d): I-cache idx[%x] tag[%016llx] utag[%016llx] stag[%016llx] "
"u[%016llx] l[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->icache_index,
info->icache_tag,
info->icache_utag,
info->icache_stag,
info->icache_upper,
info->icache_lower);
printk("%s" "ERROR(%d): I-cache INSN0[%016llx] INSN1[%016llx] INSN2[%016llx] INSN3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->icache_data[0],
info->icache_data[1],
info->icache_data[2],
info->icache_data[3]);
printk("%s" "ERROR(%d): I-cache INSN4[%016llx] INSN5[%016llx] INSN6[%016llx] INSN7[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->icache_data[4],
info->icache_data[5],
info->icache_data[6],
info->icache_data[7]);
printk("%s" "ERROR(%d): E-cache idx[%x] tag[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
(int) info->ecache_index, info->ecache_tag);
printk("%s" "ERROR(%d): E-cache data0[%016llx] data1[%016llx] data2[%016llx] data3[%016llx]\n",
(recoverable ? KERN_WARNING : KERN_CRIT), smp_processor_id(),
info->ecache_data[0],
info->ecache_data[1],
info->ecache_data[2],
info->ecache_data[3]);
afsr = (afsr & ~hipri) & cheetah_afsr_errors;
while (afsr != 0UL) {
unsigned long bit = cheetah_get_hipri(afsr);
printk("%s" "ERROR: Multiple-error (%016lx) \"%s\"\n",
(recoverable ? KERN_WARNING : KERN_CRIT),
bit, cheetah_get_string(bit));
afsr &= ~bit;
}
if (!recoverable)
printk(KERN_CRIT "ERROR: This condition is not recoverable.\n");
}
static int cheetah_recheck_errors(struct cheetah_err_info *logp)
{
unsigned long afsr, afar;
int ret = 0;
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
: "=r" (afsr)
: "i" (ASI_AFSR));
if ((afsr & cheetah_afsr_errors) != 0) {
if (logp != NULL) {
__asm__ __volatile__("ldxa [%%g0] %1, %0\n\t"
: "=r" (afar)
: "i" (ASI_AFAR));
logp->afsr = afsr;
logp->afar = afar;
}
ret = 1;
}
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync\n\t"
: : "r" (afsr), "i" (ASI_AFSR));
return ret;
}
void cheetah_fecc_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable;
/* Flush E-cache */
cheetah_flush_ecache();
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early Fast-ECC error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR. What we are looking for here is whether a new
* error was logged while we had error reporting traps disabled.
*/
if (cheetah_recheck_errors(&local_snapshot)) {
unsigned long new_afsr = local_snapshot.afsr;
/* If we got a new asynchronous error, die... */
if (new_afsr & (CHAFSR_EMU | CHAFSR_EDU |
CHAFSR_WDU | CHAFSR_CPU |
CHAFSR_IVU | CHAFSR_UE |
CHAFSR_BERR | CHAFSR_TO))
recoverable = 0;
}
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
if (!recoverable)
panic("Irrecoverable Fast-ECC error trap.\n");
/* Flush E-cache to kick the error trap handlers out. */
cheetah_flush_ecache();
}
/* Try to fix a correctable error by pushing the line out from
* the E-cache. Recheck error reporting registers to see if the
* problem is intermittent.
*/
static int cheetah_fix_ce(unsigned long physaddr)
{
unsigned long orig_estate;
unsigned long alias1, alias2;
int ret;
/* Make sure correctable error traps are disabled. */
__asm__ __volatile__("ldxa [%%g0] %2, %0\n\t"
"andn %0, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %2\n\t"
"membar #Sync"
: "=&r" (orig_estate)
: "i" (ESTATE_ERROR_CEEN),
"i" (ASI_ESTATE_ERROR_EN)
: "g1");
/* We calculate alias addresses that will force the
* cache line in question out of the E-cache. Then
* we bring it back in with an atomic instruction so
* that we get it in some modified/exclusive state,
* then we displace it again to try and get proper ECC
* pushed back into the system.
*/
physaddr &= ~(8UL - 1UL);
alias1 = (ecache_flush_physbase +
(physaddr & ((ecache_flush_size >> 1) - 1)));
alias2 = alias1 + (ecache_flush_size >> 1);
__asm__ __volatile__("ldxa [%0] %3, %%g0\n\t"
"ldxa [%1] %3, %%g0\n\t"
"casxa [%2] %3, %%g0, %%g0\n\t"
"ldxa [%0] %3, %%g0\n\t"
"ldxa [%1] %3, %%g0\n\t"
"membar #Sync"
: /* no outputs */
: "r" (alias1), "r" (alias2),
"r" (physaddr), "i" (ASI_PHYS_USE_EC));
/* Did that trigger another error? */
if (cheetah_recheck_errors(NULL)) {
/* Try one more time. */
__asm__ __volatile__("ldxa [%0] %1, %%g0\n\t"
"membar #Sync"
: : "r" (physaddr), "i" (ASI_PHYS_USE_EC));
if (cheetah_recheck_errors(NULL))
ret = 2;
else
ret = 1;
} else {
/* No new error, intermittent problem. */
ret = 0;
}
/* Restore error enables. */
__asm__ __volatile__("stxa %0, [%%g0] %1\n\t"
"membar #Sync"
: : "r" (orig_estate), "i" (ASI_ESTATE_ERROR_EN));
return ret;
}
/* Return non-zero if PADDR is a valid physical memory address. */
static int cheetah_check_main_memory(unsigned long paddr)
{
unsigned long vaddr = PAGE_OFFSET + paddr;
if (vaddr > (unsigned long) high_memory)
return 0;
return kern_addr_valid(vaddr);
}
void cheetah_cee_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable, is_memory;
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early CEE error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
is_memory = cheetah_check_main_memory(afar);
if (is_memory && (afsr & CHAFSR_CE) != 0UL) {
/* XXX Might want to log the results of this operation
* XXX somewhere... -DaveM
*/
cheetah_fix_ce(afar);
}
{
int flush_all, flush_line;
flush_all = flush_line = 0;
if ((afsr & CHAFSR_EDC) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_EDC)
flush_line = 1;
else
flush_all = 1;
} else if ((afsr & CHAFSR_CPC) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_CPC)
flush_line = 1;
else
flush_all = 1;
}
/* Trap handler only disabled I-cache, flush it. */
cheetah_flush_icache();
/* Re-enable I-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_IC)
: "g1");
if (flush_all)
cheetah_flush_ecache();
else if (flush_line)
cheetah_flush_ecache_line(afar);
}
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR */
(void) cheetah_recheck_errors(&local_snapshot);
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
if (!recoverable)
panic("Irrecoverable Correctable-ECC error trap.\n");
}
void cheetah_deferred_handler(struct pt_regs *regs, unsigned long afsr, unsigned long afar)
{
struct cheetah_err_info local_snapshot, *p;
int recoverable, is_memory;
#ifdef CONFIG_PCI
/* Check for the special PCI poke sequence. */
if (pci_poke_in_progress && pci_poke_cpu == smp_processor_id()) {
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
(void) cheetah_recheck_errors(NULL);
pci_poke_faulted = 1;
regs->tpc += 4;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
p = cheetah_get_error_log(afsr);
if (!p) {
prom_printf("ERROR: Early deferred error afsr[%016lx] afar[%016lx]\n",
afsr, afar);
prom_printf("ERROR: CPU(%d) TPC[%016lx] TNPC[%016lx] TSTATE[%016lx]\n",
smp_processor_id(), regs->tpc, regs->tnpc, regs->tstate);
prom_halt();
}
/* Grab snapshot of logged error. */
memcpy(&local_snapshot, p, sizeof(local_snapshot));
/* If the current trap snapshot does not match what the
* trap handler passed along into our args, big trouble.
* In such a case, mark the local copy as invalid.
*
* Else, it matches and we mark the afsr in the non-local
* copy as invalid so we may log new error traps there.
*/
if (p->afsr != afsr || p->afar != afar)
local_snapshot.afsr = CHAFSR_INVALID;
else
p->afsr = CHAFSR_INVALID;
is_memory = cheetah_check_main_memory(afar);
{
int flush_all, flush_line;
flush_all = flush_line = 0;
if ((afsr & CHAFSR_EDU) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_EDU)
flush_line = 1;
else
flush_all = 1;
} else if ((afsr & CHAFSR_BERR) != 0UL) {
if ((afsr & cheetah_afsr_errors) == CHAFSR_BERR)
flush_line = 1;
else
flush_all = 1;
}
cheetah_flush_icache();
cheetah_flush_dcache();
/* Re-enable I/D caches */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_IC | DCU_DC)
: "g1");
if (flush_all)
cheetah_flush_ecache();
else if (flush_line)
cheetah_flush_ecache_line(afar);
}
/* Re-enable error reporting */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_ESTATE_ERROR_EN),
"i" (ESTATE_ERROR_NCEEN | ESTATE_ERROR_CEEN)
: "g1");
/* Decide if we can continue after handling this trap and
* logging the error.
*/
recoverable = 1;
if (afsr & (CHAFSR_PERR | CHAFSR_IERR | CHAFSR_ISAP))
recoverable = 0;
/* Re-check AFSR/AFAR. What we are looking for here is whether a new
* error was logged while we had error reporting traps disabled.
*/
if (cheetah_recheck_errors(&local_snapshot)) {
unsigned long new_afsr = local_snapshot.afsr;
/* If we got a new asynchronous error, die... */
if (new_afsr & (CHAFSR_EMU | CHAFSR_EDU |
CHAFSR_WDU | CHAFSR_CPU |
CHAFSR_IVU | CHAFSR_UE |
CHAFSR_BERR | CHAFSR_TO))
recoverable = 0;
}
/* Log errors. */
cheetah_log_errors(regs, &local_snapshot, afsr, afar, recoverable);
/* "Recoverable" here means we try to yank the page from ever
* being newly used again. This depends upon a few things:
* 1) Must be main memory, and AFAR must be valid.
* 2) If we trapped from user, OK.
* 3) Else, if we trapped from kernel we must find exception
* table entry (ie. we have to have been accessing user
* space).
*
* If AFAR is not in main memory, or we trapped from kernel
* and cannot find an exception table entry, it is unacceptable
* to try and continue.
*/
if (recoverable && is_memory) {
if ((regs->tstate & TSTATE_PRIV) == 0UL) {
/* OK, usermode access. */
recoverable = 1;
} else {
const struct exception_table_entry *entry;
entry = search_exception_tables(regs->tpc);
if (entry) {
/* OK, kernel access to userspace. */
recoverable = 1;
} else {
/* BAD, privileged state is corrupted. */
recoverable = 0;
}
if (recoverable) {
if (pfn_valid(afar >> PAGE_SHIFT))
get_page(pfn_to_page(afar >> PAGE_SHIFT));
else
recoverable = 0;
/* Only perform fixup if we still have a
* recoverable condition.
*/
if (recoverable) {
regs->tpc = entry->fixup;
regs->tnpc = regs->tpc + 4;
}
}
}
} else {
recoverable = 0;
}
if (!recoverable)
panic("Irrecoverable deferred error trap.\n");
}
/* Handle a D/I cache parity error trap. TYPE is encoded as:
*
* Bit0: 0=dcache,1=icache
* Bit1: 0=recoverable,1=unrecoverable
*
* The hardware has disabled both the I-cache and D-cache in
* the %dcr register.
*/
void cheetah_plus_parity_error(int type, struct pt_regs *regs)
{
if (type & 0x1)
__cheetah_flush_icache();
else
cheetah_plus_zap_dcache_parity();
cheetah_flush_dcache();
/* Re-enable I-cache/D-cache */
__asm__ __volatile__("ldxa [%%g0] %0, %%g1\n\t"
"or %%g1, %1, %%g1\n\t"
"stxa %%g1, [%%g0] %0\n\t"
"membar #Sync"
: /* no outputs */
: "i" (ASI_DCU_CONTROL_REG),
"i" (DCU_DC | DCU_IC)
: "g1");
if (type & 0x2) {
printk(KERN_EMERG "CPU[%d]: Cheetah+ %c-cache parity error at TPC[%016lx]\n",
smp_processor_id(),
(type & 0x1) ? 'I' : 'D',
regs->tpc);
printk(KERN_EMERG "TPC<%pS>\n", (void *) regs->tpc);
panic("Irrecoverable Cheetah+ parity error.");
}
printk(KERN_WARNING "CPU[%d]: Cheetah+ %c-cache parity error at TPC[%016lx]\n",
smp_processor_id(),
(type & 0x1) ? 'I' : 'D',
regs->tpc);
printk(KERN_WARNING "TPC<%pS>\n", (void *) regs->tpc);
}
struct sun4v_error_entry {
u64 err_handle;
u64 err_stick;
u32 err_type;
#define SUN4V_ERR_TYPE_UNDEFINED 0
#define SUN4V_ERR_TYPE_UNCORRECTED_RES 1
#define SUN4V_ERR_TYPE_PRECISE_NONRES 2
#define SUN4V_ERR_TYPE_DEFERRED_NONRES 3
#define SUN4V_ERR_TYPE_WARNING_RES 4
u32 err_attrs;
#define SUN4V_ERR_ATTRS_PROCESSOR 0x00000001
#define SUN4V_ERR_ATTRS_MEMORY 0x00000002
#define SUN4V_ERR_ATTRS_PIO 0x00000004
#define SUN4V_ERR_ATTRS_INT_REGISTERS 0x00000008
#define SUN4V_ERR_ATTRS_FPU_REGISTERS 0x00000010
#define SUN4V_ERR_ATTRS_USER_MODE 0x01000000
#define SUN4V_ERR_ATTRS_PRIV_MODE 0x02000000
#define SUN4V_ERR_ATTRS_RES_QUEUE_FULL 0x80000000
u64 err_raddr;
u32 err_size;
u16 err_cpu;
u16 err_pad;
};
static atomic_t sun4v_resum_oflow_cnt = ATOMIC_INIT(0);
static atomic_t sun4v_nonresum_oflow_cnt = ATOMIC_INIT(0);
static const char *sun4v_err_type_to_str(u32 type)
{
switch (type) {
case SUN4V_ERR_TYPE_UNDEFINED:
return "undefined";
case SUN4V_ERR_TYPE_UNCORRECTED_RES:
return "uncorrected resumable";
case SUN4V_ERR_TYPE_PRECISE_NONRES:
return "precise nonresumable";
case SUN4V_ERR_TYPE_DEFERRED_NONRES:
return "deferred nonresumable";
case SUN4V_ERR_TYPE_WARNING_RES:
return "warning resumable";
default:
return "unknown";
}
}
static void sun4v_log_error(struct pt_regs *regs, struct sun4v_error_entry *ent, int cpu, const char *pfx, atomic_t *ocnt)
{
int cnt;
printk("%s: Reporting on cpu %d\n", pfx, cpu);
printk("%s: err_handle[%llx] err_stick[%llx] err_type[%08x:%s]\n",
pfx,
ent->err_handle, ent->err_stick,
ent->err_type,
sun4v_err_type_to_str(ent->err_type));
printk("%s: err_attrs[%08x:%s %s %s %s %s %s %s %s]\n",
pfx,
ent->err_attrs,
((ent->err_attrs & SUN4V_ERR_ATTRS_PROCESSOR) ?
"processor" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_MEMORY) ?
"memory" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_PIO) ?
"pio" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_INT_REGISTERS) ?
"integer-regs" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_FPU_REGISTERS) ?
"fpu-regs" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_USER_MODE) ?
"user" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_PRIV_MODE) ?
"privileged" : ""),
((ent->err_attrs & SUN4V_ERR_ATTRS_RES_QUEUE_FULL) ?
"queue-full" : ""));
printk("%s: err_raddr[%016llx] err_size[%u] err_cpu[%u]\n",
pfx,
ent->err_raddr, ent->err_size, ent->err_cpu);
show_regs(regs);
if ((cnt = atomic_read(ocnt)) != 0) {
atomic_set(ocnt, 0);
wmb();
printk("%s: Queue overflowed %d times.\n",
pfx, cnt);
}
}
/* We run with %pil set to PIL_NORMAL_MAX and PSTATE_IE enabled in %pstate.
* Log the event and clear the first word of the entry.
*/
void sun4v_resum_error(struct pt_regs *regs, unsigned long offset)
{
struct sun4v_error_entry *ent, local_copy;
struct trap_per_cpu *tb;
unsigned long paddr;
int cpu;
cpu = get_cpu();
tb = &trap_block[cpu];
paddr = tb->resum_kernel_buf_pa + offset;
ent = __va(paddr);
memcpy(&local_copy, ent, sizeof(struct sun4v_error_entry));
/* We have a local copy now, so release the entry. */
ent->err_handle = 0;
wmb();
put_cpu();
if (ent->err_type == SUN4V_ERR_TYPE_WARNING_RES) {
/* If err_type is 0x4, it's a powerdown request. Do
* not do the usual resumable error log because that
* makes it look like some abnormal error.
*/
printk(KERN_INFO "Power down request...\n");
kill_cad_pid(SIGINT, 1);
return;
}
sun4v_log_error(regs, &local_copy, cpu,
KERN_ERR "RESUMABLE ERROR",
&sun4v_resum_oflow_cnt);
}
/* If we try to printk() we'll probably make matters worse, by trying
* to retake locks this cpu already holds or causing more errors. So
* just bump a counter, and we'll report these counter bumps above.
*/
void sun4v_resum_overflow(struct pt_regs *regs)
{
atomic_inc(&sun4v_resum_oflow_cnt);
}
/* We run with %pil set to PIL_NORMAL_MAX and PSTATE_IE enabled in %pstate.
* Log the event, clear the first word of the entry, and die.
*/
void sun4v_nonresum_error(struct pt_regs *regs, unsigned long offset)
{
struct sun4v_error_entry *ent, local_copy;
struct trap_per_cpu *tb;
unsigned long paddr;
int cpu;
cpu = get_cpu();
tb = &trap_block[cpu];
paddr = tb->nonresum_kernel_buf_pa + offset;
ent = __va(paddr);
memcpy(&local_copy, ent, sizeof(struct sun4v_error_entry));
/* We have a local copy now, so release the entry. */
ent->err_handle = 0;
wmb();
put_cpu();
#ifdef CONFIG_PCI
/* Check for the special PCI poke sequence. */
if (pci_poke_in_progress && pci_poke_cpu == cpu) {
pci_poke_faulted = 1;
regs->tpc += 4;
regs->tnpc = regs->tpc + 4;
return;
}
#endif
sun4v_log_error(regs, &local_copy, cpu,
KERN_EMERG "NON-RESUMABLE ERROR",
&sun4v_nonresum_oflow_cnt);
panic("Non-resumable error.");
}
/* If we try to printk() we'll probably make matters worse, by trying
* to retake locks this cpu already holds or causing more errors. So
* just bump a counter, and we'll report these counter bumps above.
*/
void sun4v_nonresum_overflow(struct pt_regs *regs)
{
/* XXX Actually even this can make not that much sense. Perhaps
* XXX we should just pull the plug and panic directly from here?
*/
atomic_inc(&sun4v_nonresum_oflow_cnt);
}
unsigned long sun4v_err_itlb_vaddr;
unsigned long sun4v_err_itlb_ctx;
unsigned long sun4v_err_itlb_pte;
unsigned long sun4v_err_itlb_error;
void sun4v_itlb_error_report(struct pt_regs *regs, int tl)
{
if (tl > 1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
printk(KERN_EMERG "SUN4V-ITLB: Error at TPC[%lx], tl %d\n",
regs->tpc, tl);
printk(KERN_EMERG "SUN4V-ITLB: TPC<%pS>\n", (void *) regs->tpc);
printk(KERN_EMERG "SUN4V-ITLB: O7[%lx]\n", regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-ITLB: O7<%pS>\n",
(void *) regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-ITLB: vaddr[%lx] ctx[%lx] "
"pte[%lx] error[%lx]\n",
sun4v_err_itlb_vaddr, sun4v_err_itlb_ctx,
sun4v_err_itlb_pte, sun4v_err_itlb_error);
prom_halt();
}
unsigned long sun4v_err_dtlb_vaddr;
unsigned long sun4v_err_dtlb_ctx;
unsigned long sun4v_err_dtlb_pte;
unsigned long sun4v_err_dtlb_error;
void sun4v_dtlb_error_report(struct pt_regs *regs, int tl)
{
if (tl > 1)
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
printk(KERN_EMERG "SUN4V-DTLB: Error at TPC[%lx], tl %d\n",
regs->tpc, tl);
printk(KERN_EMERG "SUN4V-DTLB: TPC<%pS>\n", (void *) regs->tpc);
printk(KERN_EMERG "SUN4V-DTLB: O7[%lx]\n", regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-DTLB: O7<%pS>\n",
(void *) regs->u_regs[UREG_I7]);
printk(KERN_EMERG "SUN4V-DTLB: vaddr[%lx] ctx[%lx] "
"pte[%lx] error[%lx]\n",
sun4v_err_dtlb_vaddr, sun4v_err_dtlb_ctx,
sun4v_err_dtlb_pte, sun4v_err_dtlb_error);
prom_halt();
}
void hypervisor_tlbop_error(unsigned long err, unsigned long op)
{
printk(KERN_CRIT "SUN4V: TLB hv call error %lu for op %lu\n",
err, op);
}
void hypervisor_tlbop_error_xcall(unsigned long err, unsigned long op)
{
printk(KERN_CRIT "SUN4V: XCALL TLB hv call error %lu for op %lu\n",
err, op);
}
void do_fpe_common(struct pt_regs *regs)
{
if (regs->tstate & TSTATE_PRIV) {
regs->tpc = regs->tnpc;
regs->tnpc += 4;
} else {
unsigned long fsr = current_thread_info()->xfsr[0];
siginfo_t info;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
info.si_code = __SI_FAULT;
if ((fsr & 0x1c000) == (1 << 14)) {
if (fsr & 0x10)
info.si_code = FPE_FLTINV;
else if (fsr & 0x08)
info.si_code = FPE_FLTOVF;
else if (fsr & 0x04)
info.si_code = FPE_FLTUND;
else if (fsr & 0x02)
info.si_code = FPE_FLTDIV;
else if (fsr & 0x01)
info.si_code = FPE_FLTRES;
}
force_sig_info(SIGFPE, &info, current);
}
}
void do_fpieee(struct pt_regs *regs)
{
if (notify_die(DIE_TRAP, "fpu exception ieee", regs,
0, 0x24, SIGFPE) == NOTIFY_STOP)
return;
do_fpe_common(regs);
}
extern int do_mathemu(struct pt_regs *, struct fpustate *);
void do_fpother(struct pt_regs *regs)
{
struct fpustate *f = FPUSTATE;
int ret = 0;
if (notify_die(DIE_TRAP, "fpu exception other", regs,
0, 0x25, SIGFPE) == NOTIFY_STOP)
return;
switch ((current_thread_info()->xfsr[0] & 0x1c000)) {
case (2 << 14): /* unfinished_FPop */
case (3 << 14): /* unimplemented_FPop */
ret = do_mathemu(regs, f);
break;
}
if (ret)
return;
do_fpe_common(regs);
}
void do_tof(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "tagged arithmetic overflow", regs,
0, 0x26, SIGEMT) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV)
die_if_kernel("Penguin overflow trap from kernel mode", regs);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGEMT;
info.si_errno = 0;
info.si_code = EMT_TAGOVF;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGEMT, &info, current);
}
void do_div0(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "integer division by zero", regs,
0, 0x28, SIGFPE) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV)
die_if_kernel("TL0: Kernel divide by zero.", regs);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGFPE;
info.si_errno = 0;
info.si_code = FPE_INTDIV;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGFPE, &info, current);
}
static void instruction_dump(unsigned int *pc)
{
int i;
if ((((unsigned long) pc) & 3))
return;
printk("Instruction DUMP:");
for (i = -3; i < 6; i++)
printk("%c%08x%c",i?' ':'<',pc[i],i?' ':'>');
printk("\n");
}
static void user_instruction_dump(unsigned int __user *pc)
{
int i;
unsigned int buf[9];
if ((((unsigned long) pc) & 3))
return;
if (copy_from_user(buf, pc - 3, sizeof(buf)))
return;
printk("Instruction DUMP:");
for (i = 0; i < 9; i++)
printk("%c%08x%c",i==3?' ':'<',buf[i],i==3?' ':'>');
printk("\n");
}
void show_stack(struct task_struct *tsk, unsigned long *_ksp)
{
unsigned long fp, ksp;
struct thread_info *tp;
int count = 0;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
int graph = 0;
#endif
ksp = (unsigned long) _ksp;
if (!tsk)
tsk = current;
tp = task_thread_info(tsk);
if (ksp == 0UL) {
if (tsk == current)
asm("mov %%fp, %0" : "=r" (ksp));
else
ksp = tp->ksp;
}
if (tp == current_thread_info())
flushw_all();
fp = ksp + STACK_BIAS;
printk("Call Trace:\n");
do {
struct sparc_stackf *sf;
struct pt_regs *regs;
unsigned long pc;
if (!kstack_valid(tp, fp))
break;
sf = (struct sparc_stackf *) fp;
regs = (struct pt_regs *) (sf + 1);
if (kstack_is_trap_frame(tp, regs)) {
if (!(regs->tstate & TSTATE_PRIV))
break;
pc = regs->tpc;
fp = regs->u_regs[UREG_I6] + STACK_BIAS;
} else {
pc = sf->callers_pc;
fp = (unsigned long)sf->fp + STACK_BIAS;
}
printk(" [%016lx] %pS\n", pc, (void *) pc);
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
if ((pc + 8UL) == (unsigned long) &return_to_handler) {
int index = tsk->curr_ret_stack;
if (tsk->ret_stack && index >= graph) {
pc = tsk->ret_stack[index - graph].ret;
printk(" [%016lx] %pS\n", pc, (void *) pc);
graph++;
}
}
#endif
} while (++count < 16);
}
void dump_stack(void)
{
show_stack(current, NULL);
}
EXPORT_SYMBOL(dump_stack);
static inline struct reg_window *kernel_stack_up(struct reg_window *rw)
{
unsigned long fp = rw->ins[6];
if (!fp)
return NULL;
return (struct reg_window *) (fp + STACK_BIAS);
}
void die_if_kernel(char *str, struct pt_regs *regs)
{
static int die_counter;
int count = 0;
/* Amuse the user. */
printk(
" \\|/ ____ \\|/\n"
" \"@'/ .. \\`@\"\n"
" /_| \\__/ |_\\\n"
" \\__U_/\n");
printk("%s(%d): %s [#%d]\n", current->comm, task_pid_nr(current), str, ++die_counter);
notify_die(DIE_OOPS, str, regs, 0, 255, SIGSEGV);
__asm__ __volatile__("flushw");
show_regs(regs);
add_taint(TAINT_DIE);
if (regs->tstate & TSTATE_PRIV) {
struct thread_info *tp = current_thread_info();
struct reg_window *rw = (struct reg_window *)
(regs->u_regs[UREG_FP] + STACK_BIAS);
/* Stop the back trace when we hit userland or we
* find some badly aligned kernel stack.
*/
while (rw &&
count++ < 30 &&
kstack_valid(tp, (unsigned long) rw)) {
printk("Caller[%016lx]: %pS\n", rw->ins[7],
(void *) rw->ins[7]);
rw = kernel_stack_up(rw);
}
instruction_dump ((unsigned int *) regs->tpc);
} else {
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
user_instruction_dump ((unsigned int __user *) regs->tpc);
}
if (regs->tstate & TSTATE_PRIV)
do_exit(SIGKILL);
do_exit(SIGSEGV);
}
EXPORT_SYMBOL(die_if_kernel);
#define VIS_OPCODE_MASK ((0x3 << 30) | (0x3f << 19))
#define VIS_OPCODE_VAL ((0x2 << 30) | (0x36 << 19))
extern int handle_popc(u32 insn, struct pt_regs *regs);
extern int handle_ldf_stq(u32 insn, struct pt_regs *regs);
void do_illegal_instruction(struct pt_regs *regs)
{
unsigned long pc = regs->tpc;
unsigned long tstate = regs->tstate;
u32 insn;
siginfo_t info;
if (notify_die(DIE_TRAP, "illegal instruction", regs,
0, 0x10, SIGILL) == NOTIFY_STOP)
return;
if (tstate & TSTATE_PRIV)
die_if_kernel("Kernel illegal instruction", regs);
if (test_thread_flag(TIF_32BIT))
pc = (u32)pc;
if (get_user(insn, (u32 __user *) pc) != -EFAULT) {
if ((insn & 0xc1ffc000) == 0x81700000) /* POPC */ {
if (handle_popc(insn, regs))
return;
} else if ((insn & 0xc1580000) == 0xc1100000) /* LDQ/STQ */ {
if (handle_ldf_stq(insn, regs))
return;
} else if (tlb_type == hypervisor) {
if ((insn & VIS_OPCODE_MASK) == VIS_OPCODE_VAL) {
if (!vis_emul(regs, insn))
return;
} else {
struct fpustate *f = FPUSTATE;
/* XXX maybe verify XFSR bits like
* XXX do_fpother() does?
*/
if (do_mathemu(regs, f))
return;
}
}
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_ILLOPC;
info.si_addr = (void __user *)pc;
info.si_trapno = 0;
force_sig_info(SIGILL, &info, current);
}
extern void kernel_unaligned_trap(struct pt_regs *regs, unsigned int insn);
void mem_address_unaligned(struct pt_regs *regs, unsigned long sfar, unsigned long sfsr)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "memory address unaligned", regs,
0, 0x34, SIGSEGV) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
kernel_unaligned_trap(regs, *((unsigned int *)regs->tpc));
return;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *)sfar;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void sun4v_do_mna(struct pt_regs *regs, unsigned long addr, unsigned long type_ctx)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "memory address unaligned", regs,
0, 0x34, SIGSEGV) == NOTIFY_STOP)
return;
if (regs->tstate & TSTATE_PRIV) {
kernel_unaligned_trap(regs, *((unsigned int *)regs->tpc));
return;
}
info.si_signo = SIGBUS;
info.si_errno = 0;
info.si_code = BUS_ADRALN;
info.si_addr = (void __user *) addr;
info.si_trapno = 0;
force_sig_info(SIGBUS, &info, current);
}
void do_privop(struct pt_regs *regs)
{
siginfo_t info;
if (notify_die(DIE_TRAP, "privileged operation", regs,
0, 0x11, SIGILL) == NOTIFY_STOP)
return;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
info.si_signo = SIGILL;
info.si_errno = 0;
info.si_code = ILL_PRVOPC;
info.si_addr = (void __user *)regs->tpc;
info.si_trapno = 0;
force_sig_info(SIGILL, &info, current);
}
void do_privact(struct pt_regs *regs)
{
do_privop(regs);
}
/* Trap level 1 stuff or other traps we should never see... */
void do_cee(struct pt_regs *regs)
{
die_if_kernel("TL0: Cache Error Exception", regs);
}
void do_cee_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Cache Error Exception", regs);
}
void do_dae_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Data Access Exception", regs);
}
void do_iae_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Instruction Access Exception", regs);
}
void do_div0_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: DIV0 Exception", regs);
}
void do_fpdis_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU Disabled", regs);
}
void do_fpieee_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU IEEE Exception", regs);
}
void do_fpother_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: FPU Other Exception", regs);
}
void do_ill_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Illegal Instruction Exception", regs);
}
void do_irq_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: IRQ Exception", regs);
}
void do_lddfmna_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: LDDF Exception", regs);
}
void do_stdfmna_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: STDF Exception", regs);
}
void do_paw(struct pt_regs *regs)
{
die_if_kernel("TL0: Phys Watchpoint Exception", regs);
}
void do_paw_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Phys Watchpoint Exception", regs);
}
void do_vaw(struct pt_regs *regs)
{
die_if_kernel("TL0: Virt Watchpoint Exception", regs);
}
void do_vaw_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Virt Watchpoint Exception", regs);
}
void do_tof_tl1(struct pt_regs *regs)
{
dump_tl1_traplog((struct tl1_traplog *)(regs + 1));
die_if_kernel("TL1: Tag Overflow Exception", regs);
}
void do_getpsr(struct pt_regs *regs)
{
regs->u_regs[UREG_I0] = tstate_to_psr(regs->tstate);
regs->tpc = regs->tnpc;
regs->tnpc += 4;
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
}
struct trap_per_cpu trap_block[NR_CPUS];
EXPORT_SYMBOL(trap_block);
/* This can get invoked before sched_init() so play it super safe
* and use hard_smp_processor_id().
*/
void notrace init_cur_cpu_trap(struct thread_info *t)
{
int cpu = hard_smp_processor_id();
struct trap_per_cpu *p = &trap_block[cpu];
p->thread = t;
p->pgd_paddr = 0;
}
extern void thread_info_offsets_are_bolixed_dave(void);
extern void trap_per_cpu_offsets_are_bolixed_dave(void);
extern void tsb_config_offsets_are_bolixed_dave(void);
/* Only invoked on boot processor. */
void __init trap_init(void)
{
/* Compile time sanity check. */
BUILD_BUG_ON(TI_TASK != offsetof(struct thread_info, task) ||
TI_FLAGS != offsetof(struct thread_info, flags) ||
TI_CPU != offsetof(struct thread_info, cpu) ||
TI_FPSAVED != offsetof(struct thread_info, fpsaved) ||
TI_KSP != offsetof(struct thread_info, ksp) ||
TI_FAULT_ADDR != offsetof(struct thread_info,
fault_address) ||
TI_KREGS != offsetof(struct thread_info, kregs) ||
TI_UTRAPS != offsetof(struct thread_info, utraps) ||
TI_EXEC_DOMAIN != offsetof(struct thread_info,
exec_domain) ||
TI_REG_WINDOW != offsetof(struct thread_info,
reg_window) ||
TI_RWIN_SPTRS != offsetof(struct thread_info,
rwbuf_stkptrs) ||
TI_GSR != offsetof(struct thread_info, gsr) ||
TI_XFSR != offsetof(struct thread_info, xfsr) ||
TI_PRE_COUNT != offsetof(struct thread_info,
preempt_count) ||
TI_NEW_CHILD != offsetof(struct thread_info, new_child) ||
TI_SYS_NOERROR != offsetof(struct thread_info,
syscall_noerror) ||
TI_RESTART_BLOCK != offsetof(struct thread_info,
restart_block) ||
TI_KUNA_REGS != offsetof(struct thread_info,
kern_una_regs) ||
TI_KUNA_INSN != offsetof(struct thread_info,
kern_una_insn) ||
TI_FPREGS != offsetof(struct thread_info, fpregs) ||
(TI_FPREGS & (64 - 1)));
BUILD_BUG_ON(TRAP_PER_CPU_THREAD != offsetof(struct trap_per_cpu,
thread) ||
(TRAP_PER_CPU_PGD_PADDR !=
offsetof(struct trap_per_cpu, pgd_paddr)) ||
(TRAP_PER_CPU_CPU_MONDO_PA !=
offsetof(struct trap_per_cpu, cpu_mondo_pa)) ||
(TRAP_PER_CPU_DEV_MONDO_PA !=
offsetof(struct trap_per_cpu, dev_mondo_pa)) ||
(TRAP_PER_CPU_RESUM_MONDO_PA !=
offsetof(struct trap_per_cpu, resum_mondo_pa)) ||
(TRAP_PER_CPU_RESUM_KBUF_PA !=
offsetof(struct trap_per_cpu, resum_kernel_buf_pa)) ||
(TRAP_PER_CPU_NONRESUM_MONDO_PA !=
offsetof(struct trap_per_cpu, nonresum_mondo_pa)) ||
(TRAP_PER_CPU_NONRESUM_KBUF_PA !=
offsetof(struct trap_per_cpu, nonresum_kernel_buf_pa)) ||
(TRAP_PER_CPU_FAULT_INFO !=
offsetof(struct trap_per_cpu, fault_info)) ||
(TRAP_PER_CPU_CPU_MONDO_BLOCK_PA !=
offsetof(struct trap_per_cpu, cpu_mondo_block_pa)) ||
(TRAP_PER_CPU_CPU_LIST_PA !=
offsetof(struct trap_per_cpu, cpu_list_pa)) ||
(TRAP_PER_CPU_TSB_HUGE !=
offsetof(struct trap_per_cpu, tsb_huge)) ||
(TRAP_PER_CPU_TSB_HUGE_TEMP !=
offsetof(struct trap_per_cpu, tsb_huge_temp)) ||
(TRAP_PER_CPU_IRQ_WORKLIST_PA !=
offsetof(struct trap_per_cpu, irq_worklist_pa)) ||
(TRAP_PER_CPU_CPU_MONDO_QMASK !=
offsetof(struct trap_per_cpu, cpu_mondo_qmask)) ||
(TRAP_PER_CPU_DEV_MONDO_QMASK !=
offsetof(struct trap_per_cpu, dev_mondo_qmask)) ||
(TRAP_PER_CPU_RESUM_QMASK !=
offsetof(struct trap_per_cpu, resum_qmask)) ||
(TRAP_PER_CPU_NONRESUM_QMASK !=
offsetof(struct trap_per_cpu, nonresum_qmask)) ||
(TRAP_PER_CPU_PER_CPU_BASE !=
offsetof(struct trap_per_cpu, __per_cpu_base)));
BUILD_BUG_ON((TSB_CONFIG_TSB !=
offsetof(struct tsb_config, tsb)) ||
(TSB_CONFIG_RSS_LIMIT !=
offsetof(struct tsb_config, tsb_rss_limit)) ||
(TSB_CONFIG_NENTRIES !=
offsetof(struct tsb_config, tsb_nentries)) ||
(TSB_CONFIG_REG_VAL !=
offsetof(struct tsb_config, tsb_reg_val)) ||
(TSB_CONFIG_MAP_VADDR !=
offsetof(struct tsb_config, tsb_map_vaddr)) ||
(TSB_CONFIG_MAP_PTE !=
offsetof(struct tsb_config, tsb_map_pte)));
/* Attach to the address space of init_task. On SMP we
* do this in smp.c:smp_callin for other cpus.
*/
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
}
| gpl-2.0 |
holyangel/LGG3 | arch/sh/boards/board-sh7785lcr.c | 4400 | 8498 | /*
* Renesas Technology Corp. R0P7785LC0011RL Support.
*
* Copyright (C) 2008 Yoshihiro Shimoda
* Copyright (C) 2009 Paul Mundt
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/sm501.h>
#include <linux/sm501-regs.h>
#include <linux/fb.h>
#include <linux/mtd/physmap.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-pca-platform.h>
#include <linux/i2c-algo-pca.h>
#include <linux/usb/r8a66597.h>
#include <linux/irq.h>
#include <linux/io.h>
#include <linux/clk.h>
#include <linux/errno.h>
#include <mach/sh7785lcr.h>
#include <cpu/sh7785.h>
#include <asm/heartbeat.h>
#include <asm/clock.h>
#include <asm/bl_bit.h>
/*
* NOTE: This board has 2 physical memory maps.
* Please look at include/asm-sh/sh7785lcr.h or hardware manual.
*/
static struct resource heartbeat_resource = {
.start = PLD_LEDCR,
.end = PLD_LEDCR,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
};
static struct platform_device heartbeat_device = {
.name = "heartbeat",
.id = -1,
.num_resources = 1,
.resource = &heartbeat_resource,
};
static struct mtd_partition nor_flash_partitions[] = {
{
.name = "loader",
.offset = 0x00000000,
.size = 512 * 1024,
},
{
.name = "bootenv",
.offset = MTDPART_OFS_APPEND,
.size = 512 * 1024,
},
{
.name = "kernel",
.offset = MTDPART_OFS_APPEND,
.size = 4 * 1024 * 1024,
},
{
.name = "data",
.offset = MTDPART_OFS_APPEND,
.size = MTDPART_SIZ_FULL,
},
};
static struct physmap_flash_data nor_flash_data = {
.width = 4,
.parts = nor_flash_partitions,
.nr_parts = ARRAY_SIZE(nor_flash_partitions),
};
static struct resource nor_flash_resources[] = {
[0] = {
.start = NOR_FLASH_ADDR,
.end = NOR_FLASH_ADDR + NOR_FLASH_SIZE - 1,
.flags = IORESOURCE_MEM,
}
};
static struct platform_device nor_flash_device = {
.name = "physmap-flash",
.dev = {
.platform_data = &nor_flash_data,
},
.num_resources = ARRAY_SIZE(nor_flash_resources),
.resource = nor_flash_resources,
};
static struct r8a66597_platdata r8a66597_data = {
.xtal = R8A66597_PLATDATA_XTAL_12MHZ,
.vif = 1,
};
static struct resource r8a66597_usb_host_resources[] = {
[0] = {
.start = R8A66597_ADDR,
.end = R8A66597_ADDR + R8A66597_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = 2,
.end = 2,
.flags = IORESOURCE_IRQ | IRQF_TRIGGER_LOW,
},
};
static struct platform_device r8a66597_usb_host_device = {
.name = "r8a66597_hcd",
.id = -1,
.dev = {
.dma_mask = NULL,
.coherent_dma_mask = 0xffffffff,
.platform_data = &r8a66597_data,
},
.num_resources = ARRAY_SIZE(r8a66597_usb_host_resources),
.resource = r8a66597_usb_host_resources,
};
static struct resource sm501_resources[] = {
[0] = {
.start = SM107_MEM_ADDR,
.end = SM107_MEM_ADDR + SM107_MEM_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[1] = {
.start = SM107_REG_ADDR,
.end = SM107_REG_ADDR + SM107_REG_SIZE - 1,
.flags = IORESOURCE_MEM,
},
[2] = {
.start = 10,
.flags = IORESOURCE_IRQ,
},
};
static struct fb_videomode sm501_default_mode_crt = {
.pixclock = 35714, /* 28MHz */
.xres = 640,
.yres = 480,
.left_margin = 105,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = FB_SYNC_HOR_HIGH_ACT | FB_SYNC_VERT_HIGH_ACT,
};
static struct fb_videomode sm501_default_mode_pnl = {
.pixclock = 40000, /* 25MHz */
.xres = 640,
.yres = 480,
.left_margin = 2,
.right_margin = 16,
.upper_margin = 33,
.lower_margin = 10,
.hsync_len = 39,
.vsync_len = 2,
.sync = 0,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_pnl = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_pnl,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT |
SM501FB_FLAG_PANEL_NO_VBIASEN,
};
static struct sm501_platdata_fbsub sm501_pdata_fbsub_crt = {
.def_bpp = 16,
.def_mode = &sm501_default_mode_crt,
.flags = SM501FB_FLAG_USE_INIT_MODE |
SM501FB_FLAG_USE_HWCURSOR |
SM501FB_FLAG_USE_HWACCEL |
SM501FB_FLAG_DISABLE_AT_EXIT,
};
static struct sm501_platdata_fb sm501_fb_pdata = {
.fb_route = SM501_FB_OWN,
.fb_crt = &sm501_pdata_fbsub_crt,
.fb_pnl = &sm501_pdata_fbsub_pnl,
};
static struct sm501_initdata sm501_initdata = {
.gpio_high = {
.set = 0x00001fe0,
.mask = 0x0,
},
.devices = 0,
.mclk = 84 * 1000000,
.m1xclk = 112 * 1000000,
};
static struct sm501_platdata sm501_platform_data = {
.init = &sm501_initdata,
.fb = &sm501_fb_pdata,
};
static struct platform_device sm501_device = {
.name = "sm501",
.id = -1,
.dev = {
.platform_data = &sm501_platform_data,
},
.num_resources = ARRAY_SIZE(sm501_resources),
.resource = sm501_resources,
};
static struct resource i2c_proto_resources[] = {
[0] = {
.start = PCA9564_PROTO_32BIT_ADDR,
.end = PCA9564_PROTO_32BIT_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = 12,
.end = 12,
.flags = IORESOURCE_IRQ,
},
};
static struct resource i2c_resources[] = {
[0] = {
.start = PCA9564_ADDR,
.end = PCA9564_ADDR + PCA9564_SIZE - 1,
.flags = IORESOURCE_MEM | IORESOURCE_MEM_8BIT,
},
[1] = {
.start = 12,
.end = 12,
.flags = IORESOURCE_IRQ,
},
};
static struct i2c_pca9564_pf_platform_data i2c_platform_data = {
.gpio = 0,
.i2c_clock_speed = I2C_PCA_CON_330kHz,
.timeout = HZ,
};
static struct platform_device i2c_device = {
.name = "i2c-pca-platform",
.id = -1,
.dev = {
.platform_data = &i2c_platform_data,
},
.num_resources = ARRAY_SIZE(i2c_resources),
.resource = i2c_resources,
};
static struct platform_device *sh7785lcr_devices[] __initdata = {
&heartbeat_device,
&nor_flash_device,
&r8a66597_usb_host_device,
&sm501_device,
&i2c_device,
};
static struct i2c_board_info __initdata sh7785lcr_i2c_devices[] = {
{
I2C_BOARD_INFO("r2025sd", 0x32),
},
};
static int __init sh7785lcr_devices_setup(void)
{
i2c_register_board_info(0, sh7785lcr_i2c_devices,
ARRAY_SIZE(sh7785lcr_i2c_devices));
if (mach_is_sh7785lcr_pt()) {
i2c_device.resource = i2c_proto_resources;
i2c_device.num_resources = ARRAY_SIZE(i2c_proto_resources);
}
return platform_add_devices(sh7785lcr_devices,
ARRAY_SIZE(sh7785lcr_devices));
}
device_initcall(sh7785lcr_devices_setup);
/* Initialize IRQ setting */
void __init init_sh7785lcr_IRQ(void)
{
plat_irq_setup_pins(IRQ_MODE_IRQ7654);
plat_irq_setup_pins(IRQ_MODE_IRQ3210);
}
static int sh7785lcr_clk_init(void)
{
struct clk *clk;
int ret;
clk = clk_get(NULL, "extal");
if (IS_ERR(clk))
return PTR_ERR(clk);
ret = clk_set_rate(clk, 33333333);
clk_put(clk);
return ret;
}
static void sh7785lcr_power_off(void)
{
unsigned char *p;
p = ioremap(PLD_POFCR, PLD_POFCR + 1);
if (!p) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
*p = 0x01;
iounmap(p);
set_bl_bit();
while (1)
cpu_relax();
}
/* Initialize the board */
static void __init sh7785lcr_setup(char **cmdline_p)
{
void __iomem *sm501_reg;
printk(KERN_INFO "Renesas Technology Corp. R0P7785LC0011RL support.\n");
pm_power_off = sh7785lcr_power_off;
/* sm501 DRAM configuration */
sm501_reg = ioremap_nocache(SM107_REG_ADDR, SM501_DRAM_CONTROL);
if (!sm501_reg) {
printk(KERN_ERR "%s: ioremap error.\n", __func__);
return;
}
writel(0x000307c2, sm501_reg + SM501_DRAM_CONTROL);
iounmap(sm501_reg);
}
/* Return the board specific boot mode pin configuration */
static int sh7785lcr_mode_pins(void)
{
int value = 0;
/* These are the factory default settings of S1 and S2.
* If you change these dip switches then you will need to
* adjust the values below as well.
*/
value |= MODE_PIN4; /* Clock Mode 16 */
value |= MODE_PIN5; /* 32-bit Area0 bus width */
value |= MODE_PIN6; /* 32-bit Area0 bus width */
value |= MODE_PIN7; /* Area 0 SRAM interface [fixed] */
value |= MODE_PIN8; /* Little Endian */
value |= MODE_PIN9; /* Master Mode */
value |= MODE_PIN14; /* No PLL step-up */
return value;
}
/*
* The Machine Vector
*/
static struct sh_machine_vector mv_sh7785lcr __initmv = {
.mv_name = "SH7785LCR",
.mv_setup = sh7785lcr_setup,
.mv_clk_init = sh7785lcr_clk_init,
.mv_init_irq = init_sh7785lcr_IRQ,
.mv_mode_pins = sh7785lcr_mode_pins,
};
| gpl-2.0 |
Hardslog/grimlock_kernel_asus_tegra3_unified | arch/arm/mach-sa1100/gpio.c | 4656 | 1423 | /*
* linux/arch/arm/mach-sa1100/gpio.c
*
* Generic SA-1100 GPIO handling
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <asm/gpio.h>
#include <mach/hardware.h>
#include "generic.h"
static int sa1100_gpio_get(struct gpio_chip *chip, unsigned offset)
{
return GPLR & GPIO_GPIO(offset);
}
static void sa1100_gpio_set(struct gpio_chip *chip, unsigned offset, int value)
{
if (value)
GPSR = GPIO_GPIO(offset);
else
GPCR = GPIO_GPIO(offset);
}
static int sa1100_direction_input(struct gpio_chip *chip, unsigned offset)
{
unsigned long flags;
local_irq_save(flags);
GPDR &= ~GPIO_GPIO(offset);
local_irq_restore(flags);
return 0;
}
static int sa1100_direction_output(struct gpio_chip *chip, unsigned offset, int value)
{
unsigned long flags;
local_irq_save(flags);
sa1100_gpio_set(chip, offset, value);
GPDR |= GPIO_GPIO(offset);
local_irq_restore(flags);
return 0;
}
static struct gpio_chip sa1100_gpio_chip = {
.label = "gpio",
.direction_input = sa1100_direction_input,
.direction_output = sa1100_direction_output,
.set = sa1100_gpio_set,
.get = sa1100_gpio_get,
.base = 0,
.ngpio = GPIO_MAX + 1,
};
void __init sa1100_init_gpio(void)
{
gpiochip_add(&sa1100_gpio_chip);
}
| gpl-2.0 |
noobnl/msm-jf-kernel | drivers/infiniband/core/verbs.c | 4912 | 29882 | /*
* Copyright (c) 2004 Mellanox Technologies Ltd. All rights reserved.
* Copyright (c) 2004 Infinicon Corporation. All rights reserved.
* Copyright (c) 2004 Intel Corporation. All rights reserved.
* Copyright (c) 2004 Topspin Corporation. All rights reserved.
* Copyright (c) 2004 Voltaire Corporation. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) 2005, 2006 Cisco Systems. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <linux/errno.h>
#include <linux/err.h>
#include <linux/export.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <rdma/ib_verbs.h>
#include <rdma/ib_cache.h>
int ib_rate_to_mult(enum ib_rate rate)
{
switch (rate) {
case IB_RATE_2_5_GBPS: return 1;
case IB_RATE_5_GBPS: return 2;
case IB_RATE_10_GBPS: return 4;
case IB_RATE_20_GBPS: return 8;
case IB_RATE_30_GBPS: return 12;
case IB_RATE_40_GBPS: return 16;
case IB_RATE_60_GBPS: return 24;
case IB_RATE_80_GBPS: return 32;
case IB_RATE_120_GBPS: return 48;
default: return -1;
}
}
EXPORT_SYMBOL(ib_rate_to_mult);
enum ib_rate mult_to_ib_rate(int mult)
{
switch (mult) {
case 1: return IB_RATE_2_5_GBPS;
case 2: return IB_RATE_5_GBPS;
case 4: return IB_RATE_10_GBPS;
case 8: return IB_RATE_20_GBPS;
case 12: return IB_RATE_30_GBPS;
case 16: return IB_RATE_40_GBPS;
case 24: return IB_RATE_60_GBPS;
case 32: return IB_RATE_80_GBPS;
case 48: return IB_RATE_120_GBPS;
default: return IB_RATE_PORT_CURRENT;
}
}
EXPORT_SYMBOL(mult_to_ib_rate);
int ib_rate_to_mbps(enum ib_rate rate)
{
switch (rate) {
case IB_RATE_2_5_GBPS: return 2500;
case IB_RATE_5_GBPS: return 5000;
case IB_RATE_10_GBPS: return 10000;
case IB_RATE_20_GBPS: return 20000;
case IB_RATE_30_GBPS: return 30000;
case IB_RATE_40_GBPS: return 40000;
case IB_RATE_60_GBPS: return 60000;
case IB_RATE_80_GBPS: return 80000;
case IB_RATE_120_GBPS: return 120000;
case IB_RATE_14_GBPS: return 14062;
case IB_RATE_56_GBPS: return 56250;
case IB_RATE_112_GBPS: return 112500;
case IB_RATE_168_GBPS: return 168750;
case IB_RATE_25_GBPS: return 25781;
case IB_RATE_100_GBPS: return 103125;
case IB_RATE_200_GBPS: return 206250;
case IB_RATE_300_GBPS: return 309375;
default: return -1;
}
}
EXPORT_SYMBOL(ib_rate_to_mbps);
enum rdma_transport_type
rdma_node_get_transport(enum rdma_node_type node_type)
{
switch (node_type) {
case RDMA_NODE_IB_CA:
case RDMA_NODE_IB_SWITCH:
case RDMA_NODE_IB_ROUTER:
return RDMA_TRANSPORT_IB;
case RDMA_NODE_RNIC:
return RDMA_TRANSPORT_IWARP;
default:
BUG();
return 0;
}
}
EXPORT_SYMBOL(rdma_node_get_transport);
enum rdma_link_layer rdma_port_get_link_layer(struct ib_device *device, u8 port_num)
{
if (device->get_link_layer)
return device->get_link_layer(device, port_num);
switch (rdma_node_get_transport(device->node_type)) {
case RDMA_TRANSPORT_IB:
return IB_LINK_LAYER_INFINIBAND;
case RDMA_TRANSPORT_IWARP:
return IB_LINK_LAYER_ETHERNET;
default:
return IB_LINK_LAYER_UNSPECIFIED;
}
}
EXPORT_SYMBOL(rdma_port_get_link_layer);
/* Protection domains */
struct ib_pd *ib_alloc_pd(struct ib_device *device)
{
struct ib_pd *pd;
pd = device->alloc_pd(device, NULL, NULL);
if (!IS_ERR(pd)) {
pd->device = device;
pd->uobject = NULL;
atomic_set(&pd->usecnt, 0);
}
return pd;
}
EXPORT_SYMBOL(ib_alloc_pd);
int ib_dealloc_pd(struct ib_pd *pd)
{
if (atomic_read(&pd->usecnt))
return -EBUSY;
return pd->device->dealloc_pd(pd);
}
EXPORT_SYMBOL(ib_dealloc_pd);
/* Address handles */
struct ib_ah *ib_create_ah(struct ib_pd *pd, struct ib_ah_attr *ah_attr)
{
struct ib_ah *ah;
ah = pd->device->create_ah(pd, ah_attr);
if (!IS_ERR(ah)) {
ah->device = pd->device;
ah->pd = pd;
ah->uobject = NULL;
atomic_inc(&pd->usecnt);
}
return ah;
}
EXPORT_SYMBOL(ib_create_ah);
int ib_init_ah_from_wc(struct ib_device *device, u8 port_num, struct ib_wc *wc,
struct ib_grh *grh, struct ib_ah_attr *ah_attr)
{
u32 flow_class;
u16 gid_index;
int ret;
memset(ah_attr, 0, sizeof *ah_attr);
ah_attr->dlid = wc->slid;
ah_attr->sl = wc->sl;
ah_attr->src_path_bits = wc->dlid_path_bits;
ah_attr->port_num = port_num;
if (wc->wc_flags & IB_WC_GRH) {
ah_attr->ah_flags = IB_AH_GRH;
ah_attr->grh.dgid = grh->sgid;
ret = ib_find_cached_gid(device, &grh->dgid, &port_num,
&gid_index);
if (ret)
return ret;
ah_attr->grh.sgid_index = (u8) gid_index;
flow_class = be32_to_cpu(grh->version_tclass_flow);
ah_attr->grh.flow_label = flow_class & 0xFFFFF;
ah_attr->grh.hop_limit = 0xFF;
ah_attr->grh.traffic_class = (flow_class >> 20) & 0xFF;
}
return 0;
}
EXPORT_SYMBOL(ib_init_ah_from_wc);
struct ib_ah *ib_create_ah_from_wc(struct ib_pd *pd, struct ib_wc *wc,
struct ib_grh *grh, u8 port_num)
{
struct ib_ah_attr ah_attr;
int ret;
ret = ib_init_ah_from_wc(pd->device, port_num, wc, grh, &ah_attr);
if (ret)
return ERR_PTR(ret);
return ib_create_ah(pd, &ah_attr);
}
EXPORT_SYMBOL(ib_create_ah_from_wc);
int ib_modify_ah(struct ib_ah *ah, struct ib_ah_attr *ah_attr)
{
return ah->device->modify_ah ?
ah->device->modify_ah(ah, ah_attr) :
-ENOSYS;
}
EXPORT_SYMBOL(ib_modify_ah);
int ib_query_ah(struct ib_ah *ah, struct ib_ah_attr *ah_attr)
{
return ah->device->query_ah ?
ah->device->query_ah(ah, ah_attr) :
-ENOSYS;
}
EXPORT_SYMBOL(ib_query_ah);
int ib_destroy_ah(struct ib_ah *ah)
{
struct ib_pd *pd;
int ret;
pd = ah->pd;
ret = ah->device->destroy_ah(ah);
if (!ret)
atomic_dec(&pd->usecnt);
return ret;
}
EXPORT_SYMBOL(ib_destroy_ah);
/* Shared receive queues */
struct ib_srq *ib_create_srq(struct ib_pd *pd,
struct ib_srq_init_attr *srq_init_attr)
{
struct ib_srq *srq;
if (!pd->device->create_srq)
return ERR_PTR(-ENOSYS);
srq = pd->device->create_srq(pd, srq_init_attr, NULL);
if (!IS_ERR(srq)) {
srq->device = pd->device;
srq->pd = pd;
srq->uobject = NULL;
srq->event_handler = srq_init_attr->event_handler;
srq->srq_context = srq_init_attr->srq_context;
srq->srq_type = srq_init_attr->srq_type;
if (srq->srq_type == IB_SRQT_XRC) {
srq->ext.xrc.xrcd = srq_init_attr->ext.xrc.xrcd;
srq->ext.xrc.cq = srq_init_attr->ext.xrc.cq;
atomic_inc(&srq->ext.xrc.xrcd->usecnt);
atomic_inc(&srq->ext.xrc.cq->usecnt);
}
atomic_inc(&pd->usecnt);
atomic_set(&srq->usecnt, 0);
}
return srq;
}
EXPORT_SYMBOL(ib_create_srq);
int ib_modify_srq(struct ib_srq *srq,
struct ib_srq_attr *srq_attr,
enum ib_srq_attr_mask srq_attr_mask)
{
return srq->device->modify_srq ?
srq->device->modify_srq(srq, srq_attr, srq_attr_mask, NULL) :
-ENOSYS;
}
EXPORT_SYMBOL(ib_modify_srq);
int ib_query_srq(struct ib_srq *srq,
struct ib_srq_attr *srq_attr)
{
return srq->device->query_srq ?
srq->device->query_srq(srq, srq_attr) : -ENOSYS;
}
EXPORT_SYMBOL(ib_query_srq);
int ib_destroy_srq(struct ib_srq *srq)
{
struct ib_pd *pd;
enum ib_srq_type srq_type;
struct ib_xrcd *uninitialized_var(xrcd);
struct ib_cq *uninitialized_var(cq);
int ret;
if (atomic_read(&srq->usecnt))
return -EBUSY;
pd = srq->pd;
srq_type = srq->srq_type;
if (srq_type == IB_SRQT_XRC) {
xrcd = srq->ext.xrc.xrcd;
cq = srq->ext.xrc.cq;
}
ret = srq->device->destroy_srq(srq);
if (!ret) {
atomic_dec(&pd->usecnt);
if (srq_type == IB_SRQT_XRC) {
atomic_dec(&xrcd->usecnt);
atomic_dec(&cq->usecnt);
}
}
return ret;
}
EXPORT_SYMBOL(ib_destroy_srq);
/* Queue pairs */
static void __ib_shared_qp_event_handler(struct ib_event *event, void *context)
{
struct ib_qp *qp = context;
list_for_each_entry(event->element.qp, &qp->open_list, open_list)
event->element.qp->event_handler(event, event->element.qp->qp_context);
}
static void __ib_insert_xrcd_qp(struct ib_xrcd *xrcd, struct ib_qp *qp)
{
mutex_lock(&xrcd->tgt_qp_mutex);
list_add(&qp->xrcd_list, &xrcd->tgt_qp_list);
mutex_unlock(&xrcd->tgt_qp_mutex);
}
static struct ib_qp *__ib_open_qp(struct ib_qp *real_qp,
void (*event_handler)(struct ib_event *, void *),
void *qp_context)
{
struct ib_qp *qp;
unsigned long flags;
qp = kzalloc(sizeof *qp, GFP_KERNEL);
if (!qp)
return ERR_PTR(-ENOMEM);
qp->real_qp = real_qp;
atomic_inc(&real_qp->usecnt);
qp->device = real_qp->device;
qp->event_handler = event_handler;
qp->qp_context = qp_context;
qp->qp_num = real_qp->qp_num;
qp->qp_type = real_qp->qp_type;
spin_lock_irqsave(&real_qp->device->event_handler_lock, flags);
list_add(&qp->open_list, &real_qp->open_list);
spin_unlock_irqrestore(&real_qp->device->event_handler_lock, flags);
return qp;
}
struct ib_qp *ib_open_qp(struct ib_xrcd *xrcd,
struct ib_qp_open_attr *qp_open_attr)
{
struct ib_qp *qp, *real_qp;
if (qp_open_attr->qp_type != IB_QPT_XRC_TGT)
return ERR_PTR(-EINVAL);
qp = ERR_PTR(-EINVAL);
mutex_lock(&xrcd->tgt_qp_mutex);
list_for_each_entry(real_qp, &xrcd->tgt_qp_list, xrcd_list) {
if (real_qp->qp_num == qp_open_attr->qp_num) {
qp = __ib_open_qp(real_qp, qp_open_attr->event_handler,
qp_open_attr->qp_context);
break;
}
}
mutex_unlock(&xrcd->tgt_qp_mutex);
return qp;
}
EXPORT_SYMBOL(ib_open_qp);
struct ib_qp *ib_create_qp(struct ib_pd *pd,
struct ib_qp_init_attr *qp_init_attr)
{
struct ib_qp *qp, *real_qp;
struct ib_device *device;
device = pd ? pd->device : qp_init_attr->xrcd->device;
qp = device->create_qp(pd, qp_init_attr, NULL);
if (!IS_ERR(qp)) {
qp->device = device;
qp->real_qp = qp;
qp->uobject = NULL;
qp->qp_type = qp_init_attr->qp_type;
atomic_set(&qp->usecnt, 0);
if (qp_init_attr->qp_type == IB_QPT_XRC_TGT) {
qp->event_handler = __ib_shared_qp_event_handler;
qp->qp_context = qp;
qp->pd = NULL;
qp->send_cq = qp->recv_cq = NULL;
qp->srq = NULL;
qp->xrcd = qp_init_attr->xrcd;
atomic_inc(&qp_init_attr->xrcd->usecnt);
INIT_LIST_HEAD(&qp->open_list);
real_qp = qp;
qp = __ib_open_qp(real_qp, qp_init_attr->event_handler,
qp_init_attr->qp_context);
if (!IS_ERR(qp))
__ib_insert_xrcd_qp(qp_init_attr->xrcd, real_qp);
else
real_qp->device->destroy_qp(real_qp);
} else {
qp->event_handler = qp_init_attr->event_handler;
qp->qp_context = qp_init_attr->qp_context;
if (qp_init_attr->qp_type == IB_QPT_XRC_INI) {
qp->recv_cq = NULL;
qp->srq = NULL;
} else {
qp->recv_cq = qp_init_attr->recv_cq;
atomic_inc(&qp_init_attr->recv_cq->usecnt);
qp->srq = qp_init_attr->srq;
if (qp->srq)
atomic_inc(&qp_init_attr->srq->usecnt);
}
qp->pd = pd;
qp->send_cq = qp_init_attr->send_cq;
qp->xrcd = NULL;
atomic_inc(&pd->usecnt);
atomic_inc(&qp_init_attr->send_cq->usecnt);
}
}
return qp;
}
EXPORT_SYMBOL(ib_create_qp);
static const struct {
int valid;
enum ib_qp_attr_mask req_param[IB_QPT_MAX];
enum ib_qp_attr_mask opt_param[IB_QPT_MAX];
} qp_state_table[IB_QPS_ERR + 1][IB_QPS_ERR + 1] = {
[IB_QPS_RESET] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_INIT] = {
.valid = 1,
.req_param = {
[IB_QPT_UD] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_RC] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_XRC_INI] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_XRC_TGT] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_SMI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
}
},
},
[IB_QPS_INIT] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 },
[IB_QPS_INIT] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_RC] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_XRC_INI] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_XRC_TGT] = (IB_QP_PKEY_INDEX |
IB_QP_PORT |
IB_QP_ACCESS_FLAGS),
[IB_QPT_SMI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
}
},
[IB_QPS_RTR] = {
.valid = 1,
.req_param = {
[IB_QPT_UC] = (IB_QP_AV |
IB_QP_PATH_MTU |
IB_QP_DEST_QPN |
IB_QP_RQ_PSN),
[IB_QPT_RC] = (IB_QP_AV |
IB_QP_PATH_MTU |
IB_QP_DEST_QPN |
IB_QP_RQ_PSN |
IB_QP_MAX_DEST_RD_ATOMIC |
IB_QP_MIN_RNR_TIMER),
[IB_QPT_XRC_INI] = (IB_QP_AV |
IB_QP_PATH_MTU |
IB_QP_DEST_QPN |
IB_QP_RQ_PSN),
[IB_QPT_XRC_TGT] = (IB_QP_AV |
IB_QP_PATH_MTU |
IB_QP_DEST_QPN |
IB_QP_RQ_PSN |
IB_QP_MAX_DEST_RD_ATOMIC |
IB_QP_MIN_RNR_TIMER),
},
.opt_param = {
[IB_QPT_UD] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX),
[IB_QPT_RC] = (IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX),
[IB_QPT_XRC_INI] = (IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX),
[IB_QPT_XRC_TGT] = (IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX),
[IB_QPT_SMI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
}
}
},
[IB_QPS_RTR] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 },
[IB_QPS_RTS] = {
.valid = 1,
.req_param = {
[IB_QPT_UD] = IB_QP_SQ_PSN,
[IB_QPT_UC] = IB_QP_SQ_PSN,
[IB_QPT_RC] = (IB_QP_TIMEOUT |
IB_QP_RETRY_CNT |
IB_QP_RNR_RETRY |
IB_QP_SQ_PSN |
IB_QP_MAX_QP_RD_ATOMIC),
[IB_QPT_XRC_INI] = (IB_QP_TIMEOUT |
IB_QP_RETRY_CNT |
IB_QP_RNR_RETRY |
IB_QP_SQ_PSN |
IB_QP_MAX_QP_RD_ATOMIC),
[IB_QPT_XRC_TGT] = (IB_QP_TIMEOUT |
IB_QP_SQ_PSN),
[IB_QPT_SMI] = IB_QP_SQ_PSN,
[IB_QPT_GSI] = IB_QP_SQ_PSN,
},
.opt_param = {
[IB_QPT_UD] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PATH_MIG_STATE),
[IB_QPT_RC] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_INI] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_SMI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
}
}
},
[IB_QPS_RTS] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 },
[IB_QPS_RTS] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_CUR_STATE |
IB_QP_ACCESS_FLAGS |
IB_QP_ALT_PATH |
IB_QP_PATH_MIG_STATE),
[IB_QPT_RC] = (IB_QP_CUR_STATE |
IB_QP_ACCESS_FLAGS |
IB_QP_ALT_PATH |
IB_QP_PATH_MIG_STATE |
IB_QP_MIN_RNR_TIMER),
[IB_QPT_XRC_INI] = (IB_QP_CUR_STATE |
IB_QP_ACCESS_FLAGS |
IB_QP_ALT_PATH |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE |
IB_QP_ACCESS_FLAGS |
IB_QP_ALT_PATH |
IB_QP_PATH_MIG_STATE |
IB_QP_MIN_RNR_TIMER),
[IB_QPT_SMI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
}
},
[IB_QPS_SQD] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = IB_QP_EN_SQD_ASYNC_NOTIFY,
[IB_QPT_UC] = IB_QP_EN_SQD_ASYNC_NOTIFY,
[IB_QPT_RC] = IB_QP_EN_SQD_ASYNC_NOTIFY,
[IB_QPT_XRC_INI] = IB_QP_EN_SQD_ASYNC_NOTIFY,
[IB_QPT_XRC_TGT] = IB_QP_EN_SQD_ASYNC_NOTIFY, /* ??? */
[IB_QPT_SMI] = IB_QP_EN_SQD_ASYNC_NOTIFY,
[IB_QPT_GSI] = IB_QP_EN_SQD_ASYNC_NOTIFY
}
},
},
[IB_QPS_SQD] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 },
[IB_QPS_RTS] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PATH_MIG_STATE),
[IB_QPT_RC] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_INI] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_TGT] = (IB_QP_CUR_STATE |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_SMI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
}
},
[IB_QPS_SQD] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_AV |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX |
IB_QP_PATH_MIG_STATE),
[IB_QPT_RC] = (IB_QP_PORT |
IB_QP_AV |
IB_QP_TIMEOUT |
IB_QP_RETRY_CNT |
IB_QP_RNR_RETRY |
IB_QP_MAX_QP_RD_ATOMIC |
IB_QP_MAX_DEST_RD_ATOMIC |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_INI] = (IB_QP_PORT |
IB_QP_AV |
IB_QP_TIMEOUT |
IB_QP_RETRY_CNT |
IB_QP_RNR_RETRY |
IB_QP_MAX_QP_RD_ATOMIC |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX |
IB_QP_PATH_MIG_STATE),
[IB_QPT_XRC_TGT] = (IB_QP_PORT |
IB_QP_AV |
IB_QP_TIMEOUT |
IB_QP_MAX_DEST_RD_ATOMIC |
IB_QP_ALT_PATH |
IB_QP_ACCESS_FLAGS |
IB_QP_PKEY_INDEX |
IB_QP_MIN_RNR_TIMER |
IB_QP_PATH_MIG_STATE),
[IB_QPT_SMI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_PKEY_INDEX |
IB_QP_QKEY),
}
}
},
[IB_QPS_SQE] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 },
[IB_QPS_RTS] = {
.valid = 1,
.opt_param = {
[IB_QPT_UD] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_UC] = (IB_QP_CUR_STATE |
IB_QP_ACCESS_FLAGS),
[IB_QPT_SMI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
[IB_QPT_GSI] = (IB_QP_CUR_STATE |
IB_QP_QKEY),
}
}
},
[IB_QPS_ERR] = {
[IB_QPS_RESET] = { .valid = 1 },
[IB_QPS_ERR] = { .valid = 1 }
}
};
int ib_modify_qp_is_ok(enum ib_qp_state cur_state, enum ib_qp_state next_state,
enum ib_qp_type type, enum ib_qp_attr_mask mask)
{
enum ib_qp_attr_mask req_param, opt_param;
if (cur_state < 0 || cur_state > IB_QPS_ERR ||
next_state < 0 || next_state > IB_QPS_ERR)
return 0;
if (mask & IB_QP_CUR_STATE &&
cur_state != IB_QPS_RTR && cur_state != IB_QPS_RTS &&
cur_state != IB_QPS_SQD && cur_state != IB_QPS_SQE)
return 0;
if (!qp_state_table[cur_state][next_state].valid)
return 0;
req_param = qp_state_table[cur_state][next_state].req_param[type];
opt_param = qp_state_table[cur_state][next_state].opt_param[type];
if ((mask & req_param) != req_param)
return 0;
if (mask & ~(req_param | opt_param | IB_QP_STATE))
return 0;
return 1;
}
EXPORT_SYMBOL(ib_modify_qp_is_ok);
int ib_modify_qp(struct ib_qp *qp,
struct ib_qp_attr *qp_attr,
int qp_attr_mask)
{
return qp->device->modify_qp(qp->real_qp, qp_attr, qp_attr_mask, NULL);
}
EXPORT_SYMBOL(ib_modify_qp);
int ib_query_qp(struct ib_qp *qp,
struct ib_qp_attr *qp_attr,
int qp_attr_mask,
struct ib_qp_init_attr *qp_init_attr)
{
return qp->device->query_qp ?
qp->device->query_qp(qp->real_qp, qp_attr, qp_attr_mask, qp_init_attr) :
-ENOSYS;
}
EXPORT_SYMBOL(ib_query_qp);
int ib_close_qp(struct ib_qp *qp)
{
struct ib_qp *real_qp;
unsigned long flags;
real_qp = qp->real_qp;
if (real_qp == qp)
return -EINVAL;
spin_lock_irqsave(&real_qp->device->event_handler_lock, flags);
list_del(&qp->open_list);
spin_unlock_irqrestore(&real_qp->device->event_handler_lock, flags);
atomic_dec(&real_qp->usecnt);
kfree(qp);
return 0;
}
EXPORT_SYMBOL(ib_close_qp);
static int __ib_destroy_shared_qp(struct ib_qp *qp)
{
struct ib_xrcd *xrcd;
struct ib_qp *real_qp;
int ret;
real_qp = qp->real_qp;
xrcd = real_qp->xrcd;
mutex_lock(&xrcd->tgt_qp_mutex);
ib_close_qp(qp);
if (atomic_read(&real_qp->usecnt) == 0)
list_del(&real_qp->xrcd_list);
else
real_qp = NULL;
mutex_unlock(&xrcd->tgt_qp_mutex);
if (real_qp) {
ret = ib_destroy_qp(real_qp);
if (!ret)
atomic_dec(&xrcd->usecnt);
else
__ib_insert_xrcd_qp(xrcd, real_qp);
}
return 0;
}
int ib_destroy_qp(struct ib_qp *qp)
{
struct ib_pd *pd;
struct ib_cq *scq, *rcq;
struct ib_srq *srq;
int ret;
if (atomic_read(&qp->usecnt))
return -EBUSY;
if (qp->real_qp != qp)
return __ib_destroy_shared_qp(qp);
pd = qp->pd;
scq = qp->send_cq;
rcq = qp->recv_cq;
srq = qp->srq;
ret = qp->device->destroy_qp(qp);
if (!ret) {
if (pd)
atomic_dec(&pd->usecnt);
if (scq)
atomic_dec(&scq->usecnt);
if (rcq)
atomic_dec(&rcq->usecnt);
if (srq)
atomic_dec(&srq->usecnt);
}
return ret;
}
EXPORT_SYMBOL(ib_destroy_qp);
/* Completion queues */
struct ib_cq *ib_create_cq(struct ib_device *device,
ib_comp_handler comp_handler,
void (*event_handler)(struct ib_event *, void *),
void *cq_context, int cqe, int comp_vector)
{
struct ib_cq *cq;
cq = device->create_cq(device, cqe, comp_vector, NULL, NULL);
if (!IS_ERR(cq)) {
cq->device = device;
cq->uobject = NULL;
cq->comp_handler = comp_handler;
cq->event_handler = event_handler;
cq->cq_context = cq_context;
atomic_set(&cq->usecnt, 0);
}
return cq;
}
EXPORT_SYMBOL(ib_create_cq);
int ib_modify_cq(struct ib_cq *cq, u16 cq_count, u16 cq_period)
{
return cq->device->modify_cq ?
cq->device->modify_cq(cq, cq_count, cq_period) : -ENOSYS;
}
EXPORT_SYMBOL(ib_modify_cq);
int ib_destroy_cq(struct ib_cq *cq)
{
if (atomic_read(&cq->usecnt))
return -EBUSY;
return cq->device->destroy_cq(cq);
}
EXPORT_SYMBOL(ib_destroy_cq);
int ib_resize_cq(struct ib_cq *cq, int cqe)
{
return cq->device->resize_cq ?
cq->device->resize_cq(cq, cqe, NULL) : -ENOSYS;
}
EXPORT_SYMBOL(ib_resize_cq);
/* Memory regions */
struct ib_mr *ib_get_dma_mr(struct ib_pd *pd, int mr_access_flags)
{
struct ib_mr *mr;
mr = pd->device->get_dma_mr(pd, mr_access_flags);
if (!IS_ERR(mr)) {
mr->device = pd->device;
mr->pd = pd;
mr->uobject = NULL;
atomic_inc(&pd->usecnt);
atomic_set(&mr->usecnt, 0);
}
return mr;
}
EXPORT_SYMBOL(ib_get_dma_mr);
struct ib_mr *ib_reg_phys_mr(struct ib_pd *pd,
struct ib_phys_buf *phys_buf_array,
int num_phys_buf,
int mr_access_flags,
u64 *iova_start)
{
struct ib_mr *mr;
if (!pd->device->reg_phys_mr)
return ERR_PTR(-ENOSYS);
mr = pd->device->reg_phys_mr(pd, phys_buf_array, num_phys_buf,
mr_access_flags, iova_start);
if (!IS_ERR(mr)) {
mr->device = pd->device;
mr->pd = pd;
mr->uobject = NULL;
atomic_inc(&pd->usecnt);
atomic_set(&mr->usecnt, 0);
}
return mr;
}
EXPORT_SYMBOL(ib_reg_phys_mr);
int ib_rereg_phys_mr(struct ib_mr *mr,
int mr_rereg_mask,
struct ib_pd *pd,
struct ib_phys_buf *phys_buf_array,
int num_phys_buf,
int mr_access_flags,
u64 *iova_start)
{
struct ib_pd *old_pd;
int ret;
if (!mr->device->rereg_phys_mr)
return -ENOSYS;
if (atomic_read(&mr->usecnt))
return -EBUSY;
old_pd = mr->pd;
ret = mr->device->rereg_phys_mr(mr, mr_rereg_mask, pd,
phys_buf_array, num_phys_buf,
mr_access_flags, iova_start);
if (!ret && (mr_rereg_mask & IB_MR_REREG_PD)) {
atomic_dec(&old_pd->usecnt);
atomic_inc(&pd->usecnt);
}
return ret;
}
EXPORT_SYMBOL(ib_rereg_phys_mr);
int ib_query_mr(struct ib_mr *mr, struct ib_mr_attr *mr_attr)
{
return mr->device->query_mr ?
mr->device->query_mr(mr, mr_attr) : -ENOSYS;
}
EXPORT_SYMBOL(ib_query_mr);
int ib_dereg_mr(struct ib_mr *mr)
{
struct ib_pd *pd;
int ret;
if (atomic_read(&mr->usecnt))
return -EBUSY;
pd = mr->pd;
ret = mr->device->dereg_mr(mr);
if (!ret)
atomic_dec(&pd->usecnt);
return ret;
}
EXPORT_SYMBOL(ib_dereg_mr);
struct ib_mr *ib_alloc_fast_reg_mr(struct ib_pd *pd, int max_page_list_len)
{
struct ib_mr *mr;
if (!pd->device->alloc_fast_reg_mr)
return ERR_PTR(-ENOSYS);
mr = pd->device->alloc_fast_reg_mr(pd, max_page_list_len);
if (!IS_ERR(mr)) {
mr->device = pd->device;
mr->pd = pd;
mr->uobject = NULL;
atomic_inc(&pd->usecnt);
atomic_set(&mr->usecnt, 0);
}
return mr;
}
EXPORT_SYMBOL(ib_alloc_fast_reg_mr);
struct ib_fast_reg_page_list *ib_alloc_fast_reg_page_list(struct ib_device *device,
int max_page_list_len)
{
struct ib_fast_reg_page_list *page_list;
if (!device->alloc_fast_reg_page_list)
return ERR_PTR(-ENOSYS);
page_list = device->alloc_fast_reg_page_list(device, max_page_list_len);
if (!IS_ERR(page_list)) {
page_list->device = device;
page_list->max_page_list_len = max_page_list_len;
}
return page_list;
}
EXPORT_SYMBOL(ib_alloc_fast_reg_page_list);
void ib_free_fast_reg_page_list(struct ib_fast_reg_page_list *page_list)
{
page_list->device->free_fast_reg_page_list(page_list);
}
EXPORT_SYMBOL(ib_free_fast_reg_page_list);
/* Memory windows */
struct ib_mw *ib_alloc_mw(struct ib_pd *pd)
{
struct ib_mw *mw;
if (!pd->device->alloc_mw)
return ERR_PTR(-ENOSYS);
mw = pd->device->alloc_mw(pd);
if (!IS_ERR(mw)) {
mw->device = pd->device;
mw->pd = pd;
mw->uobject = NULL;
atomic_inc(&pd->usecnt);
}
return mw;
}
EXPORT_SYMBOL(ib_alloc_mw);
int ib_dealloc_mw(struct ib_mw *mw)
{
struct ib_pd *pd;
int ret;
pd = mw->pd;
ret = mw->device->dealloc_mw(mw);
if (!ret)
atomic_dec(&pd->usecnt);
return ret;
}
EXPORT_SYMBOL(ib_dealloc_mw);
/* "Fast" memory regions */
struct ib_fmr *ib_alloc_fmr(struct ib_pd *pd,
int mr_access_flags,
struct ib_fmr_attr *fmr_attr)
{
struct ib_fmr *fmr;
if (!pd->device->alloc_fmr)
return ERR_PTR(-ENOSYS);
fmr = pd->device->alloc_fmr(pd, mr_access_flags, fmr_attr);
if (!IS_ERR(fmr)) {
fmr->device = pd->device;
fmr->pd = pd;
atomic_inc(&pd->usecnt);
}
return fmr;
}
EXPORT_SYMBOL(ib_alloc_fmr);
int ib_unmap_fmr(struct list_head *fmr_list)
{
struct ib_fmr *fmr;
if (list_empty(fmr_list))
return 0;
fmr = list_entry(fmr_list->next, struct ib_fmr, list);
return fmr->device->unmap_fmr(fmr_list);
}
EXPORT_SYMBOL(ib_unmap_fmr);
int ib_dealloc_fmr(struct ib_fmr *fmr)
{
struct ib_pd *pd;
int ret;
pd = fmr->pd;
ret = fmr->device->dealloc_fmr(fmr);
if (!ret)
atomic_dec(&pd->usecnt);
return ret;
}
EXPORT_SYMBOL(ib_dealloc_fmr);
/* Multicast groups */
int ib_attach_mcast(struct ib_qp *qp, union ib_gid *gid, u16 lid)
{
if (!qp->device->attach_mcast)
return -ENOSYS;
if (gid->raw[0] != 0xff || qp->qp_type != IB_QPT_UD)
return -EINVAL;
return qp->device->attach_mcast(qp, gid, lid);
}
EXPORT_SYMBOL(ib_attach_mcast);
int ib_detach_mcast(struct ib_qp *qp, union ib_gid *gid, u16 lid)
{
if (!qp->device->detach_mcast)
return -ENOSYS;
if (gid->raw[0] != 0xff || qp->qp_type != IB_QPT_UD)
return -EINVAL;
return qp->device->detach_mcast(qp, gid, lid);
}
EXPORT_SYMBOL(ib_detach_mcast);
struct ib_xrcd *ib_alloc_xrcd(struct ib_device *device)
{
struct ib_xrcd *xrcd;
if (!device->alloc_xrcd)
return ERR_PTR(-ENOSYS);
xrcd = device->alloc_xrcd(device, NULL, NULL);
if (!IS_ERR(xrcd)) {
xrcd->device = device;
xrcd->inode = NULL;
atomic_set(&xrcd->usecnt, 0);
mutex_init(&xrcd->tgt_qp_mutex);
INIT_LIST_HEAD(&xrcd->tgt_qp_list);
}
return xrcd;
}
EXPORT_SYMBOL(ib_alloc_xrcd);
int ib_dealloc_xrcd(struct ib_xrcd *xrcd)
{
struct ib_qp *qp;
int ret;
if (atomic_read(&xrcd->usecnt))
return -EBUSY;
while (!list_empty(&xrcd->tgt_qp_list)) {
qp = list_entry(xrcd->tgt_qp_list.next, struct ib_qp, xrcd_list);
ret = ib_destroy_qp(qp);
if (ret)
return ret;
}
return xrcd->device->dealloc_xrcd(xrcd);
}
EXPORT_SYMBOL(ib_dealloc_xrcd);
| gpl-2.0 |
lawnn/android_kernel_samsung_msm8974 | drivers/input/tablet/kbtab.c | 4912 | 5092 | #include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/usb/input.h>
#include <asm/unaligned.h>
/*
* Version Information
* v0.0.1 - Original, extremely basic version, 2.4.xx only
* v0.0.2 - Updated, works with 2.5.62 and 2.4.20;
* - added pressure-threshold modules param code from
* Alex Perry <alex.perry@ieee.org>
*/
#define DRIVER_VERSION "v0.0.2"
#define DRIVER_AUTHOR "Josh Myer <josh@joshisanerd.com>"
#define DRIVER_DESC "USB KB Gear JamStudio Tablet driver"
#define DRIVER_LICENSE "GPL"
MODULE_AUTHOR(DRIVER_AUTHOR);
MODULE_DESCRIPTION(DRIVER_DESC);
MODULE_LICENSE(DRIVER_LICENSE);
#define USB_VENDOR_ID_KBGEAR 0x084e
static int kb_pressure_click = 0x10;
module_param(kb_pressure_click, int, 0);
MODULE_PARM_DESC(kb_pressure_click, "pressure threshold for clicks");
struct kbtab {
unsigned char *data;
dma_addr_t data_dma;
struct input_dev *dev;
struct usb_device *usbdev;
struct urb *irq;
char phys[32];
};
static void kbtab_irq(struct urb *urb)
{
struct kbtab *kbtab = urb->context;
unsigned char *data = kbtab->data;
struct input_dev *dev = kbtab->dev;
int pressure;
int retval;
switch (urb->status) {
case 0:
/* success */
break;
case -ECONNRESET:
case -ENOENT:
case -ESHUTDOWN:
/* this urb is terminated, clean up */
dbg("%s - urb shutting down with status: %d", __func__, urb->status);
return;
default:
dbg("%s - nonzero urb status received: %d", __func__, urb->status);
goto exit;
}
input_report_key(dev, BTN_TOOL_PEN, 1);
input_report_abs(dev, ABS_X, get_unaligned_le16(&data[1]));
input_report_abs(dev, ABS_Y, get_unaligned_le16(&data[3]));
/*input_report_key(dev, BTN_TOUCH , data[0] & 0x01);*/
input_report_key(dev, BTN_RIGHT, data[0] & 0x02);
pressure = data[5];
if (kb_pressure_click == -1)
input_report_abs(dev, ABS_PRESSURE, pressure);
else
input_report_key(dev, BTN_LEFT, pressure > kb_pressure_click ? 1 : 0);
input_sync(dev);
exit:
retval = usb_submit_urb(urb, GFP_ATOMIC);
if (retval)
err("%s - usb_submit_urb failed with result %d",
__func__, retval);
}
static struct usb_device_id kbtab_ids[] = {
{ USB_DEVICE(USB_VENDOR_ID_KBGEAR, 0x1001), .driver_info = 0 },
{ }
};
MODULE_DEVICE_TABLE(usb, kbtab_ids);
static int kbtab_open(struct input_dev *dev)
{
struct kbtab *kbtab = input_get_drvdata(dev);
kbtab->irq->dev = kbtab->usbdev;
if (usb_submit_urb(kbtab->irq, GFP_KERNEL))
return -EIO;
return 0;
}
static void kbtab_close(struct input_dev *dev)
{
struct kbtab *kbtab = input_get_drvdata(dev);
usb_kill_urb(kbtab->irq);
}
static int kbtab_probe(struct usb_interface *intf, const struct usb_device_id *id)
{
struct usb_device *dev = interface_to_usbdev(intf);
struct usb_endpoint_descriptor *endpoint;
struct kbtab *kbtab;
struct input_dev *input_dev;
int error = -ENOMEM;
kbtab = kzalloc(sizeof(struct kbtab), GFP_KERNEL);
input_dev = input_allocate_device();
if (!kbtab || !input_dev)
goto fail1;
kbtab->data = usb_alloc_coherent(dev, 8, GFP_KERNEL, &kbtab->data_dma);
if (!kbtab->data)
goto fail1;
kbtab->irq = usb_alloc_urb(0, GFP_KERNEL);
if (!kbtab->irq)
goto fail2;
kbtab->usbdev = dev;
kbtab->dev = input_dev;
usb_make_path(dev, kbtab->phys, sizeof(kbtab->phys));
strlcat(kbtab->phys, "/input0", sizeof(kbtab->phys));
input_dev->name = "KB Gear Tablet";
input_dev->phys = kbtab->phys;
usb_to_input_id(dev, &input_dev->id);
input_dev->dev.parent = &intf->dev;
input_set_drvdata(input_dev, kbtab);
input_dev->open = kbtab_open;
input_dev->close = kbtab_close;
input_dev->evbit[0] |= BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
input_dev->keybit[BIT_WORD(BTN_LEFT)] |=
BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT);
input_dev->keybit[BIT_WORD(BTN_DIGI)] |=
BIT_MASK(BTN_TOOL_PEN) | BIT_MASK(BTN_TOUCH);
input_set_abs_params(input_dev, ABS_X, 0, 0x2000, 4, 0);
input_set_abs_params(input_dev, ABS_Y, 0, 0x1750, 4, 0);
input_set_abs_params(input_dev, ABS_PRESSURE, 0, 0xff, 0, 0);
endpoint = &intf->cur_altsetting->endpoint[0].desc;
usb_fill_int_urb(kbtab->irq, dev,
usb_rcvintpipe(dev, endpoint->bEndpointAddress),
kbtab->data, 8,
kbtab_irq, kbtab, endpoint->bInterval);
kbtab->irq->transfer_dma = kbtab->data_dma;
kbtab->irq->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
error = input_register_device(kbtab->dev);
if (error)
goto fail3;
usb_set_intfdata(intf, kbtab);
return 0;
fail3: usb_free_urb(kbtab->irq);
fail2: usb_free_coherent(dev, 8, kbtab->data, kbtab->data_dma);
fail1: input_free_device(input_dev);
kfree(kbtab);
return error;
}
static void kbtab_disconnect(struct usb_interface *intf)
{
struct kbtab *kbtab = usb_get_intfdata(intf);
usb_set_intfdata(intf, NULL);
input_unregister_device(kbtab->dev);
usb_free_urb(kbtab->irq);
usb_free_coherent(kbtab->usbdev, 8, kbtab->data, kbtab->data_dma);
kfree(kbtab);
}
static struct usb_driver kbtab_driver = {
.name = "kbtab",
.probe = kbtab_probe,
.disconnect = kbtab_disconnect,
.id_table = kbtab_ids,
};
module_usb_driver(kbtab_driver);
| gpl-2.0 |
pvittman/donkey-cm12 | security/tomoyo/domain.c | 9264 | 25265 | /*
* security/tomoyo/domain.c
*
* Copyright (C) 2005-2011 NTT DATA CORPORATION
*/
#include "common.h"
#include <linux/binfmts.h>
#include <linux/slab.h>
/* Variables definitions.*/
/* The initial domain. */
struct tomoyo_domain_info tomoyo_kernel_domain;
/**
* tomoyo_update_policy - Update an entry for exception policy.
*
* @new_entry: Pointer to "struct tomoyo_acl_info".
* @size: Size of @new_entry in bytes.
* @param: Pointer to "struct tomoyo_acl_param".
* @check_duplicate: Callback function to find duplicated entry.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_update_policy(struct tomoyo_acl_head *new_entry, const int size,
struct tomoyo_acl_param *param,
bool (*check_duplicate) (const struct tomoyo_acl_head
*,
const struct tomoyo_acl_head
*))
{
int error = param->is_delete ? -ENOENT : -ENOMEM;
struct tomoyo_acl_head *entry;
struct list_head *list = param->list;
if (mutex_lock_interruptible(&tomoyo_policy_lock))
return -ENOMEM;
list_for_each_entry_rcu(entry, list, list) {
if (entry->is_deleted == TOMOYO_GC_IN_PROGRESS)
continue;
if (!check_duplicate(entry, new_entry))
continue;
entry->is_deleted = param->is_delete;
error = 0;
break;
}
if (error && !param->is_delete) {
entry = tomoyo_commit_ok(new_entry, size);
if (entry) {
list_add_tail_rcu(&entry->list, list);
error = 0;
}
}
mutex_unlock(&tomoyo_policy_lock);
return error;
}
/**
* tomoyo_same_acl_head - Check for duplicated "struct tomoyo_acl_info" entry.
*
* @a: Pointer to "struct tomoyo_acl_info".
* @b: Pointer to "struct tomoyo_acl_info".
*
* Returns true if @a == @b, false otherwise.
*/
static inline bool tomoyo_same_acl_head(const struct tomoyo_acl_info *a,
const struct tomoyo_acl_info *b)
{
return a->type == b->type && a->cond == b->cond;
}
/**
* tomoyo_update_domain - Update an entry for domain policy.
*
* @new_entry: Pointer to "struct tomoyo_acl_info".
* @size: Size of @new_entry in bytes.
* @param: Pointer to "struct tomoyo_acl_param".
* @check_duplicate: Callback function to find duplicated entry.
* @merge_duplicate: Callback function to merge duplicated entry.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_update_domain(struct tomoyo_acl_info *new_entry, const int size,
struct tomoyo_acl_param *param,
bool (*check_duplicate) (const struct tomoyo_acl_info
*,
const struct tomoyo_acl_info
*),
bool (*merge_duplicate) (struct tomoyo_acl_info *,
struct tomoyo_acl_info *,
const bool))
{
const bool is_delete = param->is_delete;
int error = is_delete ? -ENOENT : -ENOMEM;
struct tomoyo_acl_info *entry;
struct list_head * const list = param->list;
if (param->data[0]) {
new_entry->cond = tomoyo_get_condition(param);
if (!new_entry->cond)
return -EINVAL;
/*
* Domain transition preference is allowed for only
* "file execute" entries.
*/
if (new_entry->cond->transit &&
!(new_entry->type == TOMOYO_TYPE_PATH_ACL &&
container_of(new_entry, struct tomoyo_path_acl, head)
->perm == 1 << TOMOYO_TYPE_EXECUTE))
goto out;
}
if (mutex_lock_interruptible(&tomoyo_policy_lock))
goto out;
list_for_each_entry_rcu(entry, list, list) {
if (entry->is_deleted == TOMOYO_GC_IN_PROGRESS)
continue;
if (!tomoyo_same_acl_head(entry, new_entry) ||
!check_duplicate(entry, new_entry))
continue;
if (merge_duplicate)
entry->is_deleted = merge_duplicate(entry, new_entry,
is_delete);
else
entry->is_deleted = is_delete;
error = 0;
break;
}
if (error && !is_delete) {
entry = tomoyo_commit_ok(new_entry, size);
if (entry) {
list_add_tail_rcu(&entry->list, list);
error = 0;
}
}
mutex_unlock(&tomoyo_policy_lock);
out:
tomoyo_put_condition(new_entry->cond);
return error;
}
/**
* tomoyo_check_acl - Do permission check.
*
* @r: Pointer to "struct tomoyo_request_info".
* @check_entry: Callback function to check type specific parameters.
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
void tomoyo_check_acl(struct tomoyo_request_info *r,
bool (*check_entry) (struct tomoyo_request_info *,
const struct tomoyo_acl_info *))
{
const struct tomoyo_domain_info *domain = r->domain;
struct tomoyo_acl_info *ptr;
bool retried = false;
const struct list_head *list = &domain->acl_info_list;
retry:
list_for_each_entry_rcu(ptr, list, list) {
if (ptr->is_deleted || ptr->type != r->param_type)
continue;
if (!check_entry(r, ptr))
continue;
if (!tomoyo_condition(r, ptr->cond))
continue;
r->matched_acl = ptr;
r->granted = true;
return;
}
if (!retried) {
retried = true;
list = &domain->ns->acl_group[domain->group];
goto retry;
}
r->granted = false;
}
/* The list for "struct tomoyo_domain_info". */
LIST_HEAD(tomoyo_domain_list);
/**
* tomoyo_last_word - Get last component of a domainname.
*
* @name: Domainname to check.
*
* Returns the last word of @domainname.
*/
static const char *tomoyo_last_word(const char *name)
{
const char *cp = strrchr(name, ' ');
if (cp)
return cp + 1;
return name;
}
/**
* tomoyo_same_transition_control - Check for duplicated "struct tomoyo_transition_control" entry.
*
* @a: Pointer to "struct tomoyo_acl_head".
* @b: Pointer to "struct tomoyo_acl_head".
*
* Returns true if @a == @b, false otherwise.
*/
static bool tomoyo_same_transition_control(const struct tomoyo_acl_head *a,
const struct tomoyo_acl_head *b)
{
const struct tomoyo_transition_control *p1 = container_of(a,
typeof(*p1),
head);
const struct tomoyo_transition_control *p2 = container_of(b,
typeof(*p2),
head);
return p1->type == p2->type && p1->is_last_name == p2->is_last_name
&& p1->domainname == p2->domainname
&& p1->program == p2->program;
}
/**
* tomoyo_write_transition_control - Write "struct tomoyo_transition_control" list.
*
* @param: Pointer to "struct tomoyo_acl_param".
* @type: Type of this entry.
*
* Returns 0 on success, negative value otherwise.
*/
int tomoyo_write_transition_control(struct tomoyo_acl_param *param,
const u8 type)
{
struct tomoyo_transition_control e = { .type = type };
int error = param->is_delete ? -ENOENT : -ENOMEM;
char *program = param->data;
char *domainname = strstr(program, " from ");
if (domainname) {
*domainname = '\0';
domainname += 6;
} else if (type == TOMOYO_TRANSITION_CONTROL_NO_KEEP ||
type == TOMOYO_TRANSITION_CONTROL_KEEP) {
domainname = program;
program = NULL;
}
if (program && strcmp(program, "any")) {
if (!tomoyo_correct_path(program))
return -EINVAL;
e.program = tomoyo_get_name(program);
if (!e.program)
goto out;
}
if (domainname && strcmp(domainname, "any")) {
if (!tomoyo_correct_domain(domainname)) {
if (!tomoyo_correct_path(domainname))
goto out;
e.is_last_name = true;
}
e.domainname = tomoyo_get_name(domainname);
if (!e.domainname)
goto out;
}
param->list = ¶m->ns->policy_list[TOMOYO_ID_TRANSITION_CONTROL];
error = tomoyo_update_policy(&e.head, sizeof(e), param,
tomoyo_same_transition_control);
out:
tomoyo_put_name(e.domainname);
tomoyo_put_name(e.program);
return error;
}
/**
* tomoyo_scan_transition - Try to find specific domain transition type.
*
* @list: Pointer to "struct list_head".
* @domainname: The name of current domain.
* @program: The name of requested program.
* @last_name: The last component of @domainname.
* @type: One of values in "enum tomoyo_transition_type".
*
* Returns true if found one, false otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static inline bool tomoyo_scan_transition
(const struct list_head *list, const struct tomoyo_path_info *domainname,
const struct tomoyo_path_info *program, const char *last_name,
const enum tomoyo_transition_type type)
{
const struct tomoyo_transition_control *ptr;
list_for_each_entry_rcu(ptr, list, head.list) {
if (ptr->head.is_deleted || ptr->type != type)
continue;
if (ptr->domainname) {
if (!ptr->is_last_name) {
if (ptr->domainname != domainname)
continue;
} else {
/*
* Use direct strcmp() since this is
* unlikely used.
*/
if (strcmp(ptr->domainname->name, last_name))
continue;
}
}
if (ptr->program && tomoyo_pathcmp(ptr->program, program))
continue;
return true;
}
return false;
}
/**
* tomoyo_transition_type - Get domain transition type.
*
* @ns: Pointer to "struct tomoyo_policy_namespace".
* @domainname: The name of current domain.
* @program: The name of requested program.
*
* Returns TOMOYO_TRANSITION_CONTROL_TRANSIT if executing @program causes
* domain transition across namespaces, TOMOYO_TRANSITION_CONTROL_INITIALIZE if
* executing @program reinitializes domain transition within that namespace,
* TOMOYO_TRANSITION_CONTROL_KEEP if executing @program stays at @domainname ,
* others otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static enum tomoyo_transition_type tomoyo_transition_type
(const struct tomoyo_policy_namespace *ns,
const struct tomoyo_path_info *domainname,
const struct tomoyo_path_info *program)
{
const char *last_name = tomoyo_last_word(domainname->name);
enum tomoyo_transition_type type = TOMOYO_TRANSITION_CONTROL_NO_RESET;
while (type < TOMOYO_MAX_TRANSITION_TYPE) {
const struct list_head * const list =
&ns->policy_list[TOMOYO_ID_TRANSITION_CONTROL];
if (!tomoyo_scan_transition(list, domainname, program,
last_name, type)) {
type++;
continue;
}
if (type != TOMOYO_TRANSITION_CONTROL_NO_RESET &&
type != TOMOYO_TRANSITION_CONTROL_NO_INITIALIZE)
break;
/*
* Do not check for reset_domain if no_reset_domain matched.
* Do not check for initialize_domain if no_initialize_domain
* matched.
*/
type++;
type++;
}
return type;
}
/**
* tomoyo_same_aggregator - Check for duplicated "struct tomoyo_aggregator" entry.
*
* @a: Pointer to "struct tomoyo_acl_head".
* @b: Pointer to "struct tomoyo_acl_head".
*
* Returns true if @a == @b, false otherwise.
*/
static bool tomoyo_same_aggregator(const struct tomoyo_acl_head *a,
const struct tomoyo_acl_head *b)
{
const struct tomoyo_aggregator *p1 = container_of(a, typeof(*p1),
head);
const struct tomoyo_aggregator *p2 = container_of(b, typeof(*p2),
head);
return p1->original_name == p2->original_name &&
p1->aggregated_name == p2->aggregated_name;
}
/**
* tomoyo_write_aggregator - Write "struct tomoyo_aggregator" list.
*
* @param: Pointer to "struct tomoyo_acl_param".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_write_aggregator(struct tomoyo_acl_param *param)
{
struct tomoyo_aggregator e = { };
int error = param->is_delete ? -ENOENT : -ENOMEM;
const char *original_name = tomoyo_read_token(param);
const char *aggregated_name = tomoyo_read_token(param);
if (!tomoyo_correct_word(original_name) ||
!tomoyo_correct_path(aggregated_name))
return -EINVAL;
e.original_name = tomoyo_get_name(original_name);
e.aggregated_name = tomoyo_get_name(aggregated_name);
if (!e.original_name || !e.aggregated_name ||
e.aggregated_name->is_patterned) /* No patterns allowed. */
goto out;
param->list = ¶m->ns->policy_list[TOMOYO_ID_AGGREGATOR];
error = tomoyo_update_policy(&e.head, sizeof(e), param,
tomoyo_same_aggregator);
out:
tomoyo_put_name(e.original_name);
tomoyo_put_name(e.aggregated_name);
return error;
}
/**
* tomoyo_find_namespace - Find specified namespace.
*
* @name: Name of namespace to find.
* @len: Length of @name.
*
* Returns pointer to "struct tomoyo_policy_namespace" if found,
* NULL otherwise.
*
* Caller holds tomoyo_read_lock().
*/
static struct tomoyo_policy_namespace *tomoyo_find_namespace
(const char *name, const unsigned int len)
{
struct tomoyo_policy_namespace *ns;
list_for_each_entry(ns, &tomoyo_namespace_list, namespace_list) {
if (strncmp(name, ns->name, len) ||
(name[len] && name[len] != ' '))
continue;
return ns;
}
return NULL;
}
/**
* tomoyo_assign_namespace - Create a new namespace.
*
* @domainname: Name of namespace to create.
*
* Returns pointer to "struct tomoyo_policy_namespace" on success,
* NULL otherwise.
*
* Caller holds tomoyo_read_lock().
*/
struct tomoyo_policy_namespace *tomoyo_assign_namespace(const char *domainname)
{
struct tomoyo_policy_namespace *ptr;
struct tomoyo_policy_namespace *entry;
const char *cp = domainname;
unsigned int len = 0;
while (*cp && *cp++ != ' ')
len++;
ptr = tomoyo_find_namespace(domainname, len);
if (ptr)
return ptr;
if (len >= TOMOYO_EXEC_TMPSIZE - 10 || !tomoyo_domain_def(domainname))
return NULL;
entry = kzalloc(sizeof(*entry) + len + 1, GFP_NOFS);
if (!entry)
return NULL;
if (mutex_lock_interruptible(&tomoyo_policy_lock))
goto out;
ptr = tomoyo_find_namespace(domainname, len);
if (!ptr && tomoyo_memory_ok(entry)) {
char *name = (char *) (entry + 1);
ptr = entry;
memmove(name, domainname, len);
name[len] = '\0';
entry->name = name;
tomoyo_init_policy_namespace(entry);
entry = NULL;
}
mutex_unlock(&tomoyo_policy_lock);
out:
kfree(entry);
return ptr;
}
/**
* tomoyo_namespace_jump - Check for namespace jump.
*
* @domainname: Name of domain.
*
* Returns true if namespace differs, false otherwise.
*/
static bool tomoyo_namespace_jump(const char *domainname)
{
const char *namespace = tomoyo_current_namespace()->name;
const int len = strlen(namespace);
return strncmp(domainname, namespace, len) ||
(domainname[len] && domainname[len] != ' ');
}
/**
* tomoyo_assign_domain - Create a domain or a namespace.
*
* @domainname: The name of domain.
* @transit: True if transit to domain found or created.
*
* Returns pointer to "struct tomoyo_domain_info" on success, NULL otherwise.
*
* Caller holds tomoyo_read_lock().
*/
struct tomoyo_domain_info *tomoyo_assign_domain(const char *domainname,
const bool transit)
{
struct tomoyo_domain_info e = { };
struct tomoyo_domain_info *entry = tomoyo_find_domain(domainname);
bool created = false;
if (entry) {
if (transit) {
/*
* Since namespace is created at runtime, profiles may
* not be created by the moment the process transits to
* that domain. Do not perform domain transition if
* profile for that domain is not yet created.
*/
if (tomoyo_policy_loaded &&
!entry->ns->profile_ptr[entry->profile])
return NULL;
}
return entry;
}
/* Requested domain does not exist. */
/* Don't create requested domain if domainname is invalid. */
if (strlen(domainname) >= TOMOYO_EXEC_TMPSIZE - 10 ||
!tomoyo_correct_domain(domainname))
return NULL;
/*
* Since definition of profiles and acl_groups may differ across
* namespaces, do not inherit "use_profile" and "use_group" settings
* by automatically creating requested domain upon domain transition.
*/
if (transit && tomoyo_namespace_jump(domainname))
return NULL;
e.ns = tomoyo_assign_namespace(domainname);
if (!e.ns)
return NULL;
/*
* "use_profile" and "use_group" settings for automatically created
* domains are inherited from current domain. These are 0 for manually
* created domains.
*/
if (transit) {
const struct tomoyo_domain_info *domain = tomoyo_domain();
e.profile = domain->profile;
e.group = domain->group;
}
e.domainname = tomoyo_get_name(domainname);
if (!e.domainname)
return NULL;
if (mutex_lock_interruptible(&tomoyo_policy_lock))
goto out;
entry = tomoyo_find_domain(domainname);
if (!entry) {
entry = tomoyo_commit_ok(&e, sizeof(e));
if (entry) {
INIT_LIST_HEAD(&entry->acl_info_list);
list_add_tail_rcu(&entry->list, &tomoyo_domain_list);
created = true;
}
}
mutex_unlock(&tomoyo_policy_lock);
out:
tomoyo_put_name(e.domainname);
if (entry && transit) {
if (created) {
struct tomoyo_request_info r;
tomoyo_init_request_info(&r, entry,
TOMOYO_MAC_FILE_EXECUTE);
r.granted = false;
tomoyo_write_log(&r, "use_profile %u\n",
entry->profile);
tomoyo_write_log(&r, "use_group %u\n", entry->group);
tomoyo_update_stat(TOMOYO_STAT_POLICY_UPDATES);
}
}
return entry;
}
/**
* tomoyo_environ - Check permission for environment variable names.
*
* @ee: Pointer to "struct tomoyo_execve".
*
* Returns 0 on success, negative value otherwise.
*/
static int tomoyo_environ(struct tomoyo_execve *ee)
{
struct tomoyo_request_info *r = &ee->r;
struct linux_binprm *bprm = ee->bprm;
/* env_page.data is allocated by tomoyo_dump_page(). */
struct tomoyo_page_dump env_page = { };
char *arg_ptr; /* Size is TOMOYO_EXEC_TMPSIZE bytes */
int arg_len = 0;
unsigned long pos = bprm->p;
int offset = pos % PAGE_SIZE;
int argv_count = bprm->argc;
int envp_count = bprm->envc;
int error = -ENOMEM;
ee->r.type = TOMOYO_MAC_ENVIRON;
ee->r.profile = r->domain->profile;
ee->r.mode = tomoyo_get_mode(r->domain->ns, ee->r.profile,
TOMOYO_MAC_ENVIRON);
if (!r->mode || !envp_count)
return 0;
arg_ptr = kzalloc(TOMOYO_EXEC_TMPSIZE, GFP_NOFS);
if (!arg_ptr)
goto out;
while (error == -ENOMEM) {
if (!tomoyo_dump_page(bprm, pos, &env_page))
goto out;
pos += PAGE_SIZE - offset;
/* Read. */
while (argv_count && offset < PAGE_SIZE) {
if (!env_page.data[offset++])
argv_count--;
}
if (argv_count) {
offset = 0;
continue;
}
while (offset < PAGE_SIZE) {
const unsigned char c = env_page.data[offset++];
if (c && arg_len < TOMOYO_EXEC_TMPSIZE - 10) {
if (c == '=') {
arg_ptr[arg_len++] = '\0';
} else if (c == '\\') {
arg_ptr[arg_len++] = '\\';
arg_ptr[arg_len++] = '\\';
} else if (c > ' ' && c < 127) {
arg_ptr[arg_len++] = c;
} else {
arg_ptr[arg_len++] = '\\';
arg_ptr[arg_len++] = (c >> 6) + '0';
arg_ptr[arg_len++]
= ((c >> 3) & 7) + '0';
arg_ptr[arg_len++] = (c & 7) + '0';
}
} else {
arg_ptr[arg_len] = '\0';
}
if (c)
continue;
if (tomoyo_env_perm(r, arg_ptr)) {
error = -EPERM;
break;
}
if (!--envp_count) {
error = 0;
break;
}
arg_len = 0;
}
offset = 0;
}
out:
if (r->mode != TOMOYO_CONFIG_ENFORCING)
error = 0;
kfree(env_page.data);
kfree(arg_ptr);
return error;
}
/**
* tomoyo_find_next_domain - Find a domain.
*
* @bprm: Pointer to "struct linux_binprm".
*
* Returns 0 on success, negative value otherwise.
*
* Caller holds tomoyo_read_lock().
*/
int tomoyo_find_next_domain(struct linux_binprm *bprm)
{
struct tomoyo_domain_info *old_domain = tomoyo_domain();
struct tomoyo_domain_info *domain = NULL;
const char *original_name = bprm->filename;
int retval = -ENOMEM;
bool reject_on_transition_failure = false;
const struct tomoyo_path_info *candidate;
struct tomoyo_path_info exename;
struct tomoyo_execve *ee = kzalloc(sizeof(*ee), GFP_NOFS);
if (!ee)
return -ENOMEM;
ee->tmp = kzalloc(TOMOYO_EXEC_TMPSIZE, GFP_NOFS);
if (!ee->tmp) {
kfree(ee);
return -ENOMEM;
}
/* ee->dump->data is allocated by tomoyo_dump_page(). */
tomoyo_init_request_info(&ee->r, NULL, TOMOYO_MAC_FILE_EXECUTE);
ee->r.ee = ee;
ee->bprm = bprm;
ee->r.obj = &ee->obj;
ee->obj.path1 = bprm->file->f_path;
/* Get symlink's pathname of program. */
retval = -ENOENT;
exename.name = tomoyo_realpath_nofollow(original_name);
if (!exename.name)
goto out;
tomoyo_fill_path_info(&exename);
retry:
/* Check 'aggregator' directive. */
{
struct tomoyo_aggregator *ptr;
struct list_head *list =
&old_domain->ns->policy_list[TOMOYO_ID_AGGREGATOR];
/* Check 'aggregator' directive. */
candidate = &exename;
list_for_each_entry_rcu(ptr, list, head.list) {
if (ptr->head.is_deleted ||
!tomoyo_path_matches_pattern(&exename,
ptr->original_name))
continue;
candidate = ptr->aggregated_name;
break;
}
}
/* Check execute permission. */
retval = tomoyo_execute_permission(&ee->r, candidate);
if (retval == TOMOYO_RETRY_REQUEST)
goto retry;
if (retval < 0)
goto out;
/*
* To be able to specify domainnames with wildcards, use the
* pathname specified in the policy (which may contain
* wildcard) rather than the pathname passed to execve()
* (which never contains wildcard).
*/
if (ee->r.param.path.matched_path)
candidate = ee->r.param.path.matched_path;
/*
* Check for domain transition preference if "file execute" matched.
* If preference is given, make do_execve() fail if domain transition
* has failed, for domain transition preference should be used with
* destination domain defined.
*/
if (ee->transition) {
const char *domainname = ee->transition->name;
reject_on_transition_failure = true;
if (!strcmp(domainname, "keep"))
goto force_keep_domain;
if (!strcmp(domainname, "child"))
goto force_child_domain;
if (!strcmp(domainname, "reset"))
goto force_reset_domain;
if (!strcmp(domainname, "initialize"))
goto force_initialize_domain;
if (!strcmp(domainname, "parent")) {
char *cp;
strncpy(ee->tmp, old_domain->domainname->name,
TOMOYO_EXEC_TMPSIZE - 1);
cp = strrchr(ee->tmp, ' ');
if (cp)
*cp = '\0';
} else if (*domainname == '<')
strncpy(ee->tmp, domainname, TOMOYO_EXEC_TMPSIZE - 1);
else
snprintf(ee->tmp, TOMOYO_EXEC_TMPSIZE - 1, "%s %s",
old_domain->domainname->name, domainname);
goto force_jump_domain;
}
/*
* No domain transition preference specified.
* Calculate domain to transit to.
*/
switch (tomoyo_transition_type(old_domain->ns, old_domain->domainname,
candidate)) {
case TOMOYO_TRANSITION_CONTROL_RESET:
force_reset_domain:
/* Transit to the root of specified namespace. */
snprintf(ee->tmp, TOMOYO_EXEC_TMPSIZE - 1, "<%s>",
candidate->name);
/*
* Make do_execve() fail if domain transition across namespaces
* has failed.
*/
reject_on_transition_failure = true;
break;
case TOMOYO_TRANSITION_CONTROL_INITIALIZE:
force_initialize_domain:
/* Transit to the child of current namespace's root. */
snprintf(ee->tmp, TOMOYO_EXEC_TMPSIZE - 1, "%s %s",
old_domain->ns->name, candidate->name);
break;
case TOMOYO_TRANSITION_CONTROL_KEEP:
force_keep_domain:
/* Keep current domain. */
domain = old_domain;
break;
default:
if (old_domain == &tomoyo_kernel_domain &&
!tomoyo_policy_loaded) {
/*
* Needn't to transit from kernel domain before
* starting /sbin/init. But transit from kernel domain
* if executing initializers because they might start
* before /sbin/init.
*/
domain = old_domain;
break;
}
force_child_domain:
/* Normal domain transition. */
snprintf(ee->tmp, TOMOYO_EXEC_TMPSIZE - 1, "%s %s",
old_domain->domainname->name, candidate->name);
break;
}
force_jump_domain:
if (!domain)
domain = tomoyo_assign_domain(ee->tmp, true);
if (domain)
retval = 0;
else if (reject_on_transition_failure) {
printk(KERN_WARNING "ERROR: Domain '%s' not ready.\n",
ee->tmp);
retval = -ENOMEM;
} else if (ee->r.mode == TOMOYO_CONFIG_ENFORCING)
retval = -ENOMEM;
else {
retval = 0;
if (!old_domain->flags[TOMOYO_DIF_TRANSITION_FAILED]) {
old_domain->flags[TOMOYO_DIF_TRANSITION_FAILED] = true;
ee->r.granted = false;
tomoyo_write_log(&ee->r, "%s", tomoyo_dif
[TOMOYO_DIF_TRANSITION_FAILED]);
printk(KERN_WARNING
"ERROR: Domain '%s' not defined.\n", ee->tmp);
}
}
out:
if (!domain)
domain = old_domain;
/* Update reference count on "struct tomoyo_domain_info". */
atomic_inc(&domain->users);
bprm->cred->security = domain;
kfree(exename.name);
if (!retval) {
ee->r.domain = domain;
retval = tomoyo_environ(ee);
}
kfree(ee->tmp);
kfree(ee->dump.data);
kfree(ee);
return retval;
}
/**
* tomoyo_dump_page - Dump a page to buffer.
*
* @bprm: Pointer to "struct linux_binprm".
* @pos: Location to dump.
* @dump: Poiner to "struct tomoyo_page_dump".
*
* Returns true on success, false otherwise.
*/
bool tomoyo_dump_page(struct linux_binprm *bprm, unsigned long pos,
struct tomoyo_page_dump *dump)
{
struct page *page;
/* dump->data is released by tomoyo_find_next_domain(). */
if (!dump->data) {
dump->data = kzalloc(PAGE_SIZE, GFP_NOFS);
if (!dump->data)
return false;
}
/* Same with get_arg_page(bprm, pos, 0) in fs/exec.c */
#ifdef CONFIG_MMU
if (get_user_pages(current, bprm->mm, pos, 1, 0, 1, &page, NULL) <= 0)
return false;
#else
page = bprm->page[pos / PAGE_SIZE];
#endif
if (page != dump->page) {
const unsigned int offset = pos % PAGE_SIZE;
/*
* Maybe kmap()/kunmap() should be used here.
* But remove_arg_zero() uses kmap_atomic()/kunmap_atomic().
* So do I.
*/
char *kaddr = kmap_atomic(page);
dump->page = page;
memcpy(dump->data + offset, kaddr + offset,
PAGE_SIZE - offset);
kunmap_atomic(kaddr);
}
/* Same with put_arg_page(page) in fs/exec.c */
#ifdef CONFIG_MMU
put_page(page);
#endif
return true;
}
| gpl-2.0 |
maxfierke/axstrom-kernel | arch/powerpc/platforms/amigaone/setup.c | 10544 | 4379 | /*
* AmigaOne platform setup
*
* Copyright 2008 Gerhard Pircher (gerhard_pircher@gmx.net)
*
* Based on original amigaone_setup.c source code
* Copyright 2003 by Hans-Joerg Frieden and Thomas Frieden
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/kernel.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/seq_file.h>
#include <generated/utsrelease.h>
#include <asm/machdep.h>
#include <asm/cputable.h>
#include <asm/pci-bridge.h>
#include <asm/i8259.h>
#include <asm/time.h>
#include <asm/udbg.h>
extern void __flush_disable_L1(void);
void amigaone_show_cpuinfo(struct seq_file *m)
{
seq_printf(m, "vendor\t\t: Eyetech Ltd.\n");
}
static int __init amigaone_add_bridge(struct device_node *dev)
{
const u32 *cfg_addr, *cfg_data;
int len;
const int *bus_range;
struct pci_controller *hose;
printk(KERN_INFO "Adding PCI host bridge %s\n", dev->full_name);
cfg_addr = of_get_address(dev, 0, NULL, NULL);
cfg_data = of_get_address(dev, 1, NULL, NULL);
if ((cfg_addr == NULL) || (cfg_data == NULL))
return -ENODEV;
bus_range = of_get_property(dev, "bus-range", &len);
if ((bus_range == NULL) || (len < 2 * sizeof(int)))
printk(KERN_WARNING "Can't get bus-range for %s, assume"
" bus 0\n", dev->full_name);
hose = pcibios_alloc_controller(dev);
if (hose == NULL)
return -ENOMEM;
hose->first_busno = bus_range ? bus_range[0] : 0;
hose->last_busno = bus_range ? bus_range[1] : 0xff;
setup_indirect_pci(hose, cfg_addr[0], cfg_data[0], 0);
/* Interpret the "ranges" property */
/* This also maps the I/O region and sets isa_io/mem_base */
pci_process_bridge_OF_ranges(hose, dev, 1);
return 0;
}
void __init amigaone_setup_arch(void)
{
struct device_node *np;
int phb = -ENODEV;
/* Lookup PCI host bridges. */
for_each_compatible_node(np, "pci", "mai-logic,articia-s")
phb = amigaone_add_bridge(np);
BUG_ON(phb != 0);
if (ppc_md.progress)
ppc_md.progress("Linux/PPC "UTS_RELEASE"\n", 0);
}
void __init amigaone_init_IRQ(void)
{
struct device_node *pic, *np = NULL;
const unsigned long *prop = NULL;
unsigned long int_ack = 0;
/* Search for ISA interrupt controller. */
pic = of_find_compatible_node(NULL, "interrupt-controller",
"pnpPNP,000");
BUG_ON(pic == NULL);
/* Look for interrupt acknowledge address in the PCI root node. */
np = of_find_compatible_node(NULL, "pci", "mai-logic,articia-s");
if (np) {
prop = of_get_property(np, "8259-interrupt-acknowledge", NULL);
if (prop)
int_ack = prop[0];
of_node_put(np);
}
if (int_ack == 0)
printk(KERN_WARNING "Cannot find PCI interrupt acknowledge"
" address, polling\n");
i8259_init(pic, int_ack);
ppc_md.get_irq = i8259_irq;
irq_set_default_host(i8259_get_host());
}
static int __init request_isa_regions(void)
{
request_region(0x00, 0x20, "dma1");
request_region(0x40, 0x20, "timer");
request_region(0x80, 0x10, "dma page reg");
request_region(0xc0, 0x20, "dma2");
return 0;
}
machine_device_initcall(amigaone, request_isa_regions);
void amigaone_restart(char *cmd)
{
local_irq_disable();
/* Flush and disable caches. */
__flush_disable_L1();
/* Set SRR0 to the reset vector and turn on MSR_IP. */
mtspr(SPRN_SRR0, 0xfff00100);
mtspr(SPRN_SRR1, MSR_IP);
/* Do an rfi to jump back to firmware. */
__asm__ __volatile__("rfi" : : : "memory");
/* Not reached. */
while (1);
}
static int __init amigaone_probe(void)
{
unsigned long root = of_get_flat_dt_root();
if (of_flat_dt_is_compatible(root, "eyetech,amigaone")) {
/*
* Coherent memory access cause complete system lockup! Thus
* disable this CPU feature, even if the CPU needs it.
*/
cur_cpu_spec->cpu_features &= ~CPU_FTR_NEED_COHERENT;
ISA_DMA_THRESHOLD = 0x00ffffff;
DMA_MODE_READ = 0x44;
DMA_MODE_WRITE = 0x48;
return 1;
}
return 0;
}
define_machine(amigaone) {
.name = "AmigaOne",
.probe = amigaone_probe,
.setup_arch = amigaone_setup_arch,
.show_cpuinfo = amigaone_show_cpuinfo,
.init_IRQ = amigaone_init_IRQ,
.restart = amigaone_restart,
.calibrate_decr = generic_calibrate_decr,
.progress = udbg_progress,
};
| gpl-2.0 |
bluecherrydvr/linux | drivers/staging/lustre/lnet/klnds/socklnd/socklnd_cb.c | 49 | 68027 | /*
* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
*
* Copyright (c) 2011, 2012, Intel Corporation.
*
* Author: Zach Brown <zab@zabbo.net>
* Author: Peter J. Braam <braam@clusterfs.com>
* Author: Phil Schwan <phil@clusterfs.com>
* Author: Eric Barton <eric@bartonsoftware.com>
*
* This file is part of Portals, http://www.sf.net/projects/sandiaportals/
*
* Portals is free software; you can redistribute it and/or
* modify it under the terms of version 2 of the GNU General Public
* License as published by the Free Software Foundation.
*
* Portals is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include "socklnd.h"
struct ksock_tx *
ksocknal_alloc_tx(int type, int size)
{
struct ksock_tx *tx = NULL;
if (type == KSOCK_MSG_NOOP) {
LASSERT(size == KSOCK_NOOP_TX_SIZE);
/* searching for a noop tx in free list */
spin_lock(&ksocknal_data.ksnd_tx_lock);
if (!list_empty(&ksocknal_data.ksnd_idle_noop_txs)) {
tx = list_entry(ksocknal_data.ksnd_idle_noop_txs. \
next, struct ksock_tx, tx_list);
LASSERT(tx->tx_desc_size == size);
list_del(&tx->tx_list);
}
spin_unlock(&ksocknal_data.ksnd_tx_lock);
}
if (!tx)
LIBCFS_ALLOC(tx, size);
if (!tx)
return NULL;
atomic_set(&tx->tx_refcount, 1);
tx->tx_zc_aborted = 0;
tx->tx_zc_capable = 0;
tx->tx_zc_checked = 0;
tx->tx_desc_size = size;
atomic_inc(&ksocknal_data.ksnd_nactive_txs);
return tx;
}
struct ksock_tx *
ksocknal_alloc_tx_noop(__u64 cookie, int nonblk)
{
struct ksock_tx *tx;
tx = ksocknal_alloc_tx(KSOCK_MSG_NOOP, KSOCK_NOOP_TX_SIZE);
if (!tx) {
CERROR("Can't allocate noop tx desc\n");
return NULL;
}
tx->tx_conn = NULL;
tx->tx_lnetmsg = NULL;
tx->tx_kiov = NULL;
tx->tx_nkiov = 0;
tx->tx_iov = tx->tx_frags.virt.iov;
tx->tx_niov = 1;
tx->tx_nonblk = nonblk;
socklnd_init_msg(&tx->tx_msg, KSOCK_MSG_NOOP);
tx->tx_msg.ksm_zc_cookies[1] = cookie;
return tx;
}
void
ksocknal_free_tx(struct ksock_tx *tx)
{
atomic_dec(&ksocknal_data.ksnd_nactive_txs);
if (!tx->tx_lnetmsg && tx->tx_desc_size == KSOCK_NOOP_TX_SIZE) {
/* it's a noop tx */
spin_lock(&ksocknal_data.ksnd_tx_lock);
list_add(&tx->tx_list, &ksocknal_data.ksnd_idle_noop_txs);
spin_unlock(&ksocknal_data.ksnd_tx_lock);
} else {
LIBCFS_FREE(tx, tx->tx_desc_size);
}
}
static int
ksocknal_send_iov(struct ksock_conn *conn, struct ksock_tx *tx)
{
struct kvec *iov = tx->tx_iov;
int nob;
int rc;
LASSERT(tx->tx_niov > 0);
/* Never touch tx->tx_iov inside ksocknal_lib_send_iov() */
rc = ksocknal_lib_send_iov(conn, tx);
if (rc <= 0) /* sent nothing? */
return rc;
nob = rc;
LASSERT(nob <= tx->tx_resid);
tx->tx_resid -= nob;
/* "consume" iov */
do {
LASSERT(tx->tx_niov > 0);
if (nob < (int)iov->iov_len) {
iov->iov_base = (void *)((char *)iov->iov_base + nob);
iov->iov_len -= nob;
return rc;
}
nob -= iov->iov_len;
tx->tx_iov = ++iov;
tx->tx_niov--;
} while (nob);
return rc;
}
static int
ksocknal_send_kiov(struct ksock_conn *conn, struct ksock_tx *tx)
{
lnet_kiov_t *kiov = tx->tx_kiov;
int nob;
int rc;
LASSERT(!tx->tx_niov);
LASSERT(tx->tx_nkiov > 0);
/* Never touch tx->tx_kiov inside ksocknal_lib_send_kiov() */
rc = ksocknal_lib_send_kiov(conn, tx);
if (rc <= 0) /* sent nothing? */
return rc;
nob = rc;
LASSERT(nob <= tx->tx_resid);
tx->tx_resid -= nob;
/* "consume" kiov */
do {
LASSERT(tx->tx_nkiov > 0);
if (nob < (int)kiov->kiov_len) {
kiov->kiov_offset += nob;
kiov->kiov_len -= nob;
return rc;
}
nob -= (int)kiov->kiov_len;
tx->tx_kiov = ++kiov;
tx->tx_nkiov--;
} while (nob);
return rc;
}
static int
ksocknal_transmit(struct ksock_conn *conn, struct ksock_tx *tx)
{
int rc;
int bufnob;
if (ksocknal_data.ksnd_stall_tx) {
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(cfs_time_seconds(ksocknal_data.ksnd_stall_tx));
}
LASSERT(tx->tx_resid);
rc = ksocknal_connsock_addref(conn);
if (rc) {
LASSERT(conn->ksnc_closing);
return -ESHUTDOWN;
}
do {
if (ksocknal_data.ksnd_enomem_tx > 0) {
/* testing... */
ksocknal_data.ksnd_enomem_tx--;
rc = -EAGAIN;
} else if (tx->tx_niov) {
rc = ksocknal_send_iov(conn, tx);
} else {
rc = ksocknal_send_kiov(conn, tx);
}
bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
if (rc > 0) /* sent something? */
conn->ksnc_tx_bufnob += rc; /* account it */
if (bufnob < conn->ksnc_tx_bufnob) {
/*
* allocated send buffer bytes < computed; infer
* something got ACKed
*/
conn->ksnc_tx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
conn->ksnc_peer->ksnp_last_alive = cfs_time_current();
conn->ksnc_tx_bufnob = bufnob;
mb();
}
if (rc <= 0) { /* Didn't write anything? */
if (!rc) /* some stacks return 0 instead of -EAGAIN */
rc = -EAGAIN;
/* Check if EAGAIN is due to memory pressure */
if (rc == -EAGAIN && ksocknal_lib_memory_pressure(conn))
rc = -ENOMEM;
break;
}
/* socket's wmem_queued now includes 'rc' bytes */
atomic_sub(rc, &conn->ksnc_tx_nob);
rc = 0;
} while (tx->tx_resid);
ksocknal_connsock_decref(conn);
return rc;
}
static int
ksocknal_recv_iov(struct ksock_conn *conn)
{
struct kvec *iov = conn->ksnc_rx_iov;
int nob;
int rc;
LASSERT(conn->ksnc_rx_niov > 0);
/*
* Never touch conn->ksnc_rx_iov or change connection
* status inside ksocknal_lib_recv_iov
*/
rc = ksocknal_lib_recv_iov(conn);
if (rc <= 0)
return rc;
/* received something... */
nob = rc;
conn->ksnc_peer->ksnp_last_alive = cfs_time_current();
conn->ksnc_rx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
mb(); /* order with setting rx_started */
conn->ksnc_rx_started = 1;
conn->ksnc_rx_nob_wanted -= nob;
conn->ksnc_rx_nob_left -= nob;
do {
LASSERT(conn->ksnc_rx_niov > 0);
if (nob < (int)iov->iov_len) {
iov->iov_len -= nob;
iov->iov_base += nob;
return -EAGAIN;
}
nob -= iov->iov_len;
conn->ksnc_rx_iov = ++iov;
conn->ksnc_rx_niov--;
} while (nob);
return rc;
}
static int
ksocknal_recv_kiov(struct ksock_conn *conn)
{
lnet_kiov_t *kiov = conn->ksnc_rx_kiov;
int nob;
int rc;
LASSERT(conn->ksnc_rx_nkiov > 0);
/*
* Never touch conn->ksnc_rx_kiov or change connection
* status inside ksocknal_lib_recv_iov
*/
rc = ksocknal_lib_recv_kiov(conn);
if (rc <= 0)
return rc;
/* received something... */
nob = rc;
conn->ksnc_peer->ksnp_last_alive = cfs_time_current();
conn->ksnc_rx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
mb(); /* order with setting rx_started */
conn->ksnc_rx_started = 1;
conn->ksnc_rx_nob_wanted -= nob;
conn->ksnc_rx_nob_left -= nob;
do {
LASSERT(conn->ksnc_rx_nkiov > 0);
if (nob < (int)kiov->kiov_len) {
kiov->kiov_offset += nob;
kiov->kiov_len -= nob;
return -EAGAIN;
}
nob -= kiov->kiov_len;
conn->ksnc_rx_kiov = ++kiov;
conn->ksnc_rx_nkiov--;
} while (nob);
return 1;
}
static int
ksocknal_receive(struct ksock_conn *conn)
{
/*
* Return 1 on success, 0 on EOF, < 0 on error.
* Caller checks ksnc_rx_nob_wanted to determine
* progress/completion.
*/
int rc;
if (ksocknal_data.ksnd_stall_rx) {
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(cfs_time_seconds(ksocknal_data.ksnd_stall_rx));
}
rc = ksocknal_connsock_addref(conn);
if (rc) {
LASSERT(conn->ksnc_closing);
return -ESHUTDOWN;
}
for (;;) {
if (conn->ksnc_rx_niov)
rc = ksocknal_recv_iov(conn);
else
rc = ksocknal_recv_kiov(conn);
if (rc <= 0) {
/* error/EOF or partial receive */
if (rc == -EAGAIN) {
rc = 1;
} else if (!rc && conn->ksnc_rx_started) {
/* EOF in the middle of a message */
rc = -EPROTO;
}
break;
}
/* Completed a fragment */
if (!conn->ksnc_rx_nob_wanted) {
rc = 1;
break;
}
}
ksocknal_connsock_decref(conn);
return rc;
}
void
ksocknal_tx_done(lnet_ni_t *ni, struct ksock_tx *tx)
{
lnet_msg_t *lnetmsg = tx->tx_lnetmsg;
int rc = (!tx->tx_resid && !tx->tx_zc_aborted) ? 0 : -EIO;
LASSERT(ni || tx->tx_conn);
if (tx->tx_conn)
ksocknal_conn_decref(tx->tx_conn);
if (!ni && tx->tx_conn)
ni = tx->tx_conn->ksnc_peer->ksnp_ni;
ksocknal_free_tx(tx);
if (lnetmsg) /* KSOCK_MSG_NOOP go without lnetmsg */
lnet_finalize(ni, lnetmsg, rc);
}
void
ksocknal_txlist_done(lnet_ni_t *ni, struct list_head *txlist, int error)
{
struct ksock_tx *tx;
while (!list_empty(txlist)) {
tx = list_entry(txlist->next, struct ksock_tx, tx_list);
if (error && tx->tx_lnetmsg) {
CNETERR("Deleting packet type %d len %d %s->%s\n",
le32_to_cpu(tx->tx_lnetmsg->msg_hdr.type),
le32_to_cpu(tx->tx_lnetmsg->msg_hdr.payload_length),
libcfs_nid2str(le64_to_cpu(tx->tx_lnetmsg->msg_hdr.src_nid)),
libcfs_nid2str(le64_to_cpu(tx->tx_lnetmsg->msg_hdr.dest_nid)));
} else if (error) {
CNETERR("Deleting noop packet\n");
}
list_del(&tx->tx_list);
LASSERT(atomic_read(&tx->tx_refcount) == 1);
ksocknal_tx_done(ni, tx);
}
}
static void
ksocknal_check_zc_req(struct ksock_tx *tx)
{
struct ksock_conn *conn = tx->tx_conn;
struct ksock_peer *peer = conn->ksnc_peer;
/*
* Set tx_msg.ksm_zc_cookies[0] to a unique non-zero cookie and add tx
* to ksnp_zc_req_list if some fragment of this message should be sent
* zero-copy. Our peer will send an ACK containing this cookie when
* she has received this message to tell us we can signal completion.
* tx_msg.ksm_zc_cookies[0] remains non-zero while tx is on
* ksnp_zc_req_list.
*/
LASSERT(tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
LASSERT(tx->tx_zc_capable);
tx->tx_zc_checked = 1;
if (conn->ksnc_proto == &ksocknal_protocol_v1x ||
!conn->ksnc_zc_capable)
return;
/*
* assign cookie and queue tx to pending list, it will be released when
* a matching ack is received. See ksocknal_handle_zcack()
*/
ksocknal_tx_addref(tx);
spin_lock(&peer->ksnp_lock);
/* ZC_REQ is going to be pinned to the peer */
tx->tx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
LASSERT(!tx->tx_msg.ksm_zc_cookies[0]);
tx->tx_msg.ksm_zc_cookies[0] = peer->ksnp_zc_next_cookie++;
if (!peer->ksnp_zc_next_cookie)
peer->ksnp_zc_next_cookie = SOCKNAL_KEEPALIVE_PING + 1;
list_add_tail(&tx->tx_zc_list, &peer->ksnp_zc_req_list);
spin_unlock(&peer->ksnp_lock);
}
static void
ksocknal_uncheck_zc_req(struct ksock_tx *tx)
{
struct ksock_peer *peer = tx->tx_conn->ksnc_peer;
LASSERT(tx->tx_msg.ksm_type != KSOCK_MSG_NOOP);
LASSERT(tx->tx_zc_capable);
tx->tx_zc_checked = 0;
spin_lock(&peer->ksnp_lock);
if (!tx->tx_msg.ksm_zc_cookies[0]) {
/* Not waiting for an ACK */
spin_unlock(&peer->ksnp_lock);
return;
}
tx->tx_msg.ksm_zc_cookies[0] = 0;
list_del(&tx->tx_zc_list);
spin_unlock(&peer->ksnp_lock);
ksocknal_tx_decref(tx);
}
static int
ksocknal_process_transmit(struct ksock_conn *conn, struct ksock_tx *tx)
{
int rc;
if (tx->tx_zc_capable && !tx->tx_zc_checked)
ksocknal_check_zc_req(tx);
rc = ksocknal_transmit(conn, tx);
CDEBUG(D_NET, "send(%d) %d\n", tx->tx_resid, rc);
if (!tx->tx_resid) {
/* Sent everything OK */
LASSERT(!rc);
return 0;
}
if (rc == -EAGAIN)
return rc;
if (rc == -ENOMEM) {
static int counter;
counter++; /* exponential backoff warnings */
if ((counter & (-counter)) == counter)
CWARN("%u ENOMEM tx %p\n", counter, conn);
/* Queue on ksnd_enomem_conns for retry after a timeout */
spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
/* enomem list takes over scheduler's ref... */
LASSERT(conn->ksnc_tx_scheduled);
list_add_tail(&conn->ksnc_tx_list,
&ksocknal_data.ksnd_enomem_conns);
if (!cfs_time_aftereq(cfs_time_add(cfs_time_current(),
SOCKNAL_ENOMEM_RETRY),
ksocknal_data.ksnd_reaper_waketime))
wake_up(&ksocknal_data.ksnd_reaper_waitq);
spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
return rc;
}
/* Actual error */
LASSERT(rc < 0);
if (!conn->ksnc_closing) {
switch (rc) {
case -ECONNRESET:
LCONSOLE_WARN("Host %pI4h reset our connection while we were sending data; it may have rebooted.\n",
&conn->ksnc_ipaddr);
break;
default:
LCONSOLE_WARN("There was an unexpected network error while writing to %pI4h: %d.\n",
&conn->ksnc_ipaddr, rc);
break;
}
CDEBUG(D_NET, "[%p] Error %d on write to %s ip %pI4h:%d\n",
conn, rc,
libcfs_id2str(conn->ksnc_peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
}
if (tx->tx_zc_checked)
ksocknal_uncheck_zc_req(tx);
/* it's not an error if conn is being closed */
ksocknal_close_conn_and_siblings(conn, (conn->ksnc_closing) ? 0 : rc);
return rc;
}
static void
ksocknal_launch_connection_locked(struct ksock_route *route)
{
/* called holding write lock on ksnd_global_lock */
LASSERT(!route->ksnr_scheduled);
LASSERT(!route->ksnr_connecting);
LASSERT(ksocknal_route_mask() & ~route->ksnr_connected);
route->ksnr_scheduled = 1; /* scheduling conn for connd */
ksocknal_route_addref(route); /* extra ref for connd */
spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
list_add_tail(&route->ksnr_connd_list,
&ksocknal_data.ksnd_connd_routes);
wake_up(&ksocknal_data.ksnd_connd_waitq);
spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
}
void
ksocknal_launch_all_connections_locked(struct ksock_peer *peer)
{
struct ksock_route *route;
/* called holding write lock on ksnd_global_lock */
for (;;) {
/* launch any/all connections that need it */
route = ksocknal_find_connectable_route_locked(peer);
if (!route)
return;
ksocknal_launch_connection_locked(route);
}
}
struct ksock_conn *
ksocknal_find_conn_locked(struct ksock_peer *peer, struct ksock_tx *tx, int nonblk)
{
struct list_head *tmp;
struct ksock_conn *conn;
struct ksock_conn *typed = NULL;
struct ksock_conn *fallback = NULL;
int tnob = 0;
int fnob = 0;
list_for_each(tmp, &peer->ksnp_conns) {
struct ksock_conn *c = list_entry(tmp, struct ksock_conn, ksnc_list);
int nob = atomic_read(&c->ksnc_tx_nob) +
c->ksnc_sock->sk->sk_wmem_queued;
int rc;
LASSERT(!c->ksnc_closing);
LASSERT(c->ksnc_proto &&
c->ksnc_proto->pro_match_tx);
rc = c->ksnc_proto->pro_match_tx(c, tx, nonblk);
switch (rc) {
default:
LBUG();
case SOCKNAL_MATCH_NO: /* protocol rejected the tx */
continue;
case SOCKNAL_MATCH_YES: /* typed connection */
if (!typed || tnob > nob ||
(tnob == nob && *ksocknal_tunables.ksnd_round_robin &&
cfs_time_after(typed->ksnc_tx_last_post, c->ksnc_tx_last_post))) {
typed = c;
tnob = nob;
}
break;
case SOCKNAL_MATCH_MAY: /* fallback connection */
if (!fallback || fnob > nob ||
(fnob == nob && *ksocknal_tunables.ksnd_round_robin &&
cfs_time_after(fallback->ksnc_tx_last_post, c->ksnc_tx_last_post))) {
fallback = c;
fnob = nob;
}
break;
}
}
/* prefer the typed selection */
conn = (typed) ? typed : fallback;
if (conn)
conn->ksnc_tx_last_post = cfs_time_current();
return conn;
}
void
ksocknal_tx_prep(struct ksock_conn *conn, struct ksock_tx *tx)
{
conn->ksnc_proto->pro_pack(tx);
atomic_add(tx->tx_nob, &conn->ksnc_tx_nob);
ksocknal_conn_addref(conn); /* +1 ref for tx */
tx->tx_conn = conn;
}
void
ksocknal_queue_tx_locked(struct ksock_tx *tx, struct ksock_conn *conn)
{
struct ksock_sched *sched = conn->ksnc_scheduler;
ksock_msg_t *msg = &tx->tx_msg;
struct ksock_tx *ztx = NULL;
int bufnob = 0;
/*
* called holding global lock (read or irq-write) and caller may
* not have dropped this lock between finding conn and calling me,
* so we don't need the {get,put}connsock dance to deref
* ksnc_sock...
*/
LASSERT(!conn->ksnc_closing);
CDEBUG(D_NET, "Sending to %s ip %pI4h:%d\n",
libcfs_id2str(conn->ksnc_peer->ksnp_id),
&conn->ksnc_ipaddr, conn->ksnc_port);
ksocknal_tx_prep(conn, tx);
/*
* Ensure the frags we've been given EXACTLY match the number of
* bytes we want to send. Many TCP/IP stacks disregard any total
* size parameters passed to them and just look at the frags.
*
* We always expect at least 1 mapped fragment containing the
* complete ksocknal message header.
*/
LASSERT(lnet_iov_nob(tx->tx_niov, tx->tx_iov) +
lnet_kiov_nob(tx->tx_nkiov, tx->tx_kiov) ==
(unsigned int)tx->tx_nob);
LASSERT(tx->tx_niov >= 1);
LASSERT(tx->tx_resid == tx->tx_nob);
CDEBUG(D_NET, "Packet %p type %d, nob %d niov %d nkiov %d\n",
tx, (tx->tx_lnetmsg) ? tx->tx_lnetmsg->msg_hdr.type :
KSOCK_MSG_NOOP,
tx->tx_nob, tx->tx_niov, tx->tx_nkiov);
/*
* FIXME: SOCK_WMEM_QUEUED and SOCK_ERROR could block in __DARWIN8__
* but they're used inside spinlocks a lot.
*/
bufnob = conn->ksnc_sock->sk->sk_wmem_queued;
spin_lock_bh(&sched->kss_lock);
if (list_empty(&conn->ksnc_tx_queue) && !bufnob) {
/* First packet starts the timeout */
conn->ksnc_tx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
if (conn->ksnc_tx_bufnob > 0) /* something got ACKed */
conn->ksnc_peer->ksnp_last_alive = cfs_time_current();
conn->ksnc_tx_bufnob = 0;
mb(); /* order with adding to tx_queue */
}
if (msg->ksm_type == KSOCK_MSG_NOOP) {
/*
* The packet is noop ZC ACK, try to piggyback the ack_cookie
* on a normal packet so I don't need to send it
*/
LASSERT(msg->ksm_zc_cookies[1]);
LASSERT(conn->ksnc_proto->pro_queue_tx_zcack);
if (conn->ksnc_proto->pro_queue_tx_zcack(conn, tx, 0))
ztx = tx; /* ZC ACK piggybacked on ztx release tx later */
} else {
/*
* It's a normal packet - can it piggback a noop zc-ack that
* has been queued already?
*/
LASSERT(!msg->ksm_zc_cookies[1]);
LASSERT(conn->ksnc_proto->pro_queue_tx_msg);
ztx = conn->ksnc_proto->pro_queue_tx_msg(conn, tx);
/* ztx will be released later */
}
if (ztx) {
atomic_sub(ztx->tx_nob, &conn->ksnc_tx_nob);
list_add_tail(&ztx->tx_list, &sched->kss_zombie_noop_txs);
}
if (conn->ksnc_tx_ready && /* able to send */
!conn->ksnc_tx_scheduled) { /* not scheduled to send */
/* +1 ref for scheduler */
ksocknal_conn_addref(conn);
list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
conn->ksnc_tx_scheduled = 1;
wake_up(&sched->kss_waitq);
}
spin_unlock_bh(&sched->kss_lock);
}
struct ksock_route *
ksocknal_find_connectable_route_locked(struct ksock_peer *peer)
{
unsigned long now = cfs_time_current();
struct list_head *tmp;
struct ksock_route *route;
list_for_each(tmp, &peer->ksnp_routes) {
route = list_entry(tmp, struct ksock_route, ksnr_list);
LASSERT(!route->ksnr_connecting || route->ksnr_scheduled);
if (route->ksnr_scheduled) /* connections being established */
continue;
/* all route types connected ? */
if (!(ksocknal_route_mask() & ~route->ksnr_connected))
continue;
if (!(!route->ksnr_retry_interval || /* first attempt */
cfs_time_aftereq(now, route->ksnr_timeout))) {
CDEBUG(D_NET,
"Too soon to retry route %pI4h (cnted %d, interval %ld, %ld secs later)\n",
&route->ksnr_ipaddr,
route->ksnr_connected,
route->ksnr_retry_interval,
cfs_duration_sec(route->ksnr_timeout - now));
continue;
}
return route;
}
return NULL;
}
struct ksock_route *
ksocknal_find_connecting_route_locked(struct ksock_peer *peer)
{
struct list_head *tmp;
struct ksock_route *route;
list_for_each(tmp, &peer->ksnp_routes) {
route = list_entry(tmp, struct ksock_route, ksnr_list);
LASSERT(!route->ksnr_connecting || route->ksnr_scheduled);
if (route->ksnr_scheduled)
return route;
}
return NULL;
}
int
ksocknal_launch_packet(lnet_ni_t *ni, struct ksock_tx *tx, lnet_process_id_t id)
{
struct ksock_peer *peer;
struct ksock_conn *conn;
rwlock_t *g_lock;
int retry;
int rc;
LASSERT(!tx->tx_conn);
g_lock = &ksocknal_data.ksnd_global_lock;
for (retry = 0;; retry = 1) {
read_lock(g_lock);
peer = ksocknal_find_peer_locked(ni, id);
if (peer) {
if (!ksocknal_find_connectable_route_locked(peer)) {
conn = ksocknal_find_conn_locked(peer, tx, tx->tx_nonblk);
if (conn) {
/*
* I've got no routes that need to be
* connecting and I do have an actual
* connection...
*/
ksocknal_queue_tx_locked(tx, conn);
read_unlock(g_lock);
return 0;
}
}
}
/* I'll need a write lock... */
read_unlock(g_lock);
write_lock_bh(g_lock);
peer = ksocknal_find_peer_locked(ni, id);
if (peer)
break;
write_unlock_bh(g_lock);
if (id.pid & LNET_PID_USERFLAG) {
CERROR("Refusing to create a connection to userspace process %s\n",
libcfs_id2str(id));
return -EHOSTUNREACH;
}
if (retry) {
CERROR("Can't find peer %s\n", libcfs_id2str(id));
return -EHOSTUNREACH;
}
rc = ksocknal_add_peer(ni, id,
LNET_NIDADDR(id.nid),
lnet_acceptor_port());
if (rc) {
CERROR("Can't add peer %s: %d\n",
libcfs_id2str(id), rc);
return rc;
}
}
ksocknal_launch_all_connections_locked(peer);
conn = ksocknal_find_conn_locked(peer, tx, tx->tx_nonblk);
if (conn) {
/* Connection exists; queue message on it */
ksocknal_queue_tx_locked(tx, conn);
write_unlock_bh(g_lock);
return 0;
}
if (peer->ksnp_accepting > 0 ||
ksocknal_find_connecting_route_locked(peer)) {
/* the message is going to be pinned to the peer */
tx->tx_deadline =
cfs_time_shift(*ksocknal_tunables.ksnd_timeout);
/* Queue the message until a connection is established */
list_add_tail(&tx->tx_list, &peer->ksnp_tx_queue);
write_unlock_bh(g_lock);
return 0;
}
write_unlock_bh(g_lock);
/* NB Routes may be ignored if connections to them failed recently */
CNETERR("No usable routes to %s\n", libcfs_id2str(id));
return -EHOSTUNREACH;
}
int
ksocknal_send(lnet_ni_t *ni, void *private, lnet_msg_t *lntmsg)
{
int mpflag = 1;
int type = lntmsg->msg_type;
lnet_process_id_t target = lntmsg->msg_target;
unsigned int payload_niov = lntmsg->msg_niov;
struct kvec *payload_iov = lntmsg->msg_iov;
lnet_kiov_t *payload_kiov = lntmsg->msg_kiov;
unsigned int payload_offset = lntmsg->msg_offset;
unsigned int payload_nob = lntmsg->msg_len;
struct ksock_tx *tx;
int desc_size;
int rc;
/*
* NB 'private' is different depending on what we're sending.
* Just ignore it...
*/
CDEBUG(D_NET, "sending %u bytes in %d frags to %s\n",
payload_nob, payload_niov, libcfs_id2str(target));
LASSERT(!payload_nob || payload_niov > 0);
LASSERT(payload_niov <= LNET_MAX_IOV);
/* payload is either all vaddrs or all pages */
LASSERT(!(payload_kiov && payload_iov));
LASSERT(!in_interrupt());
if (payload_iov)
desc_size = offsetof(struct ksock_tx,
tx_frags.virt.iov[1 + payload_niov]);
else
desc_size = offsetof(struct ksock_tx,
tx_frags.paged.kiov[payload_niov]);
if (lntmsg->msg_vmflush)
mpflag = cfs_memory_pressure_get_and_set();
tx = ksocknal_alloc_tx(KSOCK_MSG_LNET, desc_size);
if (!tx) {
CERROR("Can't allocate tx desc type %d size %d\n",
type, desc_size);
if (lntmsg->msg_vmflush)
cfs_memory_pressure_restore(mpflag);
return -ENOMEM;
}
tx->tx_conn = NULL; /* set when assigned a conn */
tx->tx_lnetmsg = lntmsg;
if (payload_iov) {
tx->tx_kiov = NULL;
tx->tx_nkiov = 0;
tx->tx_iov = tx->tx_frags.virt.iov;
tx->tx_niov = 1 +
lnet_extract_iov(payload_niov, &tx->tx_iov[1],
payload_niov, payload_iov,
payload_offset, payload_nob);
} else {
tx->tx_niov = 1;
tx->tx_iov = &tx->tx_frags.paged.iov;
tx->tx_kiov = tx->tx_frags.paged.kiov;
tx->tx_nkiov = lnet_extract_kiov(payload_niov, tx->tx_kiov,
payload_niov, payload_kiov,
payload_offset, payload_nob);
if (payload_nob >= *ksocknal_tunables.ksnd_zc_min_payload)
tx->tx_zc_capable = 1;
}
socklnd_init_msg(&tx->tx_msg, KSOCK_MSG_LNET);
/* The first fragment will be set later in pro_pack */
rc = ksocknal_launch_packet(ni, tx, target);
if (!mpflag)
cfs_memory_pressure_restore(mpflag);
if (!rc)
return 0;
ksocknal_free_tx(tx);
return -EIO;
}
int
ksocknal_thread_start(int (*fn)(void *arg), void *arg, char *name)
{
struct task_struct *task = kthread_run(fn, arg, "%s", name);
if (IS_ERR(task))
return PTR_ERR(task);
write_lock_bh(&ksocknal_data.ksnd_global_lock);
ksocknal_data.ksnd_nthreads++;
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
return 0;
}
void
ksocknal_thread_fini(void)
{
write_lock_bh(&ksocknal_data.ksnd_global_lock);
ksocknal_data.ksnd_nthreads--;
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
}
int
ksocknal_new_packet(struct ksock_conn *conn, int nob_to_skip)
{
static char ksocknal_slop_buffer[4096];
int nob;
unsigned int niov;
int skipped;
LASSERT(conn->ksnc_proto);
if (*ksocknal_tunables.ksnd_eager_ack & conn->ksnc_type) {
/* Remind the socket to ack eagerly... */
ksocknal_lib_eager_ack(conn);
}
if (!nob_to_skip) { /* right at next packet boundary now */
conn->ksnc_rx_started = 0;
mb(); /* racing with timeout thread */
switch (conn->ksnc_proto->pro_version) {
case KSOCK_PROTO_V2:
case KSOCK_PROTO_V3:
conn->ksnc_rx_state = SOCKNAL_RX_KSM_HEADER;
conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
conn->ksnc_rx_iov[0].iov_base = &conn->ksnc_msg;
conn->ksnc_rx_nob_wanted = offsetof(ksock_msg_t, ksm_u);
conn->ksnc_rx_nob_left = offsetof(ksock_msg_t, ksm_u);
conn->ksnc_rx_iov[0].iov_len = offsetof(ksock_msg_t, ksm_u);
break;
case KSOCK_PROTO_V1:
/* Receiving bare lnet_hdr_t */
conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
conn->ksnc_rx_nob_wanted = sizeof(lnet_hdr_t);
conn->ksnc_rx_nob_left = sizeof(lnet_hdr_t);
conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
conn->ksnc_rx_iov[0].iov_base = &conn->ksnc_msg.ksm_u.lnetmsg;
conn->ksnc_rx_iov[0].iov_len = sizeof(lnet_hdr_t);
break;
default:
LBUG();
}
conn->ksnc_rx_niov = 1;
conn->ksnc_rx_kiov = NULL;
conn->ksnc_rx_nkiov = 0;
conn->ksnc_rx_csum = ~0;
return 1;
}
/*
* Set up to skip as much as possible now. If there's more left
* (ran out of iov entries) we'll get called again
*/
conn->ksnc_rx_state = SOCKNAL_RX_SLOP;
conn->ksnc_rx_nob_left = nob_to_skip;
conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
skipped = 0;
niov = 0;
do {
nob = min_t(int, nob_to_skip, sizeof(ksocknal_slop_buffer));
conn->ksnc_rx_iov[niov].iov_base = ksocknal_slop_buffer;
conn->ksnc_rx_iov[niov].iov_len = nob;
niov++;
skipped += nob;
nob_to_skip -= nob;
} while (nob_to_skip && /* mustn't overflow conn's rx iov */
niov < sizeof(conn->ksnc_rx_iov_space) / sizeof(struct iovec));
conn->ksnc_rx_niov = niov;
conn->ksnc_rx_kiov = NULL;
conn->ksnc_rx_nkiov = 0;
conn->ksnc_rx_nob_wanted = skipped;
return 0;
}
static int
ksocknal_process_receive(struct ksock_conn *conn)
{
lnet_hdr_t *lhdr;
lnet_process_id_t *id;
int rc;
LASSERT(atomic_read(&conn->ksnc_conn_refcount) > 0);
/* NB: sched lock NOT held */
/* SOCKNAL_RX_LNET_HEADER is here for backward compatibility */
LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_KSM_HEADER ||
conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD ||
conn->ksnc_rx_state == SOCKNAL_RX_LNET_HEADER ||
conn->ksnc_rx_state == SOCKNAL_RX_SLOP);
again:
if (conn->ksnc_rx_nob_wanted) {
rc = ksocknal_receive(conn);
if (rc <= 0) {
LASSERT(rc != -EAGAIN);
if (!rc)
CDEBUG(D_NET, "[%p] EOF from %s ip %pI4h:%d\n",
conn,
libcfs_id2str(conn->ksnc_peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
else if (!conn->ksnc_closing)
CERROR("[%p] Error %d on read from %s ip %pI4h:%d\n",
conn, rc,
libcfs_id2str(conn->ksnc_peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
/* it's not an error if conn is being closed */
ksocknal_close_conn_and_siblings(conn,
(conn->ksnc_closing) ? 0 : rc);
return (!rc ? -ESHUTDOWN : rc);
}
if (conn->ksnc_rx_nob_wanted) {
/* short read */
return -EAGAIN;
}
}
switch (conn->ksnc_rx_state) {
case SOCKNAL_RX_KSM_HEADER:
if (conn->ksnc_flip) {
__swab32s(&conn->ksnc_msg.ksm_type);
__swab32s(&conn->ksnc_msg.ksm_csum);
__swab64s(&conn->ksnc_msg.ksm_zc_cookies[0]);
__swab64s(&conn->ksnc_msg.ksm_zc_cookies[1]);
}
if (conn->ksnc_msg.ksm_type != KSOCK_MSG_NOOP &&
conn->ksnc_msg.ksm_type != KSOCK_MSG_LNET) {
CERROR("%s: Unknown message type: %x\n",
libcfs_id2str(conn->ksnc_peer->ksnp_id),
conn->ksnc_msg.ksm_type);
ksocknal_new_packet(conn, 0);
ksocknal_close_conn_and_siblings(conn, -EPROTO);
return -EPROTO;
}
if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP &&
conn->ksnc_msg.ksm_csum && /* has checksum */
conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
/* NOOP Checksum error */
CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
libcfs_id2str(conn->ksnc_peer->ksnp_id),
conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
ksocknal_new_packet(conn, 0);
ksocknal_close_conn_and_siblings(conn, -EPROTO);
return -EIO;
}
if (conn->ksnc_msg.ksm_zc_cookies[1]) {
__u64 cookie = 0;
LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP)
cookie = conn->ksnc_msg.ksm_zc_cookies[0];
rc = conn->ksnc_proto->pro_handle_zcack(conn, cookie,
conn->ksnc_msg.ksm_zc_cookies[1]);
if (rc) {
CERROR("%s: Unknown ZC-ACK cookie: %llu, %llu\n",
libcfs_id2str(conn->ksnc_peer->ksnp_id),
cookie, conn->ksnc_msg.ksm_zc_cookies[1]);
ksocknal_new_packet(conn, 0);
ksocknal_close_conn_and_siblings(conn, -EPROTO);
return rc;
}
}
if (conn->ksnc_msg.ksm_type == KSOCK_MSG_NOOP) {
ksocknal_new_packet(conn, 0);
return 0; /* NOOP is done and just return */
}
conn->ksnc_rx_state = SOCKNAL_RX_LNET_HEADER;
conn->ksnc_rx_nob_wanted = sizeof(ksock_lnet_msg_t);
conn->ksnc_rx_nob_left = sizeof(ksock_lnet_msg_t);
conn->ksnc_rx_iov = (struct kvec *)&conn->ksnc_rx_iov_space;
conn->ksnc_rx_iov[0].iov_base = &conn->ksnc_msg.ksm_u.lnetmsg;
conn->ksnc_rx_iov[0].iov_len = sizeof(ksock_lnet_msg_t);
conn->ksnc_rx_niov = 1;
conn->ksnc_rx_kiov = NULL;
conn->ksnc_rx_nkiov = 0;
goto again; /* read lnet header now */
case SOCKNAL_RX_LNET_HEADER:
/* unpack message header */
conn->ksnc_proto->pro_unpack(&conn->ksnc_msg);
if (conn->ksnc_peer->ksnp_id.pid & LNET_PID_USERFLAG) {
/* Userspace peer */
lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
id = &conn->ksnc_peer->ksnp_id;
/* Substitute process ID assigned at connection time */
lhdr->src_pid = cpu_to_le32(id->pid);
lhdr->src_nid = cpu_to_le64(id->nid);
}
conn->ksnc_rx_state = SOCKNAL_RX_PARSE;
ksocknal_conn_addref(conn); /* ++ref while parsing */
rc = lnet_parse(conn->ksnc_peer->ksnp_ni,
&conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr,
conn->ksnc_peer->ksnp_id.nid, conn, 0);
if (rc < 0) {
/* I just received garbage: give up on this conn */
ksocknal_new_packet(conn, 0);
ksocknal_close_conn_and_siblings(conn, rc);
ksocknal_conn_decref(conn);
return -EPROTO;
}
/* I'm racing with ksocknal_recv() */
LASSERT(conn->ksnc_rx_state == SOCKNAL_RX_PARSE ||
conn->ksnc_rx_state == SOCKNAL_RX_LNET_PAYLOAD);
if (conn->ksnc_rx_state != SOCKNAL_RX_LNET_PAYLOAD)
return 0;
/* ksocknal_recv() got called */
goto again;
case SOCKNAL_RX_LNET_PAYLOAD:
/* payload all received */
rc = 0;
if (!conn->ksnc_rx_nob_left && /* not truncating */
conn->ksnc_msg.ksm_csum && /* has checksum */
conn->ksnc_msg.ksm_csum != conn->ksnc_rx_csum) {
CERROR("%s: Checksum error, wire:0x%08X data:0x%08X\n",
libcfs_id2str(conn->ksnc_peer->ksnp_id),
conn->ksnc_msg.ksm_csum, conn->ksnc_rx_csum);
rc = -EIO;
}
if (!rc && conn->ksnc_msg.ksm_zc_cookies[0]) {
LASSERT(conn->ksnc_proto != &ksocknal_protocol_v1x);
lhdr = &conn->ksnc_msg.ksm_u.lnetmsg.ksnm_hdr;
id = &conn->ksnc_peer->ksnp_id;
rc = conn->ksnc_proto->pro_handle_zcreq(conn,
conn->ksnc_msg.ksm_zc_cookies[0],
*ksocknal_tunables.ksnd_nonblk_zcack ||
le64_to_cpu(lhdr->src_nid) != id->nid);
}
lnet_finalize(conn->ksnc_peer->ksnp_ni, conn->ksnc_cookie, rc);
if (rc) {
ksocknal_new_packet(conn, 0);
ksocknal_close_conn_and_siblings(conn, rc);
return -EPROTO;
}
/* Fall through */
case SOCKNAL_RX_SLOP:
/* starting new packet? */
if (ksocknal_new_packet(conn, conn->ksnc_rx_nob_left))
return 0; /* come back later */
goto again; /* try to finish reading slop now */
default:
break;
}
/* Not Reached */
LBUG();
return -EINVAL; /* keep gcc happy */
}
int
ksocknal_recv(lnet_ni_t *ni, void *private, lnet_msg_t *msg, int delayed,
unsigned int niov, struct kvec *iov, lnet_kiov_t *kiov,
unsigned int offset, unsigned int mlen, unsigned int rlen)
{
struct ksock_conn *conn = private;
struct ksock_sched *sched = conn->ksnc_scheduler;
LASSERT(mlen <= rlen);
LASSERT(niov <= LNET_MAX_IOV);
conn->ksnc_cookie = msg;
conn->ksnc_rx_nob_wanted = mlen;
conn->ksnc_rx_nob_left = rlen;
if (!mlen || iov) {
conn->ksnc_rx_nkiov = 0;
conn->ksnc_rx_kiov = NULL;
conn->ksnc_rx_iov = conn->ksnc_rx_iov_space.iov;
conn->ksnc_rx_niov =
lnet_extract_iov(LNET_MAX_IOV, conn->ksnc_rx_iov,
niov, iov, offset, mlen);
} else {
conn->ksnc_rx_niov = 0;
conn->ksnc_rx_iov = NULL;
conn->ksnc_rx_kiov = conn->ksnc_rx_iov_space.kiov;
conn->ksnc_rx_nkiov =
lnet_extract_kiov(LNET_MAX_IOV, conn->ksnc_rx_kiov,
niov, kiov, offset, mlen);
}
LASSERT(mlen ==
lnet_iov_nob(conn->ksnc_rx_niov, conn->ksnc_rx_iov) +
lnet_kiov_nob(conn->ksnc_rx_nkiov, conn->ksnc_rx_kiov));
LASSERT(conn->ksnc_rx_scheduled);
spin_lock_bh(&sched->kss_lock);
switch (conn->ksnc_rx_state) {
case SOCKNAL_RX_PARSE_WAIT:
list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
wake_up(&sched->kss_waitq);
LASSERT(conn->ksnc_rx_ready);
break;
case SOCKNAL_RX_PARSE:
/* scheduler hasn't noticed I'm parsing yet */
break;
}
conn->ksnc_rx_state = SOCKNAL_RX_LNET_PAYLOAD;
spin_unlock_bh(&sched->kss_lock);
ksocknal_conn_decref(conn);
return 0;
}
static inline int
ksocknal_sched_cansleep(struct ksock_sched *sched)
{
int rc;
spin_lock_bh(&sched->kss_lock);
rc = !ksocknal_data.ksnd_shuttingdown &&
list_empty(&sched->kss_rx_conns) &&
list_empty(&sched->kss_tx_conns);
spin_unlock_bh(&sched->kss_lock);
return rc;
}
int ksocknal_scheduler(void *arg)
{
struct ksock_sched_info *info;
struct ksock_sched *sched;
struct ksock_conn *conn;
struct ksock_tx *tx;
int rc;
int nloops = 0;
long id = (long)arg;
info = ksocknal_data.ksnd_sched_info[KSOCK_THREAD_CPT(id)];
sched = &info->ksi_scheds[KSOCK_THREAD_SID(id)];
cfs_block_allsigs();
rc = cfs_cpt_bind(lnet_cpt_table(), info->ksi_cpt);
if (rc) {
CERROR("Can't set CPT affinity to %d: %d\n",
info->ksi_cpt, rc);
}
spin_lock_bh(&sched->kss_lock);
while (!ksocknal_data.ksnd_shuttingdown) {
int did_something = 0;
/* Ensure I progress everything semi-fairly */
if (!list_empty(&sched->kss_rx_conns)) {
conn = list_entry(sched->kss_rx_conns.next,
struct ksock_conn, ksnc_rx_list);
list_del(&conn->ksnc_rx_list);
LASSERT(conn->ksnc_rx_scheduled);
LASSERT(conn->ksnc_rx_ready);
/*
* clear rx_ready in case receive isn't complete.
* Do it BEFORE we call process_recv, since
* data_ready can set it any time after we release
* kss_lock.
*/
conn->ksnc_rx_ready = 0;
spin_unlock_bh(&sched->kss_lock);
rc = ksocknal_process_receive(conn);
spin_lock_bh(&sched->kss_lock);
/* I'm the only one that can clear this flag */
LASSERT(conn->ksnc_rx_scheduled);
/* Did process_receive get everything it wanted? */
if (!rc)
conn->ksnc_rx_ready = 1;
if (conn->ksnc_rx_state == SOCKNAL_RX_PARSE) {
/*
* Conn blocked waiting for ksocknal_recv()
* I change its state (under lock) to signal
* it can be rescheduled
*/
conn->ksnc_rx_state = SOCKNAL_RX_PARSE_WAIT;
} else if (conn->ksnc_rx_ready) {
/* reschedule for rx */
list_add_tail(&conn->ksnc_rx_list,
&sched->kss_rx_conns);
} else {
conn->ksnc_rx_scheduled = 0;
/* drop my ref */
ksocknal_conn_decref(conn);
}
did_something = 1;
}
if (!list_empty(&sched->kss_tx_conns)) {
LIST_HEAD(zlist);
if (!list_empty(&sched->kss_zombie_noop_txs)) {
list_add(&zlist, &sched->kss_zombie_noop_txs);
list_del_init(&sched->kss_zombie_noop_txs);
}
conn = list_entry(sched->kss_tx_conns.next,
struct ksock_conn, ksnc_tx_list);
list_del(&conn->ksnc_tx_list);
LASSERT(conn->ksnc_tx_scheduled);
LASSERT(conn->ksnc_tx_ready);
LASSERT(!list_empty(&conn->ksnc_tx_queue));
tx = list_entry(conn->ksnc_tx_queue.next,
struct ksock_tx, tx_list);
if (conn->ksnc_tx_carrier == tx)
ksocknal_next_tx_carrier(conn);
/* dequeue now so empty list => more to send */
list_del(&tx->tx_list);
/*
* Clear tx_ready in case send isn't complete. Do
* it BEFORE we call process_transmit, since
* write_space can set it any time after we release
* kss_lock.
*/
conn->ksnc_tx_ready = 0;
spin_unlock_bh(&sched->kss_lock);
if (!list_empty(&zlist)) {
/*
* free zombie noop txs, it's fast because
* noop txs are just put in freelist
*/
ksocknal_txlist_done(NULL, &zlist, 0);
}
rc = ksocknal_process_transmit(conn, tx);
if (rc == -ENOMEM || rc == -EAGAIN) {
/* Incomplete send: replace tx on HEAD of tx_queue */
spin_lock_bh(&sched->kss_lock);
list_add(&tx->tx_list, &conn->ksnc_tx_queue);
} else {
/* Complete send; tx -ref */
ksocknal_tx_decref(tx);
spin_lock_bh(&sched->kss_lock);
/* assume space for more */
conn->ksnc_tx_ready = 1;
}
if (rc == -ENOMEM) {
/*
* Do nothing; after a short timeout, this
* conn will be reposted on kss_tx_conns.
*/
} else if (conn->ksnc_tx_ready &&
!list_empty(&conn->ksnc_tx_queue)) {
/* reschedule for tx */
list_add_tail(&conn->ksnc_tx_list,
&sched->kss_tx_conns);
} else {
conn->ksnc_tx_scheduled = 0;
/* drop my ref */
ksocknal_conn_decref(conn);
}
did_something = 1;
}
if (!did_something || /* nothing to do */
++nloops == SOCKNAL_RESCHED) { /* hogging CPU? */
spin_unlock_bh(&sched->kss_lock);
nloops = 0;
if (!did_something) { /* wait for something to do */
rc = wait_event_interruptible_exclusive(
sched->kss_waitq,
!ksocknal_sched_cansleep(sched));
LASSERT(!rc);
} else {
cond_resched();
}
spin_lock_bh(&sched->kss_lock);
}
}
spin_unlock_bh(&sched->kss_lock);
ksocknal_thread_fini();
return 0;
}
/*
* Add connection to kss_rx_conns of scheduler
* and wakeup the scheduler.
*/
void ksocknal_read_callback(struct ksock_conn *conn)
{
struct ksock_sched *sched;
sched = conn->ksnc_scheduler;
spin_lock_bh(&sched->kss_lock);
conn->ksnc_rx_ready = 1;
if (!conn->ksnc_rx_scheduled) { /* not being progressed */
list_add_tail(&conn->ksnc_rx_list, &sched->kss_rx_conns);
conn->ksnc_rx_scheduled = 1;
/* extra ref for scheduler */
ksocknal_conn_addref(conn);
wake_up(&sched->kss_waitq);
}
spin_unlock_bh(&sched->kss_lock);
}
/*
* Add connection to kss_tx_conns of scheduler
* and wakeup the scheduler.
*/
void ksocknal_write_callback(struct ksock_conn *conn)
{
struct ksock_sched *sched;
sched = conn->ksnc_scheduler;
spin_lock_bh(&sched->kss_lock);
conn->ksnc_tx_ready = 1;
if (!conn->ksnc_tx_scheduled && /* not being progressed */
!list_empty(&conn->ksnc_tx_queue)) { /* packets to send */
list_add_tail(&conn->ksnc_tx_list, &sched->kss_tx_conns);
conn->ksnc_tx_scheduled = 1;
/* extra ref for scheduler */
ksocknal_conn_addref(conn);
wake_up(&sched->kss_waitq);
}
spin_unlock_bh(&sched->kss_lock);
}
static struct ksock_proto *
ksocknal_parse_proto_version(ksock_hello_msg_t *hello)
{
__u32 version = 0;
if (hello->kshm_magic == LNET_PROTO_MAGIC)
version = hello->kshm_version;
else if (hello->kshm_magic == __swab32(LNET_PROTO_MAGIC))
version = __swab32(hello->kshm_version);
if (version) {
#if SOCKNAL_VERSION_DEBUG
if (*ksocknal_tunables.ksnd_protocol == 1)
return NULL;
if (*ksocknal_tunables.ksnd_protocol == 2 &&
version == KSOCK_PROTO_V3)
return NULL;
#endif
if (version == KSOCK_PROTO_V2)
return &ksocknal_protocol_v2x;
if (version == KSOCK_PROTO_V3)
return &ksocknal_protocol_v3x;
return NULL;
}
if (hello->kshm_magic == le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
lnet_magicversion_t *hmv = (lnet_magicversion_t *)hello;
CLASSERT(sizeof(lnet_magicversion_t) ==
offsetof(ksock_hello_msg_t, kshm_src_nid));
if (hmv->version_major == cpu_to_le16(KSOCK_PROTO_V1_MAJOR) &&
hmv->version_minor == cpu_to_le16(KSOCK_PROTO_V1_MINOR))
return &ksocknal_protocol_v1x;
}
return NULL;
}
int
ksocknal_send_hello(lnet_ni_t *ni, struct ksock_conn *conn,
lnet_nid_t peer_nid, ksock_hello_msg_t *hello)
{
/* CAVEAT EMPTOR: this byte flips 'ipaddrs' */
struct ksock_net *net = (struct ksock_net *)ni->ni_data;
LASSERT(hello->kshm_nips <= LNET_MAX_INTERFACES);
/* rely on caller to hold a ref on socket so it wouldn't disappear */
LASSERT(conn->ksnc_proto);
hello->kshm_src_nid = ni->ni_nid;
hello->kshm_dst_nid = peer_nid;
hello->kshm_src_pid = the_lnet.ln_pid;
hello->kshm_src_incarnation = net->ksnn_incarnation;
hello->kshm_ctype = conn->ksnc_type;
return conn->ksnc_proto->pro_send_hello(conn, hello);
}
static int
ksocknal_invert_type(int type)
{
switch (type) {
case SOCKLND_CONN_ANY:
case SOCKLND_CONN_CONTROL:
return type;
case SOCKLND_CONN_BULK_IN:
return SOCKLND_CONN_BULK_OUT;
case SOCKLND_CONN_BULK_OUT:
return SOCKLND_CONN_BULK_IN;
default:
return SOCKLND_CONN_NONE;
}
}
int
ksocknal_recv_hello(lnet_ni_t *ni, struct ksock_conn *conn,
ksock_hello_msg_t *hello, lnet_process_id_t *peerid,
__u64 *incarnation)
{
/* Return < 0 fatal error
* 0 success
* EALREADY lost connection race
* EPROTO protocol version mismatch
*/
struct socket *sock = conn->ksnc_sock;
int active = !!conn->ksnc_proto;
int timeout;
int proto_match;
int rc;
struct ksock_proto *proto;
lnet_process_id_t recv_id;
/* socket type set on active connections - not set on passive */
LASSERT(!active == !(conn->ksnc_type != SOCKLND_CONN_NONE));
timeout = active ? *ksocknal_tunables.ksnd_timeout :
lnet_acceptor_timeout();
rc = lnet_sock_read(sock, &hello->kshm_magic, sizeof(hello->kshm_magic), timeout);
if (rc) {
CERROR("Error %d reading HELLO from %pI4h\n",
rc, &conn->ksnc_ipaddr);
LASSERT(rc < 0);
return rc;
}
if (hello->kshm_magic != LNET_PROTO_MAGIC &&
hello->kshm_magic != __swab32(LNET_PROTO_MAGIC) &&
hello->kshm_magic != le32_to_cpu(LNET_PROTO_TCP_MAGIC)) {
/* Unexpected magic! */
CERROR("Bad magic(1) %#08x (%#08x expected) from %pI4h\n",
__cpu_to_le32(hello->kshm_magic),
LNET_PROTO_TCP_MAGIC,
&conn->ksnc_ipaddr);
return -EPROTO;
}
rc = lnet_sock_read(sock, &hello->kshm_version,
sizeof(hello->kshm_version), timeout);
if (rc) {
CERROR("Error %d reading HELLO from %pI4h\n",
rc, &conn->ksnc_ipaddr);
LASSERT(rc < 0);
return rc;
}
proto = ksocknal_parse_proto_version(hello);
if (!proto) {
if (!active) {
/* unknown protocol from peer, tell peer my protocol */
conn->ksnc_proto = &ksocknal_protocol_v3x;
#if SOCKNAL_VERSION_DEBUG
if (*ksocknal_tunables.ksnd_protocol == 2)
conn->ksnc_proto = &ksocknal_protocol_v2x;
else if (*ksocknal_tunables.ksnd_protocol == 1)
conn->ksnc_proto = &ksocknal_protocol_v1x;
#endif
hello->kshm_nips = 0;
ksocknal_send_hello(ni, conn, ni->ni_nid, hello);
}
CERROR("Unknown protocol version (%d.x expected) from %pI4h\n",
conn->ksnc_proto->pro_version,
&conn->ksnc_ipaddr);
return -EPROTO;
}
proto_match = (conn->ksnc_proto == proto);
conn->ksnc_proto = proto;
/* receive the rest of hello message anyway */
rc = conn->ksnc_proto->pro_recv_hello(conn, hello, timeout);
if (rc) {
CERROR("Error %d reading or checking hello from from %pI4h\n",
rc, &conn->ksnc_ipaddr);
LASSERT(rc < 0);
return rc;
}
*incarnation = hello->kshm_src_incarnation;
if (hello->kshm_src_nid == LNET_NID_ANY) {
CERROR("Expecting a HELLO hdr with a NID, but got LNET_NID_ANY from %pI4h\n",
&conn->ksnc_ipaddr);
return -EPROTO;
}
if (!active &&
conn->ksnc_port > LNET_ACCEPTOR_MAX_RESERVED_PORT) {
/* Userspace NAL assigns peer process ID from socket */
recv_id.pid = conn->ksnc_port | LNET_PID_USERFLAG;
recv_id.nid = LNET_MKNID(LNET_NIDNET(ni->ni_nid), conn->ksnc_ipaddr);
} else {
recv_id.nid = hello->kshm_src_nid;
recv_id.pid = hello->kshm_src_pid;
}
if (!active) {
*peerid = recv_id;
/* peer determines type */
conn->ksnc_type = ksocknal_invert_type(hello->kshm_ctype);
if (conn->ksnc_type == SOCKLND_CONN_NONE) {
CERROR("Unexpected type %d from %s ip %pI4h\n",
hello->kshm_ctype, libcfs_id2str(*peerid),
&conn->ksnc_ipaddr);
return -EPROTO;
}
return 0;
}
if (peerid->pid != recv_id.pid ||
peerid->nid != recv_id.nid) {
LCONSOLE_ERROR_MSG(0x130, "Connected successfully to %s on host %pI4h, but they claimed they were %s; please check your Lustre configuration.\n",
libcfs_id2str(*peerid),
&conn->ksnc_ipaddr,
libcfs_id2str(recv_id));
return -EPROTO;
}
if (hello->kshm_ctype == SOCKLND_CONN_NONE) {
/* Possible protocol mismatch or I lost the connection race */
return proto_match ? EALREADY : EPROTO;
}
if (ksocknal_invert_type(hello->kshm_ctype) != conn->ksnc_type) {
CERROR("Mismatched types: me %d, %s ip %pI4h %d\n",
conn->ksnc_type, libcfs_id2str(*peerid),
&conn->ksnc_ipaddr, hello->kshm_ctype);
return -EPROTO;
}
return 0;
}
static int
ksocknal_connect(struct ksock_route *route)
{
LIST_HEAD(zombies);
struct ksock_peer *peer = route->ksnr_peer;
int type;
int wanted;
struct socket *sock;
unsigned long deadline;
int retry_later = 0;
int rc = 0;
deadline = cfs_time_add(cfs_time_current(),
cfs_time_seconds(*ksocknal_tunables.ksnd_timeout));
write_lock_bh(&ksocknal_data.ksnd_global_lock);
LASSERT(route->ksnr_scheduled);
LASSERT(!route->ksnr_connecting);
route->ksnr_connecting = 1;
for (;;) {
wanted = ksocknal_route_mask() & ~route->ksnr_connected;
/*
* stop connecting if peer/route got closed under me, or
* route got connected while queued
*/
if (peer->ksnp_closing || route->ksnr_deleted ||
!wanted) {
retry_later = 0;
break;
}
/* reschedule if peer is connecting to me */
if (peer->ksnp_accepting > 0) {
CDEBUG(D_NET,
"peer %s(%d) already connecting to me, retry later.\n",
libcfs_nid2str(peer->ksnp_id.nid), peer->ksnp_accepting);
retry_later = 1;
}
if (retry_later) /* needs reschedule */
break;
if (wanted & (1 << SOCKLND_CONN_ANY)) {
type = SOCKLND_CONN_ANY;
} else if (wanted & (1 << SOCKLND_CONN_CONTROL)) {
type = SOCKLND_CONN_CONTROL;
} else if (wanted & (1 << SOCKLND_CONN_BULK_IN)) {
type = SOCKLND_CONN_BULK_IN;
} else {
LASSERT(wanted & (1 << SOCKLND_CONN_BULK_OUT));
type = SOCKLND_CONN_BULK_OUT;
}
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
if (cfs_time_aftereq(cfs_time_current(), deadline)) {
rc = -ETIMEDOUT;
lnet_connect_console_error(rc, peer->ksnp_id.nid,
route->ksnr_ipaddr,
route->ksnr_port);
goto failed;
}
rc = lnet_connect(&sock, peer->ksnp_id.nid,
route->ksnr_myipaddr,
route->ksnr_ipaddr, route->ksnr_port);
if (rc)
goto failed;
rc = ksocknal_create_conn(peer->ksnp_ni, route, sock, type);
if (rc < 0) {
lnet_connect_console_error(rc, peer->ksnp_id.nid,
route->ksnr_ipaddr,
route->ksnr_port);
goto failed;
}
/*
* A +ve RC means I have to retry because I lost the connection
* race or I have to renegotiate protocol version
*/
retry_later = (rc);
if (retry_later)
CDEBUG(D_NET, "peer %s: conn race, retry later.\n",
libcfs_nid2str(peer->ksnp_id.nid));
write_lock_bh(&ksocknal_data.ksnd_global_lock);
}
route->ksnr_scheduled = 0;
route->ksnr_connecting = 0;
if (retry_later) {
/*
* re-queue for attention; this frees me up to handle
* the peer's incoming connection request
*/
if (rc == EALREADY ||
(!rc && peer->ksnp_accepting > 0)) {
/*
* We want to introduce a delay before next
* attempt to connect if we lost conn race,
* but the race is resolved quickly usually,
* so min_reconnectms should be good heuristic
*/
route->ksnr_retry_interval =
cfs_time_seconds(*ksocknal_tunables.ksnd_min_reconnectms) / 1000;
route->ksnr_timeout = cfs_time_add(cfs_time_current(),
route->ksnr_retry_interval);
}
ksocknal_launch_connection_locked(route);
}
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
return retry_later;
failed:
write_lock_bh(&ksocknal_data.ksnd_global_lock);
route->ksnr_scheduled = 0;
route->ksnr_connecting = 0;
/* This is a retry rather than a new connection */
route->ksnr_retry_interval *= 2;
route->ksnr_retry_interval =
max(route->ksnr_retry_interval,
cfs_time_seconds(*ksocknal_tunables.ksnd_min_reconnectms) / 1000);
route->ksnr_retry_interval =
min(route->ksnr_retry_interval,
cfs_time_seconds(*ksocknal_tunables.ksnd_max_reconnectms) / 1000);
LASSERT(route->ksnr_retry_interval);
route->ksnr_timeout = cfs_time_add(cfs_time_current(),
route->ksnr_retry_interval);
if (!list_empty(&peer->ksnp_tx_queue) &&
!peer->ksnp_accepting &&
!ksocknal_find_connecting_route_locked(peer)) {
struct ksock_conn *conn;
/*
* ksnp_tx_queue is queued on a conn on successful
* connection for V1.x and V2.x
*/
if (!list_empty(&peer->ksnp_conns)) {
conn = list_entry(peer->ksnp_conns.next,
struct ksock_conn, ksnc_list);
LASSERT(conn->ksnc_proto == &ksocknal_protocol_v3x);
}
/*
* take all the blocked packets while I've got the lock and
* complete below...
*/
list_splice_init(&peer->ksnp_tx_queue, &zombies);
}
#if 0 /* irrelevant with only eager routes */
if (!route->ksnr_deleted) {
/* make this route least-favourite for re-selection */
list_del(&route->ksnr_list);
list_add_tail(&route->ksnr_list, &peer->ksnp_routes);
}
#endif
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
ksocknal_peer_failed(peer);
ksocknal_txlist_done(peer->ksnp_ni, &zombies, 1);
return 0;
}
/*
* check whether we need to create more connds.
* It will try to create new thread if it's necessary, @timeout can
* be updated if failed to create, so caller wouldn't keep try while
* running out of resource.
*/
static int
ksocknal_connd_check_start(time64_t sec, long *timeout)
{
char name[16];
int rc;
int total = ksocknal_data.ksnd_connd_starting +
ksocknal_data.ksnd_connd_running;
if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
/* still in initializing */
return 0;
}
if (total >= *ksocknal_tunables.ksnd_nconnds_max ||
total > ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV) {
/*
* can't create more connd, or still have enough
* threads to handle more connecting
*/
return 0;
}
if (list_empty(&ksocknal_data.ksnd_connd_routes)) {
/* no pending connecting request */
return 0;
}
if (sec - ksocknal_data.ksnd_connd_failed_stamp <= 1) {
/* may run out of resource, retry later */
*timeout = cfs_time_seconds(1);
return 0;
}
if (ksocknal_data.ksnd_connd_starting > 0) {
/* serialize starting to avoid flood */
return 0;
}
ksocknal_data.ksnd_connd_starting_stamp = sec;
ksocknal_data.ksnd_connd_starting++;
spin_unlock_bh(&ksocknal_data.ksnd_connd_lock);
/* NB: total is the next id */
snprintf(name, sizeof(name), "socknal_cd%02d", total);
rc = ksocknal_thread_start(ksocknal_connd, NULL, name);
spin_lock_bh(&ksocknal_data.ksnd_connd_lock);
if (!rc)
return 1;
/* we tried ... */
LASSERT(ksocknal_data.ksnd_connd_starting > 0);
ksocknal_data.ksnd_connd_starting--;
ksocknal_data.ksnd_connd_failed_stamp = ktime_get_real_seconds();
return 1;
}
/*
* check whether current thread can exit, it will return 1 if there are too
* many threads and no creating in past 120 seconds.
* Also, this function may update @timeout to make caller come back
* again to recheck these conditions.
*/
static int
ksocknal_connd_check_stop(time64_t sec, long *timeout)
{
int val;
if (unlikely(ksocknal_data.ksnd_init < SOCKNAL_INIT_ALL)) {
/* still in initializing */
return 0;
}
if (ksocknal_data.ksnd_connd_starting > 0) {
/* in progress of starting new thread */
return 0;
}
if (ksocknal_data.ksnd_connd_running <=
*ksocknal_tunables.ksnd_nconnds) { /* can't shrink */
return 0;
}
/* created thread in past 120 seconds? */
val = (int)(ksocknal_data.ksnd_connd_starting_stamp +
SOCKNAL_CONND_TIMEOUT - sec);
*timeout = (val > 0) ? cfs_time_seconds(val) :
cfs_time_seconds(SOCKNAL_CONND_TIMEOUT);
if (val > 0)
return 0;
/* no creating in past 120 seconds */
return ksocknal_data.ksnd_connd_running >
ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV;
}
/*
* Go through connd_routes queue looking for a route that we can process
* right now, @timeout_p can be updated if we need to come back later
*/
static struct ksock_route *
ksocknal_connd_get_route_locked(signed long *timeout_p)
{
struct ksock_route *route;
unsigned long now;
now = cfs_time_current();
/* connd_routes can contain both pending and ordinary routes */
list_for_each_entry(route, &ksocknal_data.ksnd_connd_routes,
ksnr_connd_list) {
if (!route->ksnr_retry_interval ||
cfs_time_aftereq(now, route->ksnr_timeout))
return route;
if (*timeout_p == MAX_SCHEDULE_TIMEOUT ||
(int)*timeout_p > (int)(route->ksnr_timeout - now))
*timeout_p = (int)(route->ksnr_timeout - now);
}
return NULL;
}
int
ksocknal_connd(void *arg)
{
spinlock_t *connd_lock = &ksocknal_data.ksnd_connd_lock;
struct ksock_connreq *cr;
wait_queue_t wait;
int nloops = 0;
int cons_retry = 0;
cfs_block_allsigs();
init_waitqueue_entry(&wait, current);
spin_lock_bh(connd_lock);
LASSERT(ksocknal_data.ksnd_connd_starting > 0);
ksocknal_data.ksnd_connd_starting--;
ksocknal_data.ksnd_connd_running++;
while (!ksocknal_data.ksnd_shuttingdown) {
struct ksock_route *route = NULL;
time64_t sec = ktime_get_real_seconds();
long timeout = MAX_SCHEDULE_TIMEOUT;
int dropped_lock = 0;
if (ksocknal_connd_check_stop(sec, &timeout)) {
/* wakeup another one to check stop */
wake_up(&ksocknal_data.ksnd_connd_waitq);
break;
}
if (ksocknal_connd_check_start(sec, &timeout)) {
/* created new thread */
dropped_lock = 1;
}
if (!list_empty(&ksocknal_data.ksnd_connd_connreqs)) {
/* Connection accepted by the listener */
cr = list_entry(ksocknal_data.ksnd_connd_connreqs.next,
struct ksock_connreq, ksncr_list);
list_del(&cr->ksncr_list);
spin_unlock_bh(connd_lock);
dropped_lock = 1;
ksocknal_create_conn(cr->ksncr_ni, NULL,
cr->ksncr_sock, SOCKLND_CONN_NONE);
lnet_ni_decref(cr->ksncr_ni);
LIBCFS_FREE(cr, sizeof(*cr));
spin_lock_bh(connd_lock);
}
/*
* Only handle an outgoing connection request if there
* is a thread left to handle incoming connections and
* create new connd
*/
if (ksocknal_data.ksnd_connd_connecting + SOCKNAL_CONND_RESV <
ksocknal_data.ksnd_connd_running) {
route = ksocknal_connd_get_route_locked(&timeout);
}
if (route) {
list_del(&route->ksnr_connd_list);
ksocknal_data.ksnd_connd_connecting++;
spin_unlock_bh(connd_lock);
dropped_lock = 1;
if (ksocknal_connect(route)) {
/* consecutive retry */
if (cons_retry++ > SOCKNAL_INSANITY_RECONN) {
CWARN("massive consecutive re-connecting to %pI4h\n",
&route->ksnr_ipaddr);
cons_retry = 0;
}
} else {
cons_retry = 0;
}
ksocknal_route_decref(route);
spin_lock_bh(connd_lock);
ksocknal_data.ksnd_connd_connecting--;
}
if (dropped_lock) {
if (++nloops < SOCKNAL_RESCHED)
continue;
spin_unlock_bh(connd_lock);
nloops = 0;
cond_resched();
spin_lock_bh(connd_lock);
continue;
}
/* Nothing to do for 'timeout' */
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue_exclusive(&ksocknal_data.ksnd_connd_waitq, &wait);
spin_unlock_bh(connd_lock);
nloops = 0;
schedule_timeout(timeout);
remove_wait_queue(&ksocknal_data.ksnd_connd_waitq, &wait);
spin_lock_bh(connd_lock);
}
ksocknal_data.ksnd_connd_running--;
spin_unlock_bh(connd_lock);
ksocknal_thread_fini();
return 0;
}
static struct ksock_conn *
ksocknal_find_timed_out_conn(struct ksock_peer *peer)
{
/* We're called with a shared lock on ksnd_global_lock */
struct ksock_conn *conn;
struct list_head *ctmp;
list_for_each(ctmp, &peer->ksnp_conns) {
int error;
conn = list_entry(ctmp, struct ksock_conn, ksnc_list);
/* Don't need the {get,put}connsock dance to deref ksnc_sock */
LASSERT(!conn->ksnc_closing);
/*
* SOCK_ERROR will reset error code of socket in
* some platform (like Darwin8.x)
*/
error = conn->ksnc_sock->sk->sk_err;
if (error) {
ksocknal_conn_addref(conn);
switch (error) {
case ECONNRESET:
CNETERR("A connection with %s (%pI4h:%d) was reset; it may have rebooted.\n",
libcfs_id2str(peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
break;
case ETIMEDOUT:
CNETERR("A connection with %s (%pI4h:%d) timed out; the network or node may be down.\n",
libcfs_id2str(peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
break;
default:
CNETERR("An unexpected network error %d occurred with %s (%pI4h:%d\n",
error,
libcfs_id2str(peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
break;
}
return conn;
}
if (conn->ksnc_rx_started &&
cfs_time_aftereq(cfs_time_current(),
conn->ksnc_rx_deadline)) {
/* Timed out incomplete incoming message */
ksocknal_conn_addref(conn);
CNETERR("Timeout receiving from %s (%pI4h:%d), state %d wanted %d left %d\n",
libcfs_id2str(peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port,
conn->ksnc_rx_state,
conn->ksnc_rx_nob_wanted,
conn->ksnc_rx_nob_left);
return conn;
}
if ((!list_empty(&conn->ksnc_tx_queue) ||
conn->ksnc_sock->sk->sk_wmem_queued) &&
cfs_time_aftereq(cfs_time_current(),
conn->ksnc_tx_deadline)) {
/*
* Timed out messages queued for sending or
* buffered in the socket's send buffer
*/
ksocknal_conn_addref(conn);
CNETERR("Timeout sending data to %s (%pI4h:%d) the network or that node may be down.\n",
libcfs_id2str(peer->ksnp_id),
&conn->ksnc_ipaddr,
conn->ksnc_port);
return conn;
}
}
return NULL;
}
static inline void
ksocknal_flush_stale_txs(struct ksock_peer *peer)
{
struct ksock_tx *tx;
struct ksock_tx *tmp;
LIST_HEAD(stale_txs);
write_lock_bh(&ksocknal_data.ksnd_global_lock);
list_for_each_entry_safe(tx, tmp, &peer->ksnp_tx_queue, tx_list) {
if (!cfs_time_aftereq(cfs_time_current(),
tx->tx_deadline))
break;
list_del(&tx->tx_list);
list_add_tail(&tx->tx_list, &stale_txs);
}
write_unlock_bh(&ksocknal_data.ksnd_global_lock);
ksocknal_txlist_done(peer->ksnp_ni, &stale_txs, 1);
}
static int
ksocknal_send_keepalive_locked(struct ksock_peer *peer)
__must_hold(&ksocknal_data.ksnd_global_lock)
{
struct ksock_sched *sched;
struct ksock_conn *conn;
struct ksock_tx *tx;
if (list_empty(&peer->ksnp_conns)) /* last_alive will be updated by create_conn */
return 0;
if (peer->ksnp_proto != &ksocknal_protocol_v3x)
return 0;
if (*ksocknal_tunables.ksnd_keepalive <= 0 ||
time_before(cfs_time_current(),
cfs_time_add(peer->ksnp_last_alive,
cfs_time_seconds(*ksocknal_tunables.ksnd_keepalive))))
return 0;
if (time_before(cfs_time_current(), peer->ksnp_send_keepalive))
return 0;
/*
* retry 10 secs later, so we wouldn't put pressure
* on this peer if we failed to send keepalive this time
*/
peer->ksnp_send_keepalive = cfs_time_shift(10);
conn = ksocknal_find_conn_locked(peer, NULL, 1);
if (conn) {
sched = conn->ksnc_scheduler;
spin_lock_bh(&sched->kss_lock);
if (!list_empty(&conn->ksnc_tx_queue)) {
spin_unlock_bh(&sched->kss_lock);
/* there is an queued ACK, don't need keepalive */
return 0;
}
spin_unlock_bh(&sched->kss_lock);
}
read_unlock(&ksocknal_data.ksnd_global_lock);
/* cookie = 1 is reserved for keepalive PING */
tx = ksocknal_alloc_tx_noop(1, 1);
if (!tx) {
read_lock(&ksocknal_data.ksnd_global_lock);
return -ENOMEM;
}
if (!ksocknal_launch_packet(peer->ksnp_ni, tx, peer->ksnp_id)) {
read_lock(&ksocknal_data.ksnd_global_lock);
return 1;
}
ksocknal_free_tx(tx);
read_lock(&ksocknal_data.ksnd_global_lock);
return -EIO;
}
static void
ksocknal_check_peer_timeouts(int idx)
{
struct list_head *peers = &ksocknal_data.ksnd_peers[idx];
struct ksock_peer *peer;
struct ksock_conn *conn;
struct ksock_tx *tx;
again:
/*
* NB. We expect to have a look at all the peers and not find any
* connections to time out, so we just use a shared lock while we
* take a look...
*/
read_lock(&ksocknal_data.ksnd_global_lock);
list_for_each_entry(peer, peers, ksnp_list) {
unsigned long deadline = 0;
int resid = 0;
int n = 0;
if (ksocknal_send_keepalive_locked(peer)) {
read_unlock(&ksocknal_data.ksnd_global_lock);
goto again;
}
conn = ksocknal_find_timed_out_conn(peer);
if (conn) {
read_unlock(&ksocknal_data.ksnd_global_lock);
ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
/*
* NB we won't find this one again, but we can't
* just proceed with the next peer, since we dropped
* ksnd_global_lock and it might be dead already!
*/
ksocknal_conn_decref(conn);
goto again;
}
/*
* we can't process stale txs right here because we're
* holding only shared lock
*/
if (!list_empty(&peer->ksnp_tx_queue)) {
struct ksock_tx *tx = list_entry(peer->ksnp_tx_queue.next,
struct ksock_tx, tx_list);
if (cfs_time_aftereq(cfs_time_current(),
tx->tx_deadline)) {
ksocknal_peer_addref(peer);
read_unlock(&ksocknal_data.ksnd_global_lock);
ksocknal_flush_stale_txs(peer);
ksocknal_peer_decref(peer);
goto again;
}
}
if (list_empty(&peer->ksnp_zc_req_list))
continue;
spin_lock(&peer->ksnp_lock);
list_for_each_entry(tx, &peer->ksnp_zc_req_list, tx_zc_list) {
if (!cfs_time_aftereq(cfs_time_current(),
tx->tx_deadline))
break;
/* ignore the TX if connection is being closed */
if (tx->tx_conn->ksnc_closing)
continue;
n++;
}
if (!n) {
spin_unlock(&peer->ksnp_lock);
continue;
}
tx = list_entry(peer->ksnp_zc_req_list.next,
struct ksock_tx, tx_zc_list);
deadline = tx->tx_deadline;
resid = tx->tx_resid;
conn = tx->tx_conn;
ksocknal_conn_addref(conn);
spin_unlock(&peer->ksnp_lock);
read_unlock(&ksocknal_data.ksnd_global_lock);
CERROR("Total %d stale ZC_REQs for peer %s detected; the oldest(%p) timed out %ld secs ago, resid: %d, wmem: %d\n",
n, libcfs_nid2str(peer->ksnp_id.nid), tx,
cfs_duration_sec(cfs_time_current() - deadline),
resid, conn->ksnc_sock->sk->sk_wmem_queued);
ksocknal_close_conn_and_siblings(conn, -ETIMEDOUT);
ksocknal_conn_decref(conn);
goto again;
}
read_unlock(&ksocknal_data.ksnd_global_lock);
}
int
ksocknal_reaper(void *arg)
{
wait_queue_t wait;
struct ksock_conn *conn;
struct ksock_sched *sched;
struct list_head enomem_conns;
int nenomem_conns;
long timeout;
int i;
int peer_index = 0;
unsigned long deadline = cfs_time_current();
cfs_block_allsigs();
INIT_LIST_HEAD(&enomem_conns);
init_waitqueue_entry(&wait, current);
spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
while (!ksocknal_data.ksnd_shuttingdown) {
if (!list_empty(&ksocknal_data.ksnd_deathrow_conns)) {
conn = list_entry(ksocknal_data.ksnd_deathrow_conns.next,
struct ksock_conn, ksnc_list);
list_del(&conn->ksnc_list);
spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
ksocknal_terminate_conn(conn);
ksocknal_conn_decref(conn);
spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
continue;
}
if (!list_empty(&ksocknal_data.ksnd_zombie_conns)) {
conn = list_entry(ksocknal_data.ksnd_zombie_conns.next,
struct ksock_conn, ksnc_list);
list_del(&conn->ksnc_list);
spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
ksocknal_destroy_conn(conn);
spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
continue;
}
if (!list_empty(&ksocknal_data.ksnd_enomem_conns)) {
list_add(&enomem_conns,
&ksocknal_data.ksnd_enomem_conns);
list_del_init(&ksocknal_data.ksnd_enomem_conns);
}
spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
/* reschedule all the connections that stalled with ENOMEM... */
nenomem_conns = 0;
while (!list_empty(&enomem_conns)) {
conn = list_entry(enomem_conns.next, struct ksock_conn,
ksnc_tx_list);
list_del(&conn->ksnc_tx_list);
sched = conn->ksnc_scheduler;
spin_lock_bh(&sched->kss_lock);
LASSERT(conn->ksnc_tx_scheduled);
conn->ksnc_tx_ready = 1;
list_add_tail(&conn->ksnc_tx_list,
&sched->kss_tx_conns);
wake_up(&sched->kss_waitq);
spin_unlock_bh(&sched->kss_lock);
nenomem_conns++;
}
/* careful with the jiffy wrap... */
while ((timeout = cfs_time_sub(deadline,
cfs_time_current())) <= 0) {
const int n = 4;
const int p = 1;
int chunk = ksocknal_data.ksnd_peer_hash_size;
/*
* Time to check for timeouts on a few more peers: I do
* checks every 'p' seconds on a proportion of the peer
* table and I need to check every connection 'n' times
* within a timeout interval, to ensure I detect a
* timeout on any connection within (n+1)/n times the
* timeout interval.
*/
if (*ksocknal_tunables.ksnd_timeout > n * p)
chunk = (chunk * n * p) /
*ksocknal_tunables.ksnd_timeout;
if (!chunk)
chunk = 1;
for (i = 0; i < chunk; i++) {
ksocknal_check_peer_timeouts(peer_index);
peer_index = (peer_index + 1) %
ksocknal_data.ksnd_peer_hash_size;
}
deadline = cfs_time_add(deadline, cfs_time_seconds(p));
}
if (nenomem_conns) {
/*
* Reduce my timeout if I rescheduled ENOMEM conns.
* This also prevents me getting woken immediately
* if any go back on my enomem list.
*/
timeout = SOCKNAL_ENOMEM_RETRY;
}
ksocknal_data.ksnd_reaper_waketime =
cfs_time_add(cfs_time_current(), timeout);
set_current_state(TASK_INTERRUPTIBLE);
add_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
if (!ksocknal_data.ksnd_shuttingdown &&
list_empty(&ksocknal_data.ksnd_deathrow_conns) &&
list_empty(&ksocknal_data.ksnd_zombie_conns))
schedule_timeout(timeout);
set_current_state(TASK_RUNNING);
remove_wait_queue(&ksocknal_data.ksnd_reaper_waitq, &wait);
spin_lock_bh(&ksocknal_data.ksnd_reaper_lock);
}
spin_unlock_bh(&ksocknal_data.ksnd_reaper_lock);
ksocknal_thread_fini();
return 0;
}
| gpl-2.0 |
linuxsky/linux-80211n-csitool | sound/soc/tegra/tegra20_spdif.c | 49 | 10083 | /*
* tegra20_spdif.c - Tegra20 SPDIF driver
*
* Author: Stephen Warren <swarren@nvidia.com>
* Copyright (C) 2011-2012 - NVIDIA, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/pm_runtime.h>
#include <linux/regmap.h>
#include <linux/slab.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include "tegra20_spdif.h"
#define DRV_NAME "tegra20-spdif"
static inline void tegra20_spdif_write(struct tegra20_spdif *spdif, u32 reg,
u32 val)
{
regmap_write(spdif->regmap, reg, val);
}
static inline u32 tegra20_spdif_read(struct tegra20_spdif *spdif, u32 reg)
{
u32 val;
regmap_read(spdif->regmap, reg, &val);
return val;
}
static int tegra20_spdif_runtime_suspend(struct device *dev)
{
struct tegra20_spdif *spdif = dev_get_drvdata(dev);
clk_disable(spdif->clk_spdif_out);
return 0;
}
static int tegra20_spdif_runtime_resume(struct device *dev)
{
struct tegra20_spdif *spdif = dev_get_drvdata(dev);
int ret;
ret = clk_enable(spdif->clk_spdif_out);
if (ret) {
dev_err(dev, "clk_enable failed: %d\n", ret);
return ret;
}
return 0;
}
static int tegra20_spdif_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params,
struct snd_soc_dai *dai)
{
struct device *dev = substream->pcm->card->dev;
struct tegra20_spdif *spdif = snd_soc_dai_get_drvdata(dai);
int ret, spdifclock;
spdif->reg_ctrl &= ~TEGRA20_SPDIF_CTRL_PACK;
spdif->reg_ctrl &= ~TEGRA20_SPDIF_CTRL_BIT_MODE_MASK;
switch (params_format(params)) {
case SNDRV_PCM_FORMAT_S16_LE:
spdif->reg_ctrl |= TEGRA20_SPDIF_CTRL_PACK;
spdif->reg_ctrl |= TEGRA20_SPDIF_CTRL_BIT_MODE_16BIT;
break;
default:
return -EINVAL;
}
switch (params_rate(params)) {
case 32000:
spdifclock = 4096000;
break;
case 44100:
spdifclock = 5644800;
break;
case 48000:
spdifclock = 6144000;
break;
case 88200:
spdifclock = 11289600;
break;
case 96000:
spdifclock = 12288000;
break;
case 176400:
spdifclock = 22579200;
break;
case 192000:
spdifclock = 24576000;
break;
default:
return -EINVAL;
}
ret = clk_set_rate(spdif->clk_spdif_out, spdifclock);
if (ret) {
dev_err(dev, "Can't set SPDIF clock rate: %d\n", ret);
return ret;
}
return 0;
}
static void tegra20_spdif_start_playback(struct tegra20_spdif *spdif)
{
spdif->reg_ctrl |= TEGRA20_SPDIF_CTRL_TX_EN;
tegra20_spdif_write(spdif, TEGRA20_SPDIF_CTRL, spdif->reg_ctrl);
}
static void tegra20_spdif_stop_playback(struct tegra20_spdif *spdif)
{
spdif->reg_ctrl &= ~TEGRA20_SPDIF_CTRL_TX_EN;
tegra20_spdif_write(spdif, TEGRA20_SPDIF_CTRL, spdif->reg_ctrl);
}
static int tegra20_spdif_trigger(struct snd_pcm_substream *substream, int cmd,
struct snd_soc_dai *dai)
{
struct tegra20_spdif *spdif = snd_soc_dai_get_drvdata(dai);
switch (cmd) {
case SNDRV_PCM_TRIGGER_START:
case SNDRV_PCM_TRIGGER_PAUSE_RELEASE:
case SNDRV_PCM_TRIGGER_RESUME:
tegra20_spdif_start_playback(spdif);
break;
case SNDRV_PCM_TRIGGER_STOP:
case SNDRV_PCM_TRIGGER_PAUSE_PUSH:
case SNDRV_PCM_TRIGGER_SUSPEND:
tegra20_spdif_stop_playback(spdif);
break;
default:
return -EINVAL;
}
return 0;
}
static int tegra20_spdif_probe(struct snd_soc_dai *dai)
{
struct tegra20_spdif *spdif = snd_soc_dai_get_drvdata(dai);
dai->capture_dma_data = NULL;
dai->playback_dma_data = &spdif->playback_dma_data;
return 0;
}
static const struct snd_soc_dai_ops tegra20_spdif_dai_ops = {
.hw_params = tegra20_spdif_hw_params,
.trigger = tegra20_spdif_trigger,
};
static struct snd_soc_dai_driver tegra20_spdif_dai = {
.name = DRV_NAME,
.probe = tegra20_spdif_probe,
.playback = {
.channels_min = 2,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_32000 | SNDRV_PCM_RATE_44100 |
SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FMTBIT_S16_LE,
},
.ops = &tegra20_spdif_dai_ops,
};
static bool tegra20_spdif_wr_rd_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TEGRA20_SPDIF_CTRL:
case TEGRA20_SPDIF_STATUS:
case TEGRA20_SPDIF_STROBE_CTRL:
case TEGRA20_SPDIF_DATA_FIFO_CSR:
case TEGRA20_SPDIF_DATA_OUT:
case TEGRA20_SPDIF_DATA_IN:
case TEGRA20_SPDIF_CH_STA_RX_A:
case TEGRA20_SPDIF_CH_STA_RX_B:
case TEGRA20_SPDIF_CH_STA_RX_C:
case TEGRA20_SPDIF_CH_STA_RX_D:
case TEGRA20_SPDIF_CH_STA_RX_E:
case TEGRA20_SPDIF_CH_STA_RX_F:
case TEGRA20_SPDIF_CH_STA_TX_A:
case TEGRA20_SPDIF_CH_STA_TX_B:
case TEGRA20_SPDIF_CH_STA_TX_C:
case TEGRA20_SPDIF_CH_STA_TX_D:
case TEGRA20_SPDIF_CH_STA_TX_E:
case TEGRA20_SPDIF_CH_STA_TX_F:
case TEGRA20_SPDIF_USR_STA_RX_A:
case TEGRA20_SPDIF_USR_DAT_TX_A:
return true;
default:
return false;
};
}
static bool tegra20_spdif_volatile_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TEGRA20_SPDIF_STATUS:
case TEGRA20_SPDIF_DATA_FIFO_CSR:
case TEGRA20_SPDIF_DATA_OUT:
case TEGRA20_SPDIF_DATA_IN:
case TEGRA20_SPDIF_CH_STA_RX_A:
case TEGRA20_SPDIF_CH_STA_RX_B:
case TEGRA20_SPDIF_CH_STA_RX_C:
case TEGRA20_SPDIF_CH_STA_RX_D:
case TEGRA20_SPDIF_CH_STA_RX_E:
case TEGRA20_SPDIF_CH_STA_RX_F:
case TEGRA20_SPDIF_USR_STA_RX_A:
case TEGRA20_SPDIF_USR_DAT_TX_A:
return true;
default:
return false;
};
}
static bool tegra20_spdif_precious_reg(struct device *dev, unsigned int reg)
{
switch (reg) {
case TEGRA20_SPDIF_DATA_OUT:
case TEGRA20_SPDIF_DATA_IN:
case TEGRA20_SPDIF_USR_STA_RX_A:
case TEGRA20_SPDIF_USR_DAT_TX_A:
return true;
default:
return false;
};
}
static const struct regmap_config tegra20_spdif_regmap_config = {
.reg_bits = 32,
.reg_stride = 4,
.val_bits = 32,
.max_register = TEGRA20_SPDIF_USR_DAT_TX_A,
.writeable_reg = tegra20_spdif_wr_rd_reg,
.readable_reg = tegra20_spdif_wr_rd_reg,
.volatile_reg = tegra20_spdif_volatile_reg,
.precious_reg = tegra20_spdif_precious_reg,
.cache_type = REGCACHE_RBTREE,
};
static __devinit int tegra20_spdif_platform_probe(struct platform_device *pdev)
{
struct tegra20_spdif *spdif;
struct resource *mem, *memregion, *dmareq;
void __iomem *regs;
int ret;
spdif = devm_kzalloc(&pdev->dev, sizeof(struct tegra20_spdif),
GFP_KERNEL);
if (!spdif) {
dev_err(&pdev->dev, "Can't allocate tegra20_spdif\n");
ret = -ENOMEM;
goto err;
}
dev_set_drvdata(&pdev->dev, spdif);
spdif->clk_spdif_out = clk_get(&pdev->dev, "spdif_out");
if (IS_ERR(spdif->clk_spdif_out)) {
pr_err("Can't retrieve spdif clock\n");
ret = PTR_ERR(spdif->clk_spdif_out);
goto err;
}
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(&pdev->dev, "No memory resource\n");
ret = -ENODEV;
goto err_clk_put;
}
dmareq = platform_get_resource(pdev, IORESOURCE_DMA, 0);
if (!dmareq) {
dev_err(&pdev->dev, "No DMA resource\n");
ret = -ENODEV;
goto err_clk_put;
}
memregion = devm_request_mem_region(&pdev->dev, mem->start,
resource_size(mem), DRV_NAME);
if (!memregion) {
dev_err(&pdev->dev, "Memory region already claimed\n");
ret = -EBUSY;
goto err_clk_put;
}
regs = devm_ioremap(&pdev->dev, mem->start, resource_size(mem));
if (!regs) {
dev_err(&pdev->dev, "ioremap failed\n");
ret = -ENOMEM;
goto err_clk_put;
}
spdif->regmap = devm_regmap_init_mmio(&pdev->dev, regs,
&tegra20_spdif_regmap_config);
if (IS_ERR(spdif->regmap)) {
dev_err(&pdev->dev, "regmap init failed\n");
ret = PTR_ERR(spdif->regmap);
goto err_clk_put;
}
spdif->playback_dma_data.addr = mem->start + TEGRA20_SPDIF_DATA_OUT;
spdif->playback_dma_data.wrap = 4;
spdif->playback_dma_data.width = 32;
spdif->playback_dma_data.req_sel = dmareq->start;
pm_runtime_enable(&pdev->dev);
if (!pm_runtime_enabled(&pdev->dev)) {
ret = tegra20_spdif_runtime_resume(&pdev->dev);
if (ret)
goto err_pm_disable;
}
ret = snd_soc_register_dai(&pdev->dev, &tegra20_spdif_dai);
if (ret) {
dev_err(&pdev->dev, "Could not register DAI: %d\n", ret);
ret = -ENOMEM;
goto err_suspend;
}
ret = tegra_pcm_platform_register(&pdev->dev);
if (ret) {
dev_err(&pdev->dev, "Could not register PCM: %d\n", ret);
goto err_unregister_dai;
}
return 0;
err_unregister_dai:
snd_soc_unregister_dai(&pdev->dev);
err_suspend:
if (!pm_runtime_status_suspended(&pdev->dev))
tegra20_spdif_runtime_suspend(&pdev->dev);
err_pm_disable:
pm_runtime_disable(&pdev->dev);
err_clk_put:
clk_put(spdif->clk_spdif_out);
err:
return ret;
}
static int __devexit tegra20_spdif_platform_remove(struct platform_device *pdev)
{
struct tegra20_spdif *spdif = dev_get_drvdata(&pdev->dev);
pm_runtime_disable(&pdev->dev);
if (!pm_runtime_status_suspended(&pdev->dev))
tegra20_spdif_runtime_suspend(&pdev->dev);
tegra_pcm_platform_unregister(&pdev->dev);
snd_soc_unregister_dai(&pdev->dev);
clk_put(spdif->clk_spdif_out);
return 0;
}
static const struct dev_pm_ops tegra20_spdif_pm_ops __devinitconst = {
SET_RUNTIME_PM_OPS(tegra20_spdif_runtime_suspend,
tegra20_spdif_runtime_resume, NULL)
};
static struct platform_driver tegra20_spdif_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
.pm = &tegra20_spdif_pm_ops,
},
.probe = tegra20_spdif_platform_probe,
.remove = __devexit_p(tegra20_spdif_platform_remove),
};
module_platform_driver(tegra20_spdif_driver);
MODULE_AUTHOR("Stephen Warren <swarren@nvidia.com>");
MODULE_DESCRIPTION("Tegra20 SPDIF ASoC driver");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:" DRV_NAME);
| gpl-2.0 |
darknighte/linux | drivers/infiniband/core/sysfs.c | 49 | 34822 | /*
* Copyright (c) 2004, 2005 Topspin Communications. All rights reserved.
* Copyright (c) 2005 Mellanox Technologies Ltd. All rights reserved.
* Copyright (c) 2005 Sun Microsystems, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "core_priv.h"
#include <linux/slab.h>
#include <linux/stat.h>
#include <linux/string.h>
#include <linux/netdevice.h>
#include <linux/ethtool.h>
#include <rdma/ib_mad.h>
#include <rdma/ib_pma.h>
struct ib_port;
struct gid_attr_group {
struct ib_port *port;
struct kobject kobj;
struct attribute_group ndev;
struct attribute_group type;
};
struct ib_port {
struct kobject kobj;
struct ib_device *ibdev;
struct gid_attr_group *gid_attr_group;
struct attribute_group gid_group;
struct attribute_group pkey_group;
struct attribute_group *pma_table;
struct attribute_group *hw_stats_ag;
struct rdma_hw_stats *hw_stats;
u8 port_num;
};
struct port_attribute {
struct attribute attr;
ssize_t (*show)(struct ib_port *, struct port_attribute *, char *buf);
ssize_t (*store)(struct ib_port *, struct port_attribute *,
const char *buf, size_t count);
};
#define PORT_ATTR(_name, _mode, _show, _store) \
struct port_attribute port_attr_##_name = __ATTR(_name, _mode, _show, _store)
#define PORT_ATTR_RO(_name) \
struct port_attribute port_attr_##_name = __ATTR_RO(_name)
struct port_table_attribute {
struct port_attribute attr;
char name[8];
int index;
__be16 attr_id;
};
struct hw_stats_attribute {
struct attribute attr;
ssize_t (*show)(struct kobject *kobj,
struct attribute *attr, char *buf);
ssize_t (*store)(struct kobject *kobj,
struct attribute *attr,
const char *buf,
size_t count);
int index;
u8 port_num;
};
static ssize_t port_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct port_attribute *port_attr =
container_of(attr, struct port_attribute, attr);
struct ib_port *p = container_of(kobj, struct ib_port, kobj);
if (!port_attr->show)
return -EIO;
return port_attr->show(p, port_attr, buf);
}
static const struct sysfs_ops port_sysfs_ops = {
.show = port_attr_show
};
static ssize_t gid_attr_show(struct kobject *kobj,
struct attribute *attr, char *buf)
{
struct port_attribute *port_attr =
container_of(attr, struct port_attribute, attr);
struct ib_port *p = container_of(kobj, struct gid_attr_group,
kobj)->port;
if (!port_attr->show)
return -EIO;
return port_attr->show(p, port_attr, buf);
}
static const struct sysfs_ops gid_attr_sysfs_ops = {
.show = gid_attr_show
};
static ssize_t state_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
static const char *state_name[] = {
[IB_PORT_NOP] = "NOP",
[IB_PORT_DOWN] = "DOWN",
[IB_PORT_INIT] = "INIT",
[IB_PORT_ARMED] = "ARMED",
[IB_PORT_ACTIVE] = "ACTIVE",
[IB_PORT_ACTIVE_DEFER] = "ACTIVE_DEFER"
};
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "%d: %s\n", attr.state,
attr.state >= 0 && attr.state < ARRAY_SIZE(state_name) ?
state_name[attr.state] : "UNKNOWN");
}
static ssize_t lid_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "0x%x\n", attr.lid);
}
static ssize_t lid_mask_count_show(struct ib_port *p,
struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "%d\n", attr.lmc);
}
static ssize_t sm_lid_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "0x%x\n", attr.sm_lid);
}
static ssize_t sm_sl_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "%d\n", attr.sm_sl);
}
static ssize_t cap_mask_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
return sprintf(buf, "0x%08x\n", attr.port_cap_flags);
}
static ssize_t rate_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
char *speed = "";
int rate; /* in deci-Gb/sec */
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
switch (attr.active_speed) {
case IB_SPEED_DDR:
speed = " DDR";
rate = 50;
break;
case IB_SPEED_QDR:
speed = " QDR";
rate = 100;
break;
case IB_SPEED_FDR10:
speed = " FDR10";
rate = 100;
break;
case IB_SPEED_FDR:
speed = " FDR";
rate = 140;
break;
case IB_SPEED_EDR:
speed = " EDR";
rate = 250;
break;
case IB_SPEED_SDR:
default: /* default to SDR for invalid rates */
rate = 25;
break;
}
rate *= ib_width_enum_to_int(attr.active_width);
if (rate < 0)
return -EINVAL;
return sprintf(buf, "%d%s Gb/sec (%dX%s)\n",
rate / 10, rate % 10 ? ".5" : "",
ib_width_enum_to_int(attr.active_width), speed);
}
static ssize_t phys_state_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
struct ib_port_attr attr;
ssize_t ret;
ret = ib_query_port(p->ibdev, p->port_num, &attr);
if (ret)
return ret;
switch (attr.phys_state) {
case 1: return sprintf(buf, "1: Sleep\n");
case 2: return sprintf(buf, "2: Polling\n");
case 3: return sprintf(buf, "3: Disabled\n");
case 4: return sprintf(buf, "4: PortConfigurationTraining\n");
case 5: return sprintf(buf, "5: LinkUp\n");
case 6: return sprintf(buf, "6: LinkErrorRecovery\n");
case 7: return sprintf(buf, "7: Phy Test\n");
default: return sprintf(buf, "%d: <unknown>\n", attr.phys_state);
}
}
static ssize_t link_layer_show(struct ib_port *p, struct port_attribute *unused,
char *buf)
{
switch (rdma_port_get_link_layer(p->ibdev, p->port_num)) {
case IB_LINK_LAYER_INFINIBAND:
return sprintf(buf, "%s\n", "InfiniBand");
case IB_LINK_LAYER_ETHERNET:
return sprintf(buf, "%s\n", "Ethernet");
default:
return sprintf(buf, "%s\n", "Unknown");
}
}
static PORT_ATTR_RO(state);
static PORT_ATTR_RO(lid);
static PORT_ATTR_RO(lid_mask_count);
static PORT_ATTR_RO(sm_lid);
static PORT_ATTR_RO(sm_sl);
static PORT_ATTR_RO(cap_mask);
static PORT_ATTR_RO(rate);
static PORT_ATTR_RO(phys_state);
static PORT_ATTR_RO(link_layer);
static struct attribute *port_default_attrs[] = {
&port_attr_state.attr,
&port_attr_lid.attr,
&port_attr_lid_mask_count.attr,
&port_attr_sm_lid.attr,
&port_attr_sm_sl.attr,
&port_attr_cap_mask.attr,
&port_attr_rate.attr,
&port_attr_phys_state.attr,
&port_attr_link_layer.attr,
NULL
};
static size_t print_ndev(struct ib_gid_attr *gid_attr, char *buf)
{
if (!gid_attr->ndev)
return -EINVAL;
return sprintf(buf, "%s\n", gid_attr->ndev->name);
}
static size_t print_gid_type(struct ib_gid_attr *gid_attr, char *buf)
{
return sprintf(buf, "%s\n", ib_cache_gid_type_str(gid_attr->gid_type));
}
static ssize_t _show_port_gid_attr(struct ib_port *p,
struct port_attribute *attr,
char *buf,
size_t (*print)(struct ib_gid_attr *gid_attr,
char *buf))
{
struct port_table_attribute *tab_attr =
container_of(attr, struct port_table_attribute, attr);
union ib_gid gid;
struct ib_gid_attr gid_attr = {};
ssize_t ret;
ret = ib_query_gid(p->ibdev, p->port_num, tab_attr->index, &gid,
&gid_attr);
if (ret)
goto err;
ret = print(&gid_attr, buf);
err:
if (gid_attr.ndev)
dev_put(gid_attr.ndev);
return ret;
}
static ssize_t show_port_gid(struct ib_port *p, struct port_attribute *attr,
char *buf)
{
struct port_table_attribute *tab_attr =
container_of(attr, struct port_table_attribute, attr);
union ib_gid gid;
ssize_t ret;
ret = ib_query_gid(p->ibdev, p->port_num, tab_attr->index, &gid, NULL);
if (ret)
return ret;
return sprintf(buf, "%pI6\n", gid.raw);
}
static ssize_t show_port_gid_attr_ndev(struct ib_port *p,
struct port_attribute *attr, char *buf)
{
return _show_port_gid_attr(p, attr, buf, print_ndev);
}
static ssize_t show_port_gid_attr_gid_type(struct ib_port *p,
struct port_attribute *attr,
char *buf)
{
return _show_port_gid_attr(p, attr, buf, print_gid_type);
}
static ssize_t show_port_pkey(struct ib_port *p, struct port_attribute *attr,
char *buf)
{
struct port_table_attribute *tab_attr =
container_of(attr, struct port_table_attribute, attr);
u16 pkey;
ssize_t ret;
ret = ib_query_pkey(p->ibdev, p->port_num, tab_attr->index, &pkey);
if (ret)
return ret;
return sprintf(buf, "0x%04x\n", pkey);
}
#define PORT_PMA_ATTR(_name, _counter, _width, _offset) \
struct port_table_attribute port_pma_attr_##_name = { \
.attr = __ATTR(_name, S_IRUGO, show_pma_counter, NULL), \
.index = (_offset) | ((_width) << 16) | ((_counter) << 24), \
.attr_id = IB_PMA_PORT_COUNTERS , \
}
#define PORT_PMA_ATTR_EXT(_name, _width, _offset) \
struct port_table_attribute port_pma_attr_ext_##_name = { \
.attr = __ATTR(_name, S_IRUGO, show_pma_counter, NULL), \
.index = (_offset) | ((_width) << 16), \
.attr_id = IB_PMA_PORT_COUNTERS_EXT , \
}
/*
* Get a Perfmgmt MAD block of data.
* Returns error code or the number of bytes retrieved.
*/
static int get_perf_mad(struct ib_device *dev, int port_num, __be16 attr,
void *data, int offset, size_t size)
{
struct ib_mad *in_mad;
struct ib_mad *out_mad;
size_t mad_size = sizeof(*out_mad);
u16 out_mad_pkey_index = 0;
ssize_t ret;
if (!dev->process_mad)
return -ENOSYS;
in_mad = kzalloc(sizeof *in_mad, GFP_KERNEL);
out_mad = kmalloc(sizeof *out_mad, GFP_KERNEL);
if (!in_mad || !out_mad) {
ret = -ENOMEM;
goto out;
}
in_mad->mad_hdr.base_version = 1;
in_mad->mad_hdr.mgmt_class = IB_MGMT_CLASS_PERF_MGMT;
in_mad->mad_hdr.class_version = 1;
in_mad->mad_hdr.method = IB_MGMT_METHOD_GET;
in_mad->mad_hdr.attr_id = attr;
if (attr != IB_PMA_CLASS_PORT_INFO)
in_mad->data[41] = port_num; /* PortSelect field */
if ((dev->process_mad(dev, IB_MAD_IGNORE_MKEY,
port_num, NULL, NULL,
(const struct ib_mad_hdr *)in_mad, mad_size,
(struct ib_mad_hdr *)out_mad, &mad_size,
&out_mad_pkey_index) &
(IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY)) !=
(IB_MAD_RESULT_SUCCESS | IB_MAD_RESULT_REPLY)) {
ret = -EINVAL;
goto out;
}
memcpy(data, out_mad->data + offset, size);
ret = size;
out:
kfree(in_mad);
kfree(out_mad);
return ret;
}
static ssize_t show_pma_counter(struct ib_port *p, struct port_attribute *attr,
char *buf)
{
struct port_table_attribute *tab_attr =
container_of(attr, struct port_table_attribute, attr);
int offset = tab_attr->index & 0xffff;
int width = (tab_attr->index >> 16) & 0xff;
ssize_t ret;
u8 data[8];
ret = get_perf_mad(p->ibdev, p->port_num, tab_attr->attr_id, &data,
40 + offset / 8, sizeof(data));
if (ret < 0)
return sprintf(buf, "N/A (no PMA)\n");
switch (width) {
case 4:
ret = sprintf(buf, "%u\n", (*data >>
(4 - (offset % 8))) & 0xf);
break;
case 8:
ret = sprintf(buf, "%u\n", *data);
break;
case 16:
ret = sprintf(buf, "%u\n",
be16_to_cpup((__be16 *)data));
break;
case 32:
ret = sprintf(buf, "%u\n",
be32_to_cpup((__be32 *)data));
break;
case 64:
ret = sprintf(buf, "%llu\n",
be64_to_cpup((__be64 *)data));
break;
default:
ret = 0;
}
return ret;
}
static PORT_PMA_ATTR(symbol_error , 0, 16, 32);
static PORT_PMA_ATTR(link_error_recovery , 1, 8, 48);
static PORT_PMA_ATTR(link_downed , 2, 8, 56);
static PORT_PMA_ATTR(port_rcv_errors , 3, 16, 64);
static PORT_PMA_ATTR(port_rcv_remote_physical_errors, 4, 16, 80);
static PORT_PMA_ATTR(port_rcv_switch_relay_errors , 5, 16, 96);
static PORT_PMA_ATTR(port_xmit_discards , 6, 16, 112);
static PORT_PMA_ATTR(port_xmit_constraint_errors , 7, 8, 128);
static PORT_PMA_ATTR(port_rcv_constraint_errors , 8, 8, 136);
static PORT_PMA_ATTR(local_link_integrity_errors , 9, 4, 152);
static PORT_PMA_ATTR(excessive_buffer_overrun_errors, 10, 4, 156);
static PORT_PMA_ATTR(VL15_dropped , 11, 16, 176);
static PORT_PMA_ATTR(port_xmit_data , 12, 32, 192);
static PORT_PMA_ATTR(port_rcv_data , 13, 32, 224);
static PORT_PMA_ATTR(port_xmit_packets , 14, 32, 256);
static PORT_PMA_ATTR(port_rcv_packets , 15, 32, 288);
static PORT_PMA_ATTR(port_xmit_wait , 0, 32, 320);
/*
* Counters added by extended set
*/
static PORT_PMA_ATTR_EXT(port_xmit_data , 64, 64);
static PORT_PMA_ATTR_EXT(port_rcv_data , 64, 128);
static PORT_PMA_ATTR_EXT(port_xmit_packets , 64, 192);
static PORT_PMA_ATTR_EXT(port_rcv_packets , 64, 256);
static PORT_PMA_ATTR_EXT(unicast_xmit_packets , 64, 320);
static PORT_PMA_ATTR_EXT(unicast_rcv_packets , 64, 384);
static PORT_PMA_ATTR_EXT(multicast_xmit_packets , 64, 448);
static PORT_PMA_ATTR_EXT(multicast_rcv_packets , 64, 512);
static struct attribute *pma_attrs[] = {
&port_pma_attr_symbol_error.attr.attr,
&port_pma_attr_link_error_recovery.attr.attr,
&port_pma_attr_link_downed.attr.attr,
&port_pma_attr_port_rcv_errors.attr.attr,
&port_pma_attr_port_rcv_remote_physical_errors.attr.attr,
&port_pma_attr_port_rcv_switch_relay_errors.attr.attr,
&port_pma_attr_port_xmit_discards.attr.attr,
&port_pma_attr_port_xmit_constraint_errors.attr.attr,
&port_pma_attr_port_rcv_constraint_errors.attr.attr,
&port_pma_attr_local_link_integrity_errors.attr.attr,
&port_pma_attr_excessive_buffer_overrun_errors.attr.attr,
&port_pma_attr_VL15_dropped.attr.attr,
&port_pma_attr_port_xmit_data.attr.attr,
&port_pma_attr_port_rcv_data.attr.attr,
&port_pma_attr_port_xmit_packets.attr.attr,
&port_pma_attr_port_rcv_packets.attr.attr,
&port_pma_attr_port_xmit_wait.attr.attr,
NULL
};
static struct attribute *pma_attrs_ext[] = {
&port_pma_attr_symbol_error.attr.attr,
&port_pma_attr_link_error_recovery.attr.attr,
&port_pma_attr_link_downed.attr.attr,
&port_pma_attr_port_rcv_errors.attr.attr,
&port_pma_attr_port_rcv_remote_physical_errors.attr.attr,
&port_pma_attr_port_rcv_switch_relay_errors.attr.attr,
&port_pma_attr_port_xmit_discards.attr.attr,
&port_pma_attr_port_xmit_constraint_errors.attr.attr,
&port_pma_attr_port_rcv_constraint_errors.attr.attr,
&port_pma_attr_local_link_integrity_errors.attr.attr,
&port_pma_attr_excessive_buffer_overrun_errors.attr.attr,
&port_pma_attr_VL15_dropped.attr.attr,
&port_pma_attr_ext_port_xmit_data.attr.attr,
&port_pma_attr_ext_port_rcv_data.attr.attr,
&port_pma_attr_ext_port_xmit_packets.attr.attr,
&port_pma_attr_port_xmit_wait.attr.attr,
&port_pma_attr_ext_port_rcv_packets.attr.attr,
&port_pma_attr_ext_unicast_rcv_packets.attr.attr,
&port_pma_attr_ext_unicast_xmit_packets.attr.attr,
&port_pma_attr_ext_multicast_rcv_packets.attr.attr,
&port_pma_attr_ext_multicast_xmit_packets.attr.attr,
NULL
};
static struct attribute *pma_attrs_noietf[] = {
&port_pma_attr_symbol_error.attr.attr,
&port_pma_attr_link_error_recovery.attr.attr,
&port_pma_attr_link_downed.attr.attr,
&port_pma_attr_port_rcv_errors.attr.attr,
&port_pma_attr_port_rcv_remote_physical_errors.attr.attr,
&port_pma_attr_port_rcv_switch_relay_errors.attr.attr,
&port_pma_attr_port_xmit_discards.attr.attr,
&port_pma_attr_port_xmit_constraint_errors.attr.attr,
&port_pma_attr_port_rcv_constraint_errors.attr.attr,
&port_pma_attr_local_link_integrity_errors.attr.attr,
&port_pma_attr_excessive_buffer_overrun_errors.attr.attr,
&port_pma_attr_VL15_dropped.attr.attr,
&port_pma_attr_ext_port_xmit_data.attr.attr,
&port_pma_attr_ext_port_rcv_data.attr.attr,
&port_pma_attr_ext_port_xmit_packets.attr.attr,
&port_pma_attr_ext_port_rcv_packets.attr.attr,
&port_pma_attr_port_xmit_wait.attr.attr,
NULL
};
static struct attribute_group pma_group = {
.name = "counters",
.attrs = pma_attrs
};
static struct attribute_group pma_group_ext = {
.name = "counters",
.attrs = pma_attrs_ext
};
static struct attribute_group pma_group_noietf = {
.name = "counters",
.attrs = pma_attrs_noietf
};
static void ib_port_release(struct kobject *kobj)
{
struct ib_port *p = container_of(kobj, struct ib_port, kobj);
struct attribute *a;
int i;
if (p->gid_group.attrs) {
for (i = 0; (a = p->gid_group.attrs[i]); ++i)
kfree(a);
kfree(p->gid_group.attrs);
}
if (p->pkey_group.attrs) {
for (i = 0; (a = p->pkey_group.attrs[i]); ++i)
kfree(a);
kfree(p->pkey_group.attrs);
}
kfree(p);
}
static void ib_port_gid_attr_release(struct kobject *kobj)
{
struct gid_attr_group *g = container_of(kobj, struct gid_attr_group,
kobj);
struct attribute *a;
int i;
if (g->ndev.attrs) {
for (i = 0; (a = g->ndev.attrs[i]); ++i)
kfree(a);
kfree(g->ndev.attrs);
}
if (g->type.attrs) {
for (i = 0; (a = g->type.attrs[i]); ++i)
kfree(a);
kfree(g->type.attrs);
}
kfree(g);
}
static struct kobj_type port_type = {
.release = ib_port_release,
.sysfs_ops = &port_sysfs_ops,
.default_attrs = port_default_attrs
};
static struct kobj_type gid_attr_type = {
.sysfs_ops = &gid_attr_sysfs_ops,
.release = ib_port_gid_attr_release
};
static struct attribute **
alloc_group_attrs(ssize_t (*show)(struct ib_port *,
struct port_attribute *, char *buf),
int len)
{
struct attribute **tab_attr;
struct port_table_attribute *element;
int i;
tab_attr = kcalloc(1 + len, sizeof(struct attribute *), GFP_KERNEL);
if (!tab_attr)
return NULL;
for (i = 0; i < len; i++) {
element = kzalloc(sizeof(struct port_table_attribute),
GFP_KERNEL);
if (!element)
goto err;
if (snprintf(element->name, sizeof(element->name),
"%d", i) >= sizeof(element->name)) {
kfree(element);
goto err;
}
element->attr.attr.name = element->name;
element->attr.attr.mode = S_IRUGO;
element->attr.show = show;
element->index = i;
sysfs_attr_init(&element->attr.attr);
tab_attr[i] = &element->attr.attr;
}
return tab_attr;
err:
while (--i >= 0)
kfree(tab_attr[i]);
kfree(tab_attr);
return NULL;
}
/*
* Figure out which counter table to use depending on
* the device capabilities.
*/
static struct attribute_group *get_counter_table(struct ib_device *dev,
int port_num)
{
struct ib_class_port_info cpi;
if (get_perf_mad(dev, port_num, IB_PMA_CLASS_PORT_INFO,
&cpi, 40, sizeof(cpi)) >= 0) {
if (cpi.capability_mask & IB_PMA_CLASS_CAP_EXT_WIDTH)
/* We have extended counters */
return &pma_group_ext;
if (cpi.capability_mask & IB_PMA_CLASS_CAP_EXT_WIDTH_NOIETF)
/* But not the IETF ones */
return &pma_group_noietf;
}
/* Fall back to normal counters */
return &pma_group;
}
static int update_hw_stats(struct ib_device *dev, struct rdma_hw_stats *stats,
u8 port_num, int index)
{
int ret;
if (time_is_after_eq_jiffies(stats->timestamp + stats->lifespan))
return 0;
ret = dev->get_hw_stats(dev, stats, port_num, index);
if (ret < 0)
return ret;
if (ret == stats->num_counters)
stats->timestamp = jiffies;
return 0;
}
static ssize_t print_hw_stat(struct rdma_hw_stats *stats, int index, char *buf)
{
return sprintf(buf, "%llu\n", stats->value[index]);
}
static ssize_t show_hw_stats(struct kobject *kobj, struct attribute *attr,
char *buf)
{
struct ib_device *dev;
struct ib_port *port;
struct hw_stats_attribute *hsa;
struct rdma_hw_stats *stats;
int ret;
hsa = container_of(attr, struct hw_stats_attribute, attr);
if (!hsa->port_num) {
dev = container_of((struct device *)kobj,
struct ib_device, dev);
stats = dev->hw_stats;
} else {
port = container_of(kobj, struct ib_port, kobj);
dev = port->ibdev;
stats = port->hw_stats;
}
ret = update_hw_stats(dev, stats, hsa->port_num, hsa->index);
if (ret)
return ret;
return print_hw_stat(stats, hsa->index, buf);
}
static ssize_t show_stats_lifespan(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
struct hw_stats_attribute *hsa;
int msecs;
hsa = container_of(attr, struct hw_stats_attribute, attr);
if (!hsa->port_num) {
struct ib_device *dev = container_of((struct device *)kobj,
struct ib_device, dev);
msecs = jiffies_to_msecs(dev->hw_stats->lifespan);
} else {
struct ib_port *p = container_of(kobj, struct ib_port, kobj);
msecs = jiffies_to_msecs(p->hw_stats->lifespan);
}
return sprintf(buf, "%d\n", msecs);
}
static ssize_t set_stats_lifespan(struct kobject *kobj,
struct attribute *attr,
const char *buf, size_t count)
{
struct hw_stats_attribute *hsa;
int msecs;
int jiffies;
int ret;
ret = kstrtoint(buf, 10, &msecs);
if (ret)
return ret;
if (msecs < 0 || msecs > 10000)
return -EINVAL;
jiffies = msecs_to_jiffies(msecs);
hsa = container_of(attr, struct hw_stats_attribute, attr);
if (!hsa->port_num) {
struct ib_device *dev = container_of((struct device *)kobj,
struct ib_device, dev);
dev->hw_stats->lifespan = jiffies;
} else {
struct ib_port *p = container_of(kobj, struct ib_port, kobj);
p->hw_stats->lifespan = jiffies;
}
return count;
}
static void free_hsag(struct kobject *kobj, struct attribute_group *attr_group)
{
struct attribute **attr;
sysfs_remove_group(kobj, attr_group);
for (attr = attr_group->attrs; *attr; attr++)
kfree(*attr);
kfree(attr_group);
}
static struct attribute *alloc_hsa(int index, u8 port_num, const char *name)
{
struct hw_stats_attribute *hsa;
hsa = kmalloc(sizeof(*hsa), GFP_KERNEL);
if (!hsa)
return NULL;
hsa->attr.name = (char *)name;
hsa->attr.mode = S_IRUGO;
hsa->show = show_hw_stats;
hsa->store = NULL;
hsa->index = index;
hsa->port_num = port_num;
return &hsa->attr;
}
static struct attribute *alloc_hsa_lifespan(char *name, u8 port_num)
{
struct hw_stats_attribute *hsa;
hsa = kmalloc(sizeof(*hsa), GFP_KERNEL);
if (!hsa)
return NULL;
hsa->attr.name = name;
hsa->attr.mode = S_IWUSR | S_IRUGO;
hsa->show = show_stats_lifespan;
hsa->store = set_stats_lifespan;
hsa->index = 0;
hsa->port_num = port_num;
return &hsa->attr;
}
static void setup_hw_stats(struct ib_device *device, struct ib_port *port,
u8 port_num)
{
struct attribute_group *hsag;
struct rdma_hw_stats *stats;
int i, ret;
stats = device->alloc_hw_stats(device, port_num);
if (!stats)
return;
if (!stats->names || stats->num_counters <= 0)
goto err_free_stats;
/*
* Two extra attribue elements here, one for the lifespan entry and
* one to NULL terminate the list for the sysfs core code
*/
hsag = kzalloc(sizeof(*hsag) +
sizeof(void *) * (stats->num_counters + 2),
GFP_KERNEL);
if (!hsag)
goto err_free_stats;
ret = device->get_hw_stats(device, stats, port_num,
stats->num_counters);
if (ret != stats->num_counters)
goto err_free_hsag;
stats->timestamp = jiffies;
hsag->name = "hw_counters";
hsag->attrs = (void *)hsag + sizeof(*hsag);
for (i = 0; i < stats->num_counters; i++) {
hsag->attrs[i] = alloc_hsa(i, port_num, stats->names[i]);
if (!hsag->attrs[i])
goto err;
sysfs_attr_init(hsag->attrs[i]);
}
/* treat an error here as non-fatal */
hsag->attrs[i] = alloc_hsa_lifespan("lifespan", port_num);
if (hsag->attrs[i])
sysfs_attr_init(hsag->attrs[i]);
if (port) {
struct kobject *kobj = &port->kobj;
ret = sysfs_create_group(kobj, hsag);
if (ret)
goto err;
port->hw_stats_ag = hsag;
port->hw_stats = stats;
} else {
struct kobject *kobj = &device->dev.kobj;
ret = sysfs_create_group(kobj, hsag);
if (ret)
goto err;
device->hw_stats_ag = hsag;
device->hw_stats = stats;
}
return;
err:
for (; i >= 0; i--)
kfree(hsag->attrs[i]);
err_free_hsag:
kfree(hsag);
err_free_stats:
kfree(stats);
return;
}
static int add_port(struct ib_device *device, int port_num,
int (*port_callback)(struct ib_device *,
u8, struct kobject *))
{
struct ib_port *p;
struct ib_port_attr attr;
int i;
int ret;
ret = ib_query_port(device, port_num, &attr);
if (ret)
return ret;
p = kzalloc(sizeof *p, GFP_KERNEL);
if (!p)
return -ENOMEM;
p->ibdev = device;
p->port_num = port_num;
ret = kobject_init_and_add(&p->kobj, &port_type,
device->ports_parent,
"%d", port_num);
if (ret) {
kfree(p);
return ret;
}
p->gid_attr_group = kzalloc(sizeof(*p->gid_attr_group), GFP_KERNEL);
if (!p->gid_attr_group) {
ret = -ENOMEM;
goto err_put;
}
p->gid_attr_group->port = p;
ret = kobject_init_and_add(&p->gid_attr_group->kobj, &gid_attr_type,
&p->kobj, "gid_attrs");
if (ret) {
kfree(p->gid_attr_group);
goto err_put;
}
p->pma_table = get_counter_table(device, port_num);
ret = sysfs_create_group(&p->kobj, p->pma_table);
if (ret)
goto err_put_gid_attrs;
p->gid_group.name = "gids";
p->gid_group.attrs = alloc_group_attrs(show_port_gid, attr.gid_tbl_len);
if (!p->gid_group.attrs) {
ret = -ENOMEM;
goto err_remove_pma;
}
ret = sysfs_create_group(&p->kobj, &p->gid_group);
if (ret)
goto err_free_gid;
p->gid_attr_group->ndev.name = "ndevs";
p->gid_attr_group->ndev.attrs = alloc_group_attrs(show_port_gid_attr_ndev,
attr.gid_tbl_len);
if (!p->gid_attr_group->ndev.attrs) {
ret = -ENOMEM;
goto err_remove_gid;
}
ret = sysfs_create_group(&p->gid_attr_group->kobj,
&p->gid_attr_group->ndev);
if (ret)
goto err_free_gid_ndev;
p->gid_attr_group->type.name = "types";
p->gid_attr_group->type.attrs = alloc_group_attrs(show_port_gid_attr_gid_type,
attr.gid_tbl_len);
if (!p->gid_attr_group->type.attrs) {
ret = -ENOMEM;
goto err_remove_gid_ndev;
}
ret = sysfs_create_group(&p->gid_attr_group->kobj,
&p->gid_attr_group->type);
if (ret)
goto err_free_gid_type;
p->pkey_group.name = "pkeys";
p->pkey_group.attrs = alloc_group_attrs(show_port_pkey,
attr.pkey_tbl_len);
if (!p->pkey_group.attrs) {
ret = -ENOMEM;
goto err_remove_gid_type;
}
ret = sysfs_create_group(&p->kobj, &p->pkey_group);
if (ret)
goto err_free_pkey;
if (port_callback) {
ret = port_callback(device, port_num, &p->kobj);
if (ret)
goto err_remove_pkey;
}
/*
* If port == 0, it means we have only one port and the parent
* device, not this port device, should be the holder of the
* hw_counters
*/
if (device->alloc_hw_stats && port_num)
setup_hw_stats(device, p, port_num);
list_add_tail(&p->kobj.entry, &device->port_list);
kobject_uevent(&p->kobj, KOBJ_ADD);
return 0;
err_remove_pkey:
sysfs_remove_group(&p->kobj, &p->pkey_group);
err_free_pkey:
for (i = 0; i < attr.pkey_tbl_len; ++i)
kfree(p->pkey_group.attrs[i]);
kfree(p->pkey_group.attrs);
p->pkey_group.attrs = NULL;
err_remove_gid_type:
sysfs_remove_group(&p->gid_attr_group->kobj,
&p->gid_attr_group->type);
err_free_gid_type:
for (i = 0; i < attr.gid_tbl_len; ++i)
kfree(p->gid_attr_group->type.attrs[i]);
kfree(p->gid_attr_group->type.attrs);
p->gid_attr_group->type.attrs = NULL;
err_remove_gid_ndev:
sysfs_remove_group(&p->gid_attr_group->kobj,
&p->gid_attr_group->ndev);
err_free_gid_ndev:
for (i = 0; i < attr.gid_tbl_len; ++i)
kfree(p->gid_attr_group->ndev.attrs[i]);
kfree(p->gid_attr_group->ndev.attrs);
p->gid_attr_group->ndev.attrs = NULL;
err_remove_gid:
sysfs_remove_group(&p->kobj, &p->gid_group);
err_free_gid:
for (i = 0; i < attr.gid_tbl_len; ++i)
kfree(p->gid_group.attrs[i]);
kfree(p->gid_group.attrs);
p->gid_group.attrs = NULL;
err_remove_pma:
sysfs_remove_group(&p->kobj, p->pma_table);
err_put_gid_attrs:
kobject_put(&p->gid_attr_group->kobj);
err_put:
kobject_put(&p->kobj);
return ret;
}
static ssize_t show_node_type(struct device *device,
struct device_attribute *attr, char *buf)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
switch (dev->node_type) {
case RDMA_NODE_IB_CA: return sprintf(buf, "%d: CA\n", dev->node_type);
case RDMA_NODE_RNIC: return sprintf(buf, "%d: RNIC\n", dev->node_type);
case RDMA_NODE_USNIC: return sprintf(buf, "%d: usNIC\n", dev->node_type);
case RDMA_NODE_USNIC_UDP: return sprintf(buf, "%d: usNIC UDP\n", dev->node_type);
case RDMA_NODE_IB_SWITCH: return sprintf(buf, "%d: switch\n", dev->node_type);
case RDMA_NODE_IB_ROUTER: return sprintf(buf, "%d: router\n", dev->node_type);
default: return sprintf(buf, "%d: <unknown>\n", dev->node_type);
}
}
static ssize_t show_sys_image_guid(struct device *device,
struct device_attribute *dev_attr, char *buf)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
return sprintf(buf, "%04x:%04x:%04x:%04x\n",
be16_to_cpu(((__be16 *) &dev->attrs.sys_image_guid)[0]),
be16_to_cpu(((__be16 *) &dev->attrs.sys_image_guid)[1]),
be16_to_cpu(((__be16 *) &dev->attrs.sys_image_guid)[2]),
be16_to_cpu(((__be16 *) &dev->attrs.sys_image_guid)[3]));
}
static ssize_t show_node_guid(struct device *device,
struct device_attribute *attr, char *buf)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
return sprintf(buf, "%04x:%04x:%04x:%04x\n",
be16_to_cpu(((__be16 *) &dev->node_guid)[0]),
be16_to_cpu(((__be16 *) &dev->node_guid)[1]),
be16_to_cpu(((__be16 *) &dev->node_guid)[2]),
be16_to_cpu(((__be16 *) &dev->node_guid)[3]));
}
static ssize_t show_node_desc(struct device *device,
struct device_attribute *attr, char *buf)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
return sprintf(buf, "%.64s\n", dev->node_desc);
}
static ssize_t set_node_desc(struct device *device,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
struct ib_device_modify desc = {};
int ret;
if (!dev->modify_device)
return -EIO;
memcpy(desc.node_desc, buf, min_t(int, count, 64));
ret = ib_modify_device(dev, IB_DEVICE_MODIFY_NODE_DESC, &desc);
if (ret)
return ret;
return count;
}
static ssize_t show_fw_ver(struct device *device, struct device_attribute *attr,
char *buf)
{
struct ib_device *dev = container_of(device, struct ib_device, dev);
ib_get_device_fw_str(dev, buf, PAGE_SIZE);
strlcat(buf, "\n", PAGE_SIZE);
return strlen(buf);
}
static DEVICE_ATTR(node_type, S_IRUGO, show_node_type, NULL);
static DEVICE_ATTR(sys_image_guid, S_IRUGO, show_sys_image_guid, NULL);
static DEVICE_ATTR(node_guid, S_IRUGO, show_node_guid, NULL);
static DEVICE_ATTR(node_desc, S_IRUGO | S_IWUSR, show_node_desc, set_node_desc);
static DEVICE_ATTR(fw_ver, S_IRUGO, show_fw_ver, NULL);
static struct device_attribute *ib_class_attributes[] = {
&dev_attr_node_type,
&dev_attr_sys_image_guid,
&dev_attr_node_guid,
&dev_attr_node_desc,
&dev_attr_fw_ver,
};
static void free_port_list_attributes(struct ib_device *device)
{
struct kobject *p, *t;
list_for_each_entry_safe(p, t, &device->port_list, entry) {
struct ib_port *port = container_of(p, struct ib_port, kobj);
list_del(&p->entry);
if (port->hw_stats) {
kfree(port->hw_stats);
free_hsag(&port->kobj, port->hw_stats_ag);
}
sysfs_remove_group(p, port->pma_table);
sysfs_remove_group(p, &port->pkey_group);
sysfs_remove_group(p, &port->gid_group);
sysfs_remove_group(&port->gid_attr_group->kobj,
&port->gid_attr_group->ndev);
sysfs_remove_group(&port->gid_attr_group->kobj,
&port->gid_attr_group->type);
kobject_put(&port->gid_attr_group->kobj);
kobject_put(p);
}
kobject_put(device->ports_parent);
}
int ib_device_register_sysfs(struct ib_device *device,
int (*port_callback)(struct ib_device *,
u8, struct kobject *))
{
struct device *class_dev = &device->dev;
int ret;
int i;
device->dev.parent = device->dma_device;
ret = dev_set_name(class_dev, "%s", device->name);
if (ret)
return ret;
ret = device_add(class_dev);
if (ret)
goto err;
for (i = 0; i < ARRAY_SIZE(ib_class_attributes); ++i) {
ret = device_create_file(class_dev, ib_class_attributes[i]);
if (ret)
goto err_unregister;
}
device->ports_parent = kobject_create_and_add("ports",
&class_dev->kobj);
if (!device->ports_parent) {
ret = -ENOMEM;
goto err_put;
}
if (rdma_cap_ib_switch(device)) {
ret = add_port(device, 0, port_callback);
if (ret)
goto err_put;
} else {
for (i = 1; i <= device->phys_port_cnt; ++i) {
ret = add_port(device, i, port_callback);
if (ret)
goto err_put;
}
}
if (device->alloc_hw_stats)
setup_hw_stats(device, NULL, 0);
return 0;
err_put:
free_port_list_attributes(device);
err_unregister:
device_unregister(class_dev);
err:
return ret;
}
void ib_device_unregister_sysfs(struct ib_device *device)
{
int i;
/* Hold kobject until ib_dealloc_device() */
kobject_get(&device->dev.kobj);
free_port_list_attributes(device);
if (device->hw_stats) {
kfree(device->hw_stats);
free_hsag(&device->dev.kobj, device->hw_stats_ag);
}
for (i = 0; i < ARRAY_SIZE(ib_class_attributes); ++i)
device_remove_file(&device->dev, ib_class_attributes[i]);
device_unregister(&device->dev);
}
| gpl-2.0 |
MatiasBjorling/lightnvm-moved-to-OpenChannelSSD-Linux | arch/mips/kernel/smp-cps.c | 49 | 8217 | /*
* Copyright (C) 2013 Imagination Technologies
* Author: Paul Burton <paul.burton@imgtec.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/io.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/smp.h>
#include <linux/types.h>
#include <asm/cacheflush.h>
#include <asm/gic.h>
#include <asm/mips-cm.h>
#include <asm/mips-cpc.h>
#include <asm/mips_mt.h>
#include <asm/mipsregs.h>
#include <asm/smp-cps.h>
#include <asm/time.h>
#include <asm/uasm.h>
static DECLARE_BITMAP(core_power, NR_CPUS);
struct boot_config mips_cps_bootcfg;
static void init_core(void)
{
unsigned int nvpes, t;
u32 mvpconf0, vpeconf0, vpecontrol, tcstatus, tcbind, status;
if (!cpu_has_mipsmt)
return;
/* Enter VPE configuration state */
dvpe();
set_c0_mvpcontrol(MVPCONTROL_VPC);
/* Retrieve the count of VPEs in this core */
mvpconf0 = read_c0_mvpconf0();
nvpes = ((mvpconf0 & MVPCONF0_PVPE) >> MVPCONF0_PVPE_SHIFT) + 1;
smp_num_siblings = nvpes;
for (t = 1; t < nvpes; t++) {
/* Use a 1:1 mapping of TC index to VPE index */
settc(t);
/* Bind 1 TC to this VPE */
tcbind = read_tc_c0_tcbind();
tcbind &= ~TCBIND_CURVPE;
tcbind |= t << TCBIND_CURVPE_SHIFT;
write_tc_c0_tcbind(tcbind);
/* Set exclusive TC, non-active, master */
vpeconf0 = read_vpe_c0_vpeconf0();
vpeconf0 &= ~(VPECONF0_XTC | VPECONF0_VPA);
vpeconf0 |= t << VPECONF0_XTC_SHIFT;
vpeconf0 |= VPECONF0_MVP;
write_vpe_c0_vpeconf0(vpeconf0);
/* Declare TC non-active, non-allocatable & interrupt exempt */
tcstatus = read_tc_c0_tcstatus();
tcstatus &= ~(TCSTATUS_A | TCSTATUS_DA);
tcstatus |= TCSTATUS_IXMT;
write_tc_c0_tcstatus(tcstatus);
/* Halt the TC */
write_tc_c0_tchalt(TCHALT_H);
/* Allow only 1 TC to execute */
vpecontrol = read_vpe_c0_vpecontrol();
vpecontrol &= ~VPECONTROL_TE;
write_vpe_c0_vpecontrol(vpecontrol);
/* Copy (most of) Status from VPE 0 */
status = read_c0_status();
status &= ~(ST0_IM | ST0_IE | ST0_KSU);
status |= ST0_CU0;
write_vpe_c0_status(status);
/* Copy Config from VPE 0 */
write_vpe_c0_config(read_c0_config());
write_vpe_c0_config7(read_c0_config7());
/* Ensure no software interrupts are pending */
write_vpe_c0_cause(0);
/* Sync Count */
write_vpe_c0_count(read_c0_count());
}
/* Leave VPE configuration state */
clear_c0_mvpcontrol(MVPCONTROL_VPC);
}
static void __init cps_smp_setup(void)
{
unsigned int ncores, nvpes, core_vpes;
int c, v;
u32 core_cfg, *entry_code;
/* Detect & record VPE topology */
ncores = mips_cm_numcores();
pr_info("VPE topology ");
for (c = nvpes = 0; c < ncores; c++) {
if (cpu_has_mipsmt && config_enabled(CONFIG_MIPS_MT_SMP)) {
write_gcr_cl_other(c << CM_GCR_Cx_OTHER_CORENUM_SHF);
core_cfg = read_gcr_co_config();
core_vpes = ((core_cfg & CM_GCR_Cx_CONFIG_PVPE_MSK) >>
CM_GCR_Cx_CONFIG_PVPE_SHF) + 1;
} else {
core_vpes = 1;
}
pr_cont("%c%u", c ? ',' : '{', core_vpes);
for (v = 0; v < min_t(int, core_vpes, NR_CPUS - nvpes); v++) {
cpu_data[nvpes + v].core = c;
#ifdef CONFIG_MIPS_MT_SMP
cpu_data[nvpes + v].vpe_id = v;
#endif
}
nvpes += core_vpes;
}
pr_cont("} total %u\n", nvpes);
/* Indicate present CPUs (CPU being synonymous with VPE) */
for (v = 0; v < min_t(unsigned, nvpes, NR_CPUS); v++) {
set_cpu_possible(v, true);
set_cpu_present(v, true);
__cpu_number_map[v] = v;
__cpu_logical_map[v] = v;
}
/* Core 0 is powered up (we're running on it) */
bitmap_set(core_power, 0, 1);
/* Disable MT - we only want to run 1 TC per VPE */
if (cpu_has_mipsmt)
dmt();
/* Initialise core 0 */
init_core();
/* Patch the start of mips_cps_core_entry to provide the CM base */
entry_code = (u32 *)&mips_cps_core_entry;
UASM_i_LA(&entry_code, 3, (long)mips_cm_base);
/* Make core 0 coherent with everything */
write_gcr_cl_coherence(0xff);
}
static void __init cps_prepare_cpus(unsigned int max_cpus)
{
mips_mt_set_cpuoptions();
}
static void boot_core(struct boot_config *cfg)
{
u32 access;
/* Select the appropriate core */
write_gcr_cl_other(cfg->core << CM_GCR_Cx_OTHER_CORENUM_SHF);
/* Set its reset vector */
write_gcr_co_reset_base(CKSEG1ADDR((unsigned long)mips_cps_core_entry));
/* Ensure its coherency is disabled */
write_gcr_co_coherence(0);
/* Ensure the core can access the GCRs */
access = read_gcr_access();
access |= 1 << (CM_GCR_ACCESS_ACCESSEN_SHF + cfg->core);
write_gcr_access(access);
/* Copy cfg */
mips_cps_bootcfg = *cfg;
if (mips_cpc_present()) {
/* Select the appropriate core */
write_cpc_cl_other(cfg->core << CPC_Cx_OTHER_CORENUM_SHF);
/* Reset the core */
write_cpc_co_cmd(CPC_Cx_CMD_RESET);
} else {
/* Take the core out of reset */
write_gcr_co_reset_release(0);
}
/* The core is now powered up */
bitmap_set(core_power, cfg->core, 1);
}
static void boot_vpe(void *info)
{
struct boot_config *cfg = info;
u32 tcstatus, vpeconf0;
/* Enter VPE configuration state */
dvpe();
set_c0_mvpcontrol(MVPCONTROL_VPC);
settc(cfg->vpe);
/* Set the TC restart PC */
write_tc_c0_tcrestart((unsigned long)&smp_bootstrap);
/* Activate the TC, allow interrupts */
tcstatus = read_tc_c0_tcstatus();
tcstatus &= ~TCSTATUS_IXMT;
tcstatus |= TCSTATUS_A;
write_tc_c0_tcstatus(tcstatus);
/* Clear the TC halt bit */
write_tc_c0_tchalt(0);
/* Activate the VPE */
vpeconf0 = read_vpe_c0_vpeconf0();
vpeconf0 |= VPECONF0_VPA;
write_vpe_c0_vpeconf0(vpeconf0);
/* Set the stack & global pointer registers */
write_tc_gpr_sp(cfg->sp);
write_tc_gpr_gp(cfg->gp);
/* Leave VPE configuration state */
clear_c0_mvpcontrol(MVPCONTROL_VPC);
/* Enable other VPEs to execute */
evpe(EVPE_ENABLE);
}
static void cps_boot_secondary(int cpu, struct task_struct *idle)
{
struct boot_config cfg;
unsigned int remote;
int err;
cfg.core = cpu_data[cpu].core;
cfg.vpe = cpu_vpe_id(&cpu_data[cpu]);
cfg.pc = (unsigned long)&smp_bootstrap;
cfg.sp = __KSTK_TOS(idle);
cfg.gp = (unsigned long)task_thread_info(idle);
if (!test_bit(cfg.core, core_power)) {
/* Boot a VPE on a powered down core */
boot_core(&cfg);
return;
}
if (cfg.core != current_cpu_data.core) {
/* Boot a VPE on another powered up core */
for (remote = 0; remote < NR_CPUS; remote++) {
if (cpu_data[remote].core != cfg.core)
continue;
if (cpu_online(remote))
break;
}
BUG_ON(remote >= NR_CPUS);
err = smp_call_function_single(remote, boot_vpe, &cfg, 1);
if (err)
panic("Failed to call remote CPU\n");
return;
}
BUG_ON(!cpu_has_mipsmt);
/* Boot a VPE on this core */
boot_vpe(&cfg);
}
static void cps_init_secondary(void)
{
/* Disable MT - we only want to run 1 TC per VPE */
if (cpu_has_mipsmt)
dmt();
/* TODO: revisit this assumption once hotplug is implemented */
if (cpu_vpe_id(¤t_cpu_data) == 0)
init_core();
change_c0_status(ST0_IM, STATUSF_IP3 | STATUSF_IP4 |
STATUSF_IP6 | STATUSF_IP7);
}
static void cps_smp_finish(void)
{
write_c0_compare(read_c0_count() + (8 * mips_hpt_frequency / HZ));
#ifdef CONFIG_MIPS_MT_FPAFF
/* If we have an FPU, enroll ourselves in the FPU-full mask */
if (cpu_has_fpu)
cpu_set(smp_processor_id(), mt_fpu_cpumask);
#endif /* CONFIG_MIPS_MT_FPAFF */
local_irq_enable();
}
static void cps_cpus_done(void)
{
}
static struct plat_smp_ops cps_smp_ops = {
.smp_setup = cps_smp_setup,
.prepare_cpus = cps_prepare_cpus,
.boot_secondary = cps_boot_secondary,
.init_secondary = cps_init_secondary,
.smp_finish = cps_smp_finish,
.send_ipi_single = gic_send_ipi_single,
.send_ipi_mask = gic_send_ipi_mask,
.cpus_done = cps_cpus_done,
};
int register_cps_smp_ops(void)
{
if (!mips_cm_present()) {
pr_warn("MIPS CPS SMP unable to proceed without a CM\n");
return -ENODEV;
}
/* check we have a GIC - we need one for IPIs */
if (!(read_gcr_gic_status() & CM_GCR_GIC_STATUS_EX_MSK)) {
pr_warn("MIPS CPS SMP unable to proceed without a GIC\n");
return -ENODEV;
}
register_smp_ops(&cps_smp_ops);
return 0;
}
| gpl-2.0 |
Pingmin/linux | drivers/media/platform/davinci/vpbe_display.c | 49 | 41383 | // SPDX-License-Identifier: GPL-2.0-only
/*
* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/string.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <linux/mm.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/slab.h>
#include <asm/pgtable.h>
#include <media/v4l2-dev.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-device.h>
#include <media/davinci/vpbe_display.h>
#include <media/davinci/vpbe_types.h>
#include <media/davinci/vpbe.h>
#include <media/davinci/vpbe_venc.h>
#include <media/davinci/vpbe_osd.h>
#include "vpbe_venc_regs.h"
#define VPBE_DISPLAY_DRIVER "vpbe-v4l2"
static int debug;
#define VPBE_DEFAULT_NUM_BUFS 3
module_param(debug, int, 0644);
static int vpbe_set_osd_display_params(struct vpbe_display *disp_dev,
struct vpbe_layer *layer);
static int venc_is_second_field(struct vpbe_display *disp_dev)
{
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
int ret, val;
ret = v4l2_subdev_call(vpbe_dev->venc,
core,
ioctl,
VENC_GET_FLD,
&val);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in getting Field ID 0\n");
return 1;
}
return val;
}
static void vpbe_isr_even_field(struct vpbe_display *disp_obj,
struct vpbe_layer *layer)
{
if (layer->cur_frm == layer->next_frm)
return;
layer->cur_frm->vb.vb2_buf.timestamp = ktime_get_ns();
vb2_buffer_done(&layer->cur_frm->vb.vb2_buf, VB2_BUF_STATE_DONE);
/* Make cur_frm pointing to next_frm */
layer->cur_frm = layer->next_frm;
}
static void vpbe_isr_odd_field(struct vpbe_display *disp_obj,
struct vpbe_layer *layer)
{
struct osd_state *osd_device = disp_obj->osd_device;
unsigned long addr;
spin_lock(&disp_obj->dma_queue_lock);
if (list_empty(&layer->dma_queue) ||
(layer->cur_frm != layer->next_frm)) {
spin_unlock(&disp_obj->dma_queue_lock);
return;
}
/*
* one field is displayed configure
* the next frame if it is available
* otherwise hold on current frame
* Get next from the buffer queue
*/
layer->next_frm = list_entry(layer->dma_queue.next,
struct vpbe_disp_buffer, list);
/* Remove that from the buffer queue */
list_del(&layer->next_frm->list);
spin_unlock(&disp_obj->dma_queue_lock);
/* Mark state of the frame to active */
layer->next_frm->vb.vb2_buf.state = VB2_BUF_STATE_ACTIVE;
addr = vb2_dma_contig_plane_dma_addr(&layer->next_frm->vb.vb2_buf, 0);
osd_device->ops.start_layer(osd_device,
layer->layer_info.id,
addr,
disp_obj->cbcr_ofst);
}
/* interrupt service routine */
static irqreturn_t venc_isr(int irq, void *arg)
{
struct vpbe_display *disp_dev = (struct vpbe_display *)arg;
struct vpbe_layer *layer;
static unsigned last_event;
unsigned event = 0;
int fid;
int i;
if (!arg || !disp_dev->dev[0])
return IRQ_HANDLED;
if (venc_is_second_field(disp_dev))
event |= VENC_SECOND_FIELD;
else
event |= VENC_FIRST_FIELD;
if (event == (last_event & ~VENC_END_OF_FRAME)) {
/*
* If the display is non-interlaced, then we need to flag the
* end-of-frame event at every interrupt regardless of the
* value of the FIDST bit. We can conclude that the display is
* non-interlaced if the value of the FIDST bit is unchanged
* from the previous interrupt.
*/
event |= VENC_END_OF_FRAME;
} else if (event == VENC_SECOND_FIELD) {
/* end-of-frame for interlaced display */
event |= VENC_END_OF_FRAME;
}
last_event = event;
for (i = 0; i < VPBE_DISPLAY_MAX_DEVICES; i++) {
layer = disp_dev->dev[i];
if (!vb2_start_streaming_called(&layer->buffer_queue))
continue;
if (layer->layer_first_int) {
layer->layer_first_int = 0;
continue;
}
/* Check the field format */
if ((V4L2_FIELD_NONE == layer->pix_fmt.field) &&
(event & VENC_END_OF_FRAME)) {
/* Progressive mode */
vpbe_isr_even_field(disp_dev, layer);
vpbe_isr_odd_field(disp_dev, layer);
} else {
/* Interlaced mode */
layer->field_id ^= 1;
if (event & VENC_FIRST_FIELD)
fid = 0;
else
fid = 1;
/*
* If field id does not match with store
* field id
*/
if (fid != layer->field_id) {
/* Make them in sync */
layer->field_id = fid;
continue;
}
/*
* device field id and local field id are
* in sync. If this is even field
*/
if (0 == fid)
vpbe_isr_even_field(disp_dev, layer);
else /* odd field */
vpbe_isr_odd_field(disp_dev, layer);
}
}
return IRQ_HANDLED;
}
/*
* vpbe_buffer_prepare()
* This is the callback function called from vb2_qbuf() function
* the buffer is prepared and user space virtual address is converted into
* physical address
*/
static int vpbe_buffer_prepare(struct vb2_buffer *vb)
{
struct vb2_queue *q = vb->vb2_queue;
struct vpbe_layer *layer = vb2_get_drv_priv(q);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
unsigned long addr;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"vpbe_buffer_prepare\n");
vb2_set_plane_payload(vb, 0, layer->pix_fmt.sizeimage);
if (vb2_get_plane_payload(vb, 0) > vb2_plane_size(vb, 0))
return -EINVAL;
addr = vb2_dma_contig_plane_dma_addr(vb, 0);
if (!IS_ALIGNED(addr, 8)) {
v4l2_err(&vpbe_dev->v4l2_dev,
"buffer_prepare:offset is not aligned to 32 bytes\n");
return -EINVAL;
}
return 0;
}
/*
* vpbe_buffer_setup()
* This function allocates memory for the buffers
*/
static int
vpbe_buffer_queue_setup(struct vb2_queue *vq,
unsigned int *nbuffers, unsigned int *nplanes,
unsigned int sizes[], struct device *alloc_devs[])
{
/* Get the file handle object and layer object */
struct vpbe_layer *layer = vb2_get_drv_priv(vq);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "vpbe_buffer_setup\n");
/* Store number of buffers allocated in numbuffer member */
if (vq->num_buffers + *nbuffers < VPBE_DEFAULT_NUM_BUFS)
*nbuffers = VPBE_DEFAULT_NUM_BUFS - vq->num_buffers;
if (*nplanes)
return sizes[0] < layer->pix_fmt.sizeimage ? -EINVAL : 0;
*nplanes = 1;
sizes[0] = layer->pix_fmt.sizeimage;
return 0;
}
/*
* vpbe_buffer_queue()
* This function adds the buffer to DMA queue
*/
static void vpbe_buffer_queue(struct vb2_buffer *vb)
{
struct vb2_v4l2_buffer *vbuf = to_vb2_v4l2_buffer(vb);
/* Get the file handle object and layer object */
struct vpbe_disp_buffer *buf = container_of(vbuf,
struct vpbe_disp_buffer, vb);
struct vpbe_layer *layer = vb2_get_drv_priv(vb->vb2_queue);
struct vpbe_display *disp = layer->disp_dev;
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
unsigned long flags;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"vpbe_buffer_queue\n");
/* add the buffer to the DMA queue */
spin_lock_irqsave(&disp->dma_queue_lock, flags);
list_add_tail(&buf->list, &layer->dma_queue);
spin_unlock_irqrestore(&disp->dma_queue_lock, flags);
}
static int vpbe_start_streaming(struct vb2_queue *vq, unsigned int count)
{
struct vpbe_layer *layer = vb2_get_drv_priv(vq);
struct osd_state *osd_device = layer->disp_dev->osd_device;
int ret;
osd_device->ops.disable_layer(osd_device, layer->layer_info.id);
/* Get the next frame from the buffer queue */
layer->next_frm = layer->cur_frm = list_entry(layer->dma_queue.next,
struct vpbe_disp_buffer, list);
/* Remove buffer from the buffer queue */
list_del(&layer->cur_frm->list);
/* Mark state of the current frame to active */
layer->cur_frm->vb.vb2_buf.state = VB2_BUF_STATE_ACTIVE;
/* Initialize field_id and started member */
layer->field_id = 0;
/* Set parameters in OSD and VENC */
ret = vpbe_set_osd_display_params(layer->disp_dev, layer);
if (ret < 0) {
struct vpbe_disp_buffer *buf, *tmp;
vb2_buffer_done(&layer->cur_frm->vb.vb2_buf,
VB2_BUF_STATE_QUEUED);
list_for_each_entry_safe(buf, tmp, &layer->dma_queue, list) {
list_del(&buf->list);
vb2_buffer_done(&buf->vb.vb2_buf,
VB2_BUF_STATE_QUEUED);
}
return ret;
}
/*
* if request format is yuv420 semiplanar, need to
* enable both video windows
*/
layer->layer_first_int = 1;
return ret;
}
static void vpbe_stop_streaming(struct vb2_queue *vq)
{
struct vpbe_layer *layer = vb2_get_drv_priv(vq);
struct osd_state *osd_device = layer->disp_dev->osd_device;
struct vpbe_display *disp = layer->disp_dev;
unsigned long flags;
if (!vb2_is_streaming(vq))
return;
osd_device->ops.disable_layer(osd_device, layer->layer_info.id);
/* release all active buffers */
spin_lock_irqsave(&disp->dma_queue_lock, flags);
if (layer->cur_frm == layer->next_frm) {
vb2_buffer_done(&layer->cur_frm->vb.vb2_buf,
VB2_BUF_STATE_ERROR);
} else {
if (layer->cur_frm)
vb2_buffer_done(&layer->cur_frm->vb.vb2_buf,
VB2_BUF_STATE_ERROR);
if (layer->next_frm)
vb2_buffer_done(&layer->next_frm->vb.vb2_buf,
VB2_BUF_STATE_ERROR);
}
while (!list_empty(&layer->dma_queue)) {
layer->next_frm = list_entry(layer->dma_queue.next,
struct vpbe_disp_buffer, list);
list_del(&layer->next_frm->list);
vb2_buffer_done(&layer->next_frm->vb.vb2_buf,
VB2_BUF_STATE_ERROR);
}
spin_unlock_irqrestore(&disp->dma_queue_lock, flags);
}
static const struct vb2_ops video_qops = {
.queue_setup = vpbe_buffer_queue_setup,
.wait_prepare = vb2_ops_wait_prepare,
.wait_finish = vb2_ops_wait_finish,
.buf_prepare = vpbe_buffer_prepare,
.start_streaming = vpbe_start_streaming,
.stop_streaming = vpbe_stop_streaming,
.buf_queue = vpbe_buffer_queue,
};
static
struct vpbe_layer*
_vpbe_display_get_other_win_layer(struct vpbe_display *disp_dev,
struct vpbe_layer *layer)
{
enum vpbe_display_device_id thiswin, otherwin;
thiswin = layer->device_id;
otherwin = (thiswin == VPBE_DISPLAY_DEVICE_0) ?
VPBE_DISPLAY_DEVICE_1 : VPBE_DISPLAY_DEVICE_0;
return disp_dev->dev[otherwin];
}
static int vpbe_set_osd_display_params(struct vpbe_display *disp_dev,
struct vpbe_layer *layer)
{
struct osd_layer_config *cfg = &layer->layer_info.config;
struct osd_state *osd_device = disp_dev->osd_device;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
unsigned long addr;
int ret;
addr = vb2_dma_contig_plane_dma_addr(&layer->cur_frm->vb.vb2_buf, 0);
/* Set address in the display registers */
osd_device->ops.start_layer(osd_device,
layer->layer_info.id,
addr,
disp_dev->cbcr_ofst);
ret = osd_device->ops.enable_layer(osd_device,
layer->layer_info.id, 0);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in enabling osd window layer 0\n");
return -1;
}
/* Enable the window */
layer->layer_info.enable = 1;
if (cfg->pixfmt == PIXFMT_NV12) {
struct vpbe_layer *otherlayer =
_vpbe_display_get_other_win_layer(disp_dev, layer);
ret = osd_device->ops.enable_layer(osd_device,
otherlayer->layer_info.id, 1);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in enabling osd window layer 1\n");
return -1;
}
otherlayer->layer_info.enable = 1;
}
return 0;
}
static void
vpbe_disp_calculate_scale_factor(struct vpbe_display *disp_dev,
struct vpbe_layer *layer,
int expected_xsize, int expected_ysize)
{
struct display_layer_info *layer_info = &layer->layer_info;
struct v4l2_pix_format *pixfmt = &layer->pix_fmt;
struct osd_layer_config *cfg = &layer->layer_info.config;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
int calculated_xsize;
int h_exp = 0;
int v_exp = 0;
int h_scale;
int v_scale;
v4l2_std_id standard_id = vpbe_dev->current_timings.std_id;
/*
* Application initially set the image format. Current display
* size is obtained from the vpbe display controller. expected_xsize
* and expected_ysize are set through S_SELECTION ioctl. Based on this,
* driver will calculate the scale factors for vertical and
* horizontal direction so that the image is displayed scaled
* and expanded. Application uses expansion to display the image
* in a square pixel. Otherwise it is displayed using displays
* pixel aspect ratio.It is expected that application chooses
* the crop coordinates for cropped or scaled display. if crop
* size is less than the image size, it is displayed cropped or
* it is displayed scaled and/or expanded.
*
* to begin with, set the crop window same as expected. Later we
* will override with scaled window size
*/
cfg->xsize = pixfmt->width;
cfg->ysize = pixfmt->height;
layer_info->h_zoom = ZOOM_X1; /* no horizontal zoom */
layer_info->v_zoom = ZOOM_X1; /* no horizontal zoom */
layer_info->h_exp = H_EXP_OFF; /* no horizontal zoom */
layer_info->v_exp = V_EXP_OFF; /* no horizontal zoom */
if (pixfmt->width < expected_xsize) {
h_scale = vpbe_dev->current_timings.xres / pixfmt->width;
if (h_scale < 2)
h_scale = 1;
else if (h_scale >= 4)
h_scale = 4;
else
h_scale = 2;
cfg->xsize *= h_scale;
if (cfg->xsize < expected_xsize) {
if ((standard_id & V4L2_STD_525_60) ||
(standard_id & V4L2_STD_625_50)) {
calculated_xsize = (cfg->xsize *
VPBE_DISPLAY_H_EXP_RATIO_N) /
VPBE_DISPLAY_H_EXP_RATIO_D;
if (calculated_xsize <= expected_xsize) {
h_exp = 1;
cfg->xsize = calculated_xsize;
}
}
}
if (h_scale == 2)
layer_info->h_zoom = ZOOM_X2;
else if (h_scale == 4)
layer_info->h_zoom = ZOOM_X4;
if (h_exp)
layer_info->h_exp = H_EXP_9_OVER_8;
} else {
/* no scaling, only cropping. Set display area to crop area */
cfg->xsize = expected_xsize;
}
if (pixfmt->height < expected_ysize) {
v_scale = expected_ysize / pixfmt->height;
if (v_scale < 2)
v_scale = 1;
else if (v_scale >= 4)
v_scale = 4;
else
v_scale = 2;
cfg->ysize *= v_scale;
if (cfg->ysize < expected_ysize) {
if ((standard_id & V4L2_STD_625_50)) {
calculated_xsize = (cfg->ysize *
VPBE_DISPLAY_V_EXP_RATIO_N) /
VPBE_DISPLAY_V_EXP_RATIO_D;
if (calculated_xsize <= expected_ysize) {
v_exp = 1;
cfg->ysize = calculated_xsize;
}
}
}
if (v_scale == 2)
layer_info->v_zoom = ZOOM_X2;
else if (v_scale == 4)
layer_info->v_zoom = ZOOM_X4;
if (v_exp)
layer_info->v_exp = V_EXP_6_OVER_5;
} else {
/* no scaling, only cropping. Set display area to crop area */
cfg->ysize = expected_ysize;
}
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"crop display xsize = %d, ysize = %d\n",
cfg->xsize, cfg->ysize);
}
static void vpbe_disp_adj_position(struct vpbe_display *disp_dev,
struct vpbe_layer *layer,
int top, int left)
{
struct osd_layer_config *cfg = &layer->layer_info.config;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
cfg->xpos = min((unsigned int)left,
vpbe_dev->current_timings.xres - cfg->xsize);
cfg->ypos = min((unsigned int)top,
vpbe_dev->current_timings.yres - cfg->ysize);
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"new xpos = %d, ypos = %d\n",
cfg->xpos, cfg->ypos);
}
static void vpbe_disp_check_window_params(struct vpbe_display *disp_dev,
struct v4l2_rect *c)
{
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
if ((c->width == 0) ||
((c->width + c->left) > vpbe_dev->current_timings.xres))
c->width = vpbe_dev->current_timings.xres - c->left;
if ((c->height == 0) || ((c->height + c->top) >
vpbe_dev->current_timings.yres))
c->height = vpbe_dev->current_timings.yres - c->top;
/* window height must be even for interlaced display */
if (vpbe_dev->current_timings.interlaced)
c->height &= (~0x01);
}
/*
* vpbe_try_format()
* If user application provides width and height, and have bytesperline set
* to zero, driver calculates bytesperline and sizeimage based on hardware
* limits.
*/
static int vpbe_try_format(struct vpbe_display *disp_dev,
struct v4l2_pix_format *pixfmt, int check)
{
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
int min_height = 1;
int min_width = 32;
int max_height;
int max_width;
int bpp;
if ((pixfmt->pixelformat != V4L2_PIX_FMT_UYVY) &&
(pixfmt->pixelformat != V4L2_PIX_FMT_NV12))
/* choose default as V4L2_PIX_FMT_UYVY */
pixfmt->pixelformat = V4L2_PIX_FMT_UYVY;
/* Check the field format */
if ((pixfmt->field != V4L2_FIELD_INTERLACED) &&
(pixfmt->field != V4L2_FIELD_NONE)) {
if (vpbe_dev->current_timings.interlaced)
pixfmt->field = V4L2_FIELD_INTERLACED;
else
pixfmt->field = V4L2_FIELD_NONE;
}
if (pixfmt->field == V4L2_FIELD_INTERLACED)
min_height = 2;
if (pixfmt->pixelformat == V4L2_PIX_FMT_NV12)
bpp = 1;
else
bpp = 2;
max_width = vpbe_dev->current_timings.xres;
max_height = vpbe_dev->current_timings.yres;
min_width /= bpp;
if (!pixfmt->width || (pixfmt->width < min_width) ||
(pixfmt->width > max_width)) {
pixfmt->width = vpbe_dev->current_timings.xres;
}
if (!pixfmt->height || (pixfmt->height < min_height) ||
(pixfmt->height > max_height)) {
pixfmt->height = vpbe_dev->current_timings.yres;
}
if (pixfmt->bytesperline < (pixfmt->width * bpp))
pixfmt->bytesperline = pixfmt->width * bpp;
/* Make the bytesperline 32 byte aligned */
pixfmt->bytesperline = ((pixfmt->width * bpp + 31) & ~31);
if (pixfmt->pixelformat == V4L2_PIX_FMT_NV12)
pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height +
(pixfmt->bytesperline * pixfmt->height >> 1);
else
pixfmt->sizeimage = pixfmt->bytesperline * pixfmt->height;
return 0;
}
static int vpbe_display_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
snprintf(cap->driver, sizeof(cap->driver), "%s",
dev_name(vpbe_dev->pdev));
snprintf(cap->bus_info, sizeof(cap->bus_info), "platform:%s",
dev_name(vpbe_dev->pdev));
strscpy(cap->card, vpbe_dev->cfg->module_name, sizeof(cap->card));
return 0;
}
static int vpbe_display_s_selection(struct file *file, void *priv,
struct v4l2_selection *sel)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_display *disp_dev = layer->disp_dev;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
struct osd_layer_config *cfg = &layer->layer_info.config;
struct osd_state *osd_device = disp_dev->osd_device;
struct v4l2_rect rect = sel->r;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"VIDIOC_S_SELECTION, layer id = %d\n", layer->device_id);
if (sel->type != V4L2_BUF_TYPE_VIDEO_OUTPUT ||
sel->target != V4L2_SEL_TGT_CROP)
return -EINVAL;
if (rect.top < 0)
rect.top = 0;
if (rect.left < 0)
rect.left = 0;
vpbe_disp_check_window_params(disp_dev, &rect);
osd_device->ops.get_layer_config(osd_device,
layer->layer_info.id, cfg);
vpbe_disp_calculate_scale_factor(disp_dev, layer,
rect.width,
rect.height);
vpbe_disp_adj_position(disp_dev, layer, rect.top,
rect.left);
ret = osd_device->ops.set_layer_config(osd_device,
layer->layer_info.id, cfg);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in set layer config:\n");
return -EINVAL;
}
/* apply zooming and h or v expansion */
osd_device->ops.set_zoom(osd_device,
layer->layer_info.id,
layer->layer_info.h_zoom,
layer->layer_info.v_zoom);
ret = osd_device->ops.set_vid_expansion(osd_device,
layer->layer_info.h_exp,
layer->layer_info.v_exp);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in set vid expansion:\n");
return -EINVAL;
}
if ((layer->layer_info.h_zoom != ZOOM_X1) ||
(layer->layer_info.v_zoom != ZOOM_X1) ||
(layer->layer_info.h_exp != H_EXP_OFF) ||
(layer->layer_info.v_exp != V_EXP_OFF))
/* Enable expansion filter */
osd_device->ops.set_interpolation_filter(osd_device, 1);
else
osd_device->ops.set_interpolation_filter(osd_device, 0);
sel->r = rect;
return 0;
}
static int vpbe_display_g_selection(struct file *file, void *priv,
struct v4l2_selection *sel)
{
struct vpbe_layer *layer = video_drvdata(file);
struct osd_layer_config *cfg = &layer->layer_info.config;
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
struct osd_state *osd_device = layer->disp_dev->osd_device;
struct v4l2_rect *rect = &sel->r;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"VIDIOC_G_SELECTION, layer id = %d\n",
layer->device_id);
if (sel->type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
return -EINVAL;
switch (sel->target) {
case V4L2_SEL_TGT_CROP:
osd_device->ops.get_layer_config(osd_device,
layer->layer_info.id, cfg);
rect->top = cfg->ypos;
rect->left = cfg->xpos;
rect->width = cfg->xsize;
rect->height = cfg->ysize;
break;
case V4L2_SEL_TGT_CROP_DEFAULT:
case V4L2_SEL_TGT_CROP_BOUNDS:
rect->left = 0;
rect->top = 0;
rect->width = vpbe_dev->current_timings.xres;
rect->height = vpbe_dev->current_timings.yres;
break;
default:
return -EINVAL;
}
return 0;
}
static int vpbe_display_g_pixelaspect(struct file *file, void *priv,
int type, struct v4l2_fract *f)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_CROPCAP ioctl\n");
if (type != V4L2_BUF_TYPE_VIDEO_OUTPUT)
return -EINVAL;
*f = vpbe_dev->current_timings.aspect;
return 0;
}
static int vpbe_display_g_fmt(struct file *file, void *priv,
struct v4l2_format *fmt)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"VIDIOC_G_FMT, layer id = %d\n",
layer->device_id);
/* If buffer type is video output */
if (V4L2_BUF_TYPE_VIDEO_OUTPUT != fmt->type) {
v4l2_err(&vpbe_dev->v4l2_dev, "invalid type\n");
return -EINVAL;
}
/* Fill in the information about format */
fmt->fmt.pix = layer->pix_fmt;
return 0;
}
static int vpbe_display_enum_fmt(struct file *file, void *priv,
struct v4l2_fmtdesc *fmt)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"VIDIOC_ENUM_FMT, layer id = %d\n",
layer->device_id);
if (fmt->index > 1) {
v4l2_err(&vpbe_dev->v4l2_dev, "Invalid format index\n");
return -EINVAL;
}
/* Fill in the information about format */
if (fmt->index == 0)
fmt->pixelformat = V4L2_PIX_FMT_UYVY;
else
fmt->pixelformat = V4L2_PIX_FMT_NV12;
return 0;
}
static int vpbe_display_s_fmt(struct file *file, void *priv,
struct v4l2_format *fmt)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_display *disp_dev = layer->disp_dev;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
struct osd_layer_config *cfg = &layer->layer_info.config;
struct v4l2_pix_format *pixfmt = &fmt->fmt.pix;
struct osd_state *osd_device = disp_dev->osd_device;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"VIDIOC_S_FMT, layer id = %d\n",
layer->device_id);
if (vb2_is_busy(&layer->buffer_queue))
return -EBUSY;
if (V4L2_BUF_TYPE_VIDEO_OUTPUT != fmt->type) {
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "invalid type\n");
return -EINVAL;
}
/* Check for valid pixel format */
ret = vpbe_try_format(disp_dev, pixfmt, 1);
if (ret)
return ret;
/* YUV420 is requested, check availability of the
other video window */
layer->pix_fmt = *pixfmt;
if (pixfmt->pixelformat == V4L2_PIX_FMT_NV12) {
struct vpbe_layer *otherlayer;
otherlayer = _vpbe_display_get_other_win_layer(disp_dev, layer);
/* if other layer is available, only
* claim it, do not configure it
*/
ret = osd_device->ops.request_layer(osd_device,
otherlayer->layer_info.id);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Display Manager failed to allocate layer\n");
return -EBUSY;
}
}
/* Get osd layer config */
osd_device->ops.get_layer_config(osd_device,
layer->layer_info.id, cfg);
/* Store the pixel format in the layer object */
cfg->xsize = pixfmt->width;
cfg->ysize = pixfmt->height;
cfg->line_length = pixfmt->bytesperline;
cfg->ypos = 0;
cfg->xpos = 0;
cfg->interlaced = vpbe_dev->current_timings.interlaced;
if (V4L2_PIX_FMT_UYVY == pixfmt->pixelformat)
cfg->pixfmt = PIXFMT_YCBCRI;
/* Change of the default pixel format for both video windows */
if (V4L2_PIX_FMT_NV12 == pixfmt->pixelformat) {
struct vpbe_layer *otherlayer;
cfg->pixfmt = PIXFMT_NV12;
otherlayer = _vpbe_display_get_other_win_layer(disp_dev,
layer);
otherlayer->layer_info.config.pixfmt = PIXFMT_NV12;
}
/* Set the layer config in the osd window */
ret = osd_device->ops.set_layer_config(osd_device,
layer->layer_info.id, cfg);
if (ret < 0) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Error in S_FMT params:\n");
return -EINVAL;
}
/* Readback and fill the local copy of current pix format */
osd_device->ops.get_layer_config(osd_device,
layer->layer_info.id, cfg);
return 0;
}
static int vpbe_display_try_fmt(struct file *file, void *priv,
struct v4l2_format *fmt)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_display *disp_dev = layer->disp_dev;
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
struct v4l2_pix_format *pixfmt = &fmt->fmt.pix;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_TRY_FMT\n");
if (V4L2_BUF_TYPE_VIDEO_OUTPUT != fmt->type) {
v4l2_err(&vpbe_dev->v4l2_dev, "invalid type\n");
return -EINVAL;
}
/* Check for valid field format */
return vpbe_try_format(disp_dev, pixfmt, 0);
}
/*
* vpbe_display_s_std - Set the given standard in the encoder
*
* Sets the standard if supported by the current encoder. Return the status.
* 0 - success & -EINVAL on error
*/
static int vpbe_display_s_std(struct file *file, void *priv,
v4l2_std_id std_id)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_S_STD\n");
if (vb2_is_busy(&layer->buffer_queue))
return -EBUSY;
if (vpbe_dev->ops.s_std) {
ret = vpbe_dev->ops.s_std(vpbe_dev, std_id);
if (ret) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Failed to set standard for sub devices\n");
return -EINVAL;
}
} else {
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_g_std - Get the standard in the current encoder
*
* Get the standard in the current encoder. Return the status. 0 - success
* -EINVAL on error
*/
static int vpbe_display_g_std(struct file *file, void *priv,
v4l2_std_id *std_id)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_G_STD\n");
/* Get the standard from the current encoder */
if (vpbe_dev->current_timings.timings_type & VPBE_ENC_STD) {
*std_id = vpbe_dev->current_timings.std_id;
return 0;
}
return -EINVAL;
}
/*
* vpbe_display_enum_output - enumerate outputs
*
* Enumerates the outputs available at the vpbe display
* returns the status, -EINVAL if end of output list
*/
static int vpbe_display_enum_output(struct file *file, void *priv,
struct v4l2_output *output)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_ENUM_OUTPUT\n");
/* Enumerate outputs */
if (!vpbe_dev->ops.enum_outputs)
return -EINVAL;
ret = vpbe_dev->ops.enum_outputs(vpbe_dev, output);
if (ret) {
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"Failed to enumerate outputs\n");
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_s_output - Set output to
* the output specified by the index
*/
static int vpbe_display_s_output(struct file *file, void *priv,
unsigned int i)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_S_OUTPUT\n");
if (vb2_is_busy(&layer->buffer_queue))
return -EBUSY;
if (!vpbe_dev->ops.set_output)
return -EINVAL;
ret = vpbe_dev->ops.set_output(vpbe_dev, i);
if (ret) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Failed to set output for sub devices\n");
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_g_output - Get output from subdevice
* for a given by the index
*/
static int vpbe_display_g_output(struct file *file, void *priv,
unsigned int *i)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_G_OUTPUT\n");
/* Get the standard from the current encoder */
*i = vpbe_dev->current_out_index;
return 0;
}
/*
* vpbe_display_enum_dv_timings - Enumerate the dv timings
*
* enum the timings in the current encoder. Return the status. 0 - success
* -EINVAL on error
*/
static int
vpbe_display_enum_dv_timings(struct file *file, void *priv,
struct v4l2_enum_dv_timings *timings)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_ENUM_DV_TIMINGS\n");
/* Enumerate outputs */
if (!vpbe_dev->ops.enum_dv_timings)
return -EINVAL;
ret = vpbe_dev->ops.enum_dv_timings(vpbe_dev, timings);
if (ret) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Failed to enumerate dv timings info\n");
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_s_dv_timings - Set the dv timings
*
* Set the timings in the current encoder. Return the status. 0 - success
* -EINVAL on error
*/
static int
vpbe_display_s_dv_timings(struct file *file, void *priv,
struct v4l2_dv_timings *timings)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
int ret;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_S_DV_TIMINGS\n");
if (vb2_is_busy(&layer->buffer_queue))
return -EBUSY;
/* Set the given standard in the encoder */
if (!vpbe_dev->ops.s_dv_timings)
return -EINVAL;
ret = vpbe_dev->ops.s_dv_timings(vpbe_dev, timings);
if (ret) {
v4l2_err(&vpbe_dev->v4l2_dev,
"Failed to set the dv timings info\n");
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_g_dv_timings - Set the dv timings
*
* Get the timings in the current encoder. Return the status. 0 - success
* -EINVAL on error
*/
static int
vpbe_display_g_dv_timings(struct file *file, void *priv,
struct v4l2_dv_timings *dv_timings)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_device *vpbe_dev = layer->disp_dev->vpbe_dev;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "VIDIOC_G_DV_TIMINGS\n");
/* Get the given standard in the encoder */
if (vpbe_dev->current_timings.timings_type &
VPBE_ENC_DV_TIMINGS) {
*dv_timings = vpbe_dev->current_timings.dv_timings;
} else {
return -EINVAL;
}
return 0;
}
/*
* vpbe_display_open()
* It creates object of file handle structure and stores it in private_data
* member of filepointer
*/
static int vpbe_display_open(struct file *file)
{
struct vpbe_layer *layer = video_drvdata(file);
struct vpbe_display *disp_dev = layer->disp_dev;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
struct osd_state *osd_device = disp_dev->osd_device;
int err;
/* creating context for file descriptor */
err = v4l2_fh_open(file);
if (err) {
v4l2_err(&vpbe_dev->v4l2_dev, "v4l2_fh_open failed\n");
return err;
}
/* leaving if layer is already initialized */
if (!v4l2_fh_is_singular_file(file))
return err;
if (!layer->usrs) {
if (mutex_lock_interruptible(&layer->opslock))
return -ERESTARTSYS;
/* First claim the layer for this device */
err = osd_device->ops.request_layer(osd_device,
layer->layer_info.id);
mutex_unlock(&layer->opslock);
if (err < 0) {
/* Couldn't get layer */
v4l2_err(&vpbe_dev->v4l2_dev,
"Display Manager failed to allocate layer\n");
v4l2_fh_release(file);
return -EINVAL;
}
}
/* Increment layer usrs counter */
layer->usrs++;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev,
"vpbe display device opened successfully\n");
return 0;
}
/*
* vpbe_display_release()
* This function deletes buffer queue, frees the buffers and the davinci
* display file * handle
*/
static int vpbe_display_release(struct file *file)
{
struct vpbe_layer *layer = video_drvdata(file);
struct osd_layer_config *cfg = &layer->layer_info.config;
struct vpbe_display *disp_dev = layer->disp_dev;
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
struct osd_state *osd_device = disp_dev->osd_device;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "vpbe_display_release\n");
mutex_lock(&layer->opslock);
osd_device->ops.disable_layer(osd_device,
layer->layer_info.id);
/* Decrement layer usrs counter */
layer->usrs--;
/* If this file handle has initialize encoder device, reset it */
if (!layer->usrs) {
if (cfg->pixfmt == PIXFMT_NV12) {
struct vpbe_layer *otherlayer;
otherlayer =
_vpbe_display_get_other_win_layer(disp_dev, layer);
osd_device->ops.disable_layer(osd_device,
otherlayer->layer_info.id);
osd_device->ops.release_layer(osd_device,
otherlayer->layer_info.id);
}
osd_device->ops.disable_layer(osd_device,
layer->layer_info.id);
osd_device->ops.release_layer(osd_device,
layer->layer_info.id);
}
_vb2_fop_release(file, NULL);
mutex_unlock(&layer->opslock);
disp_dev->cbcr_ofst = 0;
return 0;
}
/* vpbe capture ioctl operations */
static const struct v4l2_ioctl_ops vpbe_ioctl_ops = {
.vidioc_querycap = vpbe_display_querycap,
.vidioc_g_fmt_vid_out = vpbe_display_g_fmt,
.vidioc_enum_fmt_vid_out = vpbe_display_enum_fmt,
.vidioc_s_fmt_vid_out = vpbe_display_s_fmt,
.vidioc_try_fmt_vid_out = vpbe_display_try_fmt,
.vidioc_reqbufs = vb2_ioctl_reqbufs,
.vidioc_create_bufs = vb2_ioctl_create_bufs,
.vidioc_querybuf = vb2_ioctl_querybuf,
.vidioc_qbuf = vb2_ioctl_qbuf,
.vidioc_dqbuf = vb2_ioctl_dqbuf,
.vidioc_streamon = vb2_ioctl_streamon,
.vidioc_streamoff = vb2_ioctl_streamoff,
.vidioc_expbuf = vb2_ioctl_expbuf,
.vidioc_g_pixelaspect = vpbe_display_g_pixelaspect,
.vidioc_g_selection = vpbe_display_g_selection,
.vidioc_s_selection = vpbe_display_s_selection,
.vidioc_s_std = vpbe_display_s_std,
.vidioc_g_std = vpbe_display_g_std,
.vidioc_enum_output = vpbe_display_enum_output,
.vidioc_s_output = vpbe_display_s_output,
.vidioc_g_output = vpbe_display_g_output,
.vidioc_s_dv_timings = vpbe_display_s_dv_timings,
.vidioc_g_dv_timings = vpbe_display_g_dv_timings,
.vidioc_enum_dv_timings = vpbe_display_enum_dv_timings,
};
static const struct v4l2_file_operations vpbe_fops = {
.owner = THIS_MODULE,
.open = vpbe_display_open,
.release = vpbe_display_release,
.unlocked_ioctl = video_ioctl2,
.mmap = vb2_fop_mmap,
.poll = vb2_fop_poll,
};
static int vpbe_device_get(struct device *dev, void *data)
{
struct platform_device *pdev = to_platform_device(dev);
struct vpbe_display *vpbe_disp = data;
if (strcmp("vpbe_controller", pdev->name) == 0)
vpbe_disp->vpbe_dev = platform_get_drvdata(pdev);
if (strstr(pdev->name, "vpbe-osd"))
vpbe_disp->osd_device = platform_get_drvdata(pdev);
return 0;
}
static int init_vpbe_layer(int i, struct vpbe_display *disp_dev,
struct platform_device *pdev)
{
struct vpbe_layer *vpbe_display_layer = NULL;
struct video_device *vbd = NULL;
/* Allocate memory for four plane display objects */
disp_dev->dev[i] = kzalloc(sizeof(*disp_dev->dev[i]), GFP_KERNEL);
if (!disp_dev->dev[i])
return -ENOMEM;
spin_lock_init(&disp_dev->dev[i]->irqlock);
mutex_init(&disp_dev->dev[i]->opslock);
/* Get the pointer to the layer object */
vpbe_display_layer = disp_dev->dev[i];
vbd = &vpbe_display_layer->video_dev;
/* Initialize field of video device */
vbd->release = video_device_release_empty;
vbd->fops = &vpbe_fops;
vbd->ioctl_ops = &vpbe_ioctl_ops;
vbd->minor = -1;
vbd->v4l2_dev = &disp_dev->vpbe_dev->v4l2_dev;
vbd->lock = &vpbe_display_layer->opslock;
vbd->vfl_dir = VFL_DIR_TX;
vbd->device_caps = V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_STREAMING;
if (disp_dev->vpbe_dev->current_timings.timings_type &
VPBE_ENC_STD)
vbd->tvnorms = (V4L2_STD_525_60 | V4L2_STD_625_50);
snprintf(vbd->name, sizeof(vbd->name),
"DaVinci_VPBE Display_DRIVER_V%d.%d.%d",
(VPBE_DISPLAY_VERSION_CODE >> 16) & 0xff,
(VPBE_DISPLAY_VERSION_CODE >> 8) & 0xff,
(VPBE_DISPLAY_VERSION_CODE) & 0xff);
vpbe_display_layer->device_id = i;
vpbe_display_layer->layer_info.id =
((i == VPBE_DISPLAY_DEVICE_0) ? WIN_VID0 : WIN_VID1);
return 0;
}
static int register_device(struct vpbe_layer *vpbe_display_layer,
struct vpbe_display *disp_dev,
struct platform_device *pdev)
{
int err;
v4l2_info(&disp_dev->vpbe_dev->v4l2_dev,
"Trying to register VPBE display device.\n");
v4l2_info(&disp_dev->vpbe_dev->v4l2_dev,
"layer=%p,layer->video_dev=%p\n",
vpbe_display_layer,
&vpbe_display_layer->video_dev);
vpbe_display_layer->video_dev.queue = &vpbe_display_layer->buffer_queue;
err = video_register_device(&vpbe_display_layer->video_dev,
VFL_TYPE_GRABBER,
-1);
if (err)
return -ENODEV;
vpbe_display_layer->disp_dev = disp_dev;
/* set the driver data in platform device */
platform_set_drvdata(pdev, disp_dev);
video_set_drvdata(&vpbe_display_layer->video_dev,
vpbe_display_layer);
return 0;
}
/*
* vpbe_display_probe()
* This function creates device entries by register itself to the V4L2 driver
* and initializes fields of each layer objects
*/
static int vpbe_display_probe(struct platform_device *pdev)
{
struct vpbe_display *disp_dev;
struct v4l2_device *v4l2_dev;
struct resource *res = NULL;
struct vb2_queue *q;
int k;
int i;
int err;
int irq;
printk(KERN_DEBUG "vpbe_display_probe\n");
/* Allocate memory for vpbe_display */
disp_dev = devm_kzalloc(&pdev->dev, sizeof(*disp_dev), GFP_KERNEL);
if (!disp_dev)
return -ENOMEM;
spin_lock_init(&disp_dev->dma_queue_lock);
/*
* Scan all the platform devices to find the vpbe
* controller device and get the vpbe_dev object
*/
err = bus_for_each_dev(&platform_bus_type, NULL, disp_dev,
vpbe_device_get);
if (err < 0)
return err;
v4l2_dev = &disp_dev->vpbe_dev->v4l2_dev;
/* Initialize the vpbe display controller */
if (disp_dev->vpbe_dev->ops.initialize) {
err = disp_dev->vpbe_dev->ops.initialize(&pdev->dev,
disp_dev->vpbe_dev);
if (err) {
v4l2_err(v4l2_dev, "Error initing vpbe\n");
err = -ENOMEM;
goto probe_out;
}
}
for (i = 0; i < VPBE_DISPLAY_MAX_DEVICES; i++) {
if (init_vpbe_layer(i, disp_dev, pdev)) {
err = -ENODEV;
goto probe_out;
}
}
res = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (!res) {
v4l2_err(v4l2_dev, "Unable to get VENC interrupt resource\n");
err = -ENODEV;
goto probe_out;
}
irq = res->start;
err = devm_request_irq(&pdev->dev, irq, venc_isr, 0,
VPBE_DISPLAY_DRIVER, disp_dev);
if (err) {
v4l2_err(v4l2_dev, "VPBE IRQ request failed\n");
goto probe_out;
}
for (i = 0; i < VPBE_DISPLAY_MAX_DEVICES; i++) {
/* initialize vb2 queue */
q = &disp_dev->dev[i]->buffer_queue;
memset(q, 0, sizeof(*q));
q->type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_DMABUF;
q->drv_priv = disp_dev->dev[i];
q->ops = &video_qops;
q->mem_ops = &vb2_dma_contig_memops;
q->buf_struct_size = sizeof(struct vpbe_disp_buffer);
q->timestamp_flags = V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
q->min_buffers_needed = 1;
q->lock = &disp_dev->dev[i]->opslock;
q->dev = disp_dev->vpbe_dev->pdev;
err = vb2_queue_init(q);
if (err) {
v4l2_err(v4l2_dev, "vb2_queue_init() failed\n");
goto probe_out;
}
INIT_LIST_HEAD(&disp_dev->dev[i]->dma_queue);
if (register_device(disp_dev->dev[i], disp_dev, pdev)) {
err = -ENODEV;
goto probe_out;
}
}
v4l2_dbg(1, debug, v4l2_dev,
"Successfully completed the probing of vpbe v4l2 device\n");
return 0;
probe_out:
for (k = 0; k < VPBE_DISPLAY_MAX_DEVICES; k++) {
/* Unregister video device */
if (disp_dev->dev[k]) {
video_unregister_device(&disp_dev->dev[k]->video_dev);
kfree(disp_dev->dev[k]);
}
}
return err;
}
/*
* vpbe_display_remove()
* It un-register hardware layer from V4L2 driver
*/
static int vpbe_display_remove(struct platform_device *pdev)
{
struct vpbe_layer *vpbe_display_layer;
struct vpbe_display *disp_dev = platform_get_drvdata(pdev);
struct vpbe_device *vpbe_dev = disp_dev->vpbe_dev;
int i;
v4l2_dbg(1, debug, &vpbe_dev->v4l2_dev, "vpbe_display_remove\n");
/* deinitialize the vpbe display controller */
if (vpbe_dev->ops.deinitialize)
vpbe_dev->ops.deinitialize(&pdev->dev, vpbe_dev);
/* un-register device */
for (i = 0; i < VPBE_DISPLAY_MAX_DEVICES; i++) {
/* Get the pointer to the layer object */
vpbe_display_layer = disp_dev->dev[i];
/* Unregister video device */
video_unregister_device(&vpbe_display_layer->video_dev);
}
for (i = 0; i < VPBE_DISPLAY_MAX_DEVICES; i++) {
kfree(disp_dev->dev[i]);
disp_dev->dev[i] = NULL;
}
return 0;
}
static struct platform_driver vpbe_display_driver = {
.driver = {
.name = VPBE_DISPLAY_DRIVER,
.bus = &platform_bus_type,
},
.probe = vpbe_display_probe,
.remove = vpbe_display_remove,
};
module_platform_driver(vpbe_display_driver);
MODULE_DESCRIPTION("TI DM644x/DM355/DM365 VPBE Display controller");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Texas Instruments");
| gpl-2.0 |
guoyuqing/linux-drover | drivers/net/ibm_newemac/core.c | 49 | 83257 | /*
* drivers/net/ibm_newemac/core.c
*
* Driver for PowerPC 4xx on-chip ethernet controller.
*
* Copyright 2007 Benjamin Herrenschmidt, IBM Corp.
* <benh@kernel.crashing.org>
*
* Based on the arch/ppc version of the driver:
*
* Copyright (c) 2004, 2005 Zultys Technologies.
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
*
* Based on original work by
* Matt Porter <mporter@kernel.crashing.org>
* (c) 2003 Benjamin Herrenschmidt <benh@kernel.crashing.org>
* Armin Kuster <akuster@mvista.com>
* Johnnie Peters <jpeters@mvista.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/string.h>
#include <linux/errno.h>
#include <linux/delay.h>
#include <linux/types.h>
#include <linux/pci.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/crc32.h>
#include <linux/ethtool.h>
#include <linux/mii.h>
#include <linux/bitops.h>
#include <linux/workqueue.h>
#include <linux/of.h>
#include <asm/processor.h>
#include <asm/io.h>
#include <asm/dma.h>
#include <asm/uaccess.h>
#include <asm/dcr.h>
#include <asm/dcr-regs.h>
#include "core.h"
/*
* Lack of dma_unmap_???? calls is intentional.
*
* API-correct usage requires additional support state information to be
* maintained for every RX and TX buffer descriptor (BD). Unfortunately, due to
* EMAC design (e.g. TX buffer passed from network stack can be split into
* several BDs, dma_map_single/dma_map_page can be used to map particular BD),
* maintaining such information will add additional overhead.
* Current DMA API implementation for 4xx processors only ensures cache coherency
* and dma_unmap_???? routines are empty and are likely to stay this way.
* I decided to omit dma_unmap_??? calls because I don't want to add additional
* complexity just for the sake of following some abstract API, when it doesn't
* add any real benefit to the driver. I understand that this decision maybe
* controversial, but I really tried to make code API-correct and efficient
* at the same time and didn't come up with code I liked :(. --ebs
*/
#define DRV_NAME "emac"
#define DRV_VERSION "3.54"
#define DRV_DESC "PPC 4xx OCP EMAC driver"
MODULE_DESCRIPTION(DRV_DESC);
MODULE_AUTHOR
("Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>");
MODULE_LICENSE("GPL");
/*
* PPC64 doesn't (yet) have a cacheable_memcpy
*/
#ifdef CONFIG_PPC64
#define cacheable_memcpy(d,s,n) memcpy((d),(s),(n))
#endif
/* minimum number of free TX descriptors required to wake up TX process */
#define EMAC_TX_WAKEUP_THRESH (NUM_TX_BUFF / 4)
/* If packet size is less than this number, we allocate small skb and copy packet
* contents into it instead of just sending original big skb up
*/
#define EMAC_RX_COPY_THRESH CONFIG_IBM_NEW_EMAC_RX_COPY_THRESHOLD
/* Since multiple EMACs share MDIO lines in various ways, we need
* to avoid re-using the same PHY ID in cases where the arch didn't
* setup precise phy_map entries
*
* XXX This is something that needs to be reworked as we can have multiple
* EMAC "sets" (multiple ASICs containing several EMACs) though we can
* probably require in that case to have explicit PHY IDs in the device-tree
*/
static u32 busy_phy_map;
static DEFINE_MUTEX(emac_phy_map_lock);
/* This is the wait queue used to wait on any event related to probe, that
* is discovery of MALs, other EMACs, ZMII/RGMIIs, etc...
*/
static DECLARE_WAIT_QUEUE_HEAD(emac_probe_wait);
/* Having stable interface names is a doomed idea. However, it would be nice
* if we didn't have completely random interface names at boot too :-) It's
* just a matter of making everybody's life easier. Since we are doing
* threaded probing, it's a bit harder though. The base idea here is that
* we make up a list of all emacs in the device-tree before we register the
* driver. Every emac will then wait for the previous one in the list to
* initialize before itself. We should also keep that list ordered by
* cell_index.
* That list is only 4 entries long, meaning that additional EMACs don't
* get ordering guarantees unless EMAC_BOOT_LIST_SIZE is increased.
*/
#define EMAC_BOOT_LIST_SIZE 4
static struct device_node *emac_boot_list[EMAC_BOOT_LIST_SIZE];
/* How long should I wait for dependent devices ? */
#define EMAC_PROBE_DEP_TIMEOUT (HZ * 5)
/* I don't want to litter system log with timeout errors
* when we have brain-damaged PHY.
*/
static inline void emac_report_timeout_error(struct emac_instance *dev,
const char *error)
{
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX |
EMAC_FTR_460EX_PHY_CLK_FIX |
EMAC_FTR_440EP_PHY_CLK_FIX))
DBG(dev, "%s" NL, error);
else if (net_ratelimit())
printk(KERN_ERR "%s: %s\n", dev->ofdev->node->full_name, error);
}
/* EMAC PHY clock workaround:
* 440EP/440GR has more sane SDR0_MFR register implementation than 440GX,
* which allows controlling each EMAC clock
*/
static inline void emac_rx_clk_tx(struct emac_instance *dev)
{
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440EP_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR,
0, SDR0_MFR_ECS >> dev->cell_index);
#endif
}
static inline void emac_rx_clk_default(struct emac_instance *dev)
{
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440EP_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR,
SDR0_MFR_ECS >> dev->cell_index, 0);
#endif
}
/* PHY polling intervals */
#define PHY_POLL_LINK_ON HZ
#define PHY_POLL_LINK_OFF (HZ / 5)
/* Graceful stop timeouts in us.
* We should allow up to 1 frame time (full-duplex, ignoring collisions)
*/
#define STOP_TIMEOUT_10 1230
#define STOP_TIMEOUT_100 124
#define STOP_TIMEOUT_1000 13
#define STOP_TIMEOUT_1000_JUMBO 73
static unsigned char default_mcast_addr[] = {
0x01, 0x80, 0xC2, 0x00, 0x00, 0x01
};
/* Please, keep in sync with struct ibm_emac_stats/ibm_emac_error_stats */
static const char emac_stats_keys[EMAC_ETHTOOL_STATS_COUNT][ETH_GSTRING_LEN] = {
"rx_packets", "rx_bytes", "tx_packets", "tx_bytes", "rx_packets_csum",
"tx_packets_csum", "tx_undo", "rx_dropped_stack", "rx_dropped_oom",
"rx_dropped_error", "rx_dropped_resize", "rx_dropped_mtu",
"rx_stopped", "rx_bd_errors", "rx_bd_overrun", "rx_bd_bad_packet",
"rx_bd_runt_packet", "rx_bd_short_event", "rx_bd_alignment_error",
"rx_bd_bad_fcs", "rx_bd_packet_too_long", "rx_bd_out_of_range",
"rx_bd_in_range", "rx_parity", "rx_fifo_overrun", "rx_overrun",
"rx_bad_packet", "rx_runt_packet", "rx_short_event",
"rx_alignment_error", "rx_bad_fcs", "rx_packet_too_long",
"rx_out_of_range", "rx_in_range", "tx_dropped", "tx_bd_errors",
"tx_bd_bad_fcs", "tx_bd_carrier_loss", "tx_bd_excessive_deferral",
"tx_bd_excessive_collisions", "tx_bd_late_collision",
"tx_bd_multple_collisions", "tx_bd_single_collision",
"tx_bd_underrun", "tx_bd_sqe", "tx_parity", "tx_underrun", "tx_sqe",
"tx_errors"
};
static irqreturn_t emac_irq(int irq, void *dev_instance);
static void emac_clean_tx_ring(struct emac_instance *dev);
static void __emac_set_multicast_list(struct emac_instance *dev);
static inline int emac_phy_supports_gige(int phy_mode)
{
return phy_mode == PHY_MODE_GMII ||
phy_mode == PHY_MODE_RGMII ||
phy_mode == PHY_MODE_SGMII ||
phy_mode == PHY_MODE_TBI ||
phy_mode == PHY_MODE_RTBI;
}
static inline int emac_phy_gpcs(int phy_mode)
{
return phy_mode == PHY_MODE_SGMII ||
phy_mode == PHY_MODE_TBI ||
phy_mode == PHY_MODE_RTBI;
}
static inline void emac_tx_enable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "tx_enable" NL);
r = in_be32(&p->mr0);
if (!(r & EMAC_MR0_TXE))
out_be32(&p->mr0, r | EMAC_MR0_TXE);
}
static void emac_tx_disable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "tx_disable" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_TXE) {
int n = dev->stop_timeout;
out_be32(&p->mr0, r & ~EMAC_MR0_TXE);
while (!(in_be32(&p->mr0) & EMAC_MR0_TXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev, "TX disable timeout");
}
}
static void emac_rx_enable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
if (unlikely(test_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags)))
goto out;
DBG(dev, "rx_enable" NL);
r = in_be32(&p->mr0);
if (!(r & EMAC_MR0_RXE)) {
if (unlikely(!(r & EMAC_MR0_RXI))) {
/* Wait if previous async disable is still in progress */
int n = dev->stop_timeout;
while (!(r = in_be32(&p->mr0) & EMAC_MR0_RXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev,
"RX disable timeout");
}
out_be32(&p->mr0, r | EMAC_MR0_RXE);
}
out:
;
}
static void emac_rx_disable(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "rx_disable" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_RXE) {
int n = dev->stop_timeout;
out_be32(&p->mr0, r & ~EMAC_MR0_RXE);
while (!(in_be32(&p->mr0) & EMAC_MR0_RXI) && n) {
udelay(1);
--n;
}
if (unlikely(!n))
emac_report_timeout_error(dev, "RX disable timeout");
}
}
static inline void emac_netif_stop(struct emac_instance *dev)
{
netif_tx_lock_bh(dev->ndev);
netif_addr_lock(dev->ndev);
dev->no_mcast = 1;
netif_addr_unlock(dev->ndev);
netif_tx_unlock_bh(dev->ndev);
dev->ndev->trans_start = jiffies; /* prevent tx timeout */
mal_poll_disable(dev->mal, &dev->commac);
netif_tx_disable(dev->ndev);
}
static inline void emac_netif_start(struct emac_instance *dev)
{
netif_tx_lock_bh(dev->ndev);
netif_addr_lock(dev->ndev);
dev->no_mcast = 0;
if (dev->mcast_pending && netif_running(dev->ndev))
__emac_set_multicast_list(dev);
netif_addr_unlock(dev->ndev);
netif_tx_unlock_bh(dev->ndev);
netif_wake_queue(dev->ndev);
/* NOTE: unconditional netif_wake_queue is only appropriate
* so long as all callers are assured to have free tx slots
* (taken from tg3... though the case where that is wrong is
* not terribly harmful)
*/
mal_poll_enable(dev->mal, &dev->commac);
}
static inline void emac_rx_disable_async(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r;
DBG(dev, "rx_disable_async" NL);
r = in_be32(&p->mr0);
if (r & EMAC_MR0_RXE)
out_be32(&p->mr0, r & ~EMAC_MR0_RXE);
}
static int emac_reset(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
int n = 20;
DBG(dev, "reset" NL);
if (!dev->reset_failed) {
/* 40x erratum suggests stopping RX channel before reset,
* we stop TX as well
*/
emac_rx_disable(dev);
emac_tx_disable(dev);
}
#ifdef CONFIG_PPC_DCR_NATIVE
/* Enable internal clock source */
if (emac_has_feature(dev, EMAC_FTR_460EX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_ETH_CFG,
0, SDR0_ETH_CFG_ECS << dev->cell_index);
#endif
out_be32(&p->mr0, EMAC_MR0_SRST);
while ((in_be32(&p->mr0) & EMAC_MR0_SRST) && n)
--n;
#ifdef CONFIG_PPC_DCR_NATIVE
/* Enable external clock source */
if (emac_has_feature(dev, EMAC_FTR_460EX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_ETH_CFG,
SDR0_ETH_CFG_ECS << dev->cell_index, 0);
#endif
if (n) {
dev->reset_failed = 0;
return 0;
} else {
emac_report_timeout_error(dev, "reset timeout");
dev->reset_failed = 1;
return -ETIMEDOUT;
}
}
static void emac_hash_mc(struct emac_instance *dev)
{
const int regs = EMAC_XAHT_REGS(dev);
u32 *gaht_base = emac_gaht_base(dev);
u32 gaht_temp[regs];
struct dev_mc_list *dmi;
int i;
DBG(dev, "hash_mc %d" NL, dev->ndev->mc_count);
memset(gaht_temp, 0, sizeof (gaht_temp));
for (dmi = dev->ndev->mc_list; dmi; dmi = dmi->next) {
int slot, reg, mask;
DBG2(dev, "mc %pM" NL, dmi->dmi_addr);
slot = EMAC_XAHT_CRC_TO_SLOT(dev, ether_crc(ETH_ALEN, dmi->dmi_addr));
reg = EMAC_XAHT_SLOT_TO_REG(dev, slot);
mask = EMAC_XAHT_SLOT_TO_MASK(dev, slot);
gaht_temp[reg] |= mask;
}
for (i = 0; i < regs; i++)
out_be32(gaht_base + i, gaht_temp[i]);
}
static inline u32 emac_iff2rmr(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
u32 r;
r = EMAC_RMR_SP | EMAC_RMR_SFCS | EMAC_RMR_IAE | EMAC_RMR_BAE;
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r |= EMAC4_RMR_BASE;
else
r |= EMAC_RMR_BASE;
if (ndev->flags & IFF_PROMISC)
r |= EMAC_RMR_PME;
else if (ndev->flags & IFF_ALLMULTI ||
(ndev->mc_count > EMAC_XAHT_SLOTS(dev)))
r |= EMAC_RMR_PMME;
else if (ndev->mc_count > 0)
r |= EMAC_RMR_MAE;
return r;
}
static u32 __emac_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
u32 ret = EMAC_MR1_VLE | EMAC_MR1_IST | EMAC_MR1_TR0_MULT;
DBG2(dev, "__emac_calc_base_mr1" NL);
switch(tx_size) {
case 2048:
ret |= EMAC_MR1_TFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Tx FIFO size %d\n",
dev->ndev->name, tx_size);
}
switch(rx_size) {
case 16384:
ret |= EMAC_MR1_RFS_16K;
break;
case 4096:
ret |= EMAC_MR1_RFS_4K;
break;
default:
printk(KERN_WARNING "%s: Unknown Rx FIFO size %d\n",
dev->ndev->name, rx_size);
}
return ret;
}
static u32 __emac4_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
u32 ret = EMAC_MR1_VLE | EMAC_MR1_IST | EMAC4_MR1_TR |
EMAC4_MR1_OBCI(dev->opb_bus_freq / 1000000);
DBG2(dev, "__emac4_calc_base_mr1" NL);
switch(tx_size) {
case 16384:
ret |= EMAC4_MR1_TFS_16K;
break;
case 4096:
ret |= EMAC4_MR1_TFS_4K;
break;
case 2048:
ret |= EMAC4_MR1_TFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Tx FIFO size %d\n",
dev->ndev->name, tx_size);
}
switch(rx_size) {
case 16384:
ret |= EMAC4_MR1_RFS_16K;
break;
case 4096:
ret |= EMAC4_MR1_RFS_4K;
break;
case 2048:
ret |= EMAC4_MR1_RFS_2K;
break;
default:
printk(KERN_WARNING "%s: Unknown Rx FIFO size %d\n",
dev->ndev->name, rx_size);
}
return ret;
}
static u32 emac_calc_base_mr1(struct emac_instance *dev, int tx_size, int rx_size)
{
return emac_has_feature(dev, EMAC_FTR_EMAC4) ?
__emac4_calc_base_mr1(dev, tx_size, rx_size) :
__emac_calc_base_mr1(dev, tx_size, rx_size);
}
static inline u32 emac_calc_trtr(struct emac_instance *dev, unsigned int size)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return ((size >> 6) - 1) << EMAC_TRTR_SHIFT_EMAC4;
else
return ((size >> 6) - 1) << EMAC_TRTR_SHIFT;
}
static inline u32 emac_calc_rwmr(struct emac_instance *dev,
unsigned int low, unsigned int high)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return (low << 22) | ( (high & 0x3ff) << 6);
else
return (low << 23) | ( (high & 0x1ff) << 7);
}
static int emac_configure(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
struct net_device *ndev = dev->ndev;
int tx_size, rx_size, link = netif_carrier_ok(dev->ndev);
u32 r, mr1 = 0;
DBG(dev, "configure" NL);
if (!link) {
out_be32(&p->mr1, in_be32(&p->mr1)
| EMAC_MR1_FDE | EMAC_MR1_ILE);
udelay(100);
} else if (emac_reset(dev) < 0)
return -ETIMEDOUT;
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_reset(dev->tah_dev);
DBG(dev, " link = %d duplex = %d, pause = %d, asym_pause = %d\n",
link, dev->phy.duplex, dev->phy.pause, dev->phy.asym_pause);
/* Default fifo sizes */
tx_size = dev->tx_fifo_size;
rx_size = dev->rx_fifo_size;
/* No link, force loopback */
if (!link)
mr1 = EMAC_MR1_FDE | EMAC_MR1_ILE;
/* Check for full duplex */
else if (dev->phy.duplex == DUPLEX_FULL)
mr1 |= EMAC_MR1_FDE | EMAC_MR1_MWSW_001;
/* Adjust fifo sizes, mr1 and timeouts based on link speed */
dev->stop_timeout = STOP_TIMEOUT_10;
switch (dev->phy.speed) {
case SPEED_1000:
if (emac_phy_gpcs(dev->phy.mode)) {
mr1 |= EMAC_MR1_MF_1000GPCS | EMAC_MR1_MF_IPPA(
(dev->phy.gpcs_address != 0xffffffff) ?
dev->phy.gpcs_address : dev->phy.address);
/* Put some arbitrary OUI, Manuf & Rev IDs so we can
* identify this GPCS PHY later.
*/
out_be32(&p->u1.emac4.ipcr, 0xdeadbeef);
} else
mr1 |= EMAC_MR1_MF_1000;
/* Extended fifo sizes */
tx_size = dev->tx_fifo_size_gige;
rx_size = dev->rx_fifo_size_gige;
if (dev->ndev->mtu > ETH_DATA_LEN) {
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
mr1 |= EMAC4_MR1_JPSM;
else
mr1 |= EMAC_MR1_JPSM;
dev->stop_timeout = STOP_TIMEOUT_1000_JUMBO;
} else
dev->stop_timeout = STOP_TIMEOUT_1000;
break;
case SPEED_100:
mr1 |= EMAC_MR1_MF_100;
dev->stop_timeout = STOP_TIMEOUT_100;
break;
default: /* make gcc happy */
break;
}
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_set_speed(dev->rgmii_dev, dev->rgmii_port,
dev->phy.speed);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_set_speed(dev->zmii_dev, dev->zmii_port, dev->phy.speed);
/* on 40x erratum forces us to NOT use integrated flow control,
* let's hope it works on 44x ;)
*/
if (!emac_has_feature(dev, EMAC_FTR_NO_FLOW_CONTROL_40x) &&
dev->phy.duplex == DUPLEX_FULL) {
if (dev->phy.pause)
mr1 |= EMAC_MR1_EIFC | EMAC_MR1_APP;
else if (dev->phy.asym_pause)
mr1 |= EMAC_MR1_APP;
}
/* Add base settings & fifo sizes & program MR1 */
mr1 |= emac_calc_base_mr1(dev, tx_size, rx_size);
out_be32(&p->mr1, mr1);
/* Set individual MAC address */
out_be32(&p->iahr, (ndev->dev_addr[0] << 8) | ndev->dev_addr[1]);
out_be32(&p->ialr, (ndev->dev_addr[2] << 24) |
(ndev->dev_addr[3] << 16) | (ndev->dev_addr[4] << 8) |
ndev->dev_addr[5]);
/* VLAN Tag Protocol ID */
out_be32(&p->vtpid, 0x8100);
/* Receive mode register */
r = emac_iff2rmr(ndev);
if (r & EMAC_RMR_MAE)
emac_hash_mc(dev);
out_be32(&p->rmr, r);
/* FIFOs thresholds */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_TMR1((dev->mal_burst_size / dev->fifo_entry_size) + 1,
tx_size / 2 / dev->fifo_entry_size);
else
r = EMAC_TMR1((dev->mal_burst_size / dev->fifo_entry_size) + 1,
tx_size / 2 / dev->fifo_entry_size);
out_be32(&p->tmr1, r);
out_be32(&p->trtr, emac_calc_trtr(dev, tx_size / 2));
/* PAUSE frame is sent when RX FIFO reaches its high-water mark,
there should be still enough space in FIFO to allow the our link
partner time to process this frame and also time to send PAUSE
frame itself.
Here is the worst case scenario for the RX FIFO "headroom"
(from "The Switch Book") (100Mbps, without preamble, inter-frame gap):
1) One maximum-length frame on TX 1522 bytes
2) One PAUSE frame time 64 bytes
3) PAUSE frame decode time allowance 64 bytes
4) One maximum-length frame on RX 1522 bytes
5) Round-trip propagation delay of the link (100Mb) 15 bytes
----------
3187 bytes
I chose to set high-water mark to RX_FIFO_SIZE / 4 (1024 bytes)
low-water mark to RX_FIFO_SIZE / 8 (512 bytes)
*/
r = emac_calc_rwmr(dev, rx_size / 8 / dev->fifo_entry_size,
rx_size / 4 / dev->fifo_entry_size);
out_be32(&p->rwmr, r);
/* Set PAUSE timer to the maximum */
out_be32(&p->ptr, 0xffff);
/* IRQ sources */
r = EMAC_ISR_OVR | EMAC_ISR_BP | EMAC_ISR_SE |
EMAC_ISR_ALE | EMAC_ISR_BFCS | EMAC_ISR_PTLE | EMAC_ISR_ORE |
EMAC_ISR_IRE | EMAC_ISR_TE;
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r |= EMAC4_ISR_TXPE | EMAC4_ISR_RXPE /* | EMAC4_ISR_TXUE |
EMAC4_ISR_RXOE | */;
out_be32(&p->iser, r);
/* We need to take GPCS PHY out of isolate mode after EMAC reset */
if (emac_phy_gpcs(dev->phy.mode)) {
if (dev->phy.gpcs_address != 0xffffffff)
emac_mii_reset_gpcs(&dev->phy);
else
emac_mii_reset_phy(&dev->phy);
}
return 0;
}
static void emac_reinitialize(struct emac_instance *dev)
{
DBG(dev, "reinitialize" NL);
emac_netif_stop(dev);
if (!emac_configure(dev)) {
emac_tx_enable(dev);
emac_rx_enable(dev);
}
emac_netif_start(dev);
}
static void emac_full_tx_reset(struct emac_instance *dev)
{
DBG(dev, "full_tx_reset" NL);
emac_tx_disable(dev);
mal_disable_tx_channel(dev->mal, dev->mal_tx_chan);
emac_clean_tx_ring(dev);
dev->tx_cnt = dev->tx_slot = dev->ack_slot = 0;
emac_configure(dev);
mal_enable_tx_channel(dev->mal, dev->mal_tx_chan);
emac_tx_enable(dev);
emac_rx_enable(dev);
}
static void emac_reset_work(struct work_struct *work)
{
struct emac_instance *dev = container_of(work, struct emac_instance, reset_work);
DBG(dev, "reset_work" NL);
mutex_lock(&dev->link_lock);
if (dev->opened) {
emac_netif_stop(dev);
emac_full_tx_reset(dev);
emac_netif_start(dev);
}
mutex_unlock(&dev->link_lock);
}
static void emac_tx_timeout(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "tx_timeout" NL);
schedule_work(&dev->reset_work);
}
static inline int emac_phy_done(struct emac_instance *dev, u32 stacr)
{
int done = !!(stacr & EMAC_STACR_OC);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
done = !done;
return done;
};
static int __emac_mdio_read(struct emac_instance *dev, u8 id, u8 reg)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r = 0;
int n, err = -ETIMEDOUT;
mutex_lock(&dev->mdio_lock);
DBG2(dev, "mdio_read(%02x,%02x)" NL, id, reg);
/* Enable proper MDIO port */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_get_mdio(dev->zmii_dev, dev->zmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_get_mdio(dev->rgmii_dev, dev->rgmii_port);
/* Wait for management interface to become idle */
n = 20;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait idle\n");
goto bail;
}
}
/* Issue read command */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_STACR_BASE(dev->opb_bus_freq);
else
r = EMAC_STACR_BASE(dev->opb_bus_freq);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
r |= EMAC_STACR_OC;
if (emac_has_feature(dev, EMAC_FTR_HAS_NEW_STACR))
r |= EMACX_STACR_STAC_READ;
else
r |= EMAC_STACR_STAC_READ;
r |= (reg & EMAC_STACR_PRA_MASK)
| ((id & EMAC_STACR_PCDA_MASK) << EMAC_STACR_PCDA_SHIFT);
out_be32(&p->stacr, r);
/* Wait for read to complete */
n = 200;
while (!emac_phy_done(dev, (r = in_be32(&p->stacr)))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait complete\n");
goto bail;
}
}
if (unlikely(r & EMAC_STACR_PHYE)) {
DBG(dev, "mdio_read(%02x, %02x) failed" NL, id, reg);
err = -EREMOTEIO;
goto bail;
}
r = ((r >> EMAC_STACR_PHYD_SHIFT) & EMAC_STACR_PHYD_MASK);
DBG2(dev, "mdio_read -> %04x" NL, r);
err = 0;
bail:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_put_mdio(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_put_mdio(dev->zmii_dev, dev->zmii_port);
mutex_unlock(&dev->mdio_lock);
return err == 0 ? r : err;
}
static void __emac_mdio_write(struct emac_instance *dev, u8 id, u8 reg,
u16 val)
{
struct emac_regs __iomem *p = dev->emacp;
u32 r = 0;
int n, err = -ETIMEDOUT;
mutex_lock(&dev->mdio_lock);
DBG2(dev, "mdio_write(%02x,%02x,%04x)" NL, id, reg, val);
/* Enable proper MDIO port */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_get_mdio(dev->zmii_dev, dev->zmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_get_mdio(dev->rgmii_dev, dev->rgmii_port);
/* Wait for management interface to be idle */
n = 20;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait idle\n");
goto bail;
}
}
/* Issue write command */
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
r = EMAC4_STACR_BASE(dev->opb_bus_freq);
else
r = EMAC_STACR_BASE(dev->opb_bus_freq);
if (emac_has_feature(dev, EMAC_FTR_STACR_OC_INVERT))
r |= EMAC_STACR_OC;
if (emac_has_feature(dev, EMAC_FTR_HAS_NEW_STACR))
r |= EMACX_STACR_STAC_WRITE;
else
r |= EMAC_STACR_STAC_WRITE;
r |= (reg & EMAC_STACR_PRA_MASK) |
((id & EMAC_STACR_PCDA_MASK) << EMAC_STACR_PCDA_SHIFT) |
(val << EMAC_STACR_PHYD_SHIFT);
out_be32(&p->stacr, r);
/* Wait for write to complete */
n = 200;
while (!emac_phy_done(dev, in_be32(&p->stacr))) {
udelay(1);
if (!--n) {
DBG2(dev, " -> timeout wait complete\n");
goto bail;
}
}
err = 0;
bail:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_put_mdio(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_put_mdio(dev->zmii_dev, dev->zmii_port);
mutex_unlock(&dev->mdio_lock);
}
static int emac_mdio_read(struct net_device *ndev, int id, int reg)
{
struct emac_instance *dev = netdev_priv(ndev);
int res;
res = __emac_mdio_read((dev->mdio_instance &&
dev->phy.gpcs_address != id) ?
dev->mdio_instance : dev,
(u8) id, (u8) reg);
return res;
}
static void emac_mdio_write(struct net_device *ndev, int id, int reg, int val)
{
struct emac_instance *dev = netdev_priv(ndev);
__emac_mdio_write((dev->mdio_instance &&
dev->phy.gpcs_address != id) ?
dev->mdio_instance : dev,
(u8) id, (u8) reg, (u16) val);
}
/* Tx lock BH */
static void __emac_set_multicast_list(struct emac_instance *dev)
{
struct emac_regs __iomem *p = dev->emacp;
u32 rmr = emac_iff2rmr(dev->ndev);
DBG(dev, "__multicast %08x" NL, rmr);
/* I decided to relax register access rules here to avoid
* full EMAC reset.
*
* There is a real problem with EMAC4 core if we use MWSW_001 bit
* in MR1 register and do a full EMAC reset.
* One TX BD status update is delayed and, after EMAC reset, it
* never happens, resulting in TX hung (it'll be recovered by TX
* timeout handler eventually, but this is just gross).
* So we either have to do full TX reset or try to cheat here :)
*
* The only required change is to RX mode register, so I *think* all
* we need is just to stop RX channel. This seems to work on all
* tested SoCs. --ebs
*
* If we need the full reset, we might just trigger the workqueue
* and do it async... a bit nasty but should work --BenH
*/
dev->mcast_pending = 0;
emac_rx_disable(dev);
if (rmr & EMAC_RMR_MAE)
emac_hash_mc(dev);
out_be32(&p->rmr, rmr);
emac_rx_enable(dev);
}
/* Tx lock BH */
static void emac_set_multicast_list(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "multicast" NL);
BUG_ON(!netif_running(dev->ndev));
if (dev->no_mcast) {
dev->mcast_pending = 1;
return;
}
__emac_set_multicast_list(dev);
}
static int emac_resize_rx_ring(struct emac_instance *dev, int new_mtu)
{
int rx_sync_size = emac_rx_sync_size(new_mtu);
int rx_skb_size = emac_rx_skb_size(new_mtu);
int i, ret = 0;
mutex_lock(&dev->link_lock);
emac_netif_stop(dev);
emac_rx_disable(dev);
mal_disable_rx_channel(dev->mal, dev->mal_rx_chan);
if (dev->rx_sg_skb) {
++dev->estats.rx_dropped_resize;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
/* Make a first pass over RX ring and mark BDs ready, dropping
* non-processed packets on the way. We need this as a separate pass
* to simplify error recovery in the case of allocation failure later.
*/
for (i = 0; i < NUM_RX_BUFF; ++i) {
if (dev->rx_desc[i].ctrl & MAL_RX_CTRL_FIRST)
++dev->estats.rx_dropped_resize;
dev->rx_desc[i].data_len = 0;
dev->rx_desc[i].ctrl = MAL_RX_CTRL_EMPTY |
(i == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
}
/* Reallocate RX ring only if bigger skb buffers are required */
if (rx_skb_size <= dev->rx_skb_size)
goto skip;
/* Second pass, allocate new skbs */
for (i = 0; i < NUM_RX_BUFF; ++i) {
struct sk_buff *skb = alloc_skb(rx_skb_size, GFP_ATOMIC);
if (!skb) {
ret = -ENOMEM;
goto oom;
}
BUG_ON(!dev->rx_skb[i]);
dev_kfree_skb(dev->rx_skb[i]);
skb_reserve(skb, EMAC_RX_SKB_HEADROOM + 2);
dev->rx_desc[i].data_ptr =
dma_map_single(&dev->ofdev->dev, skb->data - 2, rx_sync_size,
DMA_FROM_DEVICE) + 2;
dev->rx_skb[i] = skb;
}
skip:
/* Check if we need to change "Jumbo" bit in MR1 */
if ((new_mtu > ETH_DATA_LEN) ^ (dev->ndev->mtu > ETH_DATA_LEN)) {
/* This is to prevent starting RX channel in emac_rx_enable() */
set_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->ndev->mtu = new_mtu;
emac_full_tx_reset(dev);
}
mal_set_rcbs(dev->mal, dev->mal_rx_chan, emac_rx_size(new_mtu));
oom:
/* Restart RX */
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->rx_slot = 0;
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_rx_enable(dev);
emac_netif_start(dev);
mutex_unlock(&dev->link_lock);
return ret;
}
/* Process ctx, rtnl_lock semaphore */
static int emac_change_mtu(struct net_device *ndev, int new_mtu)
{
struct emac_instance *dev = netdev_priv(ndev);
int ret = 0;
if (new_mtu < EMAC_MIN_MTU || new_mtu > dev->max_mtu)
return -EINVAL;
DBG(dev, "change_mtu(%d)" NL, new_mtu);
if (netif_running(ndev)) {
/* Check if we really need to reinitalize RX ring */
if (emac_rx_skb_size(ndev->mtu) != emac_rx_skb_size(new_mtu))
ret = emac_resize_rx_ring(dev, new_mtu);
}
if (!ret) {
ndev->mtu = new_mtu;
dev->rx_skb_size = emac_rx_skb_size(new_mtu);
dev->rx_sync_size = emac_rx_sync_size(new_mtu);
}
return ret;
}
static void emac_clean_tx_ring(struct emac_instance *dev)
{
int i;
for (i = 0; i < NUM_TX_BUFF; ++i) {
if (dev->tx_skb[i]) {
dev_kfree_skb(dev->tx_skb[i]);
dev->tx_skb[i] = NULL;
if (dev->tx_desc[i].ctrl & MAL_TX_CTRL_READY)
++dev->estats.tx_dropped;
}
dev->tx_desc[i].ctrl = 0;
dev->tx_desc[i].data_ptr = 0;
}
}
static void emac_clean_rx_ring(struct emac_instance *dev)
{
int i;
for (i = 0; i < NUM_RX_BUFF; ++i)
if (dev->rx_skb[i]) {
dev->rx_desc[i].ctrl = 0;
dev_kfree_skb(dev->rx_skb[i]);
dev->rx_skb[i] = NULL;
dev->rx_desc[i].data_ptr = 0;
}
if (dev->rx_sg_skb) {
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
}
static inline int emac_alloc_rx_skb(struct emac_instance *dev, int slot,
gfp_t flags)
{
struct sk_buff *skb = alloc_skb(dev->rx_skb_size, flags);
if (unlikely(!skb))
return -ENOMEM;
dev->rx_skb[slot] = skb;
dev->rx_desc[slot].data_len = 0;
skb_reserve(skb, EMAC_RX_SKB_HEADROOM + 2);
dev->rx_desc[slot].data_ptr =
dma_map_single(&dev->ofdev->dev, skb->data - 2, dev->rx_sync_size,
DMA_FROM_DEVICE) + 2;
wmb();
dev->rx_desc[slot].ctrl = MAL_RX_CTRL_EMPTY |
(slot == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
return 0;
}
static void emac_print_link_status(struct emac_instance *dev)
{
if (netif_carrier_ok(dev->ndev))
printk(KERN_INFO "%s: link is up, %d %s%s\n",
dev->ndev->name, dev->phy.speed,
dev->phy.duplex == DUPLEX_FULL ? "FDX" : "HDX",
dev->phy.pause ? ", pause enabled" :
dev->phy.asym_pause ? ", asymmetric pause enabled" : "");
else
printk(KERN_INFO "%s: link is down\n", dev->ndev->name);
}
/* Process ctx, rtnl_lock semaphore */
static int emac_open(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int err, i;
DBG(dev, "open" NL);
/* Setup error IRQ handler */
err = request_irq(dev->emac_irq, emac_irq, 0, "EMAC", dev);
if (err) {
printk(KERN_ERR "%s: failed to request IRQ %d\n",
ndev->name, dev->emac_irq);
return err;
}
/* Allocate RX ring */
for (i = 0; i < NUM_RX_BUFF; ++i)
if (emac_alloc_rx_skb(dev, i, GFP_KERNEL)) {
printk(KERN_ERR "%s: failed to allocate RX ring\n",
ndev->name);
goto oom;
}
dev->tx_cnt = dev->tx_slot = dev->ack_slot = dev->rx_slot = 0;
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
dev->rx_sg_skb = NULL;
mutex_lock(&dev->link_lock);
dev->opened = 1;
/* Start PHY polling now.
*/
if (dev->phy.address >= 0) {
int link_poll_interval;
if (dev->phy.def->ops->poll_link(&dev->phy)) {
dev->phy.def->ops->read_link(&dev->phy);
emac_rx_clk_default(dev);
netif_carrier_on(dev->ndev);
link_poll_interval = PHY_POLL_LINK_ON;
} else {
emac_rx_clk_tx(dev);
netif_carrier_off(dev->ndev);
link_poll_interval = PHY_POLL_LINK_OFF;
}
dev->link_polling = 1;
wmb();
schedule_delayed_work(&dev->link_work, link_poll_interval);
emac_print_link_status(dev);
} else
netif_carrier_on(dev->ndev);
/* Required for Pause packet support in EMAC */
dev_mc_add(ndev, default_mcast_addr, sizeof(default_mcast_addr), 1);
emac_configure(dev);
mal_poll_add(dev->mal, &dev->commac);
mal_enable_tx_channel(dev->mal, dev->mal_tx_chan);
mal_set_rcbs(dev->mal, dev->mal_rx_chan, emac_rx_size(ndev->mtu));
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_tx_enable(dev);
emac_rx_enable(dev);
emac_netif_start(dev);
mutex_unlock(&dev->link_lock);
return 0;
oom:
emac_clean_rx_ring(dev);
free_irq(dev->emac_irq, dev);
return -ENOMEM;
}
/* BHs disabled */
#if 0
static int emac_link_differs(struct emac_instance *dev)
{
u32 r = in_be32(&dev->emacp->mr1);
int duplex = r & EMAC_MR1_FDE ? DUPLEX_FULL : DUPLEX_HALF;
int speed, pause, asym_pause;
if (r & EMAC_MR1_MF_1000)
speed = SPEED_1000;
else if (r & EMAC_MR1_MF_100)
speed = SPEED_100;
else
speed = SPEED_10;
switch (r & (EMAC_MR1_EIFC | EMAC_MR1_APP)) {
case (EMAC_MR1_EIFC | EMAC_MR1_APP):
pause = 1;
asym_pause = 0;
break;
case EMAC_MR1_APP:
pause = 0;
asym_pause = 1;
break;
default:
pause = asym_pause = 0;
}
return speed != dev->phy.speed || duplex != dev->phy.duplex ||
pause != dev->phy.pause || asym_pause != dev->phy.asym_pause;
}
#endif
static void emac_link_timer(struct work_struct *work)
{
struct emac_instance *dev =
container_of(to_delayed_work(work),
struct emac_instance, link_work);
int link_poll_interval;
mutex_lock(&dev->link_lock);
DBG2(dev, "link timer" NL);
if (!dev->opened)
goto bail;
if (dev->phy.def->ops->poll_link(&dev->phy)) {
if (!netif_carrier_ok(dev->ndev)) {
emac_rx_clk_default(dev);
/* Get new link parameters */
dev->phy.def->ops->read_link(&dev->phy);
netif_carrier_on(dev->ndev);
emac_netif_stop(dev);
emac_full_tx_reset(dev);
emac_netif_start(dev);
emac_print_link_status(dev);
}
link_poll_interval = PHY_POLL_LINK_ON;
} else {
if (netif_carrier_ok(dev->ndev)) {
emac_rx_clk_tx(dev);
netif_carrier_off(dev->ndev);
netif_tx_disable(dev->ndev);
emac_reinitialize(dev);
emac_print_link_status(dev);
}
link_poll_interval = PHY_POLL_LINK_OFF;
}
schedule_delayed_work(&dev->link_work, link_poll_interval);
bail:
mutex_unlock(&dev->link_lock);
}
static void emac_force_link_update(struct emac_instance *dev)
{
netif_carrier_off(dev->ndev);
smp_rmb();
if (dev->link_polling) {
cancel_rearming_delayed_work(&dev->link_work);
if (dev->link_polling)
schedule_delayed_work(&dev->link_work, PHY_POLL_LINK_OFF);
}
}
/* Process ctx, rtnl_lock semaphore */
static int emac_close(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
DBG(dev, "close" NL);
if (dev->phy.address >= 0) {
dev->link_polling = 0;
cancel_rearming_delayed_work(&dev->link_work);
}
mutex_lock(&dev->link_lock);
emac_netif_stop(dev);
dev->opened = 0;
mutex_unlock(&dev->link_lock);
emac_rx_disable(dev);
emac_tx_disable(dev);
mal_disable_rx_channel(dev->mal, dev->mal_rx_chan);
mal_disable_tx_channel(dev->mal, dev->mal_tx_chan);
mal_poll_del(dev->mal, &dev->commac);
emac_clean_tx_ring(dev);
emac_clean_rx_ring(dev);
free_irq(dev->emac_irq, dev);
netif_carrier_off(ndev);
return 0;
}
static inline u16 emac_tx_csum(struct emac_instance *dev,
struct sk_buff *skb)
{
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH) &&
(skb->ip_summed == CHECKSUM_PARTIAL)) {
++dev->stats.tx_packets_csum;
return EMAC_TX_CTRL_TAH_CSUM;
}
return 0;
}
static inline int emac_xmit_finish(struct emac_instance *dev, int len)
{
struct emac_regs __iomem *p = dev->emacp;
struct net_device *ndev = dev->ndev;
/* Send the packet out. If the if makes a significant perf
* difference, then we can store the TMR0 value in "dev"
* instead
*/
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
out_be32(&p->tmr0, EMAC4_TMR0_XMIT);
else
out_be32(&p->tmr0, EMAC_TMR0_XMIT);
if (unlikely(++dev->tx_cnt == NUM_TX_BUFF)) {
netif_stop_queue(ndev);
DBG2(dev, "stopped TX queue" NL);
}
ndev->trans_start = jiffies;
++dev->stats.tx_packets;
dev->stats.tx_bytes += len;
return NETDEV_TX_OK;
}
/* Tx lock BH */
static int emac_start_xmit(struct sk_buff *skb, struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
unsigned int len = skb->len;
int slot;
u16 ctrl = EMAC_TX_CTRL_GFCS | EMAC_TX_CTRL_GP | MAL_TX_CTRL_READY |
MAL_TX_CTRL_LAST | emac_tx_csum(dev, skb);
slot = dev->tx_slot++;
if (dev->tx_slot == NUM_TX_BUFF) {
dev->tx_slot = 0;
ctrl |= MAL_TX_CTRL_WRAP;
}
DBG2(dev, "xmit(%u) %d" NL, len, slot);
dev->tx_skb[slot] = skb;
dev->tx_desc[slot].data_ptr = dma_map_single(&dev->ofdev->dev,
skb->data, len,
DMA_TO_DEVICE);
dev->tx_desc[slot].data_len = (u16) len;
wmb();
dev->tx_desc[slot].ctrl = ctrl;
return emac_xmit_finish(dev, len);
}
static inline int emac_xmit_split(struct emac_instance *dev, int slot,
u32 pd, int len, int last, u16 base_ctrl)
{
while (1) {
u16 ctrl = base_ctrl;
int chunk = min(len, MAL_MAX_TX_SIZE);
len -= chunk;
slot = (slot + 1) % NUM_TX_BUFF;
if (last && !len)
ctrl |= MAL_TX_CTRL_LAST;
if (slot == NUM_TX_BUFF - 1)
ctrl |= MAL_TX_CTRL_WRAP;
dev->tx_skb[slot] = NULL;
dev->tx_desc[slot].data_ptr = pd;
dev->tx_desc[slot].data_len = (u16) chunk;
dev->tx_desc[slot].ctrl = ctrl;
++dev->tx_cnt;
if (!len)
break;
pd += chunk;
}
return slot;
}
/* Tx lock BH disabled (SG version for TAH equipped EMACs) */
static int emac_start_xmit_sg(struct sk_buff *skb, struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int nr_frags = skb_shinfo(skb)->nr_frags;
int len = skb->len, chunk;
int slot, i;
u16 ctrl;
u32 pd;
/* This is common "fast" path */
if (likely(!nr_frags && len <= MAL_MAX_TX_SIZE))
return emac_start_xmit(skb, ndev);
len -= skb->data_len;
/* Note, this is only an *estimation*, we can still run out of empty
* slots because of the additional fragmentation into
* MAL_MAX_TX_SIZE-sized chunks
*/
if (unlikely(dev->tx_cnt + nr_frags + mal_tx_chunks(len) > NUM_TX_BUFF))
goto stop_queue;
ctrl = EMAC_TX_CTRL_GFCS | EMAC_TX_CTRL_GP | MAL_TX_CTRL_READY |
emac_tx_csum(dev, skb);
slot = dev->tx_slot;
/* skb data */
dev->tx_skb[slot] = NULL;
chunk = min(len, MAL_MAX_TX_SIZE);
dev->tx_desc[slot].data_ptr = pd =
dma_map_single(&dev->ofdev->dev, skb->data, len, DMA_TO_DEVICE);
dev->tx_desc[slot].data_len = (u16) chunk;
len -= chunk;
if (unlikely(len))
slot = emac_xmit_split(dev, slot, pd + chunk, len, !nr_frags,
ctrl);
/* skb fragments */
for (i = 0; i < nr_frags; ++i) {
struct skb_frag_struct *frag = &skb_shinfo(skb)->frags[i];
len = frag->size;
if (unlikely(dev->tx_cnt + mal_tx_chunks(len) >= NUM_TX_BUFF))
goto undo_frame;
pd = dma_map_page(&dev->ofdev->dev, frag->page, frag->page_offset, len,
DMA_TO_DEVICE);
slot = emac_xmit_split(dev, slot, pd, len, i == nr_frags - 1,
ctrl);
}
DBG2(dev, "xmit_sg(%u) %d - %d" NL, skb->len, dev->tx_slot, slot);
/* Attach skb to the last slot so we don't release it too early */
dev->tx_skb[slot] = skb;
/* Send the packet out */
if (dev->tx_slot == NUM_TX_BUFF - 1)
ctrl |= MAL_TX_CTRL_WRAP;
wmb();
dev->tx_desc[dev->tx_slot].ctrl = ctrl;
dev->tx_slot = (slot + 1) % NUM_TX_BUFF;
return emac_xmit_finish(dev, skb->len);
undo_frame:
/* Well, too bad. Our previous estimation was overly optimistic.
* Undo everything.
*/
while (slot != dev->tx_slot) {
dev->tx_desc[slot].ctrl = 0;
--dev->tx_cnt;
if (--slot < 0)
slot = NUM_TX_BUFF - 1;
}
++dev->estats.tx_undo;
stop_queue:
netif_stop_queue(ndev);
DBG2(dev, "stopped TX queue" NL);
return NETDEV_TX_BUSY;
}
/* Tx lock BHs */
static void emac_parse_tx_error(struct emac_instance *dev, u16 ctrl)
{
struct emac_error_stats *st = &dev->estats;
DBG(dev, "BD TX error %04x" NL, ctrl);
++st->tx_bd_errors;
if (ctrl & EMAC_TX_ST_BFCS)
++st->tx_bd_bad_fcs;
if (ctrl & EMAC_TX_ST_LCS)
++st->tx_bd_carrier_loss;
if (ctrl & EMAC_TX_ST_ED)
++st->tx_bd_excessive_deferral;
if (ctrl & EMAC_TX_ST_EC)
++st->tx_bd_excessive_collisions;
if (ctrl & EMAC_TX_ST_LC)
++st->tx_bd_late_collision;
if (ctrl & EMAC_TX_ST_MC)
++st->tx_bd_multple_collisions;
if (ctrl & EMAC_TX_ST_SC)
++st->tx_bd_single_collision;
if (ctrl & EMAC_TX_ST_UR)
++st->tx_bd_underrun;
if (ctrl & EMAC_TX_ST_SQE)
++st->tx_bd_sqe;
}
static void emac_poll_tx(void *param)
{
struct emac_instance *dev = param;
u32 bad_mask;
DBG2(dev, "poll_tx, %d %d" NL, dev->tx_cnt, dev->ack_slot);
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
bad_mask = EMAC_IS_BAD_TX_TAH;
else
bad_mask = EMAC_IS_BAD_TX;
netif_tx_lock_bh(dev->ndev);
if (dev->tx_cnt) {
u16 ctrl;
int slot = dev->ack_slot, n = 0;
again:
ctrl = dev->tx_desc[slot].ctrl;
if (!(ctrl & MAL_TX_CTRL_READY)) {
struct sk_buff *skb = dev->tx_skb[slot];
++n;
if (skb) {
dev_kfree_skb(skb);
dev->tx_skb[slot] = NULL;
}
slot = (slot + 1) % NUM_TX_BUFF;
if (unlikely(ctrl & bad_mask))
emac_parse_tx_error(dev, ctrl);
if (--dev->tx_cnt)
goto again;
}
if (n) {
dev->ack_slot = slot;
if (netif_queue_stopped(dev->ndev) &&
dev->tx_cnt < EMAC_TX_WAKEUP_THRESH)
netif_wake_queue(dev->ndev);
DBG2(dev, "tx %d pkts" NL, n);
}
}
netif_tx_unlock_bh(dev->ndev);
}
static inline void emac_recycle_rx_skb(struct emac_instance *dev, int slot,
int len)
{
struct sk_buff *skb = dev->rx_skb[slot];
DBG2(dev, "recycle %d %d" NL, slot, len);
if (len)
dma_map_single(&dev->ofdev->dev, skb->data - 2,
EMAC_DMA_ALIGN(len + 2), DMA_FROM_DEVICE);
dev->rx_desc[slot].data_len = 0;
wmb();
dev->rx_desc[slot].ctrl = MAL_RX_CTRL_EMPTY |
(slot == (NUM_RX_BUFF - 1) ? MAL_RX_CTRL_WRAP : 0);
}
static void emac_parse_rx_error(struct emac_instance *dev, u16 ctrl)
{
struct emac_error_stats *st = &dev->estats;
DBG(dev, "BD RX error %04x" NL, ctrl);
++st->rx_bd_errors;
if (ctrl & EMAC_RX_ST_OE)
++st->rx_bd_overrun;
if (ctrl & EMAC_RX_ST_BP)
++st->rx_bd_bad_packet;
if (ctrl & EMAC_RX_ST_RP)
++st->rx_bd_runt_packet;
if (ctrl & EMAC_RX_ST_SE)
++st->rx_bd_short_event;
if (ctrl & EMAC_RX_ST_AE)
++st->rx_bd_alignment_error;
if (ctrl & EMAC_RX_ST_BFCS)
++st->rx_bd_bad_fcs;
if (ctrl & EMAC_RX_ST_PTL)
++st->rx_bd_packet_too_long;
if (ctrl & EMAC_RX_ST_ORE)
++st->rx_bd_out_of_range;
if (ctrl & EMAC_RX_ST_IRE)
++st->rx_bd_in_range;
}
static inline void emac_rx_csum(struct emac_instance *dev,
struct sk_buff *skb, u16 ctrl)
{
#ifdef CONFIG_IBM_NEW_EMAC_TAH
if (!ctrl && dev->tah_dev) {
skb->ip_summed = CHECKSUM_UNNECESSARY;
++dev->stats.rx_packets_csum;
}
#endif
}
static inline int emac_rx_sg_append(struct emac_instance *dev, int slot)
{
if (likely(dev->rx_sg_skb != NULL)) {
int len = dev->rx_desc[slot].data_len;
int tot_len = dev->rx_sg_skb->len + len;
if (unlikely(tot_len + 2 > dev->rx_skb_size)) {
++dev->estats.rx_dropped_mtu;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
} else {
cacheable_memcpy(skb_tail_pointer(dev->rx_sg_skb),
dev->rx_skb[slot]->data, len);
skb_put(dev->rx_sg_skb, len);
emac_recycle_rx_skb(dev, slot, len);
return 0;
}
}
emac_recycle_rx_skb(dev, slot, 0);
return -1;
}
/* NAPI poll context */
static int emac_poll_rx(void *param, int budget)
{
struct emac_instance *dev = param;
int slot = dev->rx_slot, received = 0;
DBG2(dev, "poll_rx(%d)" NL, budget);
again:
while (budget > 0) {
int len;
struct sk_buff *skb;
u16 ctrl = dev->rx_desc[slot].ctrl;
if (ctrl & MAL_RX_CTRL_EMPTY)
break;
skb = dev->rx_skb[slot];
mb();
len = dev->rx_desc[slot].data_len;
if (unlikely(!MAL_IS_SINGLE_RX(ctrl)))
goto sg;
ctrl &= EMAC_BAD_RX_MASK;
if (unlikely(ctrl && ctrl != EMAC_RX_TAH_BAD_CSUM)) {
emac_parse_rx_error(dev, ctrl);
++dev->estats.rx_dropped_error;
emac_recycle_rx_skb(dev, slot, 0);
len = 0;
goto next;
}
if (len < ETH_HLEN) {
++dev->estats.rx_dropped_stack;
emac_recycle_rx_skb(dev, slot, len);
goto next;
}
if (len && len < EMAC_RX_COPY_THRESH) {
struct sk_buff *copy_skb =
alloc_skb(len + EMAC_RX_SKB_HEADROOM + 2, GFP_ATOMIC);
if (unlikely(!copy_skb))
goto oom;
skb_reserve(copy_skb, EMAC_RX_SKB_HEADROOM + 2);
cacheable_memcpy(copy_skb->data - 2, skb->data - 2,
len + 2);
emac_recycle_rx_skb(dev, slot, len);
skb = copy_skb;
} else if (unlikely(emac_alloc_rx_skb(dev, slot, GFP_ATOMIC)))
goto oom;
skb_put(skb, len);
push_packet:
skb->dev = dev->ndev;
skb->protocol = eth_type_trans(skb, dev->ndev);
emac_rx_csum(dev, skb, ctrl);
if (unlikely(netif_receive_skb(skb) == NET_RX_DROP))
++dev->estats.rx_dropped_stack;
next:
++dev->stats.rx_packets;
skip:
dev->stats.rx_bytes += len;
slot = (slot + 1) % NUM_RX_BUFF;
--budget;
++received;
continue;
sg:
if (ctrl & MAL_RX_CTRL_FIRST) {
BUG_ON(dev->rx_sg_skb);
if (unlikely(emac_alloc_rx_skb(dev, slot, GFP_ATOMIC))) {
DBG(dev, "rx OOM %d" NL, slot);
++dev->estats.rx_dropped_oom;
emac_recycle_rx_skb(dev, slot, 0);
} else {
dev->rx_sg_skb = skb;
skb_put(skb, len);
}
} else if (!emac_rx_sg_append(dev, slot) &&
(ctrl & MAL_RX_CTRL_LAST)) {
skb = dev->rx_sg_skb;
dev->rx_sg_skb = NULL;
ctrl &= EMAC_BAD_RX_MASK;
if (unlikely(ctrl && ctrl != EMAC_RX_TAH_BAD_CSUM)) {
emac_parse_rx_error(dev, ctrl);
++dev->estats.rx_dropped_error;
dev_kfree_skb(skb);
len = 0;
} else
goto push_packet;
}
goto skip;
oom:
DBG(dev, "rx OOM %d" NL, slot);
/* Drop the packet and recycle skb */
++dev->estats.rx_dropped_oom;
emac_recycle_rx_skb(dev, slot, 0);
goto next;
}
if (received) {
DBG2(dev, "rx %d BDs" NL, received);
dev->rx_slot = slot;
}
if (unlikely(budget && test_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags))) {
mb();
if (!(dev->rx_desc[slot].ctrl & MAL_RX_CTRL_EMPTY)) {
DBG2(dev, "rx restart" NL);
received = 0;
goto again;
}
if (dev->rx_sg_skb) {
DBG2(dev, "dropping partial rx packet" NL);
++dev->estats.rx_dropped_error;
dev_kfree_skb(dev->rx_sg_skb);
dev->rx_sg_skb = NULL;
}
clear_bit(MAL_COMMAC_RX_STOPPED, &dev->commac.flags);
mal_enable_rx_channel(dev->mal, dev->mal_rx_chan);
emac_rx_enable(dev);
dev->rx_slot = 0;
}
return received;
}
/* NAPI poll context */
static int emac_peek_rx(void *param)
{
struct emac_instance *dev = param;
return !(dev->rx_desc[dev->rx_slot].ctrl & MAL_RX_CTRL_EMPTY);
}
/* NAPI poll context */
static int emac_peek_rx_sg(void *param)
{
struct emac_instance *dev = param;
int slot = dev->rx_slot;
while (1) {
u16 ctrl = dev->rx_desc[slot].ctrl;
if (ctrl & MAL_RX_CTRL_EMPTY)
return 0;
else if (ctrl & MAL_RX_CTRL_LAST)
return 1;
slot = (slot + 1) % NUM_RX_BUFF;
/* I'm just being paranoid here :) */
if (unlikely(slot == dev->rx_slot))
return 0;
}
}
/* Hard IRQ */
static void emac_rxde(void *param)
{
struct emac_instance *dev = param;
++dev->estats.rx_stopped;
emac_rx_disable_async(dev);
}
/* Hard IRQ */
static irqreturn_t emac_irq(int irq, void *dev_instance)
{
struct emac_instance *dev = dev_instance;
struct emac_regs __iomem *p = dev->emacp;
struct emac_error_stats *st = &dev->estats;
u32 isr;
spin_lock(&dev->lock);
isr = in_be32(&p->isr);
out_be32(&p->isr, isr);
DBG(dev, "isr = %08x" NL, isr);
if (isr & EMAC4_ISR_TXPE)
++st->tx_parity;
if (isr & EMAC4_ISR_RXPE)
++st->rx_parity;
if (isr & EMAC4_ISR_TXUE)
++st->tx_underrun;
if (isr & EMAC4_ISR_RXOE)
++st->rx_fifo_overrun;
if (isr & EMAC_ISR_OVR)
++st->rx_overrun;
if (isr & EMAC_ISR_BP)
++st->rx_bad_packet;
if (isr & EMAC_ISR_RP)
++st->rx_runt_packet;
if (isr & EMAC_ISR_SE)
++st->rx_short_event;
if (isr & EMAC_ISR_ALE)
++st->rx_alignment_error;
if (isr & EMAC_ISR_BFCS)
++st->rx_bad_fcs;
if (isr & EMAC_ISR_PTLE)
++st->rx_packet_too_long;
if (isr & EMAC_ISR_ORE)
++st->rx_out_of_range;
if (isr & EMAC_ISR_IRE)
++st->rx_in_range;
if (isr & EMAC_ISR_SQE)
++st->tx_sqe;
if (isr & EMAC_ISR_TE)
++st->tx_errors;
spin_unlock(&dev->lock);
return IRQ_HANDLED;
}
static struct net_device_stats *emac_stats(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
struct emac_stats *st = &dev->stats;
struct emac_error_stats *est = &dev->estats;
struct net_device_stats *nst = &dev->nstats;
unsigned long flags;
DBG2(dev, "stats" NL);
/* Compute "legacy" statistics */
spin_lock_irqsave(&dev->lock, flags);
nst->rx_packets = (unsigned long)st->rx_packets;
nst->rx_bytes = (unsigned long)st->rx_bytes;
nst->tx_packets = (unsigned long)st->tx_packets;
nst->tx_bytes = (unsigned long)st->tx_bytes;
nst->rx_dropped = (unsigned long)(est->rx_dropped_oom +
est->rx_dropped_error +
est->rx_dropped_resize +
est->rx_dropped_mtu);
nst->tx_dropped = (unsigned long)est->tx_dropped;
nst->rx_errors = (unsigned long)est->rx_bd_errors;
nst->rx_fifo_errors = (unsigned long)(est->rx_bd_overrun +
est->rx_fifo_overrun +
est->rx_overrun);
nst->rx_frame_errors = (unsigned long)(est->rx_bd_alignment_error +
est->rx_alignment_error);
nst->rx_crc_errors = (unsigned long)(est->rx_bd_bad_fcs +
est->rx_bad_fcs);
nst->rx_length_errors = (unsigned long)(est->rx_bd_runt_packet +
est->rx_bd_short_event +
est->rx_bd_packet_too_long +
est->rx_bd_out_of_range +
est->rx_bd_in_range +
est->rx_runt_packet +
est->rx_short_event +
est->rx_packet_too_long +
est->rx_out_of_range +
est->rx_in_range);
nst->tx_errors = (unsigned long)(est->tx_bd_errors + est->tx_errors);
nst->tx_fifo_errors = (unsigned long)(est->tx_bd_underrun +
est->tx_underrun);
nst->tx_carrier_errors = (unsigned long)est->tx_bd_carrier_loss;
nst->collisions = (unsigned long)(est->tx_bd_excessive_deferral +
est->tx_bd_excessive_collisions +
est->tx_bd_late_collision +
est->tx_bd_multple_collisions);
spin_unlock_irqrestore(&dev->lock, flags);
return nst;
}
static struct mal_commac_ops emac_commac_ops = {
.poll_tx = &emac_poll_tx,
.poll_rx = &emac_poll_rx,
.peek_rx = &emac_peek_rx,
.rxde = &emac_rxde,
};
static struct mal_commac_ops emac_commac_sg_ops = {
.poll_tx = &emac_poll_tx,
.poll_rx = &emac_poll_rx,
.peek_rx = &emac_peek_rx_sg,
.rxde = &emac_rxde,
};
/* Ethtool support */
static int emac_ethtool_get_settings(struct net_device *ndev,
struct ethtool_cmd *cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
cmd->supported = dev->phy.features;
cmd->port = PORT_MII;
cmd->phy_address = dev->phy.address;
cmd->transceiver =
dev->phy.address >= 0 ? XCVR_EXTERNAL : XCVR_INTERNAL;
mutex_lock(&dev->link_lock);
cmd->advertising = dev->phy.advertising;
cmd->autoneg = dev->phy.autoneg;
cmd->speed = dev->phy.speed;
cmd->duplex = dev->phy.duplex;
mutex_unlock(&dev->link_lock);
return 0;
}
static int emac_ethtool_set_settings(struct net_device *ndev,
struct ethtool_cmd *cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
u32 f = dev->phy.features;
DBG(dev, "set_settings(%d, %d, %d, 0x%08x)" NL,
cmd->autoneg, cmd->speed, cmd->duplex, cmd->advertising);
/* Basic sanity checks */
if (dev->phy.address < 0)
return -EOPNOTSUPP;
if (cmd->autoneg != AUTONEG_ENABLE && cmd->autoneg != AUTONEG_DISABLE)
return -EINVAL;
if (cmd->autoneg == AUTONEG_ENABLE && cmd->advertising == 0)
return -EINVAL;
if (cmd->duplex != DUPLEX_HALF && cmd->duplex != DUPLEX_FULL)
return -EINVAL;
if (cmd->autoneg == AUTONEG_DISABLE) {
switch (cmd->speed) {
case SPEED_10:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_10baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_10baseT_Full))
return -EINVAL;
break;
case SPEED_100:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_100baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_100baseT_Full))
return -EINVAL;
break;
case SPEED_1000:
if (cmd->duplex == DUPLEX_HALF &&
!(f & SUPPORTED_1000baseT_Half))
return -EINVAL;
if (cmd->duplex == DUPLEX_FULL &&
!(f & SUPPORTED_1000baseT_Full))
return -EINVAL;
break;
default:
return -EINVAL;
}
mutex_lock(&dev->link_lock);
dev->phy.def->ops->setup_forced(&dev->phy, cmd->speed,
cmd->duplex);
mutex_unlock(&dev->link_lock);
} else {
if (!(f & SUPPORTED_Autoneg))
return -EINVAL;
mutex_lock(&dev->link_lock);
dev->phy.def->ops->setup_aneg(&dev->phy,
(cmd->advertising & f) |
(dev->phy.advertising &
(ADVERTISED_Pause |
ADVERTISED_Asym_Pause)));
mutex_unlock(&dev->link_lock);
}
emac_force_link_update(dev);
return 0;
}
static void emac_ethtool_get_ringparam(struct net_device *ndev,
struct ethtool_ringparam *rp)
{
rp->rx_max_pending = rp->rx_pending = NUM_RX_BUFF;
rp->tx_max_pending = rp->tx_pending = NUM_TX_BUFF;
}
static void emac_ethtool_get_pauseparam(struct net_device *ndev,
struct ethtool_pauseparam *pp)
{
struct emac_instance *dev = netdev_priv(ndev);
mutex_lock(&dev->link_lock);
if ((dev->phy.features & SUPPORTED_Autoneg) &&
(dev->phy.advertising & (ADVERTISED_Pause | ADVERTISED_Asym_Pause)))
pp->autoneg = 1;
if (dev->phy.duplex == DUPLEX_FULL) {
if (dev->phy.pause)
pp->rx_pause = pp->tx_pause = 1;
else if (dev->phy.asym_pause)
pp->tx_pause = 1;
}
mutex_unlock(&dev->link_lock);
}
static u32 emac_ethtool_get_rx_csum(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
return dev->tah_dev != NULL;
}
static int emac_get_regs_len(struct emac_instance *dev)
{
if (emac_has_feature(dev, EMAC_FTR_EMAC4))
return sizeof(struct emac_ethtool_regs_subhdr) +
EMAC4_ETHTOOL_REGS_SIZE(dev);
else
return sizeof(struct emac_ethtool_regs_subhdr) +
EMAC_ETHTOOL_REGS_SIZE(dev);
}
static int emac_ethtool_get_regs_len(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int size;
size = sizeof(struct emac_ethtool_regs_hdr) +
emac_get_regs_len(dev) + mal_get_regs_len(dev->mal);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
size += zmii_get_regs_len(dev->zmii_dev);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
size += rgmii_get_regs_len(dev->rgmii_dev);
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
size += tah_get_regs_len(dev->tah_dev);
return size;
}
static void *emac_dump_regs(struct emac_instance *dev, void *buf)
{
struct emac_ethtool_regs_subhdr *hdr = buf;
hdr->index = dev->cell_index;
if (emac_has_feature(dev, EMAC_FTR_EMAC4)) {
hdr->version = EMAC4_ETHTOOL_REGS_VER;
memcpy_fromio(hdr + 1, dev->emacp, EMAC4_ETHTOOL_REGS_SIZE(dev));
return ((void *)(hdr + 1) + EMAC4_ETHTOOL_REGS_SIZE(dev));
} else {
hdr->version = EMAC_ETHTOOL_REGS_VER;
memcpy_fromio(hdr + 1, dev->emacp, EMAC_ETHTOOL_REGS_SIZE(dev));
return ((void *)(hdr + 1) + EMAC_ETHTOOL_REGS_SIZE(dev));
}
}
static void emac_ethtool_get_regs(struct net_device *ndev,
struct ethtool_regs *regs, void *buf)
{
struct emac_instance *dev = netdev_priv(ndev);
struct emac_ethtool_regs_hdr *hdr = buf;
hdr->components = 0;
buf = hdr + 1;
buf = mal_dump_regs(dev->mal, buf);
buf = emac_dump_regs(dev, buf);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII)) {
hdr->components |= EMAC_ETHTOOL_REGS_ZMII;
buf = zmii_dump_regs(dev->zmii_dev, buf);
}
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII)) {
hdr->components |= EMAC_ETHTOOL_REGS_RGMII;
buf = rgmii_dump_regs(dev->rgmii_dev, buf);
}
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH)) {
hdr->components |= EMAC_ETHTOOL_REGS_TAH;
buf = tah_dump_regs(dev->tah_dev, buf);
}
}
static int emac_ethtool_nway_reset(struct net_device *ndev)
{
struct emac_instance *dev = netdev_priv(ndev);
int res = 0;
DBG(dev, "nway_reset" NL);
if (dev->phy.address < 0)
return -EOPNOTSUPP;
mutex_lock(&dev->link_lock);
if (!dev->phy.autoneg) {
res = -EINVAL;
goto out;
}
dev->phy.def->ops->setup_aneg(&dev->phy, dev->phy.advertising);
out:
mutex_unlock(&dev->link_lock);
emac_force_link_update(dev);
return res;
}
static int emac_ethtool_get_sset_count(struct net_device *ndev, int stringset)
{
if (stringset == ETH_SS_STATS)
return EMAC_ETHTOOL_STATS_COUNT;
else
return -EINVAL;
}
static void emac_ethtool_get_strings(struct net_device *ndev, u32 stringset,
u8 * buf)
{
if (stringset == ETH_SS_STATS)
memcpy(buf, &emac_stats_keys, sizeof(emac_stats_keys));
}
static void emac_ethtool_get_ethtool_stats(struct net_device *ndev,
struct ethtool_stats *estats,
u64 * tmp_stats)
{
struct emac_instance *dev = netdev_priv(ndev);
memcpy(tmp_stats, &dev->stats, sizeof(dev->stats));
tmp_stats += sizeof(dev->stats) / sizeof(u64);
memcpy(tmp_stats, &dev->estats, sizeof(dev->estats));
}
static void emac_ethtool_get_drvinfo(struct net_device *ndev,
struct ethtool_drvinfo *info)
{
struct emac_instance *dev = netdev_priv(ndev);
strcpy(info->driver, "ibm_emac");
strcpy(info->version, DRV_VERSION);
info->fw_version[0] = '\0';
sprintf(info->bus_info, "PPC 4xx EMAC-%d %s",
dev->cell_index, dev->ofdev->node->full_name);
info->regdump_len = emac_ethtool_get_regs_len(ndev);
}
static const struct ethtool_ops emac_ethtool_ops = {
.get_settings = emac_ethtool_get_settings,
.set_settings = emac_ethtool_set_settings,
.get_drvinfo = emac_ethtool_get_drvinfo,
.get_regs_len = emac_ethtool_get_regs_len,
.get_regs = emac_ethtool_get_regs,
.nway_reset = emac_ethtool_nway_reset,
.get_ringparam = emac_ethtool_get_ringparam,
.get_pauseparam = emac_ethtool_get_pauseparam,
.get_rx_csum = emac_ethtool_get_rx_csum,
.get_strings = emac_ethtool_get_strings,
.get_sset_count = emac_ethtool_get_sset_count,
.get_ethtool_stats = emac_ethtool_get_ethtool_stats,
.get_link = ethtool_op_get_link,
.get_tx_csum = ethtool_op_get_tx_csum,
.get_sg = ethtool_op_get_sg,
};
static int emac_ioctl(struct net_device *ndev, struct ifreq *rq, int cmd)
{
struct emac_instance *dev = netdev_priv(ndev);
struct mii_ioctl_data *data = if_mii(rq);
DBG(dev, "ioctl %08x" NL, cmd);
if (dev->phy.address < 0)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = dev->phy.address;
/* Fall through */
case SIOCGMIIREG:
data->val_out = emac_mdio_read(ndev, dev->phy.address,
data->reg_num);
return 0;
case SIOCSMIIREG:
emac_mdio_write(ndev, dev->phy.address, data->reg_num,
data->val_in);
return 0;
default:
return -EOPNOTSUPP;
}
}
struct emac_depentry {
u32 phandle;
struct device_node *node;
struct of_device *ofdev;
void *drvdata;
};
#define EMAC_DEP_MAL_IDX 0
#define EMAC_DEP_ZMII_IDX 1
#define EMAC_DEP_RGMII_IDX 2
#define EMAC_DEP_TAH_IDX 3
#define EMAC_DEP_MDIO_IDX 4
#define EMAC_DEP_PREV_IDX 5
#define EMAC_DEP_COUNT 6
static int __devinit emac_check_deps(struct emac_instance *dev,
struct emac_depentry *deps)
{
int i, there = 0;
struct device_node *np;
for (i = 0; i < EMAC_DEP_COUNT; i++) {
/* no dependency on that item, allright */
if (deps[i].phandle == 0) {
there++;
continue;
}
/* special case for blist as the dependency might go away */
if (i == EMAC_DEP_PREV_IDX) {
np = *(dev->blist - 1);
if (np == NULL) {
deps[i].phandle = 0;
there++;
continue;
}
if (deps[i].node == NULL)
deps[i].node = of_node_get(np);
}
if (deps[i].node == NULL)
deps[i].node = of_find_node_by_phandle(deps[i].phandle);
if (deps[i].node == NULL)
continue;
if (deps[i].ofdev == NULL)
deps[i].ofdev = of_find_device_by_node(deps[i].node);
if (deps[i].ofdev == NULL)
continue;
if (deps[i].drvdata == NULL)
deps[i].drvdata = dev_get_drvdata(&deps[i].ofdev->dev);
if (deps[i].drvdata != NULL)
there++;
}
return (there == EMAC_DEP_COUNT);
}
static void emac_put_deps(struct emac_instance *dev)
{
if (dev->mal_dev)
of_dev_put(dev->mal_dev);
if (dev->zmii_dev)
of_dev_put(dev->zmii_dev);
if (dev->rgmii_dev)
of_dev_put(dev->rgmii_dev);
if (dev->mdio_dev)
of_dev_put(dev->mdio_dev);
if (dev->tah_dev)
of_dev_put(dev->tah_dev);
}
static int __devinit emac_of_bus_notify(struct notifier_block *nb,
unsigned long action, void *data)
{
/* We are only intereted in device addition */
if (action == BUS_NOTIFY_BOUND_DRIVER)
wake_up_all(&emac_probe_wait);
return 0;
}
static struct notifier_block emac_of_bus_notifier __devinitdata = {
.notifier_call = emac_of_bus_notify
};
static int __devinit emac_wait_deps(struct emac_instance *dev)
{
struct emac_depentry deps[EMAC_DEP_COUNT];
int i, err;
memset(&deps, 0, sizeof(deps));
deps[EMAC_DEP_MAL_IDX].phandle = dev->mal_ph;
deps[EMAC_DEP_ZMII_IDX].phandle = dev->zmii_ph;
deps[EMAC_DEP_RGMII_IDX].phandle = dev->rgmii_ph;
if (dev->tah_ph)
deps[EMAC_DEP_TAH_IDX].phandle = dev->tah_ph;
if (dev->mdio_ph)
deps[EMAC_DEP_MDIO_IDX].phandle = dev->mdio_ph;
if (dev->blist && dev->blist > emac_boot_list)
deps[EMAC_DEP_PREV_IDX].phandle = 0xffffffffu;
bus_register_notifier(&of_platform_bus_type, &emac_of_bus_notifier);
wait_event_timeout(emac_probe_wait,
emac_check_deps(dev, deps),
EMAC_PROBE_DEP_TIMEOUT);
bus_unregister_notifier(&of_platform_bus_type, &emac_of_bus_notifier);
err = emac_check_deps(dev, deps) ? 0 : -ENODEV;
for (i = 0; i < EMAC_DEP_COUNT; i++) {
if (deps[i].node)
of_node_put(deps[i].node);
if (err && deps[i].ofdev)
of_dev_put(deps[i].ofdev);
}
if (err == 0) {
dev->mal_dev = deps[EMAC_DEP_MAL_IDX].ofdev;
dev->zmii_dev = deps[EMAC_DEP_ZMII_IDX].ofdev;
dev->rgmii_dev = deps[EMAC_DEP_RGMII_IDX].ofdev;
dev->tah_dev = deps[EMAC_DEP_TAH_IDX].ofdev;
dev->mdio_dev = deps[EMAC_DEP_MDIO_IDX].ofdev;
}
if (deps[EMAC_DEP_PREV_IDX].ofdev)
of_dev_put(deps[EMAC_DEP_PREV_IDX].ofdev);
return err;
}
static int __devinit emac_read_uint_prop(struct device_node *np, const char *name,
u32 *val, int fatal)
{
int len;
const u32 *prop = of_get_property(np, name, &len);
if (prop == NULL || len < sizeof(u32)) {
if (fatal)
printk(KERN_ERR "%s: missing %s property\n",
np->full_name, name);
return -ENODEV;
}
*val = *prop;
return 0;
}
static int __devinit emac_init_phy(struct emac_instance *dev)
{
struct device_node *np = dev->ofdev->node;
struct net_device *ndev = dev->ndev;
u32 phy_map, adv;
int i;
dev->phy.dev = ndev;
dev->phy.mode = dev->phy_mode;
/* PHY-less configuration.
* XXX I probably should move these settings to the dev tree
*/
if (dev->phy_address == 0xffffffff && dev->phy_map == 0xffffffff) {
emac_reset(dev);
/* PHY-less configuration.
* XXX I probably should move these settings to the dev tree
*/
dev->phy.address = -1;
dev->phy.features = SUPPORTED_MII;
if (emac_phy_supports_gige(dev->phy_mode))
dev->phy.features |= SUPPORTED_1000baseT_Full;
else
dev->phy.features |= SUPPORTED_100baseT_Full;
dev->phy.pause = 1;
return 0;
}
mutex_lock(&emac_phy_map_lock);
phy_map = dev->phy_map | busy_phy_map;
DBG(dev, "PHY maps %08x %08x" NL, dev->phy_map, busy_phy_map);
dev->phy.mdio_read = emac_mdio_read;
dev->phy.mdio_write = emac_mdio_write;
/* Enable internal clock source */
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, 0, SDR0_MFR_ECS);
#endif
/* PHY clock workaround */
emac_rx_clk_tx(dev);
/* Enable internal clock source on 440GX*/
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, 0, SDR0_MFR_ECS);
#endif
/* Configure EMAC with defaults so we can at least use MDIO
* This is needed mostly for 440GX
*/
if (emac_phy_gpcs(dev->phy.mode)) {
/* XXX
* Make GPCS PHY address equal to EMAC index.
* We probably should take into account busy_phy_map
* and/or phy_map here.
*
* Note that the busy_phy_map is currently global
* while it should probably be per-ASIC...
*/
dev->phy.gpcs_address = dev->gpcs_address;
if (dev->phy.gpcs_address == 0xffffffff)
dev->phy.address = dev->cell_index;
}
emac_configure(dev);
if (dev->phy_address != 0xffffffff)
phy_map = ~(1 << dev->phy_address);
for (i = 0; i < 0x20; phy_map >>= 1, ++i)
if (!(phy_map & 1)) {
int r;
busy_phy_map |= 1 << i;
/* Quick check if there is a PHY at the address */
r = emac_mdio_read(dev->ndev, i, MII_BMCR);
if (r == 0xffff || r < 0)
continue;
if (!emac_mii_phy_probe(&dev->phy, i))
break;
}
/* Enable external clock source */
#ifdef CONFIG_PPC_DCR_NATIVE
if (emac_has_feature(dev, EMAC_FTR_440GX_PHY_CLK_FIX))
dcri_clrset(SDR0, SDR0_MFR, SDR0_MFR_ECS, 0);
#endif
mutex_unlock(&emac_phy_map_lock);
if (i == 0x20) {
printk(KERN_WARNING "%s: can't find PHY!\n", np->full_name);
return -ENXIO;
}
/* Init PHY */
if (dev->phy.def->ops->init)
dev->phy.def->ops->init(&dev->phy);
/* Disable any PHY features not supported by the platform */
dev->phy.def->features &= ~dev->phy_feat_exc;
/* Setup initial link parameters */
if (dev->phy.features & SUPPORTED_Autoneg) {
adv = dev->phy.features;
if (!emac_has_feature(dev, EMAC_FTR_NO_FLOW_CONTROL_40x))
adv |= ADVERTISED_Pause | ADVERTISED_Asym_Pause;
/* Restart autonegotiation */
dev->phy.def->ops->setup_aneg(&dev->phy, adv);
} else {
u32 f = dev->phy.def->features;
int speed = SPEED_10, fd = DUPLEX_HALF;
/* Select highest supported speed/duplex */
if (f & SUPPORTED_1000baseT_Full) {
speed = SPEED_1000;
fd = DUPLEX_FULL;
} else if (f & SUPPORTED_1000baseT_Half)
speed = SPEED_1000;
else if (f & SUPPORTED_100baseT_Full) {
speed = SPEED_100;
fd = DUPLEX_FULL;
} else if (f & SUPPORTED_100baseT_Half)
speed = SPEED_100;
else if (f & SUPPORTED_10baseT_Full)
fd = DUPLEX_FULL;
/* Force link parameters */
dev->phy.def->ops->setup_forced(&dev->phy, speed, fd);
}
return 0;
}
static int __devinit emac_init_config(struct emac_instance *dev)
{
struct device_node *np = dev->ofdev->node;
const void *p;
unsigned int plen;
const char *pm, *phy_modes[] = {
[PHY_MODE_NA] = "",
[PHY_MODE_MII] = "mii",
[PHY_MODE_RMII] = "rmii",
[PHY_MODE_SMII] = "smii",
[PHY_MODE_RGMII] = "rgmii",
[PHY_MODE_TBI] = "tbi",
[PHY_MODE_GMII] = "gmii",
[PHY_MODE_RTBI] = "rtbi",
[PHY_MODE_SGMII] = "sgmii",
};
/* Read config from device-tree */
if (emac_read_uint_prop(np, "mal-device", &dev->mal_ph, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "mal-tx-channel", &dev->mal_tx_chan, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "mal-rx-channel", &dev->mal_rx_chan, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "cell-index", &dev->cell_index, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "max-frame-size", &dev->max_mtu, 0))
dev->max_mtu = 1500;
if (emac_read_uint_prop(np, "rx-fifo-size", &dev->rx_fifo_size, 0))
dev->rx_fifo_size = 2048;
if (emac_read_uint_prop(np, "tx-fifo-size", &dev->tx_fifo_size, 0))
dev->tx_fifo_size = 2048;
if (emac_read_uint_prop(np, "rx-fifo-size-gige", &dev->rx_fifo_size_gige, 0))
dev->rx_fifo_size_gige = dev->rx_fifo_size;
if (emac_read_uint_prop(np, "tx-fifo-size-gige", &dev->tx_fifo_size_gige, 0))
dev->tx_fifo_size_gige = dev->tx_fifo_size;
if (emac_read_uint_prop(np, "phy-address", &dev->phy_address, 0))
dev->phy_address = 0xffffffff;
if (emac_read_uint_prop(np, "phy-map", &dev->phy_map, 0))
dev->phy_map = 0xffffffff;
if (emac_read_uint_prop(np, "gpcs-address", &dev->gpcs_address, 0))
dev->gpcs_address = 0xffffffff;
if (emac_read_uint_prop(np->parent, "clock-frequency", &dev->opb_bus_freq, 1))
return -ENXIO;
if (emac_read_uint_prop(np, "tah-device", &dev->tah_ph, 0))
dev->tah_ph = 0;
if (emac_read_uint_prop(np, "tah-channel", &dev->tah_port, 0))
dev->tah_port = 0;
if (emac_read_uint_prop(np, "mdio-device", &dev->mdio_ph, 0))
dev->mdio_ph = 0;
if (emac_read_uint_prop(np, "zmii-device", &dev->zmii_ph, 0))
dev->zmii_ph = 0;
if (emac_read_uint_prop(np, "zmii-channel", &dev->zmii_port, 0))
dev->zmii_port = 0xffffffff;
if (emac_read_uint_prop(np, "rgmii-device", &dev->rgmii_ph, 0))
dev->rgmii_ph = 0;
if (emac_read_uint_prop(np, "rgmii-channel", &dev->rgmii_port, 0))
dev->rgmii_port = 0xffffffff;
if (emac_read_uint_prop(np, "fifo-entry-size", &dev->fifo_entry_size, 0))
dev->fifo_entry_size = 16;
if (emac_read_uint_prop(np, "mal-burst-size", &dev->mal_burst_size, 0))
dev->mal_burst_size = 256;
/* PHY mode needs some decoding */
dev->phy_mode = PHY_MODE_NA;
pm = of_get_property(np, "phy-mode", &plen);
if (pm != NULL) {
int i;
for (i = 0; i < ARRAY_SIZE(phy_modes); i++)
if (!strcasecmp(pm, phy_modes[i])) {
dev->phy_mode = i;
break;
}
}
/* Backward compat with non-final DT */
if (dev->phy_mode == PHY_MODE_NA && pm != NULL && plen == 4) {
u32 nmode = *(const u32 *)pm;
if (nmode > PHY_MODE_NA && nmode <= PHY_MODE_SGMII)
dev->phy_mode = nmode;
}
/* Check EMAC version */
if (of_device_is_compatible(np, "ibm,emac4sync")) {
dev->features |= (EMAC_FTR_EMAC4 | EMAC_FTR_EMAC4SYNC);
if (of_device_is_compatible(np, "ibm,emac-460ex") ||
of_device_is_compatible(np, "ibm,emac-460gt"))
dev->features |= EMAC_FTR_460EX_PHY_CLK_FIX;
if (of_device_is_compatible(np, "ibm,emac-405ex") ||
of_device_is_compatible(np, "ibm,emac-405exr"))
dev->features |= EMAC_FTR_440EP_PHY_CLK_FIX;
} else if (of_device_is_compatible(np, "ibm,emac4")) {
dev->features |= EMAC_FTR_EMAC4;
if (of_device_is_compatible(np, "ibm,emac-440gx"))
dev->features |= EMAC_FTR_440GX_PHY_CLK_FIX;
} else {
if (of_device_is_compatible(np, "ibm,emac-440ep") ||
of_device_is_compatible(np, "ibm,emac-440gr"))
dev->features |= EMAC_FTR_440EP_PHY_CLK_FIX;
if (of_device_is_compatible(np, "ibm,emac-405ez")) {
#ifdef CONFIG_IBM_NEW_EMAC_NO_FLOW_CTRL
dev->features |= EMAC_FTR_NO_FLOW_CONTROL_40x;
#else
printk(KERN_ERR "%s: Flow control not disabled!\n",
np->full_name);
return -ENXIO;
#endif
}
}
/* Fixup some feature bits based on the device tree */
if (of_get_property(np, "has-inverted-stacr-oc", NULL))
dev->features |= EMAC_FTR_STACR_OC_INVERT;
if (of_get_property(np, "has-new-stacr-staopc", NULL))
dev->features |= EMAC_FTR_HAS_NEW_STACR;
/* CAB lacks the appropriate properties */
if (of_device_is_compatible(np, "ibm,emac-axon"))
dev->features |= EMAC_FTR_HAS_NEW_STACR |
EMAC_FTR_STACR_OC_INVERT;
/* Enable TAH/ZMII/RGMII features as found */
if (dev->tah_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_TAH
dev->features |= EMAC_FTR_HAS_TAH;
#else
printk(KERN_ERR "%s: TAH support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
if (dev->zmii_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_ZMII
dev->features |= EMAC_FTR_HAS_ZMII;
#else
printk(KERN_ERR "%s: ZMII support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
if (dev->rgmii_ph != 0) {
#ifdef CONFIG_IBM_NEW_EMAC_RGMII
dev->features |= EMAC_FTR_HAS_RGMII;
#else
printk(KERN_ERR "%s: RGMII support not enabled !\n",
np->full_name);
return -ENXIO;
#endif
}
/* Read MAC-address */
p = of_get_property(np, "local-mac-address", NULL);
if (p == NULL) {
printk(KERN_ERR "%s: Can't find local-mac-address property\n",
np->full_name);
return -ENXIO;
}
memcpy(dev->ndev->dev_addr, p, 6);
/* IAHT and GAHT filter parameterization */
if (emac_has_feature(dev, EMAC_FTR_EMAC4SYNC)) {
dev->xaht_slots_shift = EMAC4SYNC_XAHT_SLOTS_SHIFT;
dev->xaht_width_shift = EMAC4SYNC_XAHT_WIDTH_SHIFT;
} else {
dev->xaht_slots_shift = EMAC4_XAHT_SLOTS_SHIFT;
dev->xaht_width_shift = EMAC4_XAHT_WIDTH_SHIFT;
}
DBG(dev, "features : 0x%08x / 0x%08x\n", dev->features, EMAC_FTRS_POSSIBLE);
DBG(dev, "tx_fifo_size : %d (%d gige)\n", dev->tx_fifo_size, dev->tx_fifo_size_gige);
DBG(dev, "rx_fifo_size : %d (%d gige)\n", dev->rx_fifo_size, dev->rx_fifo_size_gige);
DBG(dev, "max_mtu : %d\n", dev->max_mtu);
DBG(dev, "OPB freq : %d\n", dev->opb_bus_freq);
return 0;
}
static const struct net_device_ops emac_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_get_stats = emac_stats,
.ndo_set_multicast_list = emac_set_multicast_list,
.ndo_do_ioctl = emac_ioctl,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_start_xmit = emac_start_xmit,
.ndo_change_mtu = eth_change_mtu,
};
static const struct net_device_ops emac_gige_netdev_ops = {
.ndo_open = emac_open,
.ndo_stop = emac_close,
.ndo_get_stats = emac_stats,
.ndo_set_multicast_list = emac_set_multicast_list,
.ndo_do_ioctl = emac_ioctl,
.ndo_tx_timeout = emac_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_set_mac_address = eth_mac_addr,
.ndo_start_xmit = emac_start_xmit_sg,
.ndo_change_mtu = emac_change_mtu,
};
static int __devinit emac_probe(struct of_device *ofdev,
const struct of_device_id *match)
{
struct net_device *ndev;
struct emac_instance *dev;
struct device_node *np = ofdev->node;
struct device_node **blist = NULL;
int err, i;
/* Skip unused/unwired EMACS. We leave the check for an unused
* property here for now, but new flat device trees should set a
* status property to "disabled" instead.
*/
if (of_get_property(np, "unused", NULL) || !of_device_is_available(np))
return -ENODEV;
/* Find ourselves in the bootlist if we are there */
for (i = 0; i < EMAC_BOOT_LIST_SIZE; i++)
if (emac_boot_list[i] == np)
blist = &emac_boot_list[i];
/* Allocate our net_device structure */
err = -ENOMEM;
ndev = alloc_etherdev(sizeof(struct emac_instance));
if (!ndev) {
printk(KERN_ERR "%s: could not allocate ethernet device!\n",
np->full_name);
goto err_gone;
}
dev = netdev_priv(ndev);
dev->ndev = ndev;
dev->ofdev = ofdev;
dev->blist = blist;
SET_NETDEV_DEV(ndev, &ofdev->dev);
/* Initialize some embedded data structures */
mutex_init(&dev->mdio_lock);
mutex_init(&dev->link_lock);
spin_lock_init(&dev->lock);
INIT_WORK(&dev->reset_work, emac_reset_work);
/* Init various config data based on device-tree */
err = emac_init_config(dev);
if (err != 0)
goto err_free;
/* Get interrupts. EMAC irq is mandatory, WOL irq is optional */
dev->emac_irq = irq_of_parse_and_map(np, 0);
dev->wol_irq = irq_of_parse_and_map(np, 1);
if (dev->emac_irq == NO_IRQ) {
printk(KERN_ERR "%s: Can't map main interrupt\n", np->full_name);
goto err_free;
}
ndev->irq = dev->emac_irq;
/* Map EMAC regs */
if (of_address_to_resource(np, 0, &dev->rsrc_regs)) {
printk(KERN_ERR "%s: Can't get registers address\n",
np->full_name);
goto err_irq_unmap;
}
// TODO : request_mem_region
dev->emacp = ioremap(dev->rsrc_regs.start,
dev->rsrc_regs.end - dev->rsrc_regs.start + 1);
if (dev->emacp == NULL) {
printk(KERN_ERR "%s: Can't map device registers!\n",
np->full_name);
err = -ENOMEM;
goto err_irq_unmap;
}
/* Wait for dependent devices */
err = emac_wait_deps(dev);
if (err) {
printk(KERN_ERR
"%s: Timeout waiting for dependent devices\n",
np->full_name);
/* display more info about what's missing ? */
goto err_reg_unmap;
}
dev->mal = dev_get_drvdata(&dev->mal_dev->dev);
if (dev->mdio_dev != NULL)
dev->mdio_instance = dev_get_drvdata(&dev->mdio_dev->dev);
/* Register with MAL */
dev->commac.ops = &emac_commac_ops;
dev->commac.dev = dev;
dev->commac.tx_chan_mask = MAL_CHAN_MASK(dev->mal_tx_chan);
dev->commac.rx_chan_mask = MAL_CHAN_MASK(dev->mal_rx_chan);
err = mal_register_commac(dev->mal, &dev->commac);
if (err) {
printk(KERN_ERR "%s: failed to register with mal %s!\n",
np->full_name, dev->mal_dev->node->full_name);
goto err_rel_deps;
}
dev->rx_skb_size = emac_rx_skb_size(ndev->mtu);
dev->rx_sync_size = emac_rx_sync_size(ndev->mtu);
/* Get pointers to BD rings */
dev->tx_desc =
dev->mal->bd_virt + mal_tx_bd_offset(dev->mal, dev->mal_tx_chan);
dev->rx_desc =
dev->mal->bd_virt + mal_rx_bd_offset(dev->mal, dev->mal_rx_chan);
DBG(dev, "tx_desc %p" NL, dev->tx_desc);
DBG(dev, "rx_desc %p" NL, dev->rx_desc);
/* Clean rings */
memset(dev->tx_desc, 0, NUM_TX_BUFF * sizeof(struct mal_descriptor));
memset(dev->rx_desc, 0, NUM_RX_BUFF * sizeof(struct mal_descriptor));
memset(dev->tx_skb, 0, NUM_TX_BUFF * sizeof(struct sk_buff *));
memset(dev->rx_skb, 0, NUM_RX_BUFF * sizeof(struct sk_buff *));
/* Attach to ZMII, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII) &&
(err = zmii_attach(dev->zmii_dev, dev->zmii_port, &dev->phy_mode)) != 0)
goto err_unreg_commac;
/* Attach to RGMII, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII) &&
(err = rgmii_attach(dev->rgmii_dev, dev->rgmii_port, dev->phy_mode)) != 0)
goto err_detach_zmii;
/* Attach to TAH, if needed */
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH) &&
(err = tah_attach(dev->tah_dev, dev->tah_port)) != 0)
goto err_detach_rgmii;
/* Set some link defaults before we can find out real parameters */
dev->phy.speed = SPEED_100;
dev->phy.duplex = DUPLEX_FULL;
dev->phy.autoneg = AUTONEG_DISABLE;
dev->phy.pause = dev->phy.asym_pause = 0;
dev->stop_timeout = STOP_TIMEOUT_100;
INIT_DELAYED_WORK(&dev->link_work, emac_link_timer);
/* Find PHY if any */
err = emac_init_phy(dev);
if (err != 0)
goto err_detach_tah;
if (dev->tah_dev)
ndev->features |= NETIF_F_IP_CSUM | NETIF_F_SG;
ndev->watchdog_timeo = 5 * HZ;
if (emac_phy_supports_gige(dev->phy_mode)) {
ndev->netdev_ops = &emac_gige_netdev_ops;
dev->commac.ops = &emac_commac_sg_ops;
} else
ndev->netdev_ops = &emac_netdev_ops;
SET_ETHTOOL_OPS(ndev, &emac_ethtool_ops);
netif_carrier_off(ndev);
netif_stop_queue(ndev);
err = register_netdev(ndev);
if (err) {
printk(KERN_ERR "%s: failed to register net device (%d)!\n",
np->full_name, err);
goto err_detach_tah;
}
/* Set our drvdata last as we don't want them visible until we are
* fully initialized
*/
wmb();
dev_set_drvdata(&ofdev->dev, dev);
/* There's a new kid in town ! Let's tell everybody */
wake_up_all(&emac_probe_wait);
printk(KERN_INFO "%s: EMAC-%d %s, MAC %pM\n",
ndev->name, dev->cell_index, np->full_name, ndev->dev_addr);
if (dev->phy_mode == PHY_MODE_SGMII)
printk(KERN_NOTICE "%s: in SGMII mode\n", ndev->name);
if (dev->phy.address >= 0)
printk("%s: found %s PHY (0x%02x)\n", ndev->name,
dev->phy.def->name, dev->phy.address);
emac_dbg_register(dev);
/* Life is good */
return 0;
/* I have a bad feeling about this ... */
err_detach_tah:
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_detach(dev->tah_dev, dev->tah_port);
err_detach_rgmii:
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_detach(dev->rgmii_dev, dev->rgmii_port);
err_detach_zmii:
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_detach(dev->zmii_dev, dev->zmii_port);
err_unreg_commac:
mal_unregister_commac(dev->mal, &dev->commac);
err_rel_deps:
emac_put_deps(dev);
err_reg_unmap:
iounmap(dev->emacp);
err_irq_unmap:
if (dev->wol_irq != NO_IRQ)
irq_dispose_mapping(dev->wol_irq);
if (dev->emac_irq != NO_IRQ)
irq_dispose_mapping(dev->emac_irq);
err_free:
kfree(ndev);
err_gone:
/* if we were on the bootlist, remove us as we won't show up and
* wake up all waiters to notify them in case they were waiting
* on us
*/
if (blist) {
*blist = NULL;
wake_up_all(&emac_probe_wait);
}
return err;
}
static int __devexit emac_remove(struct of_device *ofdev)
{
struct emac_instance *dev = dev_get_drvdata(&ofdev->dev);
DBG(dev, "remove" NL);
dev_set_drvdata(&ofdev->dev, NULL);
unregister_netdev(dev->ndev);
flush_scheduled_work();
if (emac_has_feature(dev, EMAC_FTR_HAS_TAH))
tah_detach(dev->tah_dev, dev->tah_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_RGMII))
rgmii_detach(dev->rgmii_dev, dev->rgmii_port);
if (emac_has_feature(dev, EMAC_FTR_HAS_ZMII))
zmii_detach(dev->zmii_dev, dev->zmii_port);
mal_unregister_commac(dev->mal, &dev->commac);
emac_put_deps(dev);
emac_dbg_unregister(dev);
iounmap(dev->emacp);
if (dev->wol_irq != NO_IRQ)
irq_dispose_mapping(dev->wol_irq);
if (dev->emac_irq != NO_IRQ)
irq_dispose_mapping(dev->emac_irq);
kfree(dev->ndev);
return 0;
}
/* XXX Features in here should be replaced by properties... */
static struct of_device_id emac_match[] =
{
{
.type = "network",
.compatible = "ibm,emac",
},
{
.type = "network",
.compatible = "ibm,emac4",
},
{
.type = "network",
.compatible = "ibm,emac4sync",
},
{},
};
MODULE_DEVICE_TABLE(of, emac_match);
static struct of_platform_driver emac_driver = {
.name = "emac",
.match_table = emac_match,
.probe = emac_probe,
.remove = emac_remove,
};
static void __init emac_make_bootlist(void)
{
struct device_node *np = NULL;
int j, max, i = 0, k;
int cell_indices[EMAC_BOOT_LIST_SIZE];
/* Collect EMACs */
while((np = of_find_all_nodes(np)) != NULL) {
const u32 *idx;
if (of_match_node(emac_match, np) == NULL)
continue;
if (of_get_property(np, "unused", NULL))
continue;
idx = of_get_property(np, "cell-index", NULL);
if (idx == NULL)
continue;
cell_indices[i] = *idx;
emac_boot_list[i++] = of_node_get(np);
if (i >= EMAC_BOOT_LIST_SIZE) {
of_node_put(np);
break;
}
}
max = i;
/* Bubble sort them (doh, what a creative algorithm :-) */
for (i = 0; max > 1 && (i < (max - 1)); i++)
for (j = i; j < max; j++) {
if (cell_indices[i] > cell_indices[j]) {
np = emac_boot_list[i];
emac_boot_list[i] = emac_boot_list[j];
emac_boot_list[j] = np;
k = cell_indices[i];
cell_indices[i] = cell_indices[j];
cell_indices[j] = k;
}
}
}
static int __init emac_init(void)
{
int rc;
printk(KERN_INFO DRV_DESC ", version " DRV_VERSION "\n");
/* Init debug stuff */
emac_init_debug();
/* Build EMAC boot list */
emac_make_bootlist();
/* Init submodules */
rc = mal_init();
if (rc)
goto err;
rc = zmii_init();
if (rc)
goto err_mal;
rc = rgmii_init();
if (rc)
goto err_zmii;
rc = tah_init();
if (rc)
goto err_rgmii;
rc = of_register_platform_driver(&emac_driver);
if (rc)
goto err_tah;
return 0;
err_tah:
tah_exit();
err_rgmii:
rgmii_exit();
err_zmii:
zmii_exit();
err_mal:
mal_exit();
err:
return rc;
}
static void __exit emac_exit(void)
{
int i;
of_unregister_platform_driver(&emac_driver);
tah_exit();
rgmii_exit();
zmii_exit();
mal_exit();
emac_fini_debug();
/* Destroy EMAC boot list */
for (i = 0; i < EMAC_BOOT_LIST_SIZE; i++)
if (emac_boot_list[i])
of_node_put(emac_boot_list[i]);
}
module_init(emac_init);
module_exit(emac_exit);
| gpl-2.0 |
RaymanFX/kernel_nvidia_tegra | arch/arm/mach-mx2/mach-pca100.c | 49 | 10047 | /*
* Copyright 2007 Robert Schwebel <r.schwebel@pengutronix.de>, Pengutronix
* Copyright (C) 2009 Sascha Hauer (kernel@pengutronix.de)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/i2c.h>
#include <linux/i2c/at24.h>
#include <linux/dma-mapping.h>
#include <linux/spi/spi.h>
#include <linux/spi/eeprom.h>
#include <linux/irq.h>
#include <linux/delay.h>
#include <linux/gpio.h>
#include <linux/usb/otg.h>
#include <linux/usb/ulpi.h>
#include <linux/fsl_devices.h>
#include <asm/mach/arch.h>
#include <asm/mach-types.h>
#include <mach/common.h>
#include <mach/hardware.h>
#include <mach/iomux-mx27.h>
#include <mach/i2c.h>
#include <asm/mach/time.h>
#if defined(CONFIG_SPI_IMX) || defined(CONFIG_SPI_IMX_MODULE)
#include <mach/spi.h>
#endif
#include <mach/imx-uart.h>
#include <mach/audmux.h>
#include <mach/ssi.h>
#include <mach/mxc_nand.h>
#include <mach/irqs.h>
#include <mach/mmc.h>
#include <mach/mxc_ehci.h>
#include <mach/ulpi.h>
#include "devices.h"
#define OTG_PHY_CS_GPIO (GPIO_PORTB + 23)
#define USBH2_PHY_CS_GPIO (GPIO_PORTB + 24)
static int pca100_pins[] = {
/* UART1 */
PE12_PF_UART1_TXD,
PE13_PF_UART1_RXD,
PE14_PF_UART1_CTS,
PE15_PF_UART1_RTS,
/* SDHC */
PB4_PF_SD2_D0,
PB5_PF_SD2_D1,
PB6_PF_SD2_D2,
PB7_PF_SD2_D3,
PB8_PF_SD2_CMD,
PB9_PF_SD2_CLK,
/* FEC */
PD0_AIN_FEC_TXD0,
PD1_AIN_FEC_TXD1,
PD2_AIN_FEC_TXD2,
PD3_AIN_FEC_TXD3,
PD4_AOUT_FEC_RX_ER,
PD5_AOUT_FEC_RXD1,
PD6_AOUT_FEC_RXD2,
PD7_AOUT_FEC_RXD3,
PD8_AF_FEC_MDIO,
PD9_AIN_FEC_MDC,
PD10_AOUT_FEC_CRS,
PD11_AOUT_FEC_TX_CLK,
PD12_AOUT_FEC_RXD0,
PD13_AOUT_FEC_RX_DV,
PD14_AOUT_FEC_RX_CLK,
PD15_AOUT_FEC_COL,
PD16_AIN_FEC_TX_ER,
PF23_AIN_FEC_TX_EN,
/* SSI1 */
PC20_PF_SSI1_FS,
PC21_PF_SSI1_RXD,
PC22_PF_SSI1_TXD,
PC23_PF_SSI1_CLK,
/* onboard I2C */
PC5_PF_I2C2_SDA,
PC6_PF_I2C2_SCL,
/* external I2C */
PD17_PF_I2C_DATA,
PD18_PF_I2C_CLK,
/* SPI1 */
PD25_PF_CSPI1_RDY,
PD29_PF_CSPI1_SCLK,
PD30_PF_CSPI1_MISO,
PD31_PF_CSPI1_MOSI,
/* OTG */
OTG_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PC7_PF_USBOTG_DATA5,
PC8_PF_USBOTG_DATA6,
PC9_PF_USBOTG_DATA0,
PC10_PF_USBOTG_DATA2,
PC11_PF_USBOTG_DATA1,
PC12_PF_USBOTG_DATA4,
PC13_PF_USBOTG_DATA3,
PE0_PF_USBOTG_NXT,
PE1_PF_USBOTG_STP,
PE2_PF_USBOTG_DIR,
PE24_PF_USBOTG_CLK,
PE25_PF_USBOTG_DATA7,
/* USBH2 */
USBH2_PHY_CS_GPIO | GPIO_GPIO | GPIO_OUT,
PA0_PF_USBH2_CLK,
PA1_PF_USBH2_DIR,
PA2_PF_USBH2_DATA7,
PA3_PF_USBH2_NXT,
PA4_PF_USBH2_STP,
PD19_AF_USBH2_DATA4,
PD20_AF_USBH2_DATA3,
PD21_AF_USBH2_DATA6,
PD22_AF_USBH2_DATA0,
PD23_AF_USBH2_DATA2,
PD24_AF_USBH2_DATA1,
PD26_AF_USBH2_DATA5,
};
static struct imxuart_platform_data uart_pdata = {
.flags = IMXUART_HAVE_RTSCTS,
};
static struct mxc_nand_platform_data pca100_nand_board_info = {
.width = 1,
.hw_ecc = 1,
};
static struct platform_device *platform_devices[] __initdata = {
&mxc_w1_master_device,
&mxc_fec_device,
};
static struct imxi2c_platform_data pca100_i2c_1_data = {
.bitrate = 100000,
};
static struct at24_platform_data board_eeprom = {
.byte_len = 4096,
.page_size = 32,
.flags = AT24_FLAG_ADDR16,
};
static struct i2c_board_info pca100_i2c_devices[] = {
{
I2C_BOARD_INFO("at24", 0x52), /* E0=0, E1=1, E2=0 */
.platform_data = &board_eeprom,
}, {
I2C_BOARD_INFO("rtc-pcf8563", 0x51),
.type = "pcf8563"
}, {
I2C_BOARD_INFO("lm75", 0x4a),
.type = "lm75"
}
};
#if defined(CONFIG_SPI_IMX) || defined(CONFIG_SPI_IMX_MODULE)
static struct spi_eeprom at25320 = {
.name = "at25320an",
.byte_len = 4096,
.page_size = 32,
.flags = EE_ADDR2,
};
static struct spi_board_info pca100_spi_board_info[] __initdata = {
{
.modalias = "at25",
.max_speed_hz = 30000,
.bus_num = 0,
.chip_select = 1,
.platform_data = &at25320,
},
};
static int pca100_spi_cs[] = {GPIO_PORTD + 28, GPIO_PORTD + 27};
static struct spi_imx_master pca100_spi_0_data = {
.chipselect = pca100_spi_cs,
.num_chipselect = ARRAY_SIZE(pca100_spi_cs),
};
#endif
static void pca100_ac97_warm_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT);
gpio_set_value(GPIO_PORTC + 20, 1);
udelay(2);
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(PC20_PF_SSI1_FS);
msleep(2);
}
static void pca100_ac97_cold_reset(struct snd_ac97 *ac97)
{
mxc_gpio_mode(GPIO_PORTC | 20 | GPIO_GPIO | GPIO_OUT); /* FS */
gpio_set_value(GPIO_PORTC + 20, 0);
mxc_gpio_mode(GPIO_PORTC | 22 | GPIO_GPIO | GPIO_OUT); /* TX */
gpio_set_value(GPIO_PORTC + 22, 0);
mxc_gpio_mode(GPIO_PORTC | 28 | GPIO_GPIO | GPIO_OUT); /* reset */
gpio_set_value(GPIO_PORTC + 28, 0);
udelay(10);
gpio_set_value(GPIO_PORTC + 28, 1);
mxc_gpio_mode(PC20_PF_SSI1_FS);
mxc_gpio_mode(PC22_PF_SSI1_TXD);
msleep(2);
}
static struct imx_ssi_platform_data pca100_ssi_pdata = {
.ac97_reset = pca100_ac97_cold_reset,
.ac97_warm_reset = pca100_ac97_warm_reset,
.flags = IMX_SSI_USE_AC97,
};
static int pca100_sdhc2_init(struct device *dev, irq_handler_t detect_irq,
void *data)
{
int ret;
ret = request_irq(IRQ_GPIOC(29), detect_irq,
IRQF_DISABLED | IRQF_TRIGGER_FALLING,
"imx-mmc-detect", data);
if (ret)
printk(KERN_ERR
"pca100: Failed to reuest irq for sd/mmc detection\n");
return ret;
}
static void pca100_sdhc2_exit(struct device *dev, void *data)
{
free_irq(IRQ_GPIOC(29), data);
}
static struct imxmmc_platform_data sdhc_pdata = {
.init = pca100_sdhc2_init,
.exit = pca100_sdhc2_exit,
};
static int otg_phy_init(struct platform_device *pdev)
{
gpio_set_value(OTG_PHY_CS_GPIO, 0);
return 0;
}
static struct mxc_usbh_platform_data otg_pdata = {
.init = otg_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
.flags = MXC_EHCI_INTERFACE_DIFF_UNI,
};
static int usbh2_phy_init(struct platform_device *pdev)
{
gpio_set_value(USBH2_PHY_CS_GPIO, 0);
return 0;
}
static struct mxc_usbh_platform_data usbh2_pdata = {
.init = usbh2_phy_init,
.portsc = MXC_EHCI_MODE_ULPI,
.flags = MXC_EHCI_INTERFACE_DIFF_UNI,
};
static struct fsl_usb2_platform_data otg_device_pdata = {
.operating_mode = FSL_USB2_DR_DEVICE,
.phy_mode = FSL_USB2_PHY_ULPI,
};
static int otg_mode_host;
static int __init pca100_otg_mode(char *options)
{
if (!strcmp(options, "host"))
otg_mode_host = 1;
else if (!strcmp(options, "device"))
otg_mode_host = 0;
else
pr_info("otg_mode neither \"host\" nor \"device\". "
"Defaulting to device\n");
return 0;
}
__setup("otg_mode=", pca100_otg_mode);
static void __init pca100_init(void)
{
int ret;
/* SSI unit */
mxc_audmux_v1_configure_port(MX27_AUDMUX_HPCR1_SSI0,
MXC_AUDMUX_V1_PCR_SYN | /* 4wire mode */
MXC_AUDMUX_V1_PCR_TFCSEL(3) |
MXC_AUDMUX_V1_PCR_TCLKDIR | /* clock is output */
MXC_AUDMUX_V1_PCR_RXDSEL(3));
mxc_audmux_v1_configure_port(3,
MXC_AUDMUX_V1_PCR_SYN | /* 4wire mode */
MXC_AUDMUX_V1_PCR_TFCSEL(0) |
MXC_AUDMUX_V1_PCR_TFSDIR |
MXC_AUDMUX_V1_PCR_RXDSEL(0));
ret = mxc_gpio_setup_multiple_pins(pca100_pins,
ARRAY_SIZE(pca100_pins), "PCA100");
if (ret)
printk(KERN_ERR "pca100: Failed to setup pins (%d)\n", ret);
mxc_register_device(&imx_ssi_device0, &pca100_ssi_pdata);
mxc_register_device(&mxc_uart_device0, &uart_pdata);
mxc_gpio_mode(GPIO_PORTC | 29 | GPIO_GPIO | GPIO_IN);
mxc_register_device(&mxc_sdhc_device1, &sdhc_pdata);
mxc_register_device(&imx27_nand_device, &pca100_nand_board_info);
/* only the i2c master 1 is used on this CPU card */
i2c_register_board_info(1, pca100_i2c_devices,
ARRAY_SIZE(pca100_i2c_devices));
mxc_register_device(&mxc_i2c_device1, &pca100_i2c_1_data);
mxc_gpio_mode(GPIO_PORTD | 28 | GPIO_GPIO | GPIO_OUT);
mxc_gpio_mode(GPIO_PORTD | 27 | GPIO_GPIO | GPIO_OUT);
/* GPIO0_IRQ */
mxc_gpio_mode(GPIO_PORTC | 31 | GPIO_GPIO | GPIO_IN);
/* GPIO1_IRQ */
mxc_gpio_mode(GPIO_PORTC | 25 | GPIO_GPIO | GPIO_IN);
/* GPIO2_IRQ */
mxc_gpio_mode(GPIO_PORTE | 5 | GPIO_GPIO | GPIO_IN);
#if defined(CONFIG_SPI_IMX) || defined(CONFIG_SPI_IMX_MODULE)
spi_register_board_info(pca100_spi_board_info,
ARRAY_SIZE(pca100_spi_board_info));
mxc_register_device(&mxc_spi_device0, &pca100_spi_0_data);
#endif
gpio_request(OTG_PHY_CS_GPIO, "usb-otg-cs");
gpio_direction_output(OTG_PHY_CS_GPIO, 1);
gpio_request(USBH2_PHY_CS_GPIO, "usb-host2-cs");
gpio_direction_output(USBH2_PHY_CS_GPIO, 1);
#if defined(CONFIG_USB_ULPI)
if (otg_mode_host) {
otg_pdata.otg = otg_ulpi_create(&mxc_ulpi_access_ops,
USB_OTG_DRV_VBUS | USB_OTG_DRV_VBUS_EXT);
mxc_register_device(&mxc_otg_host, &otg_pdata);
}
usbh2_pdata.otg = otg_ulpi_create(&mxc_ulpi_access_ops,
USB_OTG_DRV_VBUS | USB_OTG_DRV_VBUS_EXT);
mxc_register_device(&mxc_usbh2, &usbh2_pdata);
#endif
if (!otg_mode_host) {
gpio_set_value(OTG_PHY_CS_GPIO, 0);
mxc_register_device(&mxc_otg_udc_device, &otg_device_pdata);
}
platform_add_devices(platform_devices, ARRAY_SIZE(platform_devices));
}
static void __init pca100_timer_init(void)
{
mx27_clocks_init(26000000);
}
static struct sys_timer pca100_timer = {
.init = pca100_timer_init,
};
MACHINE_START(PCA100, "phyCARD-i.MX27")
.phys_io = MX27_AIPI_BASE_ADDR,
.io_pg_offst = ((MX27_AIPI_BASE_ADDR_VIRT) >> 18) & 0xfffc,
.boot_params = MX27_PHYS_OFFSET + 0x100,
.map_io = mx27_map_io,
.init_irq = mx27_init_irq,
.init_machine = pca100_init,
.timer = &pca100_timer,
MACHINE_END
| gpl-2.0 |
run/IOsched | drivers/staging/xgifb/vb_ext.c | 561 | 11109 | #include <linux/io.h>
#include <linux/types.h>
#include "XGIfb.h"
#include "vb_def.h"
#include "vgatypes.h"
#include "vb_struct.h"
#include "vb_util.h"
#include "vb_setmode.h"
#include "vb_ext.h"
/**************************************************************
*********************** Dynamic Sense ************************
*************************************************************/
static unsigned char XGINew_Is301B(struct vb_device_info *pVBInfo)
{
unsigned short flag;
flag = xgifb_reg_get(pVBInfo->Part4Port, 0x01);
if (flag > 0x0B0)
return 0; /* 301b */
else
return 1;
}
static unsigned char XGINew_Sense(unsigned short tempbx,
unsigned short tempcx,
struct vb_device_info *pVBInfo)
{
unsigned short temp, i, tempch;
temp = tempbx & 0xFF;
xgifb_reg_set(pVBInfo->Part4Port, 0x11, temp);
temp = (tempbx & 0xFF00) >> 8;
temp |= (tempcx & 0x00FF);
xgifb_reg_and_or(pVBInfo->Part4Port, 0x10, ~0x1F, temp);
for (i = 0; i < 10; i++)
XGI_LongWait(pVBInfo);
tempch = (tempcx & 0x7F00) >> 8;
temp = xgifb_reg_get(pVBInfo->Part4Port, 0x03);
temp = temp ^ (0x0E);
temp &= tempch;
if (temp > 0)
return 1;
else
return 0;
}
static unsigned char
XGINew_GetLCDDDCInfo(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short temp;
/* add lcd sense */
if (HwDeviceExtension->ulCRT2LCDType == LCD_UNKNOWN) {
return 0;
} else {
temp = (unsigned short) HwDeviceExtension->ulCRT2LCDType;
switch (HwDeviceExtension->ulCRT2LCDType) {
case LCD_INVALID:
case LCD_800x600:
case LCD_1024x768:
case LCD_1280x1024:
break;
case LCD_640x480:
case LCD_1024x600:
case LCD_1152x864:
case LCD_1280x960:
case LCD_1152x768:
temp = 0;
break;
case LCD_1400x1050:
case LCD_1280x768:
case LCD_1600x1200:
break;
case LCD_1920x1440:
case LCD_2048x1536:
temp = 0;
break;
default:
break;
}
xgifb_reg_and_or(pVBInfo->P3d4, 0x36, 0xF0, temp);
return 1;
}
}
static unsigned char XGINew_GetPanelID(struct vb_device_info *pVBInfo)
{
unsigned short PanelTypeTable[16] = { SyncNN | PanelRGB18Bit
| Panel800x600 | _PanelType00, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType01, SyncNN | PanelRGB18Bit
| Panel800x600 | _PanelType02, SyncNN | PanelRGB18Bit
| Panel640x480 | _PanelType03, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType04, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType05, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType06, SyncNN | PanelRGB24Bit
| Panel1024x768 | _PanelType07, SyncNN | PanelRGB18Bit
| Panel800x600 | _PanelType08, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType09, SyncNN | PanelRGB18Bit
| Panel800x600 | _PanelType0A, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType0B, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType0C, SyncNN | PanelRGB24Bit
| Panel1024x768 | _PanelType0D, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType0E, SyncNN | PanelRGB18Bit
| Panel1024x768 | _PanelType0F };
unsigned short tempax, tempbx, temp;
/* unsigned short return_flag; */
tempax = xgifb_reg_get(pVBInfo->P3c4, 0x1A);
tempbx = tempax & 0x1E;
if (tempax == 0)
return 0;
else {
/*
if (!(tempax & 0x10)) {
if (pVBInfo->IF_DEF_LVDS == 1) {
tempbx = 0;
temp = xgifb_reg_get(pVBInfo->P3c4, 0x38);
if (temp & 0x40)
tempbx |= 0x08;
if (temp & 0x20)
tempbx |= 0x02;
if (temp & 0x01)
tempbx |= 0x01;
temp = xgifb_reg_get(pVBInfo->P3c4, 0x39);
if (temp & 0x80)
tempbx |= 0x04;
} else {
return(0);
}
}
*/
tempbx = tempbx >> 1;
temp = tempbx & 0x00F;
xgifb_reg_set(pVBInfo->P3d4, 0x36, temp);
tempbx--;
tempbx = PanelTypeTable[tempbx];
temp = (tempbx & 0xFF00) >> 8;
xgifb_reg_and_or(pVBInfo->P3d4, 0x37, ~(LCDSyncBit
| LCDRGB18Bit), temp);
return 1;
}
}
static unsigned char
XGINew_BridgeIsEnable(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short flag;
if (XGI_BridgeIsOn(pVBInfo) == 0) {
flag = xgifb_reg_get(pVBInfo->Part1Port, 0x0);
if (flag & 0x050)
return 1;
else
return 0;
}
return 0;
}
static unsigned char
XGINew_SenseHiTV(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempbx, tempcx, temp, i, tempch;
tempbx = *pVBInfo->pYCSenseData2;
tempcx = 0x0604;
temp = tempbx & 0xFF;
xgifb_reg_set(pVBInfo->Part4Port, 0x11, temp);
temp = (tempbx & 0xFF00) >> 8;
temp |= (tempcx & 0x00FF);
xgifb_reg_and_or(pVBInfo->Part4Port, 0x10, ~0x1F, temp);
for (i = 0; i < 10; i++)
XGI_LongWait(pVBInfo);
tempch = (tempcx & 0xFF00) >> 8;
temp = xgifb_reg_get(pVBInfo->Part4Port, 0x03);
temp = temp ^ (0x0E);
temp &= tempch;
if (temp != tempch)
return 0;
tempbx = *pVBInfo->pVideoSenseData2;
tempcx = 0x0804;
temp = tempbx & 0xFF;
xgifb_reg_set(pVBInfo->Part4Port, 0x11, temp);
temp = (tempbx & 0xFF00) >> 8;
temp |= (tempcx & 0x00FF);
xgifb_reg_and_or(pVBInfo->Part4Port, 0x10, ~0x1F, temp);
for (i = 0; i < 10; i++)
XGI_LongWait(pVBInfo);
tempch = (tempcx & 0xFF00) >> 8;
temp = xgifb_reg_get(pVBInfo->Part4Port, 0x03);
temp = temp ^ (0x0E);
temp &= tempch;
if (temp != tempch) {
return 0;
} else {
tempbx = 0x3FF;
tempcx = 0x0804;
temp = tempbx & 0xFF;
xgifb_reg_set(pVBInfo->Part4Port, 0x11, temp);
temp = (tempbx & 0xFF00) >> 8;
temp |= (tempcx & 0x00FF);
xgifb_reg_and_or(pVBInfo->Part4Port, 0x10, ~0x1F, temp);
for (i = 0; i < 10; i++)
XGI_LongWait(pVBInfo);
tempch = (tempcx & 0xFF00) >> 8;
temp = xgifb_reg_get(pVBInfo->Part4Port, 0x03);
temp = temp ^ (0x0E);
temp &= tempch;
if (temp != tempch)
return 1;
else
return 0;
}
}
void XGI_GetSenseStatus(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
unsigned short tempax = 0, tempbx, tempcx, temp,
P2reg0 = 0, SenseModeNo = 0,
OutputSelect = *pVBInfo->pOutputSelect,
ModeIdIndex, i;
pVBInfo->BaseAddr = (unsigned long) HwDeviceExtension->pjIOAddress;
if (pVBInfo->IF_DEF_LVDS == 1) {
/* ynlai 02/27/2002 */
tempax = xgifb_reg_get(pVBInfo->P3c4, 0x1A);
tempbx = xgifb_reg_get(pVBInfo->P3c4, 0x1B);
tempax = ((tempax & 0xFE) >> 1) | (tempbx << 8);
if (tempax == 0x00) { /* Get Panel id from DDC */
temp = XGINew_GetLCDDDCInfo(HwDeviceExtension, pVBInfo);
if (temp == 1) { /* LCD connect */
/* set CR39 bit0="1" */
xgifb_reg_and_or(pVBInfo->P3d4,
0x39, 0xFF, 0x01);
/* clean CR37 bit4="0" */
xgifb_reg_and_or(pVBInfo->P3d4,
0x37, 0xEF, 0x00);
temp = LCDSense;
} else { /* LCD don't connect */
temp = 0;
}
} else {
XGINew_GetPanelID(pVBInfo);
temp = LCDSense;
}
tempbx = ~(LCDSense | AVIDEOSense | SVIDEOSense);
xgifb_reg_and_or(pVBInfo->P3d4, 0x32, tempbx, temp);
} else { /* for 301 */
if (pVBInfo->VBInfo & SetCRT2ToHiVisionTV) { /* for HiVision */
tempax = xgifb_reg_get(pVBInfo->P3c4, 0x38);
temp = tempax & 0x01;
tempax = xgifb_reg_get(pVBInfo->P3c4, 0x3A);
temp = temp | (tempax & 0x02);
xgifb_reg_and_or(pVBInfo->P3d4, 0x32, 0xA0, temp);
} else {
if (XGI_BridgeIsOn(pVBInfo)) {
P2reg0 = xgifb_reg_get(pVBInfo->Part2Port,
0x00);
if (!XGINew_BridgeIsEnable(HwDeviceExtension,
pVBInfo)) {
SenseModeNo = 0x2e;
/* xgifb_reg_set(pVBInfo->P3d4, 0x30, 0x41);
* XGISetModeNew(HwDeviceExtension, 0x2e);
* // ynlai InitMode */
temp = XGI_SearchModeID(SenseModeNo,
&ModeIdIndex,
pVBInfo);
XGI_GetVGAType(HwDeviceExtension,
pVBInfo);
XGI_GetVBType(pVBInfo);
pVBInfo->SetFlag = 0x00;
pVBInfo->ModeType = ModeVGA;
pVBInfo->VBInfo = SetCRT2ToRAMDAC |
LoadDACFlag |
SetInSlaveMode;
XGI_GetLCDInfo(0x2e,
ModeIdIndex,
pVBInfo);
XGI_GetTVInfo(0x2e,
ModeIdIndex,
pVBInfo);
XGI_EnableBridge(HwDeviceExtension,
pVBInfo);
XGI_SetCRT2Group301(SenseModeNo,
HwDeviceExtension,
pVBInfo);
XGI_SetCRT2ModeRegs(0x2e,
HwDeviceExtension,
pVBInfo);
/* XGI_DisableBridge(HwDeviceExtension,
* pVBInfo ) ; */
/* Display Off 0212 */
xgifb_reg_and_or(pVBInfo->P3c4,
0x01,
0xDF,
0x20);
for (i = 0; i < 20; i++)
XGI_LongWait(pVBInfo);
}
xgifb_reg_set(pVBInfo->Part2Port, 0x00, 0x1c);
tempax = 0;
tempbx = *pVBInfo->pRGBSenseData;
if (!(XGINew_Is301B(pVBInfo)))
tempbx = *pVBInfo->pRGBSenseData2;
tempcx = 0x0E08;
if (XGINew_Sense(tempbx, tempcx, pVBInfo)) {
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo))
tempax |= Monitor2Sense;
}
if (pVBInfo->VBType & VB_XGI301C)
xgifb_reg_or(pVBInfo->Part4Port,
0x0d,
0x04);
/* add by kuku for Multi-adapter sense HiTV */
if (XGINew_SenseHiTV(HwDeviceExtension,
pVBInfo)) {
tempax |= HiTVSense;
if ((pVBInfo->VBType & VB_XGI301C))
tempax ^= (HiTVSense |
YPbPrSense);
}
/* start */
if (!(tempax & (HiTVSense | YPbPrSense))) {
tempbx = *pVBInfo->pYCSenseData;
if (!(XGINew_Is301B(pVBInfo)))
tempbx = *pVBInfo->pYCSenseData2;
tempcx = 0x0604;
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo)) {
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo))
tempax |= SVIDEOSense;
}
if (OutputSelect & BoardTVType) {
tempbx = *pVBInfo->pVideoSenseData;
if (!(XGINew_Is301B(pVBInfo)))
tempbx = *pVBInfo->pVideoSenseData2;
tempcx = 0x0804;
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo)) {
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo))
tempax |= AVIDEOSense;
}
} else {
if (!(tempax & SVIDEOSense)) {
tempbx = *pVBInfo->pVideoSenseData;
if (!(XGINew_Is301B(pVBInfo)))
tempbx = *pVBInfo->pVideoSenseData2;
tempcx = 0x0804;
if (XGINew_Sense(tempbx,
tempcx,
pVBInfo)) {
if (XGINew_Sense(tempbx, tempcx, pVBInfo))
tempax |= AVIDEOSense;
}
}
}
}
} /* end */
if (!(tempax & Monitor2Sense)) {
if (XGINew_SenseLCD(HwDeviceExtension, pVBInfo))
tempax |= LCDSense;
}
tempbx = 0;
tempcx = 0;
XGINew_Sense(tempbx, tempcx, pVBInfo);
xgifb_reg_and_or(pVBInfo->P3d4, 0x32, ~0xDF, tempax);
xgifb_reg_set(pVBInfo->Part2Port, 0x00, P2reg0);
if (!(P2reg0 & 0x20)) {
pVBInfo->VBInfo = DisableCRT2Display;
/* XGI_SetCRT2Group301(SenseModeNo,
* HwDeviceExtension,
* pVBInfo); */
}
}
}
XGI_DisableBridge(HwDeviceExtension, pVBInfo); /* shampoo 0226 */
}
unsigned short XGINew_SenseLCD(struct xgi_hw_device_info *HwDeviceExtension,
struct vb_device_info *pVBInfo)
{
/* unsigned short SoftSetting ; */
unsigned short temp;
temp = XGINew_GetLCDDDCInfo(HwDeviceExtension, pVBInfo);
return temp;
}
| gpl-2.0 |
varunchitre15/linux | drivers/of/selftest.c | 817 | 8726 | /*
* Self tests for device tree subsystem
*/
#define pr_fmt(fmt) "### dt-test ### " fmt
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/list.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/device.h>
static bool selftest_passed = true;
#define selftest(result, fmt, ...) { \
if (!(result)) { \
pr_err("FAIL %s:%i " fmt, __FILE__, __LINE__, ##__VA_ARGS__); \
selftest_passed = false; \
} else { \
pr_info("pass %s:%i\n", __FILE__, __LINE__); \
} \
}
static void __init of_selftest_parse_phandle_with_args(void)
{
struct device_node *np;
struct of_phandle_args args;
int i, rc;
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_err("missing testcase data\n");
return;
}
rc = of_count_phandle_with_args(np, "phandle-list", "#phandle-cells");
selftest(rc == 7, "of_count_phandle_with_args() returned %i, expected 7\n", rc);
for (i = 0; i < 8; i++) {
bool passed = true;
rc = of_parse_phandle_with_args(np, "phandle-list",
"#phandle-cells", i, &args);
/* Test the values from tests-phandle.dtsi */
switch (i) {
case 0:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == (i + 1));
break;
case 1:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 0);
break;
case 2:
passed &= (rc == -ENOENT);
break;
case 3:
passed &= !rc;
passed &= (args.args_count == 3);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 4);
passed &= (args.args[2] == 3);
break;
case 4:
passed &= !rc;
passed &= (args.args_count == 2);
passed &= (args.args[0] == (i + 1));
passed &= (args.args[1] == 100);
break;
case 5:
passed &= !rc;
passed &= (args.args_count == 0);
break;
case 6:
passed &= !rc;
passed &= (args.args_count == 1);
passed &= (args.args[0] == (i + 1));
break;
case 7:
passed &= (rc == -ENOENT);
break;
default:
passed = false;
}
selftest(passed, "index %i - data error on node %s rc=%i\n",
i, args.np->full_name, rc);
}
/* Check for missing list property */
rc = of_parse_phandle_with_args(np, "phandle-list-missing",
"#phandle-cells", 0, &args);
selftest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc);
rc = of_count_phandle_with_args(np, "phandle-list-missing",
"#phandle-cells");
selftest(rc == -ENOENT, "expected:%i got:%i\n", -ENOENT, rc);
/* Check for missing cells property */
rc = of_parse_phandle_with_args(np, "phandle-list",
"#phandle-cells-missing", 0, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list",
"#phandle-cells-missing");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
/* Check for bad phandle in list */
rc = of_parse_phandle_with_args(np, "phandle-list-bad-phandle",
"#phandle-cells", 0, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list-bad-phandle",
"#phandle-cells");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
/* Check for incorrectly formed argument list */
rc = of_parse_phandle_with_args(np, "phandle-list-bad-args",
"#phandle-cells", 1, &args);
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
rc = of_count_phandle_with_args(np, "phandle-list-bad-args",
"#phandle-cells");
selftest(rc == -EINVAL, "expected:%i got:%i\n", -EINVAL, rc);
}
static void __init of_selftest_property_string(void)
{
const char *strings[4];
struct device_node *np;
int rc;
pr_info("start\n");
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_err("No testcase data in device tree\n");
return;
}
rc = of_property_match_string(np, "phandle-list-names", "first");
selftest(rc == 0, "first expected:0 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "second");
selftest(rc == 1, "second expected:0 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "third");
selftest(rc == 2, "third expected:0 got:%i\n", rc);
rc = of_property_match_string(np, "phandle-list-names", "fourth");
selftest(rc == -ENODATA, "unmatched string; rc=%i\n", rc);
rc = of_property_match_string(np, "missing-property", "blah");
selftest(rc == -EINVAL, "missing property; rc=%i\n", rc);
rc = of_property_match_string(np, "empty-property", "blah");
selftest(rc == -ENODATA, "empty property; rc=%i\n", rc);
rc = of_property_match_string(np, "unterminated-string", "blah");
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
/* of_property_count_strings() tests */
rc = of_property_count_strings(np, "string-property");
selftest(rc == 1, "Incorrect string count; rc=%i\n", rc);
rc = of_property_count_strings(np, "phandle-list-names");
selftest(rc == 3, "Incorrect string count; rc=%i\n", rc);
rc = of_property_count_strings(np, "unterminated-string");
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
rc = of_property_count_strings(np, "unterminated-string-list");
selftest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc);
/* of_property_read_string_index() tests */
rc = of_property_read_string_index(np, "string-property", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "foobar"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "string-property", 1, strings);
selftest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 1, strings);
selftest(rc == 0 && !strcmp(strings[0], "second"), "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "phandle-list-names", 2, strings);
selftest(rc == 0 && !strcmp(strings[0], "third"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "phandle-list-names", 3, strings);
selftest(rc == -ENODATA && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "unterminated-string", 0, strings);
selftest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
rc = of_property_read_string_index(np, "unterminated-string-list", 0, strings);
selftest(rc == 0 && !strcmp(strings[0], "first"), "of_property_read_string_index() failure; rc=%i\n", rc);
strings[0] = NULL;
rc = of_property_read_string_index(np, "unterminated-string-list", 2, strings); /* should fail */
selftest(rc == -EILSEQ && strings[0] == NULL, "of_property_read_string_index() failure; rc=%i\n", rc);
strings[1] = NULL;
/* of_property_read_string_array() tests */
rc = of_property_read_string_array(np, "string-property", strings, 4);
selftest(rc == 1, "Incorrect string count; rc=%i\n", rc);
rc = of_property_read_string_array(np, "phandle-list-names", strings, 4);
selftest(rc == 3, "Incorrect string count; rc=%i\n", rc);
rc = of_property_read_string_array(np, "unterminated-string", strings, 4);
selftest(rc == -EILSEQ, "unterminated string; rc=%i\n", rc);
/* -- An incorrectly formed string should cause a failure */
rc = of_property_read_string_array(np, "unterminated-string-list", strings, 4);
selftest(rc == -EILSEQ, "unterminated string array; rc=%i\n", rc);
/* -- parsing the correctly formed strings should still work: */
strings[2] = NULL;
rc = of_property_read_string_array(np, "unterminated-string-list", strings, 2);
selftest(rc == 2 && strings[2] == NULL, "of_property_read_string_array() failure; rc=%i\n", rc);
strings[1] = NULL;
rc = of_property_read_string_array(np, "phandle-list-names", strings, 1);
selftest(rc == 1 && strings[1] == NULL, "Overwrote end of string array; rc=%i, str='%s'\n", rc, strings[1]);
}
static int __init of_selftest(void)
{
struct device_node *np;
np = of_find_node_by_path("/testcase-data/phandle-tests/consumer-a");
if (!np) {
pr_info("No testcase data in device tree; not running tests\n");
return 0;
}
of_node_put(np);
pr_info("start of selftest - you will see error messages\n");
of_selftest_parse_phandle_with_args();
of_selftest_property_string();
pr_info("end of selftest - %s\n", selftest_passed ? "PASS" : "FAIL");
return 0;
}
late_initcall(of_selftest);
| gpl-2.0 |
12019/old_samsung-lt02wifi-kernel | arch/hexagon/kernel/smp.c | 1329 | 5829 | /*
* SMP support for Hexagon
*
* Copyright (c) 2010-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <linux/err.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/sched.h>
#include <linux/smp.h>
#include <linux/spinlock.h>
#include <linux/cpu.h>
#include <asm/time.h> /* timer_interrupt */
#include <asm/hexagon_vm.h>
#define BASE_IPI_IRQ 26
/*
* cpu_possible_mask needs to be filled out prior to setup_per_cpu_areas
* (which is prior to any of our smp_prepare_cpu crap), in order to set
* up the... per_cpu areas.
*/
struct ipi_data {
unsigned long bits;
};
static DEFINE_PER_CPU(struct ipi_data, ipi_data);
static inline void __handle_ipi(unsigned long *ops, struct ipi_data *ipi,
int cpu)
{
unsigned long msg = 0;
do {
msg = find_next_bit(ops, BITS_PER_LONG, msg+1);
switch (msg) {
case IPI_TIMER:
ipi_timer();
break;
case IPI_CALL_FUNC:
generic_smp_call_function_interrupt();
break;
case IPI_CALL_FUNC_SINGLE:
generic_smp_call_function_single_interrupt();
break;
case IPI_CPU_STOP:
/*
* call vmstop()
*/
__vmstop();
break;
case IPI_RESCHEDULE:
scheduler_ipi();
break;
}
} while (msg < BITS_PER_LONG);
}
/* Used for IPI call from other CPU's to unmask int */
void smp_vm_unmask_irq(void *info)
{
__vmintop_locen((long) info);
}
/*
* This is based on Alpha's IPI stuff.
* Supposed to take (int, void*) as args now.
* Specifically, first arg is irq, second is the irq_desc.
*/
irqreturn_t handle_ipi(int irq, void *desc)
{
int cpu = smp_processor_id();
struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
unsigned long ops;
while ((ops = xchg(&ipi->bits, 0)) != 0)
__handle_ipi(&ops, ipi, cpu);
return IRQ_HANDLED;
}
void send_ipi(const struct cpumask *cpumask, enum ipi_message_type msg)
{
unsigned long flags;
unsigned long cpu;
unsigned long retval;
local_irq_save(flags);
for_each_cpu(cpu, cpumask) {
struct ipi_data *ipi = &per_cpu(ipi_data, cpu);
set_bit(msg, &ipi->bits);
/* Possible barrier here */
retval = __vmintop_post(BASE_IPI_IRQ+cpu);
if (retval != 0) {
printk(KERN_ERR "interrupt %ld not configured?\n",
BASE_IPI_IRQ+cpu);
}
}
local_irq_restore(flags);
}
static struct irqaction ipi_intdesc = {
.handler = handle_ipi,
.flags = IRQF_TRIGGER_RISING,
.name = "ipi_handler"
};
void __init smp_prepare_boot_cpu(void)
{
}
/*
* interrupts should already be disabled from the VM
* SP should already be correct; need to set THREADINFO_REG
* to point to current thread info
*/
void __cpuinit start_secondary(void)
{
unsigned int cpu;
unsigned long thread_ptr;
/* Calculate thread_info pointer from stack pointer */
__asm__ __volatile__(
"%0 = SP;\n"
: "=r" (thread_ptr)
);
thread_ptr = thread_ptr & ~(THREAD_SIZE-1);
__asm__ __volatile__(
QUOTED_THREADINFO_REG " = %0;\n"
:
: "r" (thread_ptr)
);
/* Set the memory struct */
atomic_inc(&init_mm.mm_count);
current->active_mm = &init_mm;
cpu = smp_processor_id();
setup_irq(BASE_IPI_IRQ + cpu, &ipi_intdesc);
/* Register the clock_event dummy */
setup_percpu_clockdev();
printk(KERN_INFO "%s cpu %d\n", __func__, current_thread_info()->cpu);
notify_cpu_starting(cpu);
ipi_call_lock();
set_cpu_online(cpu, true);
ipi_call_unlock();
local_irq_enable();
cpu_idle();
}
/*
* called once for each present cpu
* apparently starts up the CPU and then
* maintains control until "cpu_online(cpu)" is set.
*/
int __cpuinit __cpu_up(unsigned int cpu)
{
struct task_struct *idle;
struct thread_info *thread;
void *stack_start;
/* Create new init task for the CPU */
idle = fork_idle(cpu);
if (IS_ERR(idle))
panic(KERN_ERR "fork_idle failed\n");
thread = (struct thread_info *)idle->stack;
thread->cpu = cpu;
/* Boot to the head. */
stack_start = ((void *) thread) + THREAD_SIZE;
__vmstart(start_secondary, stack_start);
while (!cpu_online(cpu))
barrier();
return 0;
}
void __init smp_cpus_done(unsigned int max_cpus)
{
}
void __init smp_prepare_cpus(unsigned int max_cpus)
{
int i;
/*
* should eventually have some sort of machine
* descriptor that has this stuff
*/
/* Right now, let's just fake it. */
for (i = 0; i < max_cpus; i++)
set_cpu_present(i, true);
/* Also need to register the interrupts for IPI */
if (max_cpus > 1)
setup_irq(BASE_IPI_IRQ, &ipi_intdesc);
}
void smp_send_reschedule(int cpu)
{
send_ipi(cpumask_of(cpu), IPI_RESCHEDULE);
}
void smp_send_stop(void)
{
struct cpumask targets;
cpumask_copy(&targets, cpu_online_mask);
cpumask_clear_cpu(smp_processor_id(), &targets);
send_ipi(&targets, IPI_CPU_STOP);
}
void arch_send_call_function_single_ipi(int cpu)
{
send_ipi(cpumask_of(cpu), IPI_CALL_FUNC_SINGLE);
}
void arch_send_call_function_ipi_mask(const struct cpumask *mask)
{
send_ipi(mask, IPI_CALL_FUNC);
}
int setup_profiling_timer(unsigned int multiplier)
{
return -EINVAL;
}
void smp_start_cpus(void)
{
int i;
for (i = 0; i < NR_CPUS; i++)
set_cpu_possible(i, true);
}
| gpl-2.0 |
superatmos/i9100g_kernel_ics | drivers/md/dm-ioctl.c | 1585 | 37168 | /*
* Copyright (C) 2001, 2002 Sistina Software (UK) Limited.
* Copyright (C) 2004 - 2006 Red Hat, Inc. All rights reserved.
*
* This file is released under the GPL.
*/
#include "dm.h"
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/miscdevice.h>
#include <linux/init.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/dm-ioctl.h>
#include <linux/hdreg.h>
#include <linux/compat.h>
#include <asm/uaccess.h>
#define DM_MSG_PREFIX "ioctl"
#define DM_DRIVER_EMAIL "dm-devel@redhat.com"
/*-----------------------------------------------------------------
* The ioctl interface needs to be able to look up devices by
* name or uuid.
*---------------------------------------------------------------*/
struct hash_cell {
struct list_head name_list;
struct list_head uuid_list;
char *name;
char *uuid;
struct mapped_device *md;
struct dm_table *new_map;
};
struct vers_iter {
size_t param_size;
struct dm_target_versions *vers, *old_vers;
char *end;
uint32_t flags;
};
#define NUM_BUCKETS 64
#define MASK_BUCKETS (NUM_BUCKETS - 1)
static struct list_head _name_buckets[NUM_BUCKETS];
static struct list_head _uuid_buckets[NUM_BUCKETS];
static void dm_hash_remove_all(int keep_open_devices);
/*
* Guards access to both hash tables.
*/
static DECLARE_RWSEM(_hash_lock);
/*
* Protects use of mdptr to obtain hash cell name and uuid from mapped device.
*/
static DEFINE_MUTEX(dm_hash_cells_mutex);
static void init_buckets(struct list_head *buckets)
{
unsigned int i;
for (i = 0; i < NUM_BUCKETS; i++)
INIT_LIST_HEAD(buckets + i);
}
static int dm_hash_init(void)
{
init_buckets(_name_buckets);
init_buckets(_uuid_buckets);
return 0;
}
static void dm_hash_exit(void)
{
dm_hash_remove_all(0);
}
/*-----------------------------------------------------------------
* Hash function:
* We're not really concerned with the str hash function being
* fast since it's only used by the ioctl interface.
*---------------------------------------------------------------*/
static unsigned int hash_str(const char *str)
{
const unsigned int hash_mult = 2654435387U;
unsigned int h = 0;
while (*str)
h = (h + (unsigned int) *str++) * hash_mult;
return h & MASK_BUCKETS;
}
/*-----------------------------------------------------------------
* Code for looking up a device by name
*---------------------------------------------------------------*/
static struct hash_cell *__get_name_cell(const char *str)
{
struct hash_cell *hc;
unsigned int h = hash_str(str);
list_for_each_entry (hc, _name_buckets + h, name_list)
if (!strcmp(hc->name, str)) {
dm_get(hc->md);
return hc;
}
return NULL;
}
static struct hash_cell *__get_uuid_cell(const char *str)
{
struct hash_cell *hc;
unsigned int h = hash_str(str);
list_for_each_entry (hc, _uuid_buckets + h, uuid_list)
if (!strcmp(hc->uuid, str)) {
dm_get(hc->md);
return hc;
}
return NULL;
}
/*-----------------------------------------------------------------
* Inserting, removing and renaming a device.
*---------------------------------------------------------------*/
static struct hash_cell *alloc_cell(const char *name, const char *uuid,
struct mapped_device *md)
{
struct hash_cell *hc;
hc = kmalloc(sizeof(*hc), GFP_KERNEL);
if (!hc)
return NULL;
hc->name = kstrdup(name, GFP_KERNEL);
if (!hc->name) {
kfree(hc);
return NULL;
}
if (!uuid)
hc->uuid = NULL;
else {
hc->uuid = kstrdup(uuid, GFP_KERNEL);
if (!hc->uuid) {
kfree(hc->name);
kfree(hc);
return NULL;
}
}
INIT_LIST_HEAD(&hc->name_list);
INIT_LIST_HEAD(&hc->uuid_list);
hc->md = md;
hc->new_map = NULL;
return hc;
}
static void free_cell(struct hash_cell *hc)
{
if (hc) {
kfree(hc->name);
kfree(hc->uuid);
kfree(hc);
}
}
/*
* The kdev_t and uuid of a device can never change once it is
* initially inserted.
*/
static int dm_hash_insert(const char *name, const char *uuid, struct mapped_device *md)
{
struct hash_cell *cell, *hc;
/*
* Allocate the new cells.
*/
cell = alloc_cell(name, uuid, md);
if (!cell)
return -ENOMEM;
/*
* Insert the cell into both hash tables.
*/
down_write(&_hash_lock);
hc = __get_name_cell(name);
if (hc) {
dm_put(hc->md);
goto bad;
}
list_add(&cell->name_list, _name_buckets + hash_str(name));
if (uuid) {
hc = __get_uuid_cell(uuid);
if (hc) {
list_del(&cell->name_list);
dm_put(hc->md);
goto bad;
}
list_add(&cell->uuid_list, _uuid_buckets + hash_str(uuid));
}
dm_get(md);
mutex_lock(&dm_hash_cells_mutex);
dm_set_mdptr(md, cell);
mutex_unlock(&dm_hash_cells_mutex);
up_write(&_hash_lock);
return 0;
bad:
up_write(&_hash_lock);
free_cell(cell);
return -EBUSY;
}
static void __hash_remove(struct hash_cell *hc)
{
struct dm_table *table;
/* remove from the dev hash */
list_del(&hc->uuid_list);
list_del(&hc->name_list);
mutex_lock(&dm_hash_cells_mutex);
dm_set_mdptr(hc->md, NULL);
mutex_unlock(&dm_hash_cells_mutex);
table = dm_get_live_table(hc->md);
if (table) {
dm_table_event(table);
dm_table_put(table);
}
if (hc->new_map)
dm_table_destroy(hc->new_map);
dm_put(hc->md);
free_cell(hc);
}
static void dm_hash_remove_all(int keep_open_devices)
{
int i, dev_skipped;
struct hash_cell *hc;
struct mapped_device *md;
retry:
dev_skipped = 0;
down_write(&_hash_lock);
for (i = 0; i < NUM_BUCKETS; i++) {
list_for_each_entry(hc, _name_buckets + i, name_list) {
md = hc->md;
dm_get(md);
if (keep_open_devices && dm_lock_for_deletion(md)) {
dm_put(md);
dev_skipped++;
continue;
}
__hash_remove(hc);
up_write(&_hash_lock);
dm_put(md);
if (likely(keep_open_devices))
dm_destroy(md);
else
dm_destroy_immediate(md);
/*
* Some mapped devices may be using other mapped
* devices, so repeat until we make no further
* progress. If a new mapped device is created
* here it will also get removed.
*/
goto retry;
}
}
up_write(&_hash_lock);
if (dev_skipped)
DMWARN("remove_all left %d open device(s)", dev_skipped);
}
/*
* Set the uuid of a hash_cell that isn't already set.
*/
static void __set_cell_uuid(struct hash_cell *hc, char *new_uuid)
{
mutex_lock(&dm_hash_cells_mutex);
hc->uuid = new_uuid;
mutex_unlock(&dm_hash_cells_mutex);
list_add(&hc->uuid_list, _uuid_buckets + hash_str(new_uuid));
}
/*
* Changes the name of a hash_cell and returns the old name for
* the caller to free.
*/
static char *__change_cell_name(struct hash_cell *hc, char *new_name)
{
char *old_name;
/*
* Rename and move the name cell.
*/
list_del(&hc->name_list);
old_name = hc->name;
mutex_lock(&dm_hash_cells_mutex);
hc->name = new_name;
mutex_unlock(&dm_hash_cells_mutex);
list_add(&hc->name_list, _name_buckets + hash_str(new_name));
return old_name;
}
static struct mapped_device *dm_hash_rename(struct dm_ioctl *param,
const char *new)
{
char *new_data, *old_name = NULL;
struct hash_cell *hc;
struct dm_table *table;
struct mapped_device *md;
unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0;
/*
* duplicate new.
*/
new_data = kstrdup(new, GFP_KERNEL);
if (!new_data)
return ERR_PTR(-ENOMEM);
down_write(&_hash_lock);
/*
* Is new free ?
*/
if (change_uuid)
hc = __get_uuid_cell(new);
else
hc = __get_name_cell(new);
if (hc) {
DMWARN("Unable to change %s on mapped device %s to one that "
"already exists: %s",
change_uuid ? "uuid" : "name",
param->name, new);
dm_put(hc->md);
up_write(&_hash_lock);
kfree(new_data);
return ERR_PTR(-EBUSY);
}
/*
* Is there such a device as 'old' ?
*/
hc = __get_name_cell(param->name);
if (!hc) {
DMWARN("Unable to rename non-existent device, %s to %s%s",
param->name, change_uuid ? "uuid " : "", new);
up_write(&_hash_lock);
kfree(new_data);
return ERR_PTR(-ENXIO);
}
/*
* Does this device already have a uuid?
*/
if (change_uuid && hc->uuid) {
DMWARN("Unable to change uuid of mapped device %s to %s "
"because uuid is already set to %s",
param->name, new, hc->uuid);
dm_put(hc->md);
up_write(&_hash_lock);
kfree(new_data);
return ERR_PTR(-EINVAL);
}
if (change_uuid)
__set_cell_uuid(hc, new_data);
else
old_name = __change_cell_name(hc, new_data);
/*
* Wake up any dm event waiters.
*/
table = dm_get_live_table(hc->md);
if (table) {
dm_table_event(table);
dm_table_put(table);
}
if (!dm_kobject_uevent(hc->md, KOBJ_CHANGE, param->event_nr))
param->flags |= DM_UEVENT_GENERATED_FLAG;
md = hc->md;
up_write(&_hash_lock);
kfree(old_name);
return md;
}
/*-----------------------------------------------------------------
* Implementation of the ioctl commands
*---------------------------------------------------------------*/
/*
* All the ioctl commands get dispatched to functions with this
* prototype.
*/
typedef int (*ioctl_fn)(struct dm_ioctl *param, size_t param_size);
static int remove_all(struct dm_ioctl *param, size_t param_size)
{
dm_hash_remove_all(1);
param->data_size = 0;
return 0;
}
/*
* Round up the ptr to an 8-byte boundary.
*/
#define ALIGN_MASK 7
static inline void *align_ptr(void *ptr)
{
return (void *) (((size_t) (ptr + ALIGN_MASK)) & ~ALIGN_MASK);
}
/*
* Retrieves the data payload buffer from an already allocated
* struct dm_ioctl.
*/
static void *get_result_buffer(struct dm_ioctl *param, size_t param_size,
size_t *len)
{
param->data_start = align_ptr(param + 1) - (void *) param;
if (param->data_start < param_size)
*len = param_size - param->data_start;
else
*len = 0;
return ((void *) param) + param->data_start;
}
static int list_devices(struct dm_ioctl *param, size_t param_size)
{
unsigned int i;
struct hash_cell *hc;
size_t len, needed = 0;
struct gendisk *disk;
struct dm_name_list *nl, *old_nl = NULL;
down_write(&_hash_lock);
/*
* Loop through all the devices working out how much
* space we need.
*/
for (i = 0; i < NUM_BUCKETS; i++) {
list_for_each_entry (hc, _name_buckets + i, name_list) {
needed += sizeof(struct dm_name_list);
needed += strlen(hc->name) + 1;
needed += ALIGN_MASK;
}
}
/*
* Grab our output buffer.
*/
nl = get_result_buffer(param, param_size, &len);
if (len < needed) {
param->flags |= DM_BUFFER_FULL_FLAG;
goto out;
}
param->data_size = param->data_start + needed;
nl->dev = 0; /* Flags no data */
/*
* Now loop through filling out the names.
*/
for (i = 0; i < NUM_BUCKETS; i++) {
list_for_each_entry (hc, _name_buckets + i, name_list) {
if (old_nl)
old_nl->next = (uint32_t) ((void *) nl -
(void *) old_nl);
disk = dm_disk(hc->md);
nl->dev = huge_encode_dev(disk_devt(disk));
nl->next = 0;
strcpy(nl->name, hc->name);
old_nl = nl;
nl = align_ptr(((void *) ++nl) + strlen(hc->name) + 1);
}
}
out:
up_write(&_hash_lock);
return 0;
}
static void list_version_get_needed(struct target_type *tt, void *needed_param)
{
size_t *needed = needed_param;
*needed += sizeof(struct dm_target_versions);
*needed += strlen(tt->name);
*needed += ALIGN_MASK;
}
static void list_version_get_info(struct target_type *tt, void *param)
{
struct vers_iter *info = param;
/* Check space - it might have changed since the first iteration */
if ((char *)info->vers + sizeof(tt->version) + strlen(tt->name) + 1 >
info->end) {
info->flags = DM_BUFFER_FULL_FLAG;
return;
}
if (info->old_vers)
info->old_vers->next = (uint32_t) ((void *)info->vers -
(void *)info->old_vers);
info->vers->version[0] = tt->version[0];
info->vers->version[1] = tt->version[1];
info->vers->version[2] = tt->version[2];
info->vers->next = 0;
strcpy(info->vers->name, tt->name);
info->old_vers = info->vers;
info->vers = align_ptr(((void *) ++info->vers) + strlen(tt->name) + 1);
}
static int list_versions(struct dm_ioctl *param, size_t param_size)
{
size_t len, needed = 0;
struct dm_target_versions *vers;
struct vers_iter iter_info;
/*
* Loop through all the devices working out how much
* space we need.
*/
dm_target_iterate(list_version_get_needed, &needed);
/*
* Grab our output buffer.
*/
vers = get_result_buffer(param, param_size, &len);
if (len < needed) {
param->flags |= DM_BUFFER_FULL_FLAG;
goto out;
}
param->data_size = param->data_start + needed;
iter_info.param_size = param_size;
iter_info.old_vers = NULL;
iter_info.vers = vers;
iter_info.flags = 0;
iter_info.end = (char *)vers+len;
/*
* Now loop through filling out the names & versions.
*/
dm_target_iterate(list_version_get_info, &iter_info);
param->flags |= iter_info.flags;
out:
return 0;
}
static int check_name(const char *name)
{
if (strchr(name, '/')) {
DMWARN("invalid device name");
return -EINVAL;
}
return 0;
}
/*
* On successful return, the caller must not attempt to acquire
* _hash_lock without first calling dm_table_put, because dm_table_destroy
* waits for this dm_table_put and could be called under this lock.
*/
static struct dm_table *dm_get_inactive_table(struct mapped_device *md)
{
struct hash_cell *hc;
struct dm_table *table = NULL;
down_read(&_hash_lock);
hc = dm_get_mdptr(md);
if (!hc || hc->md != md) {
DMWARN("device has been removed from the dev hash table.");
goto out;
}
table = hc->new_map;
if (table)
dm_table_get(table);
out:
up_read(&_hash_lock);
return table;
}
static struct dm_table *dm_get_live_or_inactive_table(struct mapped_device *md,
struct dm_ioctl *param)
{
return (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) ?
dm_get_inactive_table(md) : dm_get_live_table(md);
}
/*
* Fills in a dm_ioctl structure, ready for sending back to
* userland.
*/
static void __dev_status(struct mapped_device *md, struct dm_ioctl *param)
{
struct gendisk *disk = dm_disk(md);
struct dm_table *table;
param->flags &= ~(DM_SUSPEND_FLAG | DM_READONLY_FLAG |
DM_ACTIVE_PRESENT_FLAG);
if (dm_suspended_md(md))
param->flags |= DM_SUSPEND_FLAG;
param->dev = huge_encode_dev(disk_devt(disk));
/*
* Yes, this will be out of date by the time it gets back
* to userland, but it is still very useful for
* debugging.
*/
param->open_count = dm_open_count(md);
param->event_nr = dm_get_event_nr(md);
param->target_count = 0;
table = dm_get_live_table(md);
if (table) {
if (!(param->flags & DM_QUERY_INACTIVE_TABLE_FLAG)) {
if (get_disk_ro(disk))
param->flags |= DM_READONLY_FLAG;
param->target_count = dm_table_get_num_targets(table);
}
dm_table_put(table);
param->flags |= DM_ACTIVE_PRESENT_FLAG;
}
if (param->flags & DM_QUERY_INACTIVE_TABLE_FLAG) {
table = dm_get_inactive_table(md);
if (table) {
if (!(dm_table_get_mode(table) & FMODE_WRITE))
param->flags |= DM_READONLY_FLAG;
param->target_count = dm_table_get_num_targets(table);
dm_table_put(table);
}
}
}
static int dev_create(struct dm_ioctl *param, size_t param_size)
{
int r, m = DM_ANY_MINOR;
struct mapped_device *md;
r = check_name(param->name);
if (r)
return r;
if (param->flags & DM_PERSISTENT_DEV_FLAG)
m = MINOR(huge_decode_dev(param->dev));
r = dm_create(m, &md);
if (r)
return r;
r = dm_hash_insert(param->name, *param->uuid ? param->uuid : NULL, md);
if (r) {
dm_put(md);
dm_destroy(md);
return r;
}
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
__dev_status(md, param);
dm_put(md);
return 0;
}
/*
* Always use UUID for lookups if it's present, otherwise use name or dev.
*/
static struct hash_cell *__find_device_hash_cell(struct dm_ioctl *param)
{
struct mapped_device *md;
void *mdptr = NULL;
if (*param->uuid)
return __get_uuid_cell(param->uuid);
if (*param->name)
return __get_name_cell(param->name);
md = dm_get_md(huge_decode_dev(param->dev));
if (!md)
goto out;
mdptr = dm_get_mdptr(md);
if (!mdptr)
dm_put(md);
out:
return mdptr;
}
static struct mapped_device *find_device(struct dm_ioctl *param)
{
struct hash_cell *hc;
struct mapped_device *md = NULL;
down_read(&_hash_lock);
hc = __find_device_hash_cell(param);
if (hc) {
md = hc->md;
/*
* Sneakily write in both the name and the uuid
* while we have the cell.
*/
strlcpy(param->name, hc->name, sizeof(param->name));
if (hc->uuid)
strlcpy(param->uuid, hc->uuid, sizeof(param->uuid));
else
param->uuid[0] = '\0';
if (hc->new_map)
param->flags |= DM_INACTIVE_PRESENT_FLAG;
else
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
}
up_read(&_hash_lock);
return md;
}
static int dev_remove(struct dm_ioctl *param, size_t param_size)
{
struct hash_cell *hc;
struct mapped_device *md;
int r;
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
return -ENXIO;
}
md = hc->md;
/*
* Ensure the device is not open and nothing further can open it.
*/
r = dm_lock_for_deletion(md);
if (r) {
DMDEBUG_LIMIT("unable to remove open device %s", hc->name);
up_write(&_hash_lock);
dm_put(md);
return r;
}
__hash_remove(hc);
up_write(&_hash_lock);
if (!dm_kobject_uevent(md, KOBJ_REMOVE, param->event_nr))
param->flags |= DM_UEVENT_GENERATED_FLAG;
dm_put(md);
dm_destroy(md);
return 0;
}
/*
* Check a string doesn't overrun the chunk of
* memory we copied from userland.
*/
static int invalid_str(char *str, void *end)
{
while ((void *) str < end)
if (!*str++)
return 0;
return -EINVAL;
}
static int dev_rename(struct dm_ioctl *param, size_t param_size)
{
int r;
char *new_data = (char *) param + param->data_start;
struct mapped_device *md;
unsigned change_uuid = (param->flags & DM_UUID_FLAG) ? 1 : 0;
if (new_data < param->data ||
invalid_str(new_data, (void *) param + param_size) ||
strlen(new_data) > (change_uuid ? DM_UUID_LEN - 1 : DM_NAME_LEN - 1)) {
DMWARN("Invalid new mapped device name or uuid string supplied.");
return -EINVAL;
}
if (!change_uuid) {
r = check_name(new_data);
if (r)
return r;
}
md = dm_hash_rename(param, new_data);
if (IS_ERR(md))
return PTR_ERR(md);
__dev_status(md, param);
dm_put(md);
return 0;
}
static int dev_set_geometry(struct dm_ioctl *param, size_t param_size)
{
int r = -EINVAL, x;
struct mapped_device *md;
struct hd_geometry geometry;
unsigned long indata[4];
char *geostr = (char *) param + param->data_start;
md = find_device(param);
if (!md)
return -ENXIO;
if (geostr < param->data ||
invalid_str(geostr, (void *) param + param_size)) {
DMWARN("Invalid geometry supplied.");
goto out;
}
x = sscanf(geostr, "%lu %lu %lu %lu", indata,
indata + 1, indata + 2, indata + 3);
if (x != 4) {
DMWARN("Unable to interpret geometry settings.");
goto out;
}
if (indata[0] > 65535 || indata[1] > 255 ||
indata[2] > 255 || indata[3] > ULONG_MAX) {
DMWARN("Geometry exceeds range limits.");
goto out;
}
geometry.cylinders = indata[0];
geometry.heads = indata[1];
geometry.sectors = indata[2];
geometry.start = indata[3];
r = dm_set_geometry(md, &geometry);
param->data_size = 0;
out:
dm_put(md);
return r;
}
static int do_suspend(struct dm_ioctl *param)
{
int r = 0;
unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG;
struct mapped_device *md;
md = find_device(param);
if (!md)
return -ENXIO;
if (param->flags & DM_SKIP_LOCKFS_FLAG)
suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
if (param->flags & DM_NOFLUSH_FLAG)
suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG;
if (!dm_suspended_md(md)) {
r = dm_suspend(md, suspend_flags);
if (r)
goto out;
}
__dev_status(md, param);
out:
dm_put(md);
return r;
}
static int do_resume(struct dm_ioctl *param)
{
int r = 0;
unsigned suspend_flags = DM_SUSPEND_LOCKFS_FLAG;
struct hash_cell *hc;
struct mapped_device *md;
struct dm_table *new_map, *old_map = NULL;
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
return -ENXIO;
}
md = hc->md;
new_map = hc->new_map;
hc->new_map = NULL;
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
up_write(&_hash_lock);
/* Do we need to load a new map ? */
if (new_map) {
/* Suspend if it isn't already suspended */
if (param->flags & DM_SKIP_LOCKFS_FLAG)
suspend_flags &= ~DM_SUSPEND_LOCKFS_FLAG;
if (param->flags & DM_NOFLUSH_FLAG)
suspend_flags |= DM_SUSPEND_NOFLUSH_FLAG;
if (!dm_suspended_md(md))
dm_suspend(md, suspend_flags);
old_map = dm_swap_table(md, new_map);
if (IS_ERR(old_map)) {
dm_table_destroy(new_map);
dm_put(md);
return PTR_ERR(old_map);
}
if (dm_table_get_mode(new_map) & FMODE_WRITE)
set_disk_ro(dm_disk(md), 0);
else
set_disk_ro(dm_disk(md), 1);
}
if (dm_suspended_md(md)) {
r = dm_resume(md);
if (!r && !dm_kobject_uevent(md, KOBJ_CHANGE, param->event_nr))
param->flags |= DM_UEVENT_GENERATED_FLAG;
}
if (old_map)
dm_table_destroy(old_map);
if (!r)
__dev_status(md, param);
dm_put(md);
return r;
}
/*
* Set or unset the suspension state of a device.
* If the device already is in the requested state we just return its status.
*/
static int dev_suspend(struct dm_ioctl *param, size_t param_size)
{
if (param->flags & DM_SUSPEND_FLAG)
return do_suspend(param);
return do_resume(param);
}
/*
* Copies device info back to user space, used by
* the create and info ioctls.
*/
static int dev_status(struct dm_ioctl *param, size_t param_size)
{
struct mapped_device *md;
md = find_device(param);
if (!md)
return -ENXIO;
__dev_status(md, param);
dm_put(md);
return 0;
}
/*
* Build up the status struct for each target
*/
static void retrieve_status(struct dm_table *table,
struct dm_ioctl *param, size_t param_size)
{
unsigned int i, num_targets;
struct dm_target_spec *spec;
char *outbuf, *outptr;
status_type_t type;
size_t remaining, len, used = 0;
outptr = outbuf = get_result_buffer(param, param_size, &len);
if (param->flags & DM_STATUS_TABLE_FLAG)
type = STATUSTYPE_TABLE;
else
type = STATUSTYPE_INFO;
/* Get all the target info */
num_targets = dm_table_get_num_targets(table);
for (i = 0; i < num_targets; i++) {
struct dm_target *ti = dm_table_get_target(table, i);
remaining = len - (outptr - outbuf);
if (remaining <= sizeof(struct dm_target_spec)) {
param->flags |= DM_BUFFER_FULL_FLAG;
break;
}
spec = (struct dm_target_spec *) outptr;
spec->status = 0;
spec->sector_start = ti->begin;
spec->length = ti->len;
strncpy(spec->target_type, ti->type->name,
sizeof(spec->target_type));
outptr += sizeof(struct dm_target_spec);
remaining = len - (outptr - outbuf);
if (remaining <= 0) {
param->flags |= DM_BUFFER_FULL_FLAG;
break;
}
/* Get the status/table string from the target driver */
if (ti->type->status) {
if (ti->type->status(ti, type, outptr, remaining)) {
param->flags |= DM_BUFFER_FULL_FLAG;
break;
}
} else
outptr[0] = '\0';
outptr += strlen(outptr) + 1;
used = param->data_start + (outptr - outbuf);
outptr = align_ptr(outptr);
spec->next = outptr - outbuf;
}
if (used)
param->data_size = used;
param->target_count = num_targets;
}
/*
* Wait for a device to report an event
*/
static int dev_wait(struct dm_ioctl *param, size_t param_size)
{
int r = 0;
struct mapped_device *md;
struct dm_table *table;
md = find_device(param);
if (!md)
return -ENXIO;
/*
* Wait for a notification event
*/
if (dm_wait_event(md, param->event_nr)) {
r = -ERESTARTSYS;
goto out;
}
/*
* The userland program is going to want to know what
* changed to trigger the event, so we may as well tell
* him and save an ioctl.
*/
__dev_status(md, param);
table = dm_get_live_or_inactive_table(md, param);
if (table) {
retrieve_status(table, param, param_size);
dm_table_put(table);
}
out:
dm_put(md);
return r;
}
static inline fmode_t get_mode(struct dm_ioctl *param)
{
fmode_t mode = FMODE_READ | FMODE_WRITE;
if (param->flags & DM_READONLY_FLAG)
mode = FMODE_READ;
return mode;
}
static int next_target(struct dm_target_spec *last, uint32_t next, void *end,
struct dm_target_spec **spec, char **target_params)
{
*spec = (struct dm_target_spec *) ((unsigned char *) last + next);
*target_params = (char *) (*spec + 1);
if (*spec < (last + 1))
return -EINVAL;
return invalid_str(*target_params, end);
}
static int populate_table(struct dm_table *table,
struct dm_ioctl *param, size_t param_size)
{
int r;
unsigned int i = 0;
struct dm_target_spec *spec = (struct dm_target_spec *) param;
uint32_t next = param->data_start;
void *end = (void *) param + param_size;
char *target_params;
if (!param->target_count) {
DMWARN("populate_table: no targets specified");
return -EINVAL;
}
for (i = 0; i < param->target_count; i++) {
r = next_target(spec, next, end, &spec, &target_params);
if (r) {
DMWARN("unable to find target");
return r;
}
r = dm_table_add_target(table, spec->target_type,
(sector_t) spec->sector_start,
(sector_t) spec->length,
target_params);
if (r) {
DMWARN("error adding target to table");
return r;
}
next = spec->next;
}
return dm_table_complete(table);
}
static int table_load(struct dm_ioctl *param, size_t param_size)
{
int r;
struct hash_cell *hc;
struct dm_table *t;
struct mapped_device *md;
md = find_device(param);
if (!md)
return -ENXIO;
r = dm_table_create(&t, get_mode(param), param->target_count, md);
if (r)
goto out;
r = populate_table(t, param, param_size);
if (r) {
dm_table_destroy(t);
goto out;
}
/* Protect md->type and md->queue against concurrent table loads. */
dm_lock_md_type(md);
if (dm_get_md_type(md) == DM_TYPE_NONE)
/* Initial table load: acquire type of table. */
dm_set_md_type(md, dm_table_get_type(t));
else if (dm_get_md_type(md) != dm_table_get_type(t)) {
DMWARN("can't change device type after initial table load.");
dm_table_destroy(t);
dm_unlock_md_type(md);
r = -EINVAL;
goto out;
}
/* setup md->queue to reflect md's type (may block) */
r = dm_setup_md_queue(md);
if (r) {
DMWARN("unable to set up device queue for new table.");
dm_table_destroy(t);
dm_unlock_md_type(md);
goto out;
}
dm_unlock_md_type(md);
/* stage inactive table */
down_write(&_hash_lock);
hc = dm_get_mdptr(md);
if (!hc || hc->md != md) {
DMWARN("device has been removed from the dev hash table.");
dm_table_destroy(t);
up_write(&_hash_lock);
r = -ENXIO;
goto out;
}
if (hc->new_map)
dm_table_destroy(hc->new_map);
hc->new_map = t;
up_write(&_hash_lock);
param->flags |= DM_INACTIVE_PRESENT_FLAG;
__dev_status(md, param);
out:
dm_put(md);
return r;
}
static int table_clear(struct dm_ioctl *param, size_t param_size)
{
struct hash_cell *hc;
struct mapped_device *md;
down_write(&_hash_lock);
hc = __find_device_hash_cell(param);
if (!hc) {
DMDEBUG_LIMIT("device doesn't appear to be in the dev hash table.");
up_write(&_hash_lock);
return -ENXIO;
}
if (hc->new_map) {
dm_table_destroy(hc->new_map);
hc->new_map = NULL;
}
param->flags &= ~DM_INACTIVE_PRESENT_FLAG;
__dev_status(hc->md, param);
md = hc->md;
up_write(&_hash_lock);
dm_put(md);
return 0;
}
/*
* Retrieves a list of devices used by a particular dm device.
*/
static void retrieve_deps(struct dm_table *table,
struct dm_ioctl *param, size_t param_size)
{
unsigned int count = 0;
struct list_head *tmp;
size_t len, needed;
struct dm_dev_internal *dd;
struct dm_target_deps *deps;
deps = get_result_buffer(param, param_size, &len);
/*
* Count the devices.
*/
list_for_each (tmp, dm_table_get_devices(table))
count++;
/*
* Check we have enough space.
*/
needed = sizeof(*deps) + (sizeof(*deps->dev) * count);
if (len < needed) {
param->flags |= DM_BUFFER_FULL_FLAG;
return;
}
/*
* Fill in the devices.
*/
deps->count = count;
count = 0;
list_for_each_entry (dd, dm_table_get_devices(table), list)
deps->dev[count++] = huge_encode_dev(dd->dm_dev.bdev->bd_dev);
param->data_size = param->data_start + needed;
}
static int table_deps(struct dm_ioctl *param, size_t param_size)
{
struct mapped_device *md;
struct dm_table *table;
md = find_device(param);
if (!md)
return -ENXIO;
__dev_status(md, param);
table = dm_get_live_or_inactive_table(md, param);
if (table) {
retrieve_deps(table, param, param_size);
dm_table_put(table);
}
dm_put(md);
return 0;
}
/*
* Return the status of a device as a text string for each
* target.
*/
static int table_status(struct dm_ioctl *param, size_t param_size)
{
struct mapped_device *md;
struct dm_table *table;
md = find_device(param);
if (!md)
return -ENXIO;
__dev_status(md, param);
table = dm_get_live_or_inactive_table(md, param);
if (table) {
retrieve_status(table, param, param_size);
dm_table_put(table);
}
dm_put(md);
return 0;
}
/*
* Pass a message to the target that's at the supplied device offset.
*/
static int target_message(struct dm_ioctl *param, size_t param_size)
{
int r, argc;
char **argv;
struct mapped_device *md;
struct dm_table *table;
struct dm_target *ti;
struct dm_target_msg *tmsg = (void *) param + param->data_start;
md = find_device(param);
if (!md)
return -ENXIO;
if (tmsg < (struct dm_target_msg *) param->data ||
invalid_str(tmsg->message, (void *) param + param_size)) {
DMWARN("Invalid target message parameters.");
r = -EINVAL;
goto out;
}
r = dm_split_args(&argc, &argv, tmsg->message);
if (r) {
DMWARN("Failed to split target message parameters");
goto out;
}
table = dm_get_live_table(md);
if (!table)
goto out_argv;
if (dm_deleting_md(md)) {
r = -ENXIO;
goto out_table;
}
ti = dm_table_find_target(table, tmsg->sector);
if (!dm_target_is_valid(ti)) {
DMWARN("Target message sector outside device.");
r = -EINVAL;
} else if (ti->type->message)
r = ti->type->message(ti, argc, argv);
else {
DMWARN("Target type does not support messages");
r = -EINVAL;
}
out_table:
dm_table_put(table);
out_argv:
kfree(argv);
out:
param->data_size = 0;
dm_put(md);
return r;
}
/*-----------------------------------------------------------------
* Implementation of open/close/ioctl on the special char
* device.
*---------------------------------------------------------------*/
static ioctl_fn lookup_ioctl(unsigned int cmd)
{
static struct {
int cmd;
ioctl_fn fn;
} _ioctls[] = {
{DM_VERSION_CMD, NULL}, /* version is dealt with elsewhere */
{DM_REMOVE_ALL_CMD, remove_all},
{DM_LIST_DEVICES_CMD, list_devices},
{DM_DEV_CREATE_CMD, dev_create},
{DM_DEV_REMOVE_CMD, dev_remove},
{DM_DEV_RENAME_CMD, dev_rename},
{DM_DEV_SUSPEND_CMD, dev_suspend},
{DM_DEV_STATUS_CMD, dev_status},
{DM_DEV_WAIT_CMD, dev_wait},
{DM_TABLE_LOAD_CMD, table_load},
{DM_TABLE_CLEAR_CMD, table_clear},
{DM_TABLE_DEPS_CMD, table_deps},
{DM_TABLE_STATUS_CMD, table_status},
{DM_LIST_VERSIONS_CMD, list_versions},
{DM_TARGET_MSG_CMD, target_message},
{DM_DEV_SET_GEOMETRY_CMD, dev_set_geometry}
};
return (cmd >= ARRAY_SIZE(_ioctls)) ? NULL : _ioctls[cmd].fn;
}
/*
* As well as checking the version compatibility this always
* copies the kernel interface version out.
*/
static int check_version(unsigned int cmd, struct dm_ioctl __user *user)
{
uint32_t version[3];
int r = 0;
if (copy_from_user(version, user->version, sizeof(version)))
return -EFAULT;
if ((DM_VERSION_MAJOR != version[0]) ||
(DM_VERSION_MINOR < version[1])) {
DMWARN("ioctl interface mismatch: "
"kernel(%u.%u.%u), user(%u.%u.%u), cmd(%d)",
DM_VERSION_MAJOR, DM_VERSION_MINOR,
DM_VERSION_PATCHLEVEL,
version[0], version[1], version[2], cmd);
r = -EINVAL;
}
/*
* Fill in the kernel version.
*/
version[0] = DM_VERSION_MAJOR;
version[1] = DM_VERSION_MINOR;
version[2] = DM_VERSION_PATCHLEVEL;
if (copy_to_user(user->version, version, sizeof(version)))
return -EFAULT;
return r;
}
static int copy_params(struct dm_ioctl __user *user, struct dm_ioctl **param)
{
struct dm_ioctl tmp, *dmi;
int secure_data;
if (copy_from_user(&tmp, user, sizeof(tmp) - sizeof(tmp.data)))
return -EFAULT;
if (tmp.data_size < (sizeof(tmp) - sizeof(tmp.data)))
return -EINVAL;
secure_data = tmp.flags & DM_SECURE_DATA_FLAG;
dmi = vmalloc(tmp.data_size);
if (!dmi) {
if (secure_data && clear_user(user, tmp.data_size))
return -EFAULT;
return -ENOMEM;
}
if (copy_from_user(dmi, user, tmp.data_size))
goto bad;
/* Wipe the user buffer so we do not return it to userspace */
if (secure_data && clear_user(user, tmp.data_size))
goto bad;
*param = dmi;
return 0;
bad:
if (secure_data)
memset(dmi, 0, tmp.data_size);
vfree(dmi);
return -EFAULT;
}
static int validate_params(uint cmd, struct dm_ioctl *param)
{
/* Always clear this flag */
param->flags &= ~DM_BUFFER_FULL_FLAG;
param->flags &= ~DM_UEVENT_GENERATED_FLAG;
param->flags &= ~DM_SECURE_DATA_FLAG;
/* Ignores parameters */
if (cmd == DM_REMOVE_ALL_CMD ||
cmd == DM_LIST_DEVICES_CMD ||
cmd == DM_LIST_VERSIONS_CMD)
return 0;
if ((cmd == DM_DEV_CREATE_CMD)) {
if (!*param->name) {
DMWARN("name not supplied when creating device");
return -EINVAL;
}
} else if ((*param->uuid && *param->name)) {
DMWARN("only supply one of name or uuid, cmd(%u)", cmd);
return -EINVAL;
}
/* Ensure strings are terminated */
param->name[DM_NAME_LEN - 1] = '\0';
param->uuid[DM_UUID_LEN - 1] = '\0';
return 0;
}
static int ctl_ioctl(uint command, struct dm_ioctl __user *user)
{
int r = 0;
int wipe_buffer;
unsigned int cmd;
struct dm_ioctl *uninitialized_var(param);
ioctl_fn fn = NULL;
size_t input_param_size;
/* only root can play with this */
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
if (_IOC_TYPE(command) != DM_IOCTL)
return -ENOTTY;
cmd = _IOC_NR(command);
/*
* Check the interface version passed in. This also
* writes out the kernel's interface version.
*/
r = check_version(cmd, user);
if (r)
return r;
/*
* Nothing more to do for the version command.
*/
if (cmd == DM_VERSION_CMD)
return 0;
fn = lookup_ioctl(cmd);
if (!fn) {
DMWARN("dm_ctl_ioctl: unknown command 0x%x", command);
return -ENOTTY;
}
/*
* Trying to avoid low memory issues when a device is
* suspended.
*/
current->flags |= PF_MEMALLOC;
/*
* Copy the parameters into kernel space.
*/
r = copy_params(user, ¶m);
current->flags &= ~PF_MEMALLOC;
if (r)
return r;
input_param_size = param->data_size;
wipe_buffer = param->flags & DM_SECURE_DATA_FLAG;
r = validate_params(cmd, param);
if (r)
goto out;
param->data_size = sizeof(*param);
r = fn(param, input_param_size);
/*
* Copy the results back to userland.
*/
if (!r && copy_to_user(user, param, param->data_size))
r = -EFAULT;
out:
if (wipe_buffer)
memset(param, 0, input_param_size);
vfree(param);
return r;
}
static long dm_ctl_ioctl(struct file *file, uint command, ulong u)
{
return (long)ctl_ioctl(command, (struct dm_ioctl __user *)u);
}
#ifdef CONFIG_COMPAT
static long dm_compat_ctl_ioctl(struct file *file, uint command, ulong u)
{
return (long)dm_ctl_ioctl(file, command, (ulong) compat_ptr(u));
}
#else
#define dm_compat_ctl_ioctl NULL
#endif
static const struct file_operations _ctl_fops = {
.open = nonseekable_open,
.unlocked_ioctl = dm_ctl_ioctl,
.compat_ioctl = dm_compat_ctl_ioctl,
.owner = THIS_MODULE,
.llseek = noop_llseek,
};
static struct miscdevice _dm_misc = {
.minor = MAPPER_CTRL_MINOR,
.name = DM_NAME,
.nodename = DM_DIR "/" DM_CONTROL_NODE,
.fops = &_ctl_fops
};
MODULE_ALIAS_MISCDEV(MAPPER_CTRL_MINOR);
MODULE_ALIAS("devname:" DM_DIR "/" DM_CONTROL_NODE);
/*
* Create misc character device and link to DM_DIR/control.
*/
int __init dm_interface_init(void)
{
int r;
r = dm_hash_init();
if (r)
return r;
r = misc_register(&_dm_misc);
if (r) {
DMERR("misc_register failed for control device");
dm_hash_exit();
return r;
}
DMINFO("%d.%d.%d%s initialised: %s", DM_VERSION_MAJOR,
DM_VERSION_MINOR, DM_VERSION_PATCHLEVEL, DM_VERSION_EXTRA,
DM_DRIVER_EMAIL);
return 0;
}
void dm_interface_exit(void)
{
if (misc_deregister(&_dm_misc) < 0)
DMERR("misc_deregister failed for control device");
dm_hash_exit();
}
/**
* dm_copy_name_and_uuid - Copy mapped device name & uuid into supplied buffers
* @md: Pointer to mapped_device
* @name: Buffer (size DM_NAME_LEN) for name
* @uuid: Buffer (size DM_UUID_LEN) for uuid or empty string if uuid not defined
*/
int dm_copy_name_and_uuid(struct mapped_device *md, char *name, char *uuid)
{
int r = 0;
struct hash_cell *hc;
if (!md)
return -ENXIO;
mutex_lock(&dm_hash_cells_mutex);
hc = dm_get_mdptr(md);
if (!hc || hc->md != md) {
r = -ENXIO;
goto out;
}
if (name)
strcpy(name, hc->name);
if (uuid)
strcpy(uuid, hc->uuid ? : "");
out:
mutex_unlock(&dm_hash_cells_mutex);
return r;
}
| gpl-2.0 |
soderstrom-rikard/adi-linux | arch/ia64/xen/xencomm.c | 2353 | 2826 | /*
* Copyright (C) 2006 Hollis Blanchard <hollisb@us.ibm.com>, IBM Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/mm.h>
#include <linux/err.h>
static unsigned long kernel_virtual_offset;
static int is_xencomm_initialized;
/* for xen early printk. It uses console io hypercall which uses xencomm.
* However early printk may use it before xencomm initialization.
*/
int
xencomm_is_initialized(void)
{
return is_xencomm_initialized;
}
void
xencomm_initialize(void)
{
kernel_virtual_offset = KERNEL_START - ia64_tpa(KERNEL_START);
is_xencomm_initialized = 1;
}
/* Translate virtual address to physical address. */
unsigned long
xencomm_vtop(unsigned long vaddr)
{
struct page *page;
struct vm_area_struct *vma;
if (vaddr == 0)
return 0UL;
if (REGION_NUMBER(vaddr) == 5) {
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *ptep;
/* On ia64, TASK_SIZE refers to current. It is not initialized
during boot.
Furthermore the kernel is relocatable and __pa() doesn't
work on addresses. */
if (vaddr >= KERNEL_START
&& vaddr < (KERNEL_START + KERNEL_TR_PAGE_SIZE))
return vaddr - kernel_virtual_offset;
/* In kernel area -- virtually mapped. */
pgd = pgd_offset_k(vaddr);
if (pgd_none(*pgd) || pgd_bad(*pgd))
return ~0UL;
pud = pud_offset(pgd, vaddr);
if (pud_none(*pud) || pud_bad(*pud))
return ~0UL;
pmd = pmd_offset(pud, vaddr);
if (pmd_none(*pmd) || pmd_bad(*pmd))
return ~0UL;
ptep = pte_offset_kernel(pmd, vaddr);
if (!ptep)
return ~0UL;
return (pte_val(*ptep) & _PFN_MASK) | (vaddr & ~PAGE_MASK);
}
if (vaddr > TASK_SIZE) {
/* percpu variables */
if (REGION_NUMBER(vaddr) == 7 &&
REGION_OFFSET(vaddr) >= (1ULL << IA64_MAX_PHYS_BITS))
ia64_tpa(vaddr);
/* kernel address */
return __pa(vaddr);
}
/* XXX double-check (lack of) locking */
vma = find_extend_vma(current->mm, vaddr);
if (!vma)
return ~0UL;
/* We assume the page is modified. */
page = follow_page(vma, vaddr, FOLL_WRITE | FOLL_TOUCH);
if (IS_ERR_OR_NULL(page))
return ~0UL;
return (page_to_pfn(page) << PAGE_SHIFT) | (vaddr & ~PAGE_MASK);
}
| gpl-2.0 |
Fusion-Devices/android_kernel_moto_shamu_old | drivers/i2c/busses/scx200_acb.c | 2609 | 14021 | /*
Copyright (c) 2001,2002 Christer Weinigel <wingel@nano-system.com>
National Semiconductor SCx200 ACCESS.bus support
Also supports the AMD CS5535 and AMD CS5536
Based on i2c-keywest.c which is:
Copyright (c) 2001 Benjamin Herrenschmidt <benh@kernel.crashing.org>
Copyright (c) 2000 Philip Edelbrock <phil@stimpy.netroedge.com>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/pci.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <linux/io.h>
#include <linux/scx200.h>
MODULE_AUTHOR("Christer Weinigel <wingel@nano-system.com>");
MODULE_DESCRIPTION("NatSemi SCx200 ACCESS.bus Driver");
MODULE_ALIAS("platform:cs5535-smb");
MODULE_LICENSE("GPL");
#define MAX_DEVICES 4
static int base[MAX_DEVICES] = { 0x820, 0x840 };
module_param_array(base, int, NULL, 0);
MODULE_PARM_DESC(base, "Base addresses for the ACCESS.bus controllers");
#define POLL_TIMEOUT (HZ/5)
enum scx200_acb_state {
state_idle,
state_address,
state_command,
state_repeat_start,
state_quick,
state_read,
state_write,
};
static const char *scx200_acb_state_name[] = {
"idle",
"address",
"command",
"repeat_start",
"quick",
"read",
"write",
};
/* Physical interface */
struct scx200_acb_iface {
struct scx200_acb_iface *next;
struct i2c_adapter adapter;
unsigned base;
struct mutex mutex;
/* State machine data */
enum scx200_acb_state state;
int result;
u8 address_byte;
u8 command;
u8 *ptr;
char needs_reset;
unsigned len;
};
/* Register Definitions */
#define ACBSDA (iface->base + 0)
#define ACBST (iface->base + 1)
#define ACBST_SDAST 0x40 /* SDA Status */
#define ACBST_BER 0x20
#define ACBST_NEGACK 0x10 /* Negative Acknowledge */
#define ACBST_STASTR 0x08 /* Stall After Start */
#define ACBST_MASTER 0x02
#define ACBCST (iface->base + 2)
#define ACBCST_BB 0x02
#define ACBCTL1 (iface->base + 3)
#define ACBCTL1_STASTRE 0x80
#define ACBCTL1_NMINTE 0x40
#define ACBCTL1_ACK 0x10
#define ACBCTL1_STOP 0x02
#define ACBCTL1_START 0x01
#define ACBADDR (iface->base + 4)
#define ACBCTL2 (iface->base + 5)
#define ACBCTL2_ENABLE 0x01
/************************************************************************/
static void scx200_acb_machine(struct scx200_acb_iface *iface, u8 status)
{
const char *errmsg;
dev_dbg(&iface->adapter.dev, "state %s, status = 0x%02x\n",
scx200_acb_state_name[iface->state], status);
if (status & ACBST_BER) {
errmsg = "bus error";
goto error;
}
if (!(status & ACBST_MASTER)) {
errmsg = "not master";
goto error;
}
if (status & ACBST_NEGACK) {
dev_dbg(&iface->adapter.dev, "negative ack in state %s\n",
scx200_acb_state_name[iface->state]);
iface->state = state_idle;
iface->result = -ENXIO;
outb(inb(ACBCTL1) | ACBCTL1_STOP, ACBCTL1);
outb(ACBST_STASTR | ACBST_NEGACK, ACBST);
/* Reset the status register */
outb(0, ACBST);
return;
}
switch (iface->state) {
case state_idle:
dev_warn(&iface->adapter.dev, "interrupt in idle state\n");
break;
case state_address:
/* Do a pointer write first */
outb(iface->address_byte & ~1, ACBSDA);
iface->state = state_command;
break;
case state_command:
outb(iface->command, ACBSDA);
if (iface->address_byte & 1)
iface->state = state_repeat_start;
else
iface->state = state_write;
break;
case state_repeat_start:
outb(inb(ACBCTL1) | ACBCTL1_START, ACBCTL1);
/* fallthrough */
case state_quick:
if (iface->address_byte & 1) {
if (iface->len == 1)
outb(inb(ACBCTL1) | ACBCTL1_ACK, ACBCTL1);
else
outb(inb(ACBCTL1) & ~ACBCTL1_ACK, ACBCTL1);
outb(iface->address_byte, ACBSDA);
iface->state = state_read;
} else {
outb(iface->address_byte, ACBSDA);
iface->state = state_write;
}
break;
case state_read:
/* Set ACK if _next_ byte will be the last one */
if (iface->len == 2)
outb(inb(ACBCTL1) | ACBCTL1_ACK, ACBCTL1);
else
outb(inb(ACBCTL1) & ~ACBCTL1_ACK, ACBCTL1);
if (iface->len == 1) {
iface->result = 0;
iface->state = state_idle;
outb(inb(ACBCTL1) | ACBCTL1_STOP, ACBCTL1);
}
*iface->ptr++ = inb(ACBSDA);
--iface->len;
break;
case state_write:
if (iface->len == 0) {
iface->result = 0;
iface->state = state_idle;
outb(inb(ACBCTL1) | ACBCTL1_STOP, ACBCTL1);
break;
}
outb(*iface->ptr++, ACBSDA);
--iface->len;
break;
}
return;
error:
dev_err(&iface->adapter.dev,
"%s in state %s (addr=0x%02x, len=%d, status=0x%02x)\n", errmsg,
scx200_acb_state_name[iface->state], iface->address_byte,
iface->len, status);
iface->state = state_idle;
iface->result = -EIO;
iface->needs_reset = 1;
}
static void scx200_acb_poll(struct scx200_acb_iface *iface)
{
u8 status;
unsigned long timeout;
timeout = jiffies + POLL_TIMEOUT;
while (1) {
status = inb(ACBST);
/* Reset the status register to avoid the hang */
outb(0, ACBST);
if ((status & (ACBST_SDAST|ACBST_BER|ACBST_NEGACK)) != 0) {
scx200_acb_machine(iface, status);
return;
}
if (time_after(jiffies, timeout))
break;
cpu_relax();
cond_resched();
}
dev_err(&iface->adapter.dev, "timeout in state %s\n",
scx200_acb_state_name[iface->state]);
iface->state = state_idle;
iface->result = -EIO;
iface->needs_reset = 1;
}
static void scx200_acb_reset(struct scx200_acb_iface *iface)
{
/* Disable the ACCESS.bus device and Configure the SCL
frequency: 16 clock cycles */
outb(0x70, ACBCTL2);
/* Polling mode */
outb(0, ACBCTL1);
/* Disable slave address */
outb(0, ACBADDR);
/* Enable the ACCESS.bus device */
outb(inb(ACBCTL2) | ACBCTL2_ENABLE, ACBCTL2);
/* Free STALL after START */
outb(inb(ACBCTL1) & ~(ACBCTL1_STASTRE | ACBCTL1_NMINTE), ACBCTL1);
/* Send a STOP */
outb(inb(ACBCTL1) | ACBCTL1_STOP, ACBCTL1);
/* Clear BER, NEGACK and STASTR bits */
outb(ACBST_BER | ACBST_NEGACK | ACBST_STASTR, ACBST);
/* Clear BB bit */
outb(inb(ACBCST) | ACBCST_BB, ACBCST);
}
static s32 scx200_acb_smbus_xfer(struct i2c_adapter *adapter,
u16 address, unsigned short flags,
char rw, u8 command, int size,
union i2c_smbus_data *data)
{
struct scx200_acb_iface *iface = i2c_get_adapdata(adapter);
int len;
u8 *buffer;
u16 cur_word;
int rc;
switch (size) {
case I2C_SMBUS_QUICK:
len = 0;
buffer = NULL;
break;
case I2C_SMBUS_BYTE:
len = 1;
buffer = rw ? &data->byte : &command;
break;
case I2C_SMBUS_BYTE_DATA:
len = 1;
buffer = &data->byte;
break;
case I2C_SMBUS_WORD_DATA:
len = 2;
cur_word = cpu_to_le16(data->word);
buffer = (u8 *)&cur_word;
break;
case I2C_SMBUS_I2C_BLOCK_DATA:
len = data->block[0];
if (len == 0 || len > I2C_SMBUS_BLOCK_MAX)
return -EINVAL;
buffer = &data->block[1];
break;
default:
return -EINVAL;
}
dev_dbg(&adapter->dev,
"size=%d, address=0x%x, command=0x%x, len=%d, read=%d\n",
size, address, command, len, rw);
if (!len && rw == I2C_SMBUS_READ) {
dev_dbg(&adapter->dev, "zero length read\n");
return -EINVAL;
}
mutex_lock(&iface->mutex);
iface->address_byte = (address << 1) | rw;
iface->command = command;
iface->ptr = buffer;
iface->len = len;
iface->result = -EINVAL;
iface->needs_reset = 0;
outb(inb(ACBCTL1) | ACBCTL1_START, ACBCTL1);
if (size == I2C_SMBUS_QUICK || size == I2C_SMBUS_BYTE)
iface->state = state_quick;
else
iface->state = state_address;
while (iface->state != state_idle)
scx200_acb_poll(iface);
if (iface->needs_reset)
scx200_acb_reset(iface);
rc = iface->result;
mutex_unlock(&iface->mutex);
if (rc == 0 && size == I2C_SMBUS_WORD_DATA && rw == I2C_SMBUS_READ)
data->word = le16_to_cpu(cur_word);
#ifdef DEBUG
dev_dbg(&adapter->dev, "transfer done, result: %d", rc);
if (buffer) {
int i;
printk(" data:");
for (i = 0; i < len; ++i)
printk(" %02x", buffer[i]);
}
printk("\n");
#endif
return rc;
}
static u32 scx200_acb_func(struct i2c_adapter *adapter)
{
return I2C_FUNC_SMBUS_QUICK | I2C_FUNC_SMBUS_BYTE |
I2C_FUNC_SMBUS_BYTE_DATA | I2C_FUNC_SMBUS_WORD_DATA |
I2C_FUNC_SMBUS_I2C_BLOCK;
}
/* For now, we only handle combined mode (smbus) */
static const struct i2c_algorithm scx200_acb_algorithm = {
.smbus_xfer = scx200_acb_smbus_xfer,
.functionality = scx200_acb_func,
};
static struct scx200_acb_iface *scx200_acb_list;
static DEFINE_MUTEX(scx200_acb_list_mutex);
static int scx200_acb_probe(struct scx200_acb_iface *iface)
{
u8 val;
/* Disable the ACCESS.bus device and Configure the SCL
frequency: 16 clock cycles */
outb(0x70, ACBCTL2);
if (inb(ACBCTL2) != 0x70) {
pr_debug("ACBCTL2 readback failed\n");
return -ENXIO;
}
outb(inb(ACBCTL1) | ACBCTL1_NMINTE, ACBCTL1);
val = inb(ACBCTL1);
if (val) {
pr_debug("disabled, but ACBCTL1=0x%02x\n", val);
return -ENXIO;
}
outb(inb(ACBCTL2) | ACBCTL2_ENABLE, ACBCTL2);
outb(inb(ACBCTL1) | ACBCTL1_NMINTE, ACBCTL1);
val = inb(ACBCTL1);
if ((val & ACBCTL1_NMINTE) != ACBCTL1_NMINTE) {
pr_debug("enabled, but NMINTE won't be set, ACBCTL1=0x%02x\n",
val);
return -ENXIO;
}
return 0;
}
static struct scx200_acb_iface *scx200_create_iface(const char *text,
struct device *dev, int index)
{
struct scx200_acb_iface *iface;
struct i2c_adapter *adapter;
iface = kzalloc(sizeof(*iface), GFP_KERNEL);
if (!iface) {
pr_err("can't allocate memory\n");
return NULL;
}
adapter = &iface->adapter;
i2c_set_adapdata(adapter, iface);
snprintf(adapter->name, sizeof(adapter->name), "%s ACB%d", text, index);
adapter->owner = THIS_MODULE;
adapter->algo = &scx200_acb_algorithm;
adapter->class = I2C_CLASS_HWMON | I2C_CLASS_SPD;
adapter->dev.parent = dev;
mutex_init(&iface->mutex);
return iface;
}
static int scx200_acb_create(struct scx200_acb_iface *iface)
{
struct i2c_adapter *adapter;
int rc;
adapter = &iface->adapter;
rc = scx200_acb_probe(iface);
if (rc) {
pr_warn("probe failed\n");
return rc;
}
scx200_acb_reset(iface);
if (i2c_add_adapter(adapter) < 0) {
pr_err("failed to register\n");
return -ENODEV;
}
if (!adapter->dev.parent) {
/* If there's no dev, we're tracking (ISA) ifaces manually */
mutex_lock(&scx200_acb_list_mutex);
iface->next = scx200_acb_list;
scx200_acb_list = iface;
mutex_unlock(&scx200_acb_list_mutex);
}
return 0;
}
static struct scx200_acb_iface *scx200_create_dev(const char *text,
unsigned long base, int index, struct device *dev)
{
struct scx200_acb_iface *iface;
int rc;
iface = scx200_create_iface(text, dev, index);
if (iface == NULL)
return NULL;
if (!request_region(base, 8, iface->adapter.name)) {
pr_err("can't allocate io 0x%lx-0x%lx\n", base, base + 8 - 1);
goto errout_free;
}
iface->base = base;
rc = scx200_acb_create(iface);
if (rc == 0)
return iface;
release_region(base, 8);
errout_free:
kfree(iface);
return NULL;
}
static int scx200_probe(struct platform_device *pdev)
{
struct scx200_acb_iface *iface;
struct resource *res;
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!res) {
dev_err(&pdev->dev, "can't fetch device resource info\n");
return -ENODEV;
}
iface = scx200_create_dev("CS5535", res->start, 0, &pdev->dev);
if (!iface)
return -EIO;
dev_info(&pdev->dev, "SCx200 device '%s' registered\n",
iface->adapter.name);
platform_set_drvdata(pdev, iface);
return 0;
}
static void scx200_cleanup_iface(struct scx200_acb_iface *iface)
{
i2c_del_adapter(&iface->adapter);
release_region(iface->base, 8);
kfree(iface);
}
static int scx200_remove(struct platform_device *pdev)
{
struct scx200_acb_iface *iface;
iface = platform_get_drvdata(pdev);
scx200_cleanup_iface(iface);
return 0;
}
static struct platform_driver scx200_pci_driver = {
.driver = {
.name = "cs5535-smb",
.owner = THIS_MODULE,
},
.probe = scx200_probe,
.remove = scx200_remove,
};
static DEFINE_PCI_DEVICE_TABLE(scx200_isa) = {
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SCx200_BRIDGE) },
{ PCI_DEVICE(PCI_VENDOR_ID_NS, PCI_DEVICE_ID_NS_SC1100_BRIDGE) },
{ 0, }
};
static __init void scx200_scan_isa(void)
{
int i;
if (!pci_dev_present(scx200_isa))
return;
for (i = 0; i < MAX_DEVICES; ++i) {
if (base[i] == 0)
continue;
/* XXX: should we care about failures? */
scx200_create_dev("SCx200", base[i], i, NULL);
}
}
static int __init scx200_acb_init(void)
{
pr_debug("NatSemi SCx200 ACCESS.bus Driver\n");
/* First scan for ISA-based devices */
scx200_scan_isa(); /* XXX: should we care about errors? */
/* If at least one bus was created, init must succeed */
if (scx200_acb_list)
return 0;
/* No ISA devices; register the platform driver for PCI-based devices */
return platform_driver_register(&scx200_pci_driver);
}
static void __exit scx200_acb_cleanup(void)
{
struct scx200_acb_iface *iface;
platform_driver_unregister(&scx200_pci_driver);
mutex_lock(&scx200_acb_list_mutex);
while ((iface = scx200_acb_list) != NULL) {
scx200_acb_list = iface->next;
mutex_unlock(&scx200_acb_list_mutex);
scx200_cleanup_iface(iface);
mutex_lock(&scx200_acb_list_mutex);
}
mutex_unlock(&scx200_acb_list_mutex);
}
module_init(scx200_acb_init);
module_exit(scx200_acb_cleanup);
| gpl-2.0 |
anwarMov/android_kernel_asus_a500cg | drivers/net/phy/national.c | 3377 | 4393 | /*
* drivers/net/phy/national.c
*
* Driver for National Semiconductor PHYs
*
* Author: Stuart Menefy <stuart.menefy@st.com>
* Maintainer: Giuseppe Cavallaro <peppe.cavallaro@st.com>
*
* Copyright (c) 2008 STMicroelectronics Limited
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/phy.h>
#include <linux/netdevice.h>
#define DEBUG
/* DP83865 phy identifier values */
#define DP83865_PHY_ID 0x20005c7a
#define DP83865_INT_STATUS 0x14
#define DP83865_INT_MASK 0x15
#define DP83865_INT_CLEAR 0x17
#define DP83865_INT_REMOTE_FAULT 0x0008
#define DP83865_INT_ANE_COMPLETED 0x0010
#define DP83865_INT_LINK_CHANGE 0xe000
#define DP83865_INT_MASK_DEFAULT (DP83865_INT_REMOTE_FAULT | \
DP83865_INT_ANE_COMPLETED | \
DP83865_INT_LINK_CHANGE)
/* Advanced proprietary configuration */
#define NS_EXP_MEM_CTL 0x16
#define NS_EXP_MEM_DATA 0x1d
#define NS_EXP_MEM_ADD 0x1e
#define LED_CTRL_REG 0x13
#define AN_FALLBACK_AN 0x0001
#define AN_FALLBACK_CRC 0x0002
#define AN_FALLBACK_IE 0x0004
#define ALL_FALLBACK_ON (AN_FALLBACK_AN | AN_FALLBACK_CRC | AN_FALLBACK_IE)
enum hdx_loopback {
hdx_loopback_on = 0,
hdx_loopback_off = 1,
};
static u8 ns_exp_read(struct phy_device *phydev, u16 reg)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
return phy_read(phydev, NS_EXP_MEM_DATA);
}
static void ns_exp_write(struct phy_device *phydev, u16 reg, u8 data)
{
phy_write(phydev, NS_EXP_MEM_ADD, reg);
phy_write(phydev, NS_EXP_MEM_DATA, data);
}
static int ns_config_intr(struct phy_device *phydev)
{
int err;
if (phydev->interrupts == PHY_INTERRUPT_ENABLED)
err = phy_write(phydev, DP83865_INT_MASK,
DP83865_INT_MASK_DEFAULT);
else
err = phy_write(phydev, DP83865_INT_MASK, 0);
return err;
}
static int ns_ack_interrupt(struct phy_device *phydev)
{
int ret = phy_read(phydev, DP83865_INT_STATUS);
if (ret < 0)
return ret;
/* Clear the interrupt status bit by writing a “1”
* to the corresponding bit in INT_CLEAR (2:0 are reserved) */
ret = phy_write(phydev, DP83865_INT_CLEAR, ret & ~0x7);
return ret;
}
static void ns_giga_speed_fallback(struct phy_device *phydev, int mode)
{
int bmcr = phy_read(phydev, MII_BMCR);
phy_write(phydev, MII_BMCR, (bmcr | BMCR_PDOWN));
/* Enable 8 bit expended memory read/write (no auto increment) */
phy_write(phydev, NS_EXP_MEM_CTL, 0);
phy_write(phydev, NS_EXP_MEM_ADD, 0x1C0);
phy_write(phydev, NS_EXP_MEM_DATA, 0x0008);
phy_write(phydev, MII_BMCR, (bmcr & ~BMCR_PDOWN));
phy_write(phydev, LED_CTRL_REG, mode);
}
static void ns_10_base_t_hdx_loopack(struct phy_device *phydev, int disable)
{
if (disable)
ns_exp_write(phydev, 0x1c0, ns_exp_read(phydev, 0x1c0) | 1);
else
ns_exp_write(phydev, 0x1c0,
ns_exp_read(phydev, 0x1c0) & 0xfffe);
pr_debug("10BASE-T HDX loopback %s\n",
(ns_exp_read(phydev, 0x1c0) & 0x0001) ? "off" : "on");
}
static int ns_config_init(struct phy_device *phydev)
{
ns_giga_speed_fallback(phydev, ALL_FALLBACK_ON);
/* In the latest MAC or switches design, the 10 Mbps loopback
is desired to be turned off. */
ns_10_base_t_hdx_loopack(phydev, hdx_loopback_off);
return ns_ack_interrupt(phydev);
}
static struct phy_driver dp83865_driver = {
.phy_id = DP83865_PHY_ID,
.phy_id_mask = 0xfffffff0,
.name = "NatSemi DP83865",
.features = PHY_GBIT_FEATURES | SUPPORTED_Pause | SUPPORTED_Asym_Pause,
.flags = PHY_HAS_INTERRUPT,
.config_init = ns_config_init,
.config_aneg = genphy_config_aneg,
.read_status = genphy_read_status,
.ack_interrupt = ns_ack_interrupt,
.config_intr = ns_config_intr,
.driver = {.owner = THIS_MODULE,}
};
static int __init ns_init(void)
{
return phy_driver_register(&dp83865_driver);
}
static void __exit ns_exit(void)
{
phy_driver_unregister(&dp83865_driver);
}
MODULE_DESCRIPTION("NatSemi PHY driver");
MODULE_AUTHOR("Stuart Menefy");
MODULE_LICENSE("GPL");
module_init(ns_init);
module_exit(ns_exit);
static struct mdio_device_id __maybe_unused ns_tbl[] = {
{ DP83865_PHY_ID, 0xfffffff0 },
{ }
};
MODULE_DEVICE_TABLE(mdio, ns_tbl);
| gpl-2.0 |
nycbjr/tf700t_kernel | drivers/dma/coh901318_lli.c | 4145 | 6503 | /*
* driver/dma/coh901318_lli.c
*
* Copyright (C) 2007-2009 ST-Ericsson
* License terms: GNU General Public License (GPL) version 2
* Support functions for handling lli for dma
* Author: Per Friden <per.friden@stericsson.com>
*/
#include <linux/dma-mapping.h>
#include <linux/spinlock.h>
#include <linux/dmapool.h>
#include <linux/memory.h>
#include <linux/gfp.h>
#include <mach/coh901318.h>
#include "coh901318_lli.h"
#if (defined(CONFIG_DEBUG_FS) && defined(CONFIG_U300_DEBUG))
#define DEBUGFS_POOL_COUNTER_RESET(pool) (pool->debugfs_pool_counter = 0)
#define DEBUGFS_POOL_COUNTER_ADD(pool, add) (pool->debugfs_pool_counter += add)
#else
#define DEBUGFS_POOL_COUNTER_RESET(pool)
#define DEBUGFS_POOL_COUNTER_ADD(pool, add)
#endif
static struct coh901318_lli *
coh901318_lli_next(struct coh901318_lli *data)
{
if (data == NULL || data->link_addr == 0)
return NULL;
return (struct coh901318_lli *) data->virt_link_addr;
}
int coh901318_pool_create(struct coh901318_pool *pool,
struct device *dev,
size_t size, size_t align)
{
spin_lock_init(&pool->lock);
pool->dev = dev;
pool->dmapool = dma_pool_create("lli_pool", dev, size, align, 0);
DEBUGFS_POOL_COUNTER_RESET(pool);
return 0;
}
int coh901318_pool_destroy(struct coh901318_pool *pool)
{
dma_pool_destroy(pool->dmapool);
return 0;
}
struct coh901318_lli *
coh901318_lli_alloc(struct coh901318_pool *pool, unsigned int len)
{
int i;
struct coh901318_lli *head;
struct coh901318_lli *lli;
struct coh901318_lli *lli_prev;
dma_addr_t phy;
if (len == 0)
goto err;
spin_lock(&pool->lock);
head = dma_pool_alloc(pool->dmapool, GFP_NOWAIT, &phy);
if (head == NULL)
goto err;
DEBUGFS_POOL_COUNTER_ADD(pool, 1);
lli = head;
lli->phy_this = phy;
lli->link_addr = 0x00000000;
lli->virt_link_addr = 0x00000000U;
for (i = 1; i < len; i++) {
lli_prev = lli;
lli = dma_pool_alloc(pool->dmapool, GFP_NOWAIT, &phy);
if (lli == NULL)
goto err_clean_up;
DEBUGFS_POOL_COUNTER_ADD(pool, 1);
lli->phy_this = phy;
lli->link_addr = 0x00000000;
lli->virt_link_addr = 0x00000000U;
lli_prev->link_addr = phy;
lli_prev->virt_link_addr = lli;
}
spin_unlock(&pool->lock);
return head;
err:
spin_unlock(&pool->lock);
return NULL;
err_clean_up:
lli_prev->link_addr = 0x00000000U;
spin_unlock(&pool->lock);
coh901318_lli_free(pool, &head);
return NULL;
}
void coh901318_lli_free(struct coh901318_pool *pool,
struct coh901318_lli **lli)
{
struct coh901318_lli *l;
struct coh901318_lli *next;
if (lli == NULL)
return;
l = *lli;
if (l == NULL)
return;
spin_lock(&pool->lock);
while (l->link_addr) {
next = l->virt_link_addr;
dma_pool_free(pool->dmapool, l, l->phy_this);
DEBUGFS_POOL_COUNTER_ADD(pool, -1);
l = next;
}
dma_pool_free(pool->dmapool, l, l->phy_this);
DEBUGFS_POOL_COUNTER_ADD(pool, -1);
spin_unlock(&pool->lock);
*lli = NULL;
}
int
coh901318_lli_fill_memcpy(struct coh901318_pool *pool,
struct coh901318_lli *lli,
dma_addr_t source, unsigned int size,
dma_addr_t destination, u32 ctrl_chained,
u32 ctrl_eom)
{
int s = size;
dma_addr_t src = source;
dma_addr_t dst = destination;
lli->src_addr = src;
lli->dst_addr = dst;
while (lli->link_addr) {
lli->control = ctrl_chained | MAX_DMA_PACKET_SIZE;
lli->src_addr = src;
lli->dst_addr = dst;
s -= MAX_DMA_PACKET_SIZE;
lli = coh901318_lli_next(lli);
src += MAX_DMA_PACKET_SIZE;
dst += MAX_DMA_PACKET_SIZE;
}
lli->control = ctrl_eom | s;
lli->src_addr = src;
lli->dst_addr = dst;
return 0;
}
int
coh901318_lli_fill_single(struct coh901318_pool *pool,
struct coh901318_lli *lli,
dma_addr_t buf, unsigned int size,
dma_addr_t dev_addr, u32 ctrl_chained, u32 ctrl_eom,
enum dma_data_direction dir)
{
int s = size;
dma_addr_t src;
dma_addr_t dst;
if (dir == DMA_TO_DEVICE) {
src = buf;
dst = dev_addr;
} else if (dir == DMA_FROM_DEVICE) {
src = dev_addr;
dst = buf;
} else {
return -EINVAL;
}
while (lli->link_addr) {
size_t block_size = MAX_DMA_PACKET_SIZE;
lli->control = ctrl_chained | MAX_DMA_PACKET_SIZE;
/* If we are on the next-to-final block and there will
* be less than half a DMA packet left for the last
* block, then we want to make this block a little
* smaller to balance the sizes. This is meant to
* avoid too small transfers if the buffer size is
* (MAX_DMA_PACKET_SIZE*N + 1) */
if (s < (MAX_DMA_PACKET_SIZE + MAX_DMA_PACKET_SIZE/2))
block_size = MAX_DMA_PACKET_SIZE/2;
s -= block_size;
lli->src_addr = src;
lli->dst_addr = dst;
lli = coh901318_lli_next(lli);
if (dir == DMA_TO_DEVICE)
src += block_size;
else if (dir == DMA_FROM_DEVICE)
dst += block_size;
}
lli->control = ctrl_eom | s;
lli->src_addr = src;
lli->dst_addr = dst;
return 0;
}
int
coh901318_lli_fill_sg(struct coh901318_pool *pool,
struct coh901318_lli *lli,
struct scatterlist *sgl, unsigned int nents,
dma_addr_t dev_addr, u32 ctrl_chained, u32 ctrl,
u32 ctrl_last,
enum dma_data_direction dir, u32 ctrl_irq_mask)
{
int i;
struct scatterlist *sg;
u32 ctrl_sg;
dma_addr_t src = 0;
dma_addr_t dst = 0;
u32 bytes_to_transfer;
u32 elem_size;
if (lli == NULL)
goto err;
spin_lock(&pool->lock);
if (dir == DMA_TO_DEVICE)
dst = dev_addr;
else if (dir == DMA_FROM_DEVICE)
src = dev_addr;
else
goto err;
for_each_sg(sgl, sg, nents, i) {
if (sg_is_chain(sg)) {
/* sg continues to the next sg-element don't
* send ctrl_finish until the last
* sg-element in the chain
*/
ctrl_sg = ctrl_chained;
} else if (i == nents - 1)
ctrl_sg = ctrl_last;
else
ctrl_sg = ctrl ? ctrl : ctrl_last;
if (dir == DMA_TO_DEVICE)
/* increment source address */
src = sg_phys(sg);
else
/* increment destination address */
dst = sg_phys(sg);
bytes_to_transfer = sg_dma_len(sg);
while (bytes_to_transfer) {
u32 val;
if (bytes_to_transfer > MAX_DMA_PACKET_SIZE) {
elem_size = MAX_DMA_PACKET_SIZE;
val = ctrl_chained;
} else {
elem_size = bytes_to_transfer;
val = ctrl_sg;
}
lli->control = val | elem_size;
lli->src_addr = src;
lli->dst_addr = dst;
if (dir == DMA_FROM_DEVICE)
dst += elem_size;
else
src += elem_size;
BUG_ON(lli->link_addr & 3);
bytes_to_transfer -= elem_size;
lli = coh901318_lli_next(lli);
}
}
spin_unlock(&pool->lock);
return 0;
err:
spin_unlock(&pool->lock);
return -EINVAL;
}
| gpl-2.0 |
dastuam/linux37-beaglebone | arch/arm/mach-imx/mmdc.c | 5169 | 1683 | /*
* Copyright 2011 Freescale Semiconductor, Inc.
* Copyright 2011 Linaro Ltd.
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#define MMDC_MAPSR 0x404
#define BP_MMDC_MAPSR_PSD 0
#define BP_MMDC_MAPSR_PSS 4
static int __devinit imx_mmdc_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
void __iomem *mmdc_base, *reg;
u32 val;
int timeout = 0x400;
mmdc_base = of_iomap(np, 0);
WARN_ON(!mmdc_base);
reg = mmdc_base + MMDC_MAPSR;
/* Enable automatic power saving */
val = readl_relaxed(reg);
val &= ~(1 << BP_MMDC_MAPSR_PSD);
writel_relaxed(val, reg);
/* Ensure it's successfully enabled */
while (!(readl_relaxed(reg) & 1 << BP_MMDC_MAPSR_PSS) && --timeout)
cpu_relax();
if (unlikely(!timeout)) {
pr_warn("%s: failed to enable automatic power saving\n",
__func__);
return -EBUSY;
}
return 0;
}
static struct of_device_id imx_mmdc_dt_ids[] = {
{ .compatible = "fsl,imx6q-mmdc", },
{ /* sentinel */ }
};
static struct platform_driver imx_mmdc_driver = {
.driver = {
.name = "imx-mmdc",
.owner = THIS_MODULE,
.of_match_table = imx_mmdc_dt_ids,
},
.probe = imx_mmdc_probe,
};
static int __init imx_mmdc_init(void)
{
return platform_driver_register(&imx_mmdc_driver);
}
postcore_initcall(imx_mmdc_init);
| gpl-2.0 |
oppo-source/Find5-4.2-kernel-source | arch/arm/mach-imx/mmdc.c | 5169 | 1683 | /*
* Copyright 2011 Freescale Semiconductor, Inc.
* Copyright 2011 Linaro Ltd.
*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <linux/init.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_address.h>
#include <linux/of_device.h>
#define MMDC_MAPSR 0x404
#define BP_MMDC_MAPSR_PSD 0
#define BP_MMDC_MAPSR_PSS 4
static int __devinit imx_mmdc_probe(struct platform_device *pdev)
{
struct device_node *np = pdev->dev.of_node;
void __iomem *mmdc_base, *reg;
u32 val;
int timeout = 0x400;
mmdc_base = of_iomap(np, 0);
WARN_ON(!mmdc_base);
reg = mmdc_base + MMDC_MAPSR;
/* Enable automatic power saving */
val = readl_relaxed(reg);
val &= ~(1 << BP_MMDC_MAPSR_PSD);
writel_relaxed(val, reg);
/* Ensure it's successfully enabled */
while (!(readl_relaxed(reg) & 1 << BP_MMDC_MAPSR_PSS) && --timeout)
cpu_relax();
if (unlikely(!timeout)) {
pr_warn("%s: failed to enable automatic power saving\n",
__func__);
return -EBUSY;
}
return 0;
}
static struct of_device_id imx_mmdc_dt_ids[] = {
{ .compatible = "fsl,imx6q-mmdc", },
{ /* sentinel */ }
};
static struct platform_driver imx_mmdc_driver = {
.driver = {
.name = "imx-mmdc",
.owner = THIS_MODULE,
.of_match_table = imx_mmdc_dt_ids,
},
.probe = imx_mmdc_probe,
};
static int __init imx_mmdc_init(void)
{
return platform_driver_register(&imx_mmdc_driver);
}
postcore_initcall(imx_mmdc_init);
| gpl-2.0 |
boa19861105/Test-1-dlxp_ul | drivers/staging/comedi/drivers/dt2811.c | 7985 | 15049 | /*
comedi/drivers/dt2811.c
Hardware driver for Data Translation DT2811
COMEDI - Linux Control and Measurement Device Interface
History:
Base Version - David A. Schleef <ds@schleef.org>
December 1998 - Updated to work. David does not have a DT2811
board any longer so this was suffering from bitrot.
Updated performed by ...
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: dt2811
Description: Data Translation DT2811
Author: ds
Devices: [Data Translation] DT2811-PGL (dt2811-pgl), DT2811-PGH (dt2811-pgh)
Status: works
Configuration options:
[0] - I/O port base address
[1] - IRQ, although this is currently unused
[2] - A/D reference
0 = signle-ended
1 = differential
2 = pseudo-differential (common reference)
[3] - A/D range
0 = [-5, 5]
1 = [-2.5, 2.5]
2 = [0, 5]
[4] - D/A 0 range (same choices)
[4] - D/A 1 range (same choices)
*/
#include <linux/interrupt.h>
#include "../comedidev.h"
#include <linux/ioport.h>
static const char *driver_name = "dt2811";
static const struct comedi_lrange range_dt2811_pgh_ai_5_unipolar = {
4, {
RANGE(0, 5),
RANGE(0, 2.5),
RANGE(0, 1.25),
RANGE(0, 0.625)
}
};
static const struct comedi_lrange range_dt2811_pgh_ai_2_5_bipolar = {
4, {
RANGE(-2.5, 2.5),
RANGE(-1.25, 1.25),
RANGE(-0.625, 0.625),
RANGE(-0.3125, 0.3125)
}
};
static const struct comedi_lrange range_dt2811_pgh_ai_5_bipolar = {
4, {
RANGE(-5, 5),
RANGE(-2.5, 2.5),
RANGE(-1.25, 1.25),
RANGE(-0.625, 0.625)
}
};
static const struct comedi_lrange range_dt2811_pgl_ai_5_unipolar = {
4, {
RANGE(0, 5),
RANGE(0, 0.5),
RANGE(0, 0.05),
RANGE(0, 0.01)
}
};
static const struct comedi_lrange range_dt2811_pgl_ai_2_5_bipolar = {
4, {
RANGE(-2.5, 2.5),
RANGE(-0.25, 0.25),
RANGE(-0.025, 0.025),
RANGE(-0.005, 0.005)
}
};
static const struct comedi_lrange range_dt2811_pgl_ai_5_bipolar = {
4, {
RANGE(-5, 5),
RANGE(-0.5, 0.5),
RANGE(-0.05, 0.05),
RANGE(-0.01, 0.01)
}
};
/*
0x00 ADCSR R/W A/D Control/Status Register
bit 7 - (R) 1 indicates A/D conversion done
reading ADDAT clears bit
(W) ignored
bit 6 - (R) 1 indicates A/D error
(W) ignored
bit 5 - (R) 1 indicates A/D busy, cleared at end
of conversion
(W) ignored
bit 4 - (R) 0
(W)
bit 3 - (R) 0
bit 2 - (R/W) 1 indicates interrupts enabled
bits 1,0 - (R/W) mode bits
00 single conversion on ADGCR load
01 continuous conversion, internal clock,
(clock enabled on ADGCR load)
10 continuous conversion, internal clock,
external trigger
11 continuous conversion, external clock,
external trigger
0x01 ADGCR R/W A/D Gain/Channel Register
bit 6,7 - (R/W) gain select
00 gain=1, both PGH, PGL models
01 gain=2 PGH, 10 PGL
10 gain=4 PGH, 100 PGL
11 gain=8 PGH, 500 PGL
bit 4,5 - reserved
bit 3-0 - (R/W) channel select
channel number from 0-15
0x02,0x03 (R) ADDAT A/D Data Register
(W) DADAT0 D/A Data Register 0
0x02 low byte
0x03 high byte
0x04,0x05 (W) DADAT0 D/A Data Register 1
0x06 (R) DIO0 Digital Input Port 0
(W) DIO1 Digital Output Port 1
0x07 TMRCTR (R/W) Timer/Counter Register
bits 6,7 - reserved
bits 5-3 - Timer frequency control (mantissa)
543 divisor freqency (kHz)
000 1 600
001 10 60
010 2 300
011 3 200
100 4 150
101 5 120
110 6 100
111 12 50
bits 2-0 - Timer frequency control (exponent)
210 multiply divisor/divide frequency by
000 1
001 10
010 100
011 1000
100 10000
101 100000
110 1000000
111 10000000
*/
#define TIMEOUT 10000
#define DT2811_SIZE 8
#define DT2811_ADCSR 0
#define DT2811_ADGCR 1
#define DT2811_ADDATLO 2
#define DT2811_ADDATHI 3
#define DT2811_DADAT0LO 2
#define DT2811_DADAT0HI 3
#define DT2811_DADAT1LO 4
#define DT2811_DADAT1HI 5
#define DT2811_DIO 6
#define DT2811_TMRCTR 7
/*
* flags
*/
/* ADCSR */
#define DT2811_ADDONE 0x80
#define DT2811_ADERROR 0x40
#define DT2811_ADBUSY 0x20
#define DT2811_CLRERROR 0x10
#define DT2811_INTENB 0x04
#define DT2811_ADMODE 0x03
struct dt2811_board {
const char *name;
const struct comedi_lrange *bip_5;
const struct comedi_lrange *bip_2_5;
const struct comedi_lrange *unip_5;
};
static const struct dt2811_board boardtypes[] = {
{"dt2811-pgh",
&range_dt2811_pgh_ai_5_bipolar,
&range_dt2811_pgh_ai_2_5_bipolar,
&range_dt2811_pgh_ai_5_unipolar,
},
{"dt2811-pgl",
&range_dt2811_pgl_ai_5_bipolar,
&range_dt2811_pgl_ai_2_5_bipolar,
&range_dt2811_pgl_ai_5_unipolar,
},
};
#define this_board ((const struct dt2811_board *)dev->board_ptr)
static int dt2811_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int dt2811_detach(struct comedi_device *dev);
static struct comedi_driver driver_dt2811 = {
.driver_name = "dt2811",
.module = THIS_MODULE,
.attach = dt2811_attach,
.detach = dt2811_detach,
.board_name = &boardtypes[0].name,
.num_names = ARRAY_SIZE(boardtypes),
.offset = sizeof(struct dt2811_board),
};
static int __init driver_dt2811_init_module(void)
{
return comedi_driver_register(&driver_dt2811);
}
static void __exit driver_dt2811_cleanup_module(void)
{
comedi_driver_unregister(&driver_dt2811);
}
module_init(driver_dt2811_init_module);
module_exit(driver_dt2811_cleanup_module);
static int dt2811_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int dt2811_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int dt2811_ao_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int dt2811_di_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int dt2811_do_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
enum { card_2811_pgh, card_2811_pgl };
struct dt2811_private {
int ntrig;
int curadchan;
enum {
adc_singleended, adc_diff, adc_pseudo_diff
} adc_mux;
enum {
dac_bipolar_5, dac_bipolar_2_5, dac_unipolar_5
} dac_range[2];
const struct comedi_lrange *range_type_list[2];
unsigned int ao_readback[2];
};
#define devpriv ((struct dt2811_private *)dev->private)
static const struct comedi_lrange *dac_range_types[] = {
&range_bipolar5,
&range_bipolar2_5,
&range_unipolar5
};
#define DT2811_TIMEOUT 5
#if 0
static irqreturn_t dt2811_interrupt(int irq, void *d)
{
int lo, hi;
int data;
struct comedi_device *dev = d;
if (!dev->attached) {
comedi_error(dev, "spurious interrupt");
return IRQ_HANDLED;
}
lo = inb(dev->iobase + DT2811_ADDATLO);
hi = inb(dev->iobase + DT2811_ADDATHI);
data = lo + (hi << 8);
if (!(--devpriv->ntrig)) {
/* how to turn off acquisition */
s->async->events |= COMEDI_SB_EOA;
}
comedi_event(dev, s);
return IRQ_HANDLED;
}
#endif
/*
options[0] Board base address
options[1] IRQ
options[2] Input configuration
0 == single-ended
1 == differential
2 == pseudo-differential
options[3] Analog input range configuration
0 == bipolar 5 (-5V -- +5V)
1 == bipolar 2.5V (-2.5V -- +2.5V)
2 == unipolar 5V (0V -- +5V)
options[4] Analog output 0 range configuration
0 == bipolar 5 (-5V -- +5V)
1 == bipolar 2.5V (-2.5V -- +2.5V)
2 == unipolar 5V (0V -- +5V)
options[5] Analog output 1 range configuration
0 == bipolar 5 (-5V -- +5V)
1 == bipolar 2.5V (-2.5V -- +2.5V)
2 == unipolar 5V (0V -- +5V)
*/
static int dt2811_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
/* int i, irq; */
/* unsigned long irqs; */
/* long flags; */
int ret;
struct comedi_subdevice *s;
unsigned long iobase;
iobase = it->options[0];
printk(KERN_INFO "comedi%d: dt2811:base=0x%04lx\n", dev->minor, iobase);
if (!request_region(iobase, DT2811_SIZE, driver_name)) {
printk(KERN_ERR "I/O port conflict\n");
return -EIO;
}
dev->iobase = iobase;
dev->board_name = this_board->name;
#if 0
outb(0, dev->iobase + DT2811_ADCSR);
udelay(100);
i = inb(dev->iobase + DT2811_ADDATLO);
i = inb(dev->iobase + DT2811_ADDATHI);
#endif
#if 0
irq = it->options[1];
if (irq < 0) {
save_flags(flags);
sti();
irqs = probe_irq_on();
outb(DT2811_CLRERROR | DT2811_INTENB,
dev->iobase + DT2811_ADCSR);
outb(0, dev->iobase + DT2811_ADGCR);
udelay(100);
irq = probe_irq_off(irqs);
restore_flags(flags);
/*outb(DT2811_CLRERROR|DT2811_INTENB,
dev->iobase+DT2811_ADCSR);*/
if (inb(dev->iobase + DT2811_ADCSR) & DT2811_ADERROR)
printk(KERN_ERR "error probing irq (bad)\n");
dev->irq = 0;
if (irq > 0) {
i = inb(dev->iobase + DT2811_ADDATLO);
i = inb(dev->iobase + DT2811_ADDATHI);
printk(KERN_INFO "(irq = %d)\n", irq);
ret = request_irq(irq, dt2811_interrupt, 0,
driver_name, dev);
if (ret < 0)
return -EIO;
dev->irq = irq;
} else if (irq == 0) {
printk(KERN_INFO "(no irq)\n");
} else {
printk(KERN_ERR "( multiple irq's -- this is bad! )\n");
}
}
#endif
ret = alloc_subdevices(dev, 4);
if (ret < 0)
return ret;
ret = alloc_private(dev, sizeof(struct dt2811_private));
if (ret < 0)
return ret;
switch (it->options[2]) {
case 0:
devpriv->adc_mux = adc_singleended;
break;
case 1:
devpriv->adc_mux = adc_diff;
break;
case 2:
devpriv->adc_mux = adc_pseudo_diff;
break;
default:
devpriv->adc_mux = adc_singleended;
break;
}
switch (it->options[4]) {
case 0:
devpriv->dac_range[0] = dac_bipolar_5;
break;
case 1:
devpriv->dac_range[0] = dac_bipolar_2_5;
break;
case 2:
devpriv->dac_range[0] = dac_unipolar_5;
break;
default:
devpriv->dac_range[0] = dac_bipolar_5;
break;
}
switch (it->options[5]) {
case 0:
devpriv->dac_range[1] = dac_bipolar_5;
break;
case 1:
devpriv->dac_range[1] = dac_bipolar_2_5;
break;
case 2:
devpriv->dac_range[1] = dac_unipolar_5;
break;
default:
devpriv->dac_range[1] = dac_bipolar_5;
break;
}
s = dev->subdevices + 0;
/* initialize the ADC subdevice */
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_GROUND;
s->n_chan = devpriv->adc_mux == adc_diff ? 8 : 16;
s->insn_read = dt2811_ai_insn;
s->maxdata = 0xfff;
switch (it->options[3]) {
case 0:
default:
s->range_table = this_board->bip_5;
break;
case 1:
s->range_table = this_board->bip_2_5;
break;
case 2:
s->range_table = this_board->unip_5;
break;
}
s = dev->subdevices + 1;
/* ao subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = 2;
s->insn_write = dt2811_ao_insn;
s->insn_read = dt2811_ao_insn_read;
s->maxdata = 0xfff;
s->range_table_list = devpriv->range_type_list;
devpriv->range_type_list[0] = dac_range_types[devpriv->dac_range[0]];
devpriv->range_type_list[1] = dac_range_types[devpriv->dac_range[1]];
s = dev->subdevices + 2;
/* di subdevice */
s->type = COMEDI_SUBD_DI;
s->subdev_flags = SDF_READABLE;
s->n_chan = 8;
s->insn_bits = dt2811_di_insn_bits;
s->maxdata = 1;
s->range_table = &range_digital;
s = dev->subdevices + 3;
/* do subdevice */
s->type = COMEDI_SUBD_DO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = 8;
s->insn_bits = dt2811_do_insn_bits;
s->maxdata = 1;
s->state = 0;
s->range_table = &range_digital;
return 0;
}
static int dt2811_detach(struct comedi_device *dev)
{
printk(KERN_INFO "comedi%d: dt2811: remove\n", dev->minor);
if (dev->irq)
free_irq(dev->irq, dev);
if (dev->iobase)
release_region(dev->iobase, DT2811_SIZE);
return 0;
}
static int dt2811_ai_insn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int chan = CR_CHAN(insn->chanspec);
int timeout = DT2811_TIMEOUT;
int i;
for (i = 0; i < insn->n; i++) {
outb(chan, dev->iobase + DT2811_ADGCR);
while (timeout
&& inb(dev->iobase + DT2811_ADCSR) & DT2811_ADBUSY)
timeout--;
if (!timeout)
return -ETIME;
data[i] = inb(dev->iobase + DT2811_ADDATLO);
data[i] |= inb(dev->iobase + DT2811_ADDATHI) << 8;
data[i] &= 0xfff;
}
return i;
}
#if 0
/* Wow. This is code from the Comedi stone age. But it hasn't been
* replaced, so I'll let it stay. */
int dt2811_adtrig(kdev_t minor, comedi_adtrig *adtrig)
{
struct comedi_device *dev = comedi_devices + minor;
if (adtrig->n < 1)
return 0;
dev->curadchan = adtrig->chan;
switch (dev->i_admode) {
case COMEDI_MDEMAND:
dev->ntrig = adtrig->n - 1;
/* not necessary */
/*printk("dt2811: AD soft trigger\n"); */
/*outb(DT2811_CLRERROR|DT2811_INTENB,
dev->iobase+DT2811_ADCSR); */
outb(dev->curadchan, dev->iobase + DT2811_ADGCR);
do_gettimeofday(&trigtime);
break;
case COMEDI_MCONTS:
dev->ntrig = adtrig->n;
break;
}
return 0;
}
#endif
static int dt2811_ao_insn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan;
chan = CR_CHAN(insn->chanspec);
for (i = 0; i < insn->n; i++) {
outb(data[i] & 0xff, dev->iobase + DT2811_DADAT0LO + 2 * chan);
outb((data[i] >> 8) & 0xff,
dev->iobase + DT2811_DADAT0HI + 2 * chan);
devpriv->ao_readback[chan] = data[i];
}
return i;
}
static int dt2811_ao_insn_read(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan;
chan = CR_CHAN(insn->chanspec);
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[chan];
return i;
}
static int dt2811_di_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (insn->n != 2)
return -EINVAL;
data[1] = inb(dev->iobase + DT2811_DIO);
return 2;
}
static int dt2811_do_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (insn->n != 2)
return -EINVAL;
s->state &= ~data[0];
s->state |= data[0] & data[1];
outb(s->state, dev->iobase + DT2811_DIO);
data[1] = s->state;
return 2;
}
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
santod/android_GE_kernel_htc_m7vzw | drivers/s390/char/keyboard.c | 7985 | 12529 | /*
* drivers/s390/char/keyboard.c
* ebcdic keycode functions for s390 console drivers
*
* S390 version
* Copyright (C) 2003 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sysrq.h>
#include <linux/consolemap.h>
#include <linux/kbd_kern.h>
#include <linux/kbd_diacr.h>
#include <asm/uaccess.h>
#include "keyboard.h"
/*
* Handler Tables.
*/
#define K_HANDLERS\
k_self, k_fn, k_spec, k_ignore,\
k_dead, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore
typedef void (k_handler_fn)(struct kbd_data *, unsigned char);
static k_handler_fn K_HANDLERS;
static k_handler_fn *k_handler[16] = { K_HANDLERS };
/* maximum values each key_handler can handle */
static const int kbd_max_vals[] = {
255, ARRAY_SIZE(func_table) - 1, NR_FN_HANDLER - 1, 0,
NR_DEAD - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static const int KBD_NR_TYPES = ARRAY_SIZE(kbd_max_vals);
static unsigned char ret_diacr[NR_DEAD] = {
'`', '\'', '^', '~', '"', ','
};
/*
* Alloc/free of kbd_data structures.
*/
struct kbd_data *
kbd_alloc(void) {
struct kbd_data *kbd;
int i;
kbd = kzalloc(sizeof(struct kbd_data), GFP_KERNEL);
if (!kbd)
goto out;
kbd->key_maps = kzalloc(sizeof(key_maps), GFP_KERNEL);
if (!kbd->key_maps)
goto out_kbd;
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
if (key_maps[i]) {
kbd->key_maps[i] = kmemdup(key_maps[i],
sizeof(u_short) * NR_KEYS,
GFP_KERNEL);
if (!kbd->key_maps[i])
goto out_maps;
}
}
kbd->func_table = kzalloc(sizeof(func_table), GFP_KERNEL);
if (!kbd->func_table)
goto out_maps;
for (i = 0; i < ARRAY_SIZE(func_table); i++) {
if (func_table[i]) {
kbd->func_table[i] = kstrdup(func_table[i],
GFP_KERNEL);
if (!kbd->func_table[i])
goto out_func;
}
}
kbd->fn_handler =
kzalloc(sizeof(fn_handler_fn *) * NR_FN_HANDLER, GFP_KERNEL);
if (!kbd->fn_handler)
goto out_func;
kbd->accent_table = kmemdup(accent_table,
sizeof(struct kbdiacruc) * MAX_DIACR,
GFP_KERNEL);
if (!kbd->accent_table)
goto out_fn_handler;
kbd->accent_table_size = accent_table_size;
return kbd;
out_fn_handler:
kfree(kbd->fn_handler);
out_func:
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
out_maps:
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
out_kbd:
kfree(kbd);
out:
return NULL;
}
void
kbd_free(struct kbd_data *kbd)
{
int i;
kfree(kbd->accent_table);
kfree(kbd->fn_handler);
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
kfree(kbd);
}
/*
* Generate ascii -> ebcdic translation table from kbd_data.
*/
void
kbd_ascebc(struct kbd_data *kbd, unsigned char *ascebc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ascebc, 0x40, 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
k = ((i & 1) << 7) + j;
keysym = keymap[j];
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ascebc[KVAL(keysym)] = k;
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ascebc[ret_diacr[KVAL(keysym)]] = k;
}
}
}
#if 0
/*
* Generate ebcdic -> ascii translation table from kbd_data.
*/
void
kbd_ebcasc(struct kbd_data *kbd, unsigned char *ebcasc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ebcasc, ' ', 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
keysym = keymap[j];
k = ((i & 1) << 7) + j;
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ebcasc[k] = KVAL(keysym);
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ebcasc[k] = ret_diacr[KVAL(keysym)];
}
}
}
#endif
/*
* We have a combining character DIACR here, followed by the character CH.
* If the combination occurs in the table, return the corresponding value.
* Otherwise, if CH is a space or equals DIACR, return DIACR.
* Otherwise, conclude that DIACR was not combining after all,
* queue it and return CH.
*/
static unsigned int
handle_diacr(struct kbd_data *kbd, unsigned int ch)
{
int i, d;
d = kbd->diacr;
kbd->diacr = 0;
for (i = 0; i < kbd->accent_table_size; i++) {
if (kbd->accent_table[i].diacr == d &&
kbd->accent_table[i].base == ch)
return kbd->accent_table[i].result;
}
if (ch == ' ' || ch == d)
return d;
kbd_put_queue(kbd->tty, d);
return ch;
}
/*
* Handle dead key.
*/
static void
k_dead(struct kbd_data *kbd, unsigned char value)
{
value = ret_diacr[value];
kbd->diacr = (kbd->diacr ? handle_diacr(kbd, value) : value);
}
/*
* Normal character handler.
*/
static void
k_self(struct kbd_data *kbd, unsigned char value)
{
if (kbd->diacr)
value = handle_diacr(kbd, value);
kbd_put_queue(kbd->tty, value);
}
/*
* Special key handlers
*/
static void
k_ignore(struct kbd_data *kbd, unsigned char value)
{
}
/*
* Function key handler.
*/
static void
k_fn(struct kbd_data *kbd, unsigned char value)
{
if (kbd->func_table[value])
kbd_puts_queue(kbd->tty, kbd->func_table[value]);
}
static void
k_spec(struct kbd_data *kbd, unsigned char value)
{
if (value >= NR_FN_HANDLER)
return;
if (kbd->fn_handler[value])
kbd->fn_handler[value](kbd);
}
/*
* Put utf8 character to tty flip buffer.
* UTF-8 is defined for words of up to 31 bits,
* but we need only 16 bits here
*/
static void
to_utf8(struct tty_struct *tty, ushort c)
{
if (c < 0x80)
/* 0******* */
kbd_put_queue(tty, c);
else if (c < 0x800) {
/* 110***** 10****** */
kbd_put_queue(tty, 0xc0 | (c >> 6));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
} else {
/* 1110**** 10****** 10****** */
kbd_put_queue(tty, 0xe0 | (c >> 12));
kbd_put_queue(tty, 0x80 | ((c >> 6) & 0x3f));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
}
}
/*
* Process keycode.
*/
void
kbd_keycode(struct kbd_data *kbd, unsigned int keycode)
{
unsigned short keysym;
unsigned char type, value;
if (!kbd || !kbd->tty)
return;
if (keycode >= 384)
keysym = kbd->key_maps[5][keycode - 384];
else if (keycode >= 256)
keysym = kbd->key_maps[4][keycode - 256];
else if (keycode >= 128)
keysym = kbd->key_maps[1][keycode - 128];
else
keysym = kbd->key_maps[0][keycode];
type = KTYP(keysym);
if (type >= 0xf0) {
type -= 0xf0;
if (type == KT_LETTER)
type = KT_LATIN;
value = KVAL(keysym);
#ifdef CONFIG_MAGIC_SYSRQ /* Handle the SysRq Hack */
if (kbd->sysrq) {
if (kbd->sysrq == K(KT_LATIN, '-')) {
kbd->sysrq = 0;
handle_sysrq(value);
return;
}
if (value == '-') {
kbd->sysrq = K(KT_LATIN, '-');
return;
}
/* Incomplete sysrq sequence. */
(*k_handler[KTYP(kbd->sysrq)])(kbd, KVAL(kbd->sysrq));
kbd->sysrq = 0;
} else if ((type == KT_LATIN && value == '^') ||
(type == KT_DEAD && ret_diacr[value] == '^')) {
kbd->sysrq = K(type, value);
return;
}
#endif
(*k_handler[type])(kbd, value);
} else
to_utf8(kbd->tty, keysym);
}
/*
* Ioctl stuff.
*/
static int
do_kdsk_ioctl(struct kbd_data *kbd, struct kbentry __user *user_kbe,
int cmd, int perm)
{
struct kbentry tmp;
ushort *key_map, val, ov;
if (copy_from_user(&tmp, user_kbe, sizeof(struct kbentry)))
return -EFAULT;
#if NR_KEYS < 256
if (tmp.kb_index >= NR_KEYS)
return -EINVAL;
#endif
#if MAX_NR_KEYMAPS < 256
if (tmp.kb_table >= MAX_NR_KEYMAPS)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBENT:
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
val = U(key_map[tmp.kb_index]);
if (KTYP(val) >= KBD_NR_TYPES)
val = K_HOLE;
} else
val = (tmp.kb_index ? K_HOLE : K_NOSUCHMAP);
return put_user(val, &user_kbe->kb_value);
case KDSKBENT:
if (!perm)
return -EPERM;
if (!tmp.kb_index && tmp.kb_value == K_NOSUCHMAP) {
/* disallocate map */
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
kbd->key_maps[tmp.kb_table] = NULL;
kfree(key_map);
}
break;
}
if (KTYP(tmp.kb_value) >= KBD_NR_TYPES)
return -EINVAL;
if (KVAL(tmp.kb_value) > kbd_max_vals[KTYP(tmp.kb_value)])
return -EINVAL;
if (!(key_map = kbd->key_maps[tmp.kb_table])) {
int j;
key_map = kmalloc(sizeof(plain_map),
GFP_KERNEL);
if (!key_map)
return -ENOMEM;
kbd->key_maps[tmp.kb_table] = key_map;
for (j = 0; j < NR_KEYS; j++)
key_map[j] = U(K_HOLE);
}
ov = U(key_map[tmp.kb_index]);
if (tmp.kb_value == ov)
break; /* nothing to do */
/*
* Attention Key.
*/
if (((ov == K_SAK) || (tmp.kb_value == K_SAK)) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
key_map[tmp.kb_index] = U(tmp.kb_value);
break;
}
return 0;
}
static int
do_kdgkb_ioctl(struct kbd_data *kbd, struct kbsentry __user *u_kbs,
int cmd, int perm)
{
unsigned char kb_func;
char *p;
int len;
/* Get u_kbs->kb_func. */
if (get_user(kb_func, &u_kbs->kb_func))
return -EFAULT;
#if MAX_NR_FUNC < 256
if (kb_func >= MAX_NR_FUNC)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBSENT:
p = kbd->func_table[kb_func];
if (p) {
len = strlen(p);
if (len >= sizeof(u_kbs->kb_string))
len = sizeof(u_kbs->kb_string) - 1;
if (copy_to_user(u_kbs->kb_string, p, len))
return -EFAULT;
} else
len = 0;
if (put_user('\0', u_kbs->kb_string + len))
return -EFAULT;
break;
case KDSKBSENT:
if (!perm)
return -EPERM;
len = strnlen_user(u_kbs->kb_string,
sizeof(u_kbs->kb_string) - 1);
if (!len)
return -EFAULT;
if (len > sizeof(u_kbs->kb_string) - 1)
return -EINVAL;
p = kmalloc(len + 1, GFP_KERNEL);
if (!p)
return -ENOMEM;
if (copy_from_user(p, u_kbs->kb_string, len)) {
kfree(p);
return -EFAULT;
}
p[len] = 0;
kfree(kbd->func_table[kb_func]);
kbd->func_table[kb_func] = p;
break;
}
return 0;
}
int kbd_ioctl(struct kbd_data *kbd, unsigned int cmd, unsigned long arg)
{
void __user *argp;
unsigned int ct;
int perm;
argp = (void __user *)arg;
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = current->signal->tty == kbd->tty || capable(CAP_SYS_TTY_CONFIG);
switch (cmd) {
case KDGKBTYPE:
return put_user(KB_101, (char __user *)argp);
case KDGKBENT:
case KDSKBENT:
return do_kdsk_ioctl(kbd, argp, cmd, perm);
case KDGKBSENT:
case KDSKBSENT:
return do_kdgkb_ioctl(kbd, argp, cmd, perm);
case KDGKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (put_user(kbd->accent_table_size, &a->kb_cnt))
return -EFAULT;
for (i = 0; i < kbd->accent_table_size; i++) {
diacr.diacr = kbd->accent_table[i].diacr;
diacr.base = kbd->accent_table[i].base;
diacr.result = kbd->accent_table[i].result;
if (copy_to_user(a->kbdiacr + i, &diacr, sizeof(struct kbdiacr)))
return -EFAULT;
}
return 0;
}
case KDGKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
ct = kbd->accent_table_size;
if (put_user(ct, &a->kb_cnt))
return -EFAULT;
if (copy_to_user(a->kbdiacruc, kbd->accent_table,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
case KDSKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
for (i = 0; i < ct; i++) {
if (copy_from_user(&diacr, a->kbdiacr + i, sizeof(struct kbdiacr)))
return -EFAULT;
kbd->accent_table[i].diacr = diacr.diacr;
kbd->accent_table[i].base = diacr.base;
kbd->accent_table[i].result = diacr.result;
}
return 0;
}
case KDSKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
if (copy_from_user(kbd->accent_table, a->kbdiacruc,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
default:
return -ENOIOCTLCMD;
}
}
EXPORT_SYMBOL(kbd_ioctl);
EXPORT_SYMBOL(kbd_ascebc);
EXPORT_SYMBOL(kbd_free);
EXPORT_SYMBOL(kbd_alloc);
EXPORT_SYMBOL(kbd_keycode);
| gpl-2.0 |
Stuxnet-Kernel/kernel_mako | drivers/s390/char/keyboard.c | 7985 | 12529 | /*
* drivers/s390/char/keyboard.c
* ebcdic keycode functions for s390 console drivers
*
* S390 version
* Copyright (C) 2003 IBM Deutschland Entwicklung GmbH, IBM Corporation
* Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com),
*/
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/sysrq.h>
#include <linux/consolemap.h>
#include <linux/kbd_kern.h>
#include <linux/kbd_diacr.h>
#include <asm/uaccess.h>
#include "keyboard.h"
/*
* Handler Tables.
*/
#define K_HANDLERS\
k_self, k_fn, k_spec, k_ignore,\
k_dead, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore,\
k_ignore, k_ignore, k_ignore, k_ignore
typedef void (k_handler_fn)(struct kbd_data *, unsigned char);
static k_handler_fn K_HANDLERS;
static k_handler_fn *k_handler[16] = { K_HANDLERS };
/* maximum values each key_handler can handle */
static const int kbd_max_vals[] = {
255, ARRAY_SIZE(func_table) - 1, NR_FN_HANDLER - 1, 0,
NR_DEAD - 1, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
static const int KBD_NR_TYPES = ARRAY_SIZE(kbd_max_vals);
static unsigned char ret_diacr[NR_DEAD] = {
'`', '\'', '^', '~', '"', ','
};
/*
* Alloc/free of kbd_data structures.
*/
struct kbd_data *
kbd_alloc(void) {
struct kbd_data *kbd;
int i;
kbd = kzalloc(sizeof(struct kbd_data), GFP_KERNEL);
if (!kbd)
goto out;
kbd->key_maps = kzalloc(sizeof(key_maps), GFP_KERNEL);
if (!kbd->key_maps)
goto out_kbd;
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
if (key_maps[i]) {
kbd->key_maps[i] = kmemdup(key_maps[i],
sizeof(u_short) * NR_KEYS,
GFP_KERNEL);
if (!kbd->key_maps[i])
goto out_maps;
}
}
kbd->func_table = kzalloc(sizeof(func_table), GFP_KERNEL);
if (!kbd->func_table)
goto out_maps;
for (i = 0; i < ARRAY_SIZE(func_table); i++) {
if (func_table[i]) {
kbd->func_table[i] = kstrdup(func_table[i],
GFP_KERNEL);
if (!kbd->func_table[i])
goto out_func;
}
}
kbd->fn_handler =
kzalloc(sizeof(fn_handler_fn *) * NR_FN_HANDLER, GFP_KERNEL);
if (!kbd->fn_handler)
goto out_func;
kbd->accent_table = kmemdup(accent_table,
sizeof(struct kbdiacruc) * MAX_DIACR,
GFP_KERNEL);
if (!kbd->accent_table)
goto out_fn_handler;
kbd->accent_table_size = accent_table_size;
return kbd;
out_fn_handler:
kfree(kbd->fn_handler);
out_func:
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
out_maps:
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
out_kbd:
kfree(kbd);
out:
return NULL;
}
void
kbd_free(struct kbd_data *kbd)
{
int i;
kfree(kbd->accent_table);
kfree(kbd->fn_handler);
for (i = 0; i < ARRAY_SIZE(func_table); i++)
kfree(kbd->func_table[i]);
kfree(kbd->func_table);
for (i = 0; i < ARRAY_SIZE(key_maps); i++)
kfree(kbd->key_maps[i]);
kfree(kbd->key_maps);
kfree(kbd);
}
/*
* Generate ascii -> ebcdic translation table from kbd_data.
*/
void
kbd_ascebc(struct kbd_data *kbd, unsigned char *ascebc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ascebc, 0x40, 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
k = ((i & 1) << 7) + j;
keysym = keymap[j];
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ascebc[KVAL(keysym)] = k;
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ascebc[ret_diacr[KVAL(keysym)]] = k;
}
}
}
#if 0
/*
* Generate ebcdic -> ascii translation table from kbd_data.
*/
void
kbd_ebcasc(struct kbd_data *kbd, unsigned char *ebcasc)
{
unsigned short *keymap, keysym;
int i, j, k;
memset(ebcasc, ' ', 256);
for (i = 0; i < ARRAY_SIZE(key_maps); i++) {
keymap = kbd->key_maps[i];
if (!keymap)
continue;
for (j = 0; j < NR_KEYS; j++) {
keysym = keymap[j];
k = ((i & 1) << 7) + j;
if (KTYP(keysym) == (KT_LATIN | 0xf0) ||
KTYP(keysym) == (KT_LETTER | 0xf0))
ebcasc[k] = KVAL(keysym);
else if (KTYP(keysym) == (KT_DEAD | 0xf0))
ebcasc[k] = ret_diacr[KVAL(keysym)];
}
}
}
#endif
/*
* We have a combining character DIACR here, followed by the character CH.
* If the combination occurs in the table, return the corresponding value.
* Otherwise, if CH is a space or equals DIACR, return DIACR.
* Otherwise, conclude that DIACR was not combining after all,
* queue it and return CH.
*/
static unsigned int
handle_diacr(struct kbd_data *kbd, unsigned int ch)
{
int i, d;
d = kbd->diacr;
kbd->diacr = 0;
for (i = 0; i < kbd->accent_table_size; i++) {
if (kbd->accent_table[i].diacr == d &&
kbd->accent_table[i].base == ch)
return kbd->accent_table[i].result;
}
if (ch == ' ' || ch == d)
return d;
kbd_put_queue(kbd->tty, d);
return ch;
}
/*
* Handle dead key.
*/
static void
k_dead(struct kbd_data *kbd, unsigned char value)
{
value = ret_diacr[value];
kbd->diacr = (kbd->diacr ? handle_diacr(kbd, value) : value);
}
/*
* Normal character handler.
*/
static void
k_self(struct kbd_data *kbd, unsigned char value)
{
if (kbd->diacr)
value = handle_diacr(kbd, value);
kbd_put_queue(kbd->tty, value);
}
/*
* Special key handlers
*/
static void
k_ignore(struct kbd_data *kbd, unsigned char value)
{
}
/*
* Function key handler.
*/
static void
k_fn(struct kbd_data *kbd, unsigned char value)
{
if (kbd->func_table[value])
kbd_puts_queue(kbd->tty, kbd->func_table[value]);
}
static void
k_spec(struct kbd_data *kbd, unsigned char value)
{
if (value >= NR_FN_HANDLER)
return;
if (kbd->fn_handler[value])
kbd->fn_handler[value](kbd);
}
/*
* Put utf8 character to tty flip buffer.
* UTF-8 is defined for words of up to 31 bits,
* but we need only 16 bits here
*/
static void
to_utf8(struct tty_struct *tty, ushort c)
{
if (c < 0x80)
/* 0******* */
kbd_put_queue(tty, c);
else if (c < 0x800) {
/* 110***** 10****** */
kbd_put_queue(tty, 0xc0 | (c >> 6));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
} else {
/* 1110**** 10****** 10****** */
kbd_put_queue(tty, 0xe0 | (c >> 12));
kbd_put_queue(tty, 0x80 | ((c >> 6) & 0x3f));
kbd_put_queue(tty, 0x80 | (c & 0x3f));
}
}
/*
* Process keycode.
*/
void
kbd_keycode(struct kbd_data *kbd, unsigned int keycode)
{
unsigned short keysym;
unsigned char type, value;
if (!kbd || !kbd->tty)
return;
if (keycode >= 384)
keysym = kbd->key_maps[5][keycode - 384];
else if (keycode >= 256)
keysym = kbd->key_maps[4][keycode - 256];
else if (keycode >= 128)
keysym = kbd->key_maps[1][keycode - 128];
else
keysym = kbd->key_maps[0][keycode];
type = KTYP(keysym);
if (type >= 0xf0) {
type -= 0xf0;
if (type == KT_LETTER)
type = KT_LATIN;
value = KVAL(keysym);
#ifdef CONFIG_MAGIC_SYSRQ /* Handle the SysRq Hack */
if (kbd->sysrq) {
if (kbd->sysrq == K(KT_LATIN, '-')) {
kbd->sysrq = 0;
handle_sysrq(value);
return;
}
if (value == '-') {
kbd->sysrq = K(KT_LATIN, '-');
return;
}
/* Incomplete sysrq sequence. */
(*k_handler[KTYP(kbd->sysrq)])(kbd, KVAL(kbd->sysrq));
kbd->sysrq = 0;
} else if ((type == KT_LATIN && value == '^') ||
(type == KT_DEAD && ret_diacr[value] == '^')) {
kbd->sysrq = K(type, value);
return;
}
#endif
(*k_handler[type])(kbd, value);
} else
to_utf8(kbd->tty, keysym);
}
/*
* Ioctl stuff.
*/
static int
do_kdsk_ioctl(struct kbd_data *kbd, struct kbentry __user *user_kbe,
int cmd, int perm)
{
struct kbentry tmp;
ushort *key_map, val, ov;
if (copy_from_user(&tmp, user_kbe, sizeof(struct kbentry)))
return -EFAULT;
#if NR_KEYS < 256
if (tmp.kb_index >= NR_KEYS)
return -EINVAL;
#endif
#if MAX_NR_KEYMAPS < 256
if (tmp.kb_table >= MAX_NR_KEYMAPS)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBENT:
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
val = U(key_map[tmp.kb_index]);
if (KTYP(val) >= KBD_NR_TYPES)
val = K_HOLE;
} else
val = (tmp.kb_index ? K_HOLE : K_NOSUCHMAP);
return put_user(val, &user_kbe->kb_value);
case KDSKBENT:
if (!perm)
return -EPERM;
if (!tmp.kb_index && tmp.kb_value == K_NOSUCHMAP) {
/* disallocate map */
key_map = kbd->key_maps[tmp.kb_table];
if (key_map) {
kbd->key_maps[tmp.kb_table] = NULL;
kfree(key_map);
}
break;
}
if (KTYP(tmp.kb_value) >= KBD_NR_TYPES)
return -EINVAL;
if (KVAL(tmp.kb_value) > kbd_max_vals[KTYP(tmp.kb_value)])
return -EINVAL;
if (!(key_map = kbd->key_maps[tmp.kb_table])) {
int j;
key_map = kmalloc(sizeof(plain_map),
GFP_KERNEL);
if (!key_map)
return -ENOMEM;
kbd->key_maps[tmp.kb_table] = key_map;
for (j = 0; j < NR_KEYS; j++)
key_map[j] = U(K_HOLE);
}
ov = U(key_map[tmp.kb_index]);
if (tmp.kb_value == ov)
break; /* nothing to do */
/*
* Attention Key.
*/
if (((ov == K_SAK) || (tmp.kb_value == K_SAK)) &&
!capable(CAP_SYS_ADMIN))
return -EPERM;
key_map[tmp.kb_index] = U(tmp.kb_value);
break;
}
return 0;
}
static int
do_kdgkb_ioctl(struct kbd_data *kbd, struct kbsentry __user *u_kbs,
int cmd, int perm)
{
unsigned char kb_func;
char *p;
int len;
/* Get u_kbs->kb_func. */
if (get_user(kb_func, &u_kbs->kb_func))
return -EFAULT;
#if MAX_NR_FUNC < 256
if (kb_func >= MAX_NR_FUNC)
return -EINVAL;
#endif
switch (cmd) {
case KDGKBSENT:
p = kbd->func_table[kb_func];
if (p) {
len = strlen(p);
if (len >= sizeof(u_kbs->kb_string))
len = sizeof(u_kbs->kb_string) - 1;
if (copy_to_user(u_kbs->kb_string, p, len))
return -EFAULT;
} else
len = 0;
if (put_user('\0', u_kbs->kb_string + len))
return -EFAULT;
break;
case KDSKBSENT:
if (!perm)
return -EPERM;
len = strnlen_user(u_kbs->kb_string,
sizeof(u_kbs->kb_string) - 1);
if (!len)
return -EFAULT;
if (len > sizeof(u_kbs->kb_string) - 1)
return -EINVAL;
p = kmalloc(len + 1, GFP_KERNEL);
if (!p)
return -ENOMEM;
if (copy_from_user(p, u_kbs->kb_string, len)) {
kfree(p);
return -EFAULT;
}
p[len] = 0;
kfree(kbd->func_table[kb_func]);
kbd->func_table[kb_func] = p;
break;
}
return 0;
}
int kbd_ioctl(struct kbd_data *kbd, unsigned int cmd, unsigned long arg)
{
void __user *argp;
unsigned int ct;
int perm;
argp = (void __user *)arg;
/*
* To have permissions to do most of the vt ioctls, we either have
* to be the owner of the tty, or have CAP_SYS_TTY_CONFIG.
*/
perm = current->signal->tty == kbd->tty || capable(CAP_SYS_TTY_CONFIG);
switch (cmd) {
case KDGKBTYPE:
return put_user(KB_101, (char __user *)argp);
case KDGKBENT:
case KDSKBENT:
return do_kdsk_ioctl(kbd, argp, cmd, perm);
case KDGKBSENT:
case KDSKBSENT:
return do_kdgkb_ioctl(kbd, argp, cmd, perm);
case KDGKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (put_user(kbd->accent_table_size, &a->kb_cnt))
return -EFAULT;
for (i = 0; i < kbd->accent_table_size; i++) {
diacr.diacr = kbd->accent_table[i].diacr;
diacr.base = kbd->accent_table[i].base;
diacr.result = kbd->accent_table[i].result;
if (copy_to_user(a->kbdiacr + i, &diacr, sizeof(struct kbdiacr)))
return -EFAULT;
}
return 0;
}
case KDGKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
ct = kbd->accent_table_size;
if (put_user(ct, &a->kb_cnt))
return -EFAULT;
if (copy_to_user(a->kbdiacruc, kbd->accent_table,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
case KDSKBDIACR:
{
struct kbdiacrs __user *a = argp;
struct kbdiacr diacr;
int i;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
for (i = 0; i < ct; i++) {
if (copy_from_user(&diacr, a->kbdiacr + i, sizeof(struct kbdiacr)))
return -EFAULT;
kbd->accent_table[i].diacr = diacr.diacr;
kbd->accent_table[i].base = diacr.base;
kbd->accent_table[i].result = diacr.result;
}
return 0;
}
case KDSKBDIACRUC:
{
struct kbdiacrsuc __user *a = argp;
if (!perm)
return -EPERM;
if (get_user(ct, &a->kb_cnt))
return -EFAULT;
if (ct >= MAX_DIACR)
return -EINVAL;
kbd->accent_table_size = ct;
if (copy_from_user(kbd->accent_table, a->kbdiacruc,
ct * sizeof(struct kbdiacruc)))
return -EFAULT;
return 0;
}
default:
return -ENOIOCTLCMD;
}
}
EXPORT_SYMBOL(kbd_ioctl);
EXPORT_SYMBOL(kbd_ascebc);
EXPORT_SYMBOL(kbd_free);
EXPORT_SYMBOL(kbd_alloc);
EXPORT_SYMBOL(kbd_keycode);
| gpl-2.0 |
bju2000/lge-kernel-gproj | drivers/infiniband/hw/amso1100/c2_cm.c | 11569 | 10009 | /*
* Copyright (c) 2005 Ammasso, Inc. All rights reserved.
* Copyright (c) 2005 Open Grid Computing, Inc. All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* OpenIB.org BSD license below:
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
*
* - 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.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
#include <linux/slab.h>
#include "c2.h"
#include "c2_wr.h"
#include "c2_vq.h"
#include <rdma/iw_cm.h>
int c2_llp_connect(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
struct c2_dev *c2dev = to_c2dev(cm_id->device);
struct ib_qp *ibqp;
struct c2_qp *qp;
struct c2wr_qp_connect_req *wr; /* variable size needs a malloc. */
struct c2_vq_req *vq_req;
int err;
ibqp = c2_get_qp(cm_id->device, iw_param->qpn);
if (!ibqp)
return -EINVAL;
qp = to_c2qp(ibqp);
/* Associate QP <--> CM_ID */
cm_id->provider_data = qp;
cm_id->add_ref(cm_id);
qp->cm_id = cm_id;
/*
* only support the max private_data length
*/
if (iw_param->private_data_len > C2_MAX_PRIVATE_DATA_SIZE) {
err = -EINVAL;
goto bail0;
}
/*
* Set the rdma read limits
*/
err = c2_qp_set_read_limits(c2dev, qp, iw_param->ord, iw_param->ird);
if (err)
goto bail0;
/*
* Create and send a WR_QP_CONNECT...
*/
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail0;
}
vq_req = vq_req_alloc(c2dev);
if (!vq_req) {
err = -ENOMEM;
goto bail1;
}
c2_wr_set_id(wr, CCWR_QP_CONNECT);
wr->hdr.context = 0;
wr->rnic_handle = c2dev->adapter_handle;
wr->qp_handle = qp->adapter_handle;
wr->remote_addr = cm_id->remote_addr.sin_addr.s_addr;
wr->remote_port = cm_id->remote_addr.sin_port;
/*
* Move any private data from the callers's buf into
* the WR.
*/
if (iw_param->private_data) {
wr->private_data_length =
cpu_to_be32(iw_param->private_data_len);
memcpy(&wr->private_data[0], iw_param->private_data,
iw_param->private_data_len);
} else
wr->private_data_length = 0;
/*
* Send WR to adapter. NOTE: There is no synch reply from
* the adapter.
*/
err = vq_send_wr(c2dev, (union c2wr *) wr);
vq_req_free(c2dev, vq_req);
bail1:
kfree(wr);
bail0:
if (err) {
/*
* If we fail, release reference on QP and
* disassociate QP from CM_ID
*/
cm_id->provider_data = NULL;
qp->cm_id = NULL;
cm_id->rem_ref(cm_id);
}
return err;
}
int c2_llp_service_create(struct iw_cm_id *cm_id, int backlog)
{
struct c2_dev *c2dev;
struct c2wr_ep_listen_create_req wr;
struct c2wr_ep_listen_create_rep *reply;
struct c2_vq_req *vq_req;
int err;
c2dev = to_c2dev(cm_id->device);
if (c2dev == NULL)
return -EINVAL;
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_EP_LISTEN_CREATE);
wr.hdr.context = (u64) (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.local_addr = cm_id->local_addr.sin_addr.s_addr;
wr.local_port = cm_id->local_addr.sin_port;
wr.backlog = cpu_to_be32(backlog);
wr.user_context = (u64) (unsigned long) cm_id;
/*
* Reference the request struct. Dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply =
(struct c2wr_ep_listen_create_rep *) (unsigned long) vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail1;
}
if ((err = c2_errno(reply)) != 0)
goto bail1;
/*
* Keep the adapter handle. Used in subsequent destroy
*/
cm_id->provider_data = (void*)(unsigned long) reply->ep_handle;
/*
* free vq stuff
*/
vq_repbuf_free(c2dev, reply);
vq_req_free(c2dev, vq_req);
return 0;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
int c2_llp_service_destroy(struct iw_cm_id *cm_id)
{
struct c2_dev *c2dev;
struct c2wr_ep_listen_destroy_req wr;
struct c2wr_ep_listen_destroy_rep *reply;
struct c2_vq_req *vq_req;
int err;
c2dev = to_c2dev(cm_id->device);
if (c2dev == NULL)
return -EINVAL;
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_EP_LISTEN_DESTROY);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.ep_handle = (u32)(unsigned long)cm_id->provider_data;
/*
* reference the request struct. dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply=(struct c2wr_ep_listen_destroy_rep *)(unsigned long)vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
if ((err = c2_errno(reply)) != 0)
goto bail1;
bail1:
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
int c2_llp_accept(struct iw_cm_id *cm_id, struct iw_cm_conn_param *iw_param)
{
struct c2_dev *c2dev = to_c2dev(cm_id->device);
struct c2_qp *qp;
struct ib_qp *ibqp;
struct c2wr_cr_accept_req *wr; /* variable length WR */
struct c2_vq_req *vq_req;
struct c2wr_cr_accept_rep *reply; /* VQ Reply msg ptr. */
int err;
ibqp = c2_get_qp(cm_id->device, iw_param->qpn);
if (!ibqp)
return -EINVAL;
qp = to_c2qp(ibqp);
/* Set the RDMA read limits */
err = c2_qp_set_read_limits(c2dev, qp, iw_param->ord, iw_param->ird);
if (err)
goto bail0;
/* Allocate verbs request. */
vq_req = vq_req_alloc(c2dev);
if (!vq_req) {
err = -ENOMEM;
goto bail0;
}
vq_req->qp = qp;
vq_req->cm_id = cm_id;
vq_req->event = IW_CM_EVENT_ESTABLISHED;
wr = kmalloc(c2dev->req_vq.msg_size, GFP_KERNEL);
if (!wr) {
err = -ENOMEM;
goto bail1;
}
/* Build the WR */
c2_wr_set_id(wr, CCWR_CR_ACCEPT);
wr->hdr.context = (unsigned long) vq_req;
wr->rnic_handle = c2dev->adapter_handle;
wr->ep_handle = (u32) (unsigned long) cm_id->provider_data;
wr->qp_handle = qp->adapter_handle;
/* Replace the cr_handle with the QP after accept */
cm_id->provider_data = qp;
cm_id->add_ref(cm_id);
qp->cm_id = cm_id;
cm_id->provider_data = qp;
/* Validate private_data length */
if (iw_param->private_data_len > C2_MAX_PRIVATE_DATA_SIZE) {
err = -EINVAL;
goto bail1;
}
if (iw_param->private_data) {
wr->private_data_length = cpu_to_be32(iw_param->private_data_len);
memcpy(&wr->private_data[0],
iw_param->private_data, iw_param->private_data_len);
} else
wr->private_data_length = 0;
/* Reference the request struct. Dereferenced in the int handler. */
vq_req_get(c2dev, vq_req);
/* Send WR to adapter */
err = vq_send_wr(c2dev, (union c2wr *) wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail1;
}
/* Wait for reply from adapter */
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail1;
/* Check that reply is present */
reply = (struct c2wr_cr_accept_rep *) (unsigned long) vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail1;
}
err = c2_errno(reply);
vq_repbuf_free(c2dev, reply);
if (!err)
c2_set_qp_state(qp, C2_QP_STATE_RTS);
bail1:
kfree(wr);
vq_req_free(c2dev, vq_req);
bail0:
if (err) {
/*
* If we fail, release reference on QP and
* disassociate QP from CM_ID
*/
cm_id->provider_data = NULL;
qp->cm_id = NULL;
cm_id->rem_ref(cm_id);
}
return err;
}
int c2_llp_reject(struct iw_cm_id *cm_id, const void *pdata, u8 pdata_len)
{
struct c2_dev *c2dev;
struct c2wr_cr_reject_req wr;
struct c2_vq_req *vq_req;
struct c2wr_cr_reject_rep *reply;
int err;
c2dev = to_c2dev(cm_id->device);
/*
* Allocate verbs request.
*/
vq_req = vq_req_alloc(c2dev);
if (!vq_req)
return -ENOMEM;
/*
* Build the WR
*/
c2_wr_set_id(&wr, CCWR_CR_REJECT);
wr.hdr.context = (unsigned long) vq_req;
wr.rnic_handle = c2dev->adapter_handle;
wr.ep_handle = (u32) (unsigned long) cm_id->provider_data;
/*
* reference the request struct. dereferenced in the int handler.
*/
vq_req_get(c2dev, vq_req);
/*
* Send WR to adapter
*/
err = vq_send_wr(c2dev, (union c2wr *) & wr);
if (err) {
vq_req_put(c2dev, vq_req);
goto bail0;
}
/*
* Wait for reply from adapter
*/
err = vq_wait_for_reply(c2dev, vq_req);
if (err)
goto bail0;
/*
* Process reply
*/
reply = (struct c2wr_cr_reject_rep *) (unsigned long)
vq_req->reply_msg;
if (!reply) {
err = -ENOMEM;
goto bail0;
}
err = c2_errno(reply);
/*
* free vq stuff
*/
vq_repbuf_free(c2dev, reply);
bail0:
vq_req_free(c2dev, vq_req);
return err;
}
| gpl-2.0 |
Pesach85/PH85-KERNEL | arch/mips/txx9/jmr3927/setup.c | 12849 | 6221 | /*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``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.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Copyright 2001 MontaVista Software Inc.
* Author: MontaVista Software, Inc.
* ahennessy@mvista.com
*
* Copyright (C) 2000-2001 Toshiba Corporation
* Copyright (C) 2007 Ralf Baechle (ralf@linux-mips.org)
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <asm/reboot.h>
#include <asm/txx9pio.h>
#include <asm/txx9/generic.h>
#include <asm/txx9/pci.h>
#include <asm/txx9/jmr3927.h>
#include <asm/mipsregs.h>
static void jmr3927_machine_restart(char *command)
{
local_irq_disable();
#if 1 /* Resetting PCI bus */
jmr3927_ioc_reg_out(0, JMR3927_IOC_RESET_ADDR);
jmr3927_ioc_reg_out(JMR3927_IOC_RESET_PCI, JMR3927_IOC_RESET_ADDR);
(void)jmr3927_ioc_reg_in(JMR3927_IOC_RESET_ADDR); /* flush WB */
mdelay(1);
jmr3927_ioc_reg_out(0, JMR3927_IOC_RESET_ADDR);
#endif
jmr3927_ioc_reg_out(JMR3927_IOC_RESET_CPU, JMR3927_IOC_RESET_ADDR);
/* fallback */
(*_machine_halt)();
}
static void __init jmr3927_time_init(void)
{
tx3927_time_init(0, 1);
}
#define DO_WRITE_THROUGH
static void jmr3927_board_init(void);
static void __init jmr3927_mem_setup(void)
{
set_io_port_base(JMR3927_PORT_BASE + JMR3927_PCIIO);
_machine_restart = jmr3927_machine_restart;
/* cache setup */
{
unsigned int conf;
#ifdef DO_WRITE_THROUGH
int mips_config_cwfon = 0;
int mips_config_wbon = 0;
#else
int mips_config_cwfon = 1;
int mips_config_wbon = 1;
#endif
conf = read_c0_conf();
conf &= ~(TX39_CONF_WBON | TX39_CONF_CWFON);
conf |= mips_config_wbon ? TX39_CONF_WBON : 0;
conf |= mips_config_cwfon ? TX39_CONF_CWFON : 0;
write_c0_conf(conf);
write_c0_cache(0);
}
/* initialize board */
jmr3927_board_init();
tx3927_sio_init(0, 1 << 1); /* ch1: noCTS */
}
static void __init jmr3927_pci_setup(void)
{
#ifdef CONFIG_PCI
int extarb = !(tx3927_ccfgptr->ccfg & TX3927_CCFG_PCIXARB);
struct pci_controller *c;
c = txx9_alloc_pci_controller(&txx9_primary_pcic,
JMR3927_PCIMEM, JMR3927_PCIMEM_SIZE,
JMR3927_PCIIO, JMR3927_PCIIO_SIZE);
register_pci_controller(c);
if (!extarb) {
/* Reset PCI Bus */
jmr3927_ioc_reg_out(0, JMR3927_IOC_RESET_ADDR);
udelay(100);
jmr3927_ioc_reg_out(JMR3927_IOC_RESET_PCI,
JMR3927_IOC_RESET_ADDR);
udelay(100);
jmr3927_ioc_reg_out(0, JMR3927_IOC_RESET_ADDR);
}
tx3927_pcic_setup(c, JMR3927_SDRAM_SIZE, extarb);
tx3927_setup_pcierr_irq();
#endif /* CONFIG_PCI */
}
static void __init jmr3927_board_init(void)
{
txx9_cpu_clock = JMR3927_CORECLK;
/* SDRAMC are configured by PROM */
/* ROMC */
tx3927_romcptr->cr[1] = JMR3927_ROMCE1 | 0x00030048;
tx3927_romcptr->cr[2] = JMR3927_ROMCE2 | 0x000064c8;
tx3927_romcptr->cr[3] = JMR3927_ROMCE3 | 0x0003f698;
tx3927_romcptr->cr[5] = JMR3927_ROMCE5 | 0x0000f218;
/* Pin selection */
tx3927_ccfgptr->pcfg &= ~TX3927_PCFG_SELALL;
tx3927_ccfgptr->pcfg |=
TX3927_PCFG_SELSIOC(0) | TX3927_PCFG_SELSIO_ALL |
(TX3927_PCFG_SELDMA_ALL & ~TX3927_PCFG_SELDMA(1));
tx3927_setup();
/* PIO[15:12] connected to LEDs */
__raw_writel(0x0000f000, &tx3927_pioptr->dir);
gpio_request(11, "dipsw1");
gpio_request(10, "dipsw2");
jmr3927_pci_setup();
/* SIO0 DTR on */
jmr3927_ioc_reg_out(0, JMR3927_IOC_DTR_ADDR);
jmr3927_led_set(0);
printk(KERN_INFO
"JMR-TX3927 (Rev %d) --- IOC(Rev %d) DIPSW:%d,%d,%d,%d\n",
jmr3927_ioc_reg_in(JMR3927_IOC_BREV_ADDR) & JMR3927_REV_MASK,
jmr3927_ioc_reg_in(JMR3927_IOC_REV_ADDR) & JMR3927_REV_MASK,
jmr3927_dipsw1(), jmr3927_dipsw2(),
jmr3927_dipsw3(), jmr3927_dipsw4());
}
/* This trick makes rtc-ds1742 driver usable as is. */
static unsigned long jmr3927_swizzle_addr_b(unsigned long port)
{
if ((port & 0xffff0000) != JMR3927_IOC_NVRAMB_ADDR)
return port;
port = (port & 0xffff0000) | (port & 0x7fff << 1);
#ifdef __BIG_ENDIAN
return port;
#else
return port | 1;
#endif
}
static void __init jmr3927_rtc_init(void)
{
static struct resource __initdata res = {
.start = JMR3927_IOC_NVRAMB_ADDR - IO_BASE,
.end = JMR3927_IOC_NVRAMB_ADDR - IO_BASE + 0x800 - 1,
.flags = IORESOURCE_MEM,
};
platform_device_register_simple("rtc-ds1742", -1, &res, 1);
}
static void __init jmr3927_mtd_init(void)
{
int i;
for (i = 0; i < 2; i++)
tx3927_mtd_init(i);
}
static void __init jmr3927_device_init(void)
{
unsigned long iocled_base = JMR3927_IOC_LED_ADDR - IO_BASE;
#ifdef __LITTLE_ENDIAN
iocled_base |= 1;
#endif
__swizzle_addr_b = jmr3927_swizzle_addr_b;
jmr3927_rtc_init();
tx3927_wdt_init();
jmr3927_mtd_init();
txx9_iocled_init(iocled_base, -1, 8, 1, "green", NULL);
}
struct txx9_board_vec jmr3927_vec __initdata = {
.system = "Toshiba JMR_TX3927",
.prom_init = jmr3927_prom_init,
.mem_setup = jmr3927_mem_setup,
.irq_setup = jmr3927_irq_setup,
.time_init = jmr3927_time_init,
.device_init = jmr3927_device_init,
#ifdef CONFIG_PCI
.pci_map_irq = jmr3927_pci_map_irq,
#endif
};
| gpl-2.0 |
virtuous/kernel-7x30-gingerbread-v3 | arch/arm/mach-msm/smd_qmi.c | 50 | 19001 | /* arch/arm/mach-msm/smd_qmi.c
*
* QMI Control Driver -- Manages network data connections.
*
* Copyright (C) 2007 Google, Inc.
* Author: Brian Swetland <swetland@google.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/miscdevice.h>
#include <linux/workqueue.h>
#include <linux/wakelock.h>
#include <asm/uaccess.h>
#include <mach/msm_smd.h>
#define QMI_CTL 0x00
#define QMI_WDS 0x01
#define QMI_DMS 0x02
#define QMI_NAS 0x03
#define QMI_RESULT_SUCCESS 0x0000
#define QMI_RESULT_FAILURE 0x0001
struct qmi_msg {
unsigned char service;
unsigned char client_id;
unsigned short txn_id;
unsigned short type;
unsigned short size;
unsigned char *tlv;
};
#define qmi_ctl_client_id 0
#define STATE_OFFLINE 0
#define STATE_QUERYING 1
#define STATE_ONLINE 2
struct qmi_ctxt {
struct miscdevice misc;
struct mutex lock;
unsigned char ctl_txn_id;
unsigned char wds_client_id;
unsigned short wds_txn_id;
unsigned wds_busy;
unsigned wds_handle;
unsigned state_dirty;
unsigned state;
unsigned char addr[4];
unsigned char mask[4];
unsigned char gateway[4];
unsigned char dns1[4];
unsigned char dns2[4];
smd_channel_t *ch;
const char *ch_name;
struct wake_lock wake_lock;
struct work_struct open_work;
struct work_struct read_work;
};
static struct qmi_ctxt *qmi_minor_to_ctxt(unsigned n);
static void qmi_read_work(struct work_struct *ws);
static void qmi_open_work(struct work_struct *work);
void qmi_ctxt_init(struct qmi_ctxt *ctxt, unsigned n)
{
mutex_init(&ctxt->lock);
INIT_WORK(&ctxt->read_work, qmi_read_work);
INIT_WORK(&ctxt->open_work, qmi_open_work);
wake_lock_init(&ctxt->wake_lock, WAKE_LOCK_SUSPEND, ctxt->misc.name);
ctxt->ctl_txn_id = 1;
ctxt->wds_txn_id = 1;
ctxt->wds_busy = 1;
ctxt->state = STATE_OFFLINE;
}
static struct workqueue_struct *qmi_wq;
static int verbose = 0;
/* anyone waiting for a state change waits here */
static DECLARE_WAIT_QUEUE_HEAD(qmi_wait_queue);
static void qmi_dump_msg(struct qmi_msg *msg, const char *prefix)
{
unsigned sz, n;
unsigned char *x;
if (!verbose)
return;
printk(KERN_INFO
"qmi: %s: svc=%02x cid=%02x tid=%04x type=%04x size=%04x\n",
prefix, msg->service, msg->client_id,
msg->txn_id, msg->type, msg->size);
x = msg->tlv;
sz = msg->size;
while (sz >= 3) {
sz -= 3;
n = x[1] | (x[2] << 8);
if (n > sz)
break;
printk(KERN_INFO "qmi: %s: tlv: %02x %04x { ",
prefix, x[0], n);
x += 3;
sz -= n;
while (n-- > 0)
printk("%02x ", *x++);
printk("}\n");
}
}
int qmi_add_tlv(struct qmi_msg *msg,
unsigned type, unsigned size, const void *data)
{
unsigned char *x = msg->tlv + msg->size;
x[0] = type;
x[1] = size;
x[2] = size >> 8;
memcpy(x + 3, data, size);
msg->size += (size + 3);
return 0;
}
/* Extract a tagged item from a qmi message buffer,
** taking care not to overrun the buffer.
*/
static int qmi_get_tlv(struct qmi_msg *msg,
unsigned type, unsigned size, void *data)
{
unsigned char *x = msg->tlv;
unsigned len = msg->size;
unsigned n;
while (len >= 3) {
len -= 3;
/* size of this item */
n = x[1] | (x[2] << 8);
if (n > len)
break;
if (x[0] == type) {
if (n != size)
return -1;
memcpy(data, x + 3, size);
return 0;
}
x += (n + 3);
len -= n;
}
return -1;
}
static unsigned qmi_get_status(struct qmi_msg *msg, unsigned *error)
{
unsigned short status[2];
if (qmi_get_tlv(msg, 0x02, sizeof(status), status)) {
*error = 0;
return QMI_RESULT_FAILURE;
} else {
*error = status[1];
return status[0];
}
}
/* 0x01 <qmux-header> <payload> */
#define QMUX_HEADER 13
/* should be >= HEADER + FOOTER */
#define QMUX_OVERHEAD 16
static int qmi_send(struct qmi_ctxt *ctxt, struct qmi_msg *msg)
{
unsigned char *data;
unsigned hlen;
unsigned len;
int r;
qmi_dump_msg(msg, "send");
if (msg->service == QMI_CTL) {
hlen = QMUX_HEADER - 1;
} else {
hlen = QMUX_HEADER;
}
/* QMUX length is total header + total payload - IFC selector */
len = hlen + msg->size - 1;
if (len > 0xffff)
return -1;
data = msg->tlv - hlen;
/* prepend encap and qmux header */
*data++ = 0x01; /* ifc selector */
/* qmux header */
*data++ = len;
*data++ = len >> 8;
*data++ = 0x00; /* flags: client */
*data++ = msg->service;
*data++ = msg->client_id;
/* qmi header */
*data++ = 0x00; /* flags: send */
*data++ = msg->txn_id;
if (msg->service != QMI_CTL)
*data++ = msg->txn_id >> 8;
*data++ = msg->type;
*data++ = msg->type >> 8;
*data++ = msg->size;
*data++ = msg->size >> 8;
/* len + 1 takes the interface selector into account */
r = smd_write(ctxt->ch, msg->tlv - hlen, len + 1);
if (r != len) {
return -1;
} else {
return 0;
}
}
static void qmi_process_ctl_msg(struct qmi_ctxt *ctxt, struct qmi_msg *msg)
{
unsigned err;
if (msg->type == 0x0022) {
unsigned char n[2];
if (qmi_get_status(msg, &err))
return;
if (qmi_get_tlv(msg, 0x01, sizeof(n), n))
return;
if (n[0] == QMI_WDS) {
printk(KERN_INFO
"qmi: ctl: wds use client_id 0x%02x\n", n[1]);
ctxt->wds_client_id = n[1];
ctxt->wds_busy = 0;
}
}
}
static int qmi_network_get_profile(struct qmi_ctxt *ctxt);
static void swapaddr(unsigned char *src, unsigned char *dst)
{
dst[0] = src[3];
dst[1] = src[2];
dst[2] = src[1];
dst[3] = src[0];
}
static unsigned char zero[4];
static void qmi_read_runtime_profile(struct qmi_ctxt *ctxt, struct qmi_msg *msg)
{
unsigned char tmp[4];
unsigned r;
r = qmi_get_tlv(msg, 0x1e, 4, tmp);
swapaddr(r ? zero : tmp, ctxt->addr);
r = qmi_get_tlv(msg, 0x21, 4, tmp);
swapaddr(r ? zero : tmp, ctxt->mask);
r = qmi_get_tlv(msg, 0x20, 4, tmp);
swapaddr(r ? zero : tmp, ctxt->gateway);
r = qmi_get_tlv(msg, 0x15, 4, tmp);
swapaddr(r ? zero : tmp, ctxt->dns1);
r = qmi_get_tlv(msg, 0x16, 4, tmp);
swapaddr(r ? zero : tmp, ctxt->dns2);
}
static void qmi_process_unicast_wds_msg(struct qmi_ctxt *ctxt,
struct qmi_msg *msg)
{
unsigned err;
switch (msg->type) {
case 0x0021:
if (qmi_get_status(msg, &err)) {
printk(KERN_ERR
"qmi: wds: network stop failed (%04x)\n", err);
} else {
printk(KERN_INFO
"qmi: wds: network stopped\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
}
break;
case 0x0020:
if (qmi_get_status(msg, &err)) {
printk(KERN_INFO
"qmi: wds: network start failed (%04x)\n", err);
//++Make pdp state always be sent to QMI channel when activating PDP context fails
printk(KERN_INFO
"qmi: wds: Make pdp state always be sent to QMI channel when activating PDP context fails .\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
//--Make pdp state always be sent to QMI channel when activating PDP context fails
if (msg->size == 0x000c && (msg->tlv)[10] == 0x0b) {
printk(KERN_ERR
"qmi: wds: pdp activation collided with CCFC\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
}
if (msg->size == 0x000c && (msg->tlv)[10] == 0x0c) {
printk(KERN_ERR
"qmi: wds: pdp activation failed. Cause: Operator-determined barring\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
}
} else if (qmi_get_tlv(msg, 0x01, sizeof(ctxt->wds_handle), &ctxt->wds_handle)) {
printk(KERN_INFO
"qmi: wds no handle?\n");
} else {
printk(KERN_INFO
"qmi: wds: got handle 0x%08x\n",
ctxt->wds_handle);
}
break;
case 0x002D:
printk("qmi: got network profile\n");
if (ctxt->state == STATE_QUERYING) {
qmi_read_runtime_profile(ctxt, msg);
ctxt->state = STATE_ONLINE;
ctxt->state_dirty = 1;
}
break;
default:
printk(KERN_ERR "qmi: unknown msg type 0x%04x\n", msg->type);
}
ctxt->wds_busy = 0;
}
static void qmi_process_broadcast_wds_msg(struct qmi_ctxt *ctxt,
struct qmi_msg *msg)
{
if (msg->type == 0x0022) {
unsigned char n[2];
if (qmi_get_tlv(msg, 0x01, sizeof(n), n))
return;
switch (n[0]) {
case 1:
printk(KERN_INFO "qmi: wds: DISCONNECTED\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
break;
case 2:
printk(KERN_INFO "qmi: wds: CONNECTED\n");
ctxt->state = STATE_QUERYING;
ctxt->state_dirty = 1;
qmi_network_get_profile(ctxt);
break;
case 3:
printk(KERN_INFO "qmi: wds: SUSPENDED\n");
ctxt->state = STATE_OFFLINE;
ctxt->state_dirty = 1;
}
} else {
printk(KERN_ERR "qmi: unknown bcast msg type 0x%04x\n", msg->type);
}
}
static void qmi_process_wds_msg(struct qmi_ctxt *ctxt,
struct qmi_msg *msg)
{
printk("wds: %04x @ %02x\n", msg->type, msg->client_id);
if (msg->client_id == ctxt->wds_client_id) {
qmi_process_unicast_wds_msg(ctxt, msg);
} else if (msg->client_id == 0xff) {
qmi_process_broadcast_wds_msg(ctxt, msg);
} else {
printk(KERN_ERR
"qmi_process_wds_msg client id 0x%02x unknown\n",
msg->client_id);
}
}
static void qmi_process_qmux(struct qmi_ctxt *ctxt,
unsigned char *buf, unsigned sz)
{
struct qmi_msg msg;
/* require a full header */
if (sz < 5)
return;
/* require a size that matches the buffer size */
if (sz != (buf[0] | (buf[1] << 8)))
return;
/* only messages from a service (bit7=1) are allowed */
if (buf[2] != 0x80)
return;
msg.service = buf[3];
msg.client_id = buf[4];
/* annoyingly, CTL messages have a shorter TID */
if (buf[3] == 0) {
if (sz < 7)
return;
msg.txn_id = buf[6];
buf += 7;
sz -= 7;
} else {
if (sz < 8)
return;
msg.txn_id = buf[6] | (buf[7] << 8);
buf += 8;
sz -= 8;
}
/* no type and size!? */
if (sz < 4)
return;
sz -= 4;
msg.type = buf[0] | (buf[1] << 8);
msg.size = buf[2] | (buf[3] << 8);
msg.tlv = buf + 4;
if (sz != msg.size)
return;
qmi_dump_msg(&msg, "recv");
mutex_lock(&ctxt->lock);
switch (msg.service) {
case QMI_CTL:
qmi_process_ctl_msg(ctxt, &msg);
break;
case QMI_WDS:
qmi_process_wds_msg(ctxt, &msg);
break;
default:
printk(KERN_ERR "qmi: msg from unknown svc 0x%02x\n",
msg.service);
break;
}
mutex_unlock(&ctxt->lock);
wake_up(&qmi_wait_queue);
}
#define QMI_MAX_PACKET (256 + QMUX_OVERHEAD)
static void qmi_read_work(struct work_struct *ws)
{
struct qmi_ctxt *ctxt = container_of(ws, struct qmi_ctxt, read_work);
struct smd_channel *ch = ctxt->ch;
unsigned char buf[QMI_MAX_PACKET];
int sz;
for (;;) {
sz = smd_cur_packet_size(ch);
if (sz == 0)
break;
if (sz < smd_read_avail(ch))
break;
if (sz > QMI_MAX_PACKET) {
smd_read(ch, 0, sz);
continue;
}
if (smd_read(ch, buf, sz) != sz) {
printk(KERN_ERR "qmi: not enough data?!\n");
continue;
}
/* interface selector must be 1 */
if (buf[0] != 0x01)
continue;
qmi_process_qmux(ctxt, buf + 1, sz - 1);
}
}
static int qmi_request_wds_cid(struct qmi_ctxt *ctxt);
static void qmi_open_work(struct work_struct *ws)
{
struct qmi_ctxt *ctxt = container_of(ws, struct qmi_ctxt, open_work);
mutex_lock(&ctxt->lock);
qmi_request_wds_cid(ctxt);
mutex_unlock(&ctxt->lock);
}
static void qmi_notify(void *priv, unsigned event)
{
struct qmi_ctxt *ctxt = priv;
switch (event) {
case SMD_EVENT_DATA: {
int sz;
sz = smd_cur_packet_size(ctxt->ch);
if ((sz > 0) && (sz <= smd_read_avail(ctxt->ch))) {
wake_lock_timeout(&ctxt->wake_lock, HZ / 2);
queue_work(qmi_wq, &ctxt->read_work);
}
break;
}
case SMD_EVENT_OPEN:
printk(KERN_INFO "qmi: smd opened\n");
queue_work(qmi_wq, &ctxt->open_work);
break;
case SMD_EVENT_CLOSE:
printk(KERN_INFO "qmi: smd closed\n");
break;
}
}
static int qmi_request_wds_cid(struct qmi_ctxt *ctxt)
{
unsigned char data[64 + QMUX_OVERHEAD];
struct qmi_msg msg;
unsigned char n;
msg.service = QMI_CTL;
msg.client_id = qmi_ctl_client_id;
msg.txn_id = ctxt->ctl_txn_id;
msg.type = 0x0022;
msg.size = 0;
msg.tlv = data + QMUX_HEADER;
ctxt->ctl_txn_id += 2;
n = QMI_WDS;
qmi_add_tlv(&msg, 0x01, 0x01, &n);
return qmi_send(ctxt, &msg);
}
static int qmi_network_get_profile(struct qmi_ctxt *ctxt)
{
unsigned char data[96 + QMUX_OVERHEAD];
struct qmi_msg msg;
msg.service = QMI_WDS;
msg.client_id = ctxt->wds_client_id;
msg.txn_id = ctxt->wds_txn_id;
msg.type = 0x002D;
msg.size = 0;
msg.tlv = data + QMUX_HEADER;
ctxt->wds_txn_id += 2;
return qmi_send(ctxt, &msg);
}
static int qmi_network_up(struct qmi_ctxt *ctxt, char *apn)
{
unsigned char data[96 + QMUX_OVERHEAD];
struct qmi_msg msg;
char *auth_type;
char *user;
char *pass;
for (user = apn; *user; user++) {
if (*user == ' ') {
*user++ = 0;
break;
}
}
for (pass = user; *pass; pass++) {
if (*pass == ' ') {
*pass++ = 0;
break;
}
}
for (auth_type = pass; *auth_type; auth_type++) {
if (*auth_type == ' ') {
*auth_type++ = 0;
break;
}
}
msg.service = QMI_WDS;
msg.client_id = ctxt->wds_client_id;
msg.txn_id = ctxt->wds_txn_id;
msg.type = 0x0020;
msg.size = 0;
msg.tlv = data + QMUX_HEADER;
ctxt->wds_txn_id += 2;
qmi_add_tlv(&msg, 0x14, strlen(apn), apn);
if (*auth_type)
qmi_add_tlv(&msg, 0x16, strlen(auth_type), auth_type);
if (*user) {
if (!*auth_type) {
unsigned char x;
x = 3;
qmi_add_tlv(&msg, 0x16, 1, &x);
}
qmi_add_tlv(&msg, 0x17, strlen(user), user);
if (*pass)
qmi_add_tlv(&msg, 0x18, strlen(pass), pass);
}
return qmi_send(ctxt, &msg);
}
static int qmi_network_down(struct qmi_ctxt *ctxt)
{
unsigned char data[16 + QMUX_OVERHEAD];
struct qmi_msg msg;
msg.service = QMI_WDS;
msg.client_id = ctxt->wds_client_id;
msg.txn_id = ctxt->wds_txn_id;
msg.type = 0x0021;
msg.size = 0;
msg.tlv = data + QMUX_HEADER;
ctxt->wds_txn_id += 2;
qmi_add_tlv(&msg, 0x01, sizeof(ctxt->wds_handle), &ctxt->wds_handle);
return qmi_send(ctxt, &msg);
}
static int qmi_print_state(struct qmi_ctxt *ctxt, char *buf, int max)
{
int i;
char *statename;
if (ctxt->state == STATE_ONLINE) {
statename = "up";
} else if (ctxt->state == STATE_OFFLINE) {
statename = "down";
} else {
statename = "busy";
}
i = scnprintf(buf, max, "STATE=%s\n", statename);
i += scnprintf(buf + i, max - i, "CID=%d\n",ctxt->misc.minor);
if (ctxt->state != STATE_ONLINE){
return i;
}
i += scnprintf(buf + i, max - i, "ADDR=%d.%d.%d.%d\n",
ctxt->addr[0], ctxt->addr[1], ctxt->addr[2], ctxt->addr[3]);
i += scnprintf(buf + i, max - i, "MASK=%d.%d.%d.%d\n",
ctxt->mask[0], ctxt->mask[1], ctxt->mask[2], ctxt->mask[3]);
i += scnprintf(buf + i, max - i, "GATEWAY=%d.%d.%d.%d\n",
ctxt->gateway[0], ctxt->gateway[1], ctxt->gateway[2],
ctxt->gateway[3]);
i += scnprintf(buf + i, max - i, "DNS1=%d.%d.%d.%d\n",
ctxt->dns1[0], ctxt->dns1[1], ctxt->dns1[2], ctxt->dns1[3]);
i += scnprintf(buf + i, max - i, "DNS2=%d.%d.%d.%d\n",
ctxt->dns2[0], ctxt->dns2[1], ctxt->dns2[2], ctxt->dns2[3]);
return i;
}
static ssize_t qmi_read(struct file *fp, char __user *buf,
size_t count, loff_t *pos)
{
struct qmi_ctxt *ctxt = fp->private_data;
char msg[256];
int len;
int r;
mutex_lock(&ctxt->lock);
for (;;) {
if (ctxt->state_dirty) {
ctxt->state_dirty = 0;
len = qmi_print_state(ctxt, msg, 256);
break;
}
mutex_unlock(&ctxt->lock);
r = wait_event_interruptible(qmi_wait_queue, ctxt->state_dirty);
if (r < 0)
return r;
mutex_lock(&ctxt->lock);
}
mutex_unlock(&ctxt->lock);
if (len > count)
len = count;
if (copy_to_user(buf, msg, len))
return -EFAULT;
return len;
}
static ssize_t qmi_write(struct file *fp, const char __user *buf,
size_t count, loff_t *pos)
{
struct qmi_ctxt *ctxt = fp->private_data;
unsigned char cmd[64];
int len;
int r;
if (count < 1)
return 0;
len = count > 63 ? 63 : count;
if (copy_from_user(cmd, buf, len))
return -EFAULT;
cmd[len] = 0;
/* lazy */
if (cmd[len-1] == '\n') {
cmd[len-1] = 0;
len--;
}
if (!strncmp(cmd, "verbose", 7)) {
verbose = 1;
} else if (!strncmp(cmd, "terse", 5)) {
verbose = 0;
} else if (!strncmp(cmd, "poll", 4)) {
ctxt->state_dirty = 1;
wake_up(&qmi_wait_queue);
} else if (!strncmp(cmd, "down", 4)) {
retry_down:
mutex_lock(&ctxt->lock);
if (ctxt->wds_busy) {
mutex_unlock(&ctxt->lock);
r = wait_event_interruptible(qmi_wait_queue, !ctxt->wds_busy);
if (r < 0)
return r;
goto retry_down;
}
ctxt->wds_busy = 1;
qmi_network_down(ctxt);
mutex_unlock(&ctxt->lock);
} else if (!strncmp(cmd, "up:", 3)) {
retry_up:
mutex_lock(&ctxt->lock);
if (ctxt->wds_busy) {
mutex_unlock(&ctxt->lock);
r = wait_event_interruptible(qmi_wait_queue, !ctxt->wds_busy);
if (r < 0)
return r;
goto retry_up;
}
ctxt->wds_busy = 1;
qmi_network_up(ctxt, cmd+3);
mutex_unlock(&ctxt->lock);
} else {
return -EINVAL;
}
return count;
}
static int qmi_open(struct inode *ip, struct file *fp)
{
struct qmi_ctxt *ctxt = qmi_minor_to_ctxt(MINOR(ip->i_rdev));
int r = 0;
if (!ctxt) {
printk(KERN_ERR "unknown qmi misc %d\n", MINOR(ip->i_rdev));
return -ENODEV;
}
fp->private_data = ctxt;
mutex_lock(&ctxt->lock);
if (ctxt->ch == 0)
r = smd_open(ctxt->ch_name, &ctxt->ch, ctxt, qmi_notify);
if (r == 0)
wake_up(&qmi_wait_queue);
mutex_unlock(&ctxt->lock);
return r;
}
static int qmi_release(struct inode *ip, struct file *fp)
{
return 0;
}
static struct file_operations qmi_fops = {
.owner = THIS_MODULE,
.read = qmi_read,
.write = qmi_write,
.open = qmi_open,
.release = qmi_release,
};
static struct qmi_ctxt qmi_device0 = {
.ch_name = "SMD_DATA5_CNTL",
.misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "qmi0",
.fops = &qmi_fops,
}
};
static struct qmi_ctxt qmi_device1 = {
.ch_name = "SMD_DATA6_CNTL",
.misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "qmi1",
.fops = &qmi_fops,
}
};
static struct qmi_ctxt qmi_device2 = {
.ch_name = "SMD_DATA7_CNTL",
.misc = {
.minor = MISC_DYNAMIC_MINOR,
.name = "qmi2",
.fops = &qmi_fops,
}
};
static struct qmi_ctxt *qmi_minor_to_ctxt(unsigned n)
{
if (n == qmi_device0.misc.minor)
return &qmi_device0;
if (n == qmi_device1.misc.minor)
return &qmi_device1;
if (n == qmi_device2.misc.minor)
return &qmi_device2;
return 0;
}
static int __init qmi_init(void)
{
int ret;
qmi_wq = create_singlethread_workqueue("qmi");
if (qmi_wq == 0)
return -ENOMEM;
qmi_ctxt_init(&qmi_device0, 0);
qmi_ctxt_init(&qmi_device1, 1);
qmi_ctxt_init(&qmi_device2, 2);
ret = misc_register(&qmi_device0.misc);
if (ret == 0)
ret = misc_register(&qmi_device1.misc);
if (ret == 0)
ret = misc_register(&qmi_device2.misc);
return ret;
}
module_init(qmi_init);
| gpl-2.0 |
ivanmeler/android_kernel_samsung_smdk4412 | security/selinux/selinuxfs.c | 50 | 45339 | /* Updated: Karl MacMillan <kmacmillan@tresys.com>
*
* Added conditional policy language extensions
*
* Updated: Hewlett-Packard <paul.moore@hp.com>
*
* Added support for the policy capability bitmap
*
* Copyright (C) 2007 Hewlett-Packard Development Company, L.P.
* Copyright (C) 2003 - 2004 Tresys Technology, LLC
* Copyright (C) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 2.
*/
#include <linux/kernel.h>
#include <linux/pagemap.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/fs.h>
#include <linux/mutex.h>
#include <linux/init.h>
#include <linux/string.h>
#include <linux/security.h>
#include <linux/major.h>
#include <linux/seq_file.h>
#include <linux/percpu.h>
#include <linux/audit.h>
#include <linux/uaccess.h>
#include <linux/kobject.h>
#include <linux/ctype.h>
/* selinuxfs pseudo filesystem for exporting the security policy API.
Based on the proc code and the fs/nfsd/nfsctl.c code. */
#include "flask.h"
#include "avc.h"
#include "avc_ss.h"
#include "security.h"
#include "objsec.h"
#include "conditional.h"
/* Policy capability filenames */
static char *policycap_names[] = {
"network_peer_controls",
"open_perms"
};
unsigned int selinux_checkreqprot = CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
static int __init checkreqprot_setup(char *str)
{
unsigned long checkreqprot;
if (!strict_strtoul(str, 0, &checkreqprot))
selinux_checkreqprot = checkreqprot ? 1 : 0;
return 1;
}
__setup("checkreqprot=", checkreqprot_setup);
static DEFINE_MUTEX(sel_mutex);
/* global data for booleans */
static struct dentry *bool_dir;
static int bool_num;
static char **bool_pending_names;
static int *bool_pending_values;
/* global data for classes */
static struct dentry *class_dir;
static unsigned long last_class_ino;
static char policy_opened;
/* global data for policy capabilities */
static struct dentry *policycap_dir;
extern void selnl_notify_setenforce(int val);
/* Check whether a task is allowed to use a security operation. */
static int task_has_security(struct task_struct *tsk,
u32 perms)
{
const struct task_security_struct *tsec;
u32 sid = 0;
rcu_read_lock();
tsec = __task_cred(tsk)->security;
if (tsec)
sid = tsec->sid;
rcu_read_unlock();
if (!tsec)
return -EACCES;
return avc_has_perm(sid, SECINITSID_SECURITY,
SECCLASS_SECURITY, perms, NULL);
}
enum sel_inos {
SEL_ROOT_INO = 2,
SEL_LOAD, /* load policy */
SEL_ENFORCE, /* get or set enforcing status */
SEL_CONTEXT, /* validate context */
SEL_ACCESS, /* compute access decision */
SEL_CREATE, /* compute create labeling decision */
SEL_RELABEL, /* compute relabeling decision */
SEL_USER, /* compute reachable user contexts */
SEL_POLICYVERS, /* return policy version for this kernel */
SEL_COMMIT_BOOLS, /* commit new boolean values */
SEL_MLS, /* return if MLS policy is enabled */
SEL_DISABLE, /* disable SELinux until next reboot */
SEL_MEMBER, /* compute polyinstantiation membership decision */
SEL_CHECKREQPROT, /* check requested protection, not kernel-applied one */
SEL_COMPAT_NET, /* whether to use old compat network packet controls */
SEL_REJECT_UNKNOWN, /* export unknown reject handling to userspace */
SEL_DENY_UNKNOWN, /* export unknown deny handling to userspace */
SEL_STATUS, /* export current status using mmap() */
SEL_POLICY, /* allow userspace to read the in kernel policy */
SEL_INO_NEXT, /* The next inode number to use */
};
static unsigned long sel_last_ino = SEL_INO_NEXT - 1;
#define SEL_INITCON_INO_OFFSET 0x01000000
#define SEL_BOOL_INO_OFFSET 0x02000000
#define SEL_CLASS_INO_OFFSET 0x04000000
#define SEL_POLICYCAP_INO_OFFSET 0x08000000
#define SEL_INO_MASK 0x00ffffff
#define TMPBUFLEN 12
static ssize_t sel_read_enforce(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
length = scnprintf(tmpbuf, TMPBUFLEN, "%d", selinux_enforcing);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
#ifdef CONFIG_SECURITY_SELINUX_DEVELOP
static ssize_t sel_write_enforce(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
int new_value;
length = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
length = EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
length = -EINVAL;
if (sscanf(page, "%d", &new_value) != 1)
goto out;
#ifdef CONFIG_ALWAYS_ENFORCE
// If build is user build and enforce option is set, selinux is always enforcing
new_value = 1;
length = task_has_security(current, SECURITY__SETENFORCE);
audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_STATUS,
"config_always_enforce - true; enforcing=%d old_enforcing=%d auid=%u ses=%u",
new_value, selinux_enforcing,
audit_get_loginuid(current),
audit_get_sessionid(current));
selinux_enforcing = new_value;
avc_ss_reset(0);
selnl_notify_setenforce(new_value);
selinux_status_update_setenforce(new_value);
#else
if (new_value != selinux_enforcing) {
length = task_has_security(current, SECURITY__SETENFORCE);
if (length)
goto out;
audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_STATUS,
"enforcing=%d old_enforcing=%d auid=%u ses=%u",
new_value, selinux_enforcing,
audit_get_loginuid(current),
audit_get_sessionid(current));
selinux_enforcing = new_value;
if (selinux_enforcing)
avc_ss_reset(0);
selnl_notify_setenforce(selinux_enforcing);
selinux_status_update_setenforce(selinux_enforcing);
}
#endif
length = count;
out:
free_page((unsigned long) page);
return length;
}
#else
#define sel_write_enforce NULL
#endif
static const struct file_operations sel_enforce_ops = {
.read = sel_read_enforce,
.write = sel_write_enforce,
.llseek = generic_file_llseek,
};
static ssize_t sel_read_handle_unknown(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
ino_t ino = filp->f_path.dentry->d_inode->i_ino;
int handle_unknown = (ino == SEL_REJECT_UNKNOWN) ?
security_get_reject_unknown() : !security_get_allow_unknown();
length = scnprintf(tmpbuf, TMPBUFLEN, "%d", handle_unknown);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations sel_handle_unknown_ops = {
.read = sel_read_handle_unknown,
.llseek = generic_file_llseek,
};
static int sel_open_handle_status(struct inode *inode, struct file *filp)
{
struct page *status = selinux_kernel_status_page();
if (!status)
return -ENOMEM;
filp->private_data = status;
return 0;
}
static ssize_t sel_read_handle_status(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
struct page *status = filp->private_data;
BUG_ON(!status);
return simple_read_from_buffer(buf, count, ppos,
page_address(status),
sizeof(struct selinux_kernel_status));
}
static int sel_mmap_handle_status(struct file *filp,
struct vm_area_struct *vma)
{
struct page *status = filp->private_data;
unsigned long size = vma->vm_end - vma->vm_start;
BUG_ON(!status);
/* only allows one page from the head */
if (vma->vm_pgoff > 0 || size != PAGE_SIZE)
return -EIO;
/* disallow writable mapping */
if (vma->vm_flags & VM_WRITE)
return -EPERM;
/* disallow mprotect() turns it into writable */
vma->vm_flags &= ~VM_MAYWRITE;
return remap_pfn_range(vma, vma->vm_start,
page_to_pfn(status),
size, vma->vm_page_prot);
}
static const struct file_operations sel_handle_status_ops = {
.open = sel_open_handle_status,
.read = sel_read_handle_status,
.mmap = sel_mmap_handle_status,
.llseek = generic_file_llseek,
};
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
static ssize_t sel_write_disable(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
int new_value;
extern int selinux_disable(void);
length = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
length = -EINVAL;
if (sscanf(page, "%d", &new_value) != 1)
goto out;
if (new_value) {
length = selinux_disable();
if (length)
goto out;
audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_STATUS,
"selinux=0 auid=%u ses=%u",
audit_get_loginuid(current),
audit_get_sessionid(current));
}
length = count;
out:
free_page((unsigned long) page);
return length;
}
#else
#define sel_write_disable NULL
#endif
static const struct file_operations sel_disable_ops = {
.write = sel_write_disable,
.llseek = generic_file_llseek,
};
static ssize_t sel_read_policyvers(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u", POLICYDB_VERSION_MAX);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations sel_policyvers_ops = {
.read = sel_read_policyvers,
.llseek = generic_file_llseek,
};
/* declaration for sel_write_load */
static int sel_make_bools(void);
static int sel_make_classes(void);
static int sel_make_policycap(void);
/* declaration for sel_make_class_dirs */
static int sel_make_dir(struct inode *dir, struct dentry *dentry,
unsigned long *ino);
static ssize_t sel_read_mls(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
length = scnprintf(tmpbuf, TMPBUFLEN, "%d",
security_mls_enabled());
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations sel_mls_ops = {
.read = sel_read_mls,
.llseek = generic_file_llseek,
};
struct policy_load_memory {
size_t len;
void *data;
};
static int sel_open_policy(struct inode *inode, struct file *filp)
{
struct policy_load_memory *plm = NULL;
int rc;
BUG_ON(filp->private_data);
mutex_lock(&sel_mutex);
rc = task_has_security(current, SECURITY__READ_POLICY);
if (rc)
goto err;
rc = -EBUSY;
if (policy_opened)
goto err;
rc = -ENOMEM;
plm = kzalloc(sizeof(*plm), GFP_KERNEL);
if (!plm)
goto err;
if (i_size_read(inode) != security_policydb_len()) {
mutex_lock(&inode->i_mutex);
i_size_write(inode, security_policydb_len());
mutex_unlock(&inode->i_mutex);
}
rc = security_read_policy(&plm->data, &plm->len);
if (rc)
goto err;
policy_opened = 1;
filp->private_data = plm;
mutex_unlock(&sel_mutex);
return 0;
err:
mutex_unlock(&sel_mutex);
if (plm)
vfree(plm->data);
kfree(plm);
return rc;
}
static int sel_release_policy(struct inode *inode, struct file *filp)
{
struct policy_load_memory *plm = filp->private_data;
BUG_ON(!plm);
policy_opened = 0;
vfree(plm->data);
kfree(plm);
return 0;
}
static ssize_t sel_read_policy(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
struct policy_load_memory *plm = filp->private_data;
int ret;
mutex_lock(&sel_mutex);
ret = task_has_security(current, SECURITY__READ_POLICY);
if (ret)
goto out;
ret = simple_read_from_buffer(buf, count, ppos, plm->data, plm->len);
out:
mutex_unlock(&sel_mutex);
return ret;
}
static int sel_mmap_policy_fault(struct vm_area_struct *vma,
struct vm_fault *vmf)
{
struct policy_load_memory *plm = vma->vm_file->private_data;
unsigned long offset;
struct page *page;
if (vmf->flags & (FAULT_FLAG_MKWRITE | FAULT_FLAG_WRITE))
return VM_FAULT_SIGBUS;
offset = vmf->pgoff << PAGE_SHIFT;
if (offset >= roundup(plm->len, PAGE_SIZE))
return VM_FAULT_SIGBUS;
page = vmalloc_to_page(plm->data + offset);
get_page(page);
vmf->page = page;
return 0;
}
static struct vm_operations_struct sel_mmap_policy_ops = {
.fault = sel_mmap_policy_fault,
.page_mkwrite = sel_mmap_policy_fault,
};
int sel_mmap_policy(struct file *filp, struct vm_area_struct *vma)
{
if (vma->vm_flags & VM_SHARED) {
/* do not allow mprotect to make mapping writable */
vma->vm_flags &= ~VM_MAYWRITE;
if (vma->vm_flags & VM_WRITE)
return -EACCES;
}
vma->vm_flags |= VM_RESERVED;
vma->vm_ops = &sel_mmap_policy_ops;
return 0;
}
static const struct file_operations sel_policy_ops = {
.open = sel_open_policy,
.read = sel_read_policy,
.mmap = sel_mmap_policy,
.release = sel_release_policy,
};
static ssize_t sel_write_load(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
ssize_t length;
void *data = NULL;
mutex_lock(&sel_mutex);
length = task_has_security(current, SECURITY__LOAD_POLICY);
if (length)
goto out;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -EFBIG;
if (count > 64 * 1024 * 1024)
goto out;
length = -ENOMEM;
data = vmalloc(count);
if (!data)
goto out;
length = -EFAULT;
if (copy_from_user(data, buf, count) != 0)
goto out;
length = security_load_policy(data, count);
if (length)
goto out;
length = sel_make_bools();
if (length)
goto out1;
length = sel_make_classes();
if (length)
goto out1;
length = sel_make_policycap();
if (length)
goto out1;
length = count;
out1:
audit_log(current->audit_context, GFP_KERNEL, AUDIT_MAC_POLICY_LOAD,
"policy loaded auid=%u ses=%u",
audit_get_loginuid(current),
audit_get_sessionid(current));
out:
mutex_unlock(&sel_mutex);
vfree(data);
return length;
}
static const struct file_operations sel_load_ops = {
.write = sel_write_load,
.llseek = generic_file_llseek,
};
static ssize_t sel_write_context(struct file *file, char *buf, size_t size)
{
char *canon = NULL;
u32 sid, len;
ssize_t length;
length = task_has_security(current, SECURITY__CHECK_CONTEXT);
if (length)
goto out;
length = security_context_to_sid(buf, size, &sid);
if (length)
goto out;
length = security_sid_to_context(sid, &canon, &len);
if (length)
goto out;
length = -ERANGE;
if (len > SIMPLE_TRANSACTION_LIMIT) {
printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
"payload max\n", __func__, len);
goto out;
}
memcpy(buf, canon, len);
length = len;
out:
kfree(canon);
return length;
}
static ssize_t sel_read_checkreqprot(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u", selinux_checkreqprot);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static ssize_t sel_write_checkreqprot(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
unsigned int new_value;
length = task_has_security(current, SECURITY__SETCHECKREQPROT);
if (length)
goto out;
length = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
length = -EINVAL;
if (sscanf(page, "%u", &new_value) != 1)
goto out;
selinux_checkreqprot = new_value ? 1 : 0;
length = count;
out:
free_page((unsigned long) page);
return length;
}
static const struct file_operations sel_checkreqprot_ops = {
.read = sel_read_checkreqprot,
.write = sel_write_checkreqprot,
.llseek = generic_file_llseek,
};
/*
* Remaining nodes use transaction based IO methods like nfsd/nfsctl.c
*/
static ssize_t sel_write_access(struct file *file, char *buf, size_t size);
static ssize_t sel_write_create(struct file *file, char *buf, size_t size);
static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size);
static ssize_t sel_write_user(struct file *file, char *buf, size_t size);
static ssize_t sel_write_member(struct file *file, char *buf, size_t size);
static ssize_t (*write_op[])(struct file *, char *, size_t) = {
[SEL_ACCESS] = sel_write_access,
[SEL_CREATE] = sel_write_create,
[SEL_RELABEL] = sel_write_relabel,
[SEL_USER] = sel_write_user,
[SEL_MEMBER] = sel_write_member,
[SEL_CONTEXT] = sel_write_context,
};
static ssize_t selinux_transaction_write(struct file *file, const char __user *buf, size_t size, loff_t *pos)
{
ino_t ino = file->f_path.dentry->d_inode->i_ino;
char *data;
ssize_t rv;
if (ino >= ARRAY_SIZE(write_op) || !write_op[ino])
return -EINVAL;
data = simple_transaction_get(file, buf, size);
if (IS_ERR(data))
return PTR_ERR(data);
rv = write_op[ino](file, data, size);
if (rv > 0) {
simple_transaction_set(file, rv);
rv = size;
}
return rv;
}
static const struct file_operations transaction_ops = {
.write = selinux_transaction_write,
.read = simple_transaction_read,
.release = simple_transaction_release,
.llseek = generic_file_llseek,
};
/*
* payload - write methods
* If the method has a response, the response should be put in buf,
* and the length returned. Otherwise return 0 or and -error.
*/
static ssize_t sel_write_access(struct file *file, char *buf, size_t size)
{
char *scon = NULL, *tcon = NULL;
u32 ssid, tsid;
u16 tclass;
struct av_decision avd;
ssize_t length;
length = task_has_security(current, SECURITY__COMPUTE_AV);
if (length)
goto out;
length = -ENOMEM;
scon = kzalloc(size + 1, GFP_KERNEL);
if (!scon)
goto out;
length = -ENOMEM;
tcon = kzalloc(size + 1, GFP_KERNEL);
if (!tcon)
goto out;
length = -EINVAL;
if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
goto out;
length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
if (length)
goto out;
length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
if (length)
goto out;
security_compute_av_user(ssid, tsid, tclass, &avd);
length = scnprintf(buf, SIMPLE_TRANSACTION_LIMIT,
"%x %x %x %x %u %x",
avd.allowed, 0xffffffff,
avd.auditallow, avd.auditdeny,
avd.seqno, avd.flags);
out:
kfree(tcon);
kfree(scon);
return length;
}
static inline int hexcode_to_int(int code) {
if (code == '\0' || !isxdigit(code))
return -1;
if (isdigit(code))
return code - '0';
return tolower(code) - 'a' + 10;
}
static ssize_t sel_write_create(struct file *file, char *buf, size_t size)
{
char *scon = NULL, *tcon = NULL;
char *namebuf = NULL, *objname = NULL;
u32 ssid, tsid, newsid;
u16 tclass;
ssize_t length;
char *newcon = NULL;
u32 len;
int nargs;
length = task_has_security(current, SECURITY__COMPUTE_CREATE);
if (length)
goto out;
length = -ENOMEM;
scon = kzalloc(size + 1, GFP_KERNEL);
if (!scon)
goto out;
length = -ENOMEM;
tcon = kzalloc(size + 1, GFP_KERNEL);
if (!tcon)
goto out;
length = -ENOMEM;
namebuf = kzalloc(size + 1, GFP_KERNEL);
if (!namebuf)
goto out;
length = -EINVAL;
nargs = sscanf(buf, "%s %s %hu %s", scon, tcon, &tclass, namebuf);
if (nargs < 3 || nargs > 4)
goto out;
if (nargs == 4) {
/*
* If and when the name of new object to be queried contains
* either whitespace or multibyte characters, they shall be
* encoded based on the percentage-encoding rule.
* If not encoded, the sscanf logic picks up only left-half
* of the supplied name; splitted by a whitespace unexpectedly.
*/
char *r, *w;
int c1, c2;
r = w = namebuf;
do {
c1 = *r++;
if (c1 == '+')
c1 = ' ';
else if (c1 == '%') {
if ((c1 = hexcode_to_int(*r++)) < 0)
goto out;
if ((c2 = hexcode_to_int(*r++)) < 0)
goto out;
c1 = (c1 << 4) | c2;
}
*w++ = c1;
} while (c1 != '\0');
objname = namebuf;
}
length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
if (length)
goto out;
length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
if (length)
goto out;
length = security_transition_sid_user(ssid, tsid, tclass,
objname, &newsid);
if (length)
goto out;
length = security_sid_to_context(newsid, &newcon, &len);
if (length)
goto out;
length = -ERANGE;
if (len > SIMPLE_TRANSACTION_LIMIT) {
printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
"payload max\n", __func__, len);
goto out;
}
memcpy(buf, newcon, len);
length = len;
out:
kfree(newcon);
kfree(namebuf);
kfree(tcon);
kfree(scon);
return length;
}
static ssize_t sel_write_relabel(struct file *file, char *buf, size_t size)
{
char *scon = NULL, *tcon = NULL;
u32 ssid, tsid, newsid;
u16 tclass;
ssize_t length;
char *newcon = NULL;
u32 len;
length = task_has_security(current, SECURITY__COMPUTE_RELABEL);
if (length)
goto out;
length = -ENOMEM;
scon = kzalloc(size + 1, GFP_KERNEL);
if (!scon)
goto out;
length = -ENOMEM;
tcon = kzalloc(size + 1, GFP_KERNEL);
if (!tcon)
goto out;
length = -EINVAL;
if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
goto out;
length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
if (length)
goto out;
length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
if (length)
goto out;
length = security_change_sid(ssid, tsid, tclass, &newsid);
if (length)
goto out;
length = security_sid_to_context(newsid, &newcon, &len);
if (length)
goto out;
length = -ERANGE;
if (len > SIMPLE_TRANSACTION_LIMIT)
goto out;
memcpy(buf, newcon, len);
length = len;
out:
kfree(newcon);
kfree(tcon);
kfree(scon);
return length;
}
static ssize_t sel_write_user(struct file *file, char *buf, size_t size)
{
char *con = NULL, *user = NULL, *ptr;
u32 sid, *sids = NULL;
ssize_t length;
char *newcon;
int i, rc;
u32 len, nsids;
length = task_has_security(current, SECURITY__COMPUTE_USER);
if (length)
goto out;
length = -ENOMEM;
con = kzalloc(size + 1, GFP_KERNEL);
if (!con)
goto out;
length = -ENOMEM;
user = kzalloc(size + 1, GFP_KERNEL);
if (!user)
goto out;
length = -EINVAL;
if (sscanf(buf, "%s %s", con, user) != 2)
goto out;
length = security_context_to_sid(con, strlen(con) + 1, &sid);
if (length)
goto out;
length = security_get_user_sids(sid, user, &sids, &nsids);
if (length)
goto out;
length = sprintf(buf, "%u", nsids) + 1;
ptr = buf + length;
for (i = 0; i < nsids; i++) {
rc = security_sid_to_context(sids[i], &newcon, &len);
if (rc) {
length = rc;
goto out;
}
if ((length + len) >= SIMPLE_TRANSACTION_LIMIT) {
kfree(newcon);
length = -ERANGE;
goto out;
}
memcpy(ptr, newcon, len);
kfree(newcon);
ptr += len;
length += len;
}
out:
kfree(sids);
kfree(user);
kfree(con);
return length;
}
static ssize_t sel_write_member(struct file *file, char *buf, size_t size)
{
char *scon = NULL, *tcon = NULL;
u32 ssid, tsid, newsid;
u16 tclass;
ssize_t length;
char *newcon = NULL;
u32 len;
length = task_has_security(current, SECURITY__COMPUTE_MEMBER);
if (length)
goto out;
length = -ENOMEM;
scon = kzalloc(size + 1, GFP_KERNEL);
if (!scon)
goto out;
length = -ENOMEM;
tcon = kzalloc(size + 1, GFP_KERNEL);
if (!tcon)
goto out;
length = -EINVAL;
if (sscanf(buf, "%s %s %hu", scon, tcon, &tclass) != 3)
goto out;
length = security_context_to_sid(scon, strlen(scon) + 1, &ssid);
if (length)
goto out;
length = security_context_to_sid(tcon, strlen(tcon) + 1, &tsid);
if (length)
goto out;
length = security_member_sid(ssid, tsid, tclass, &newsid);
if (length)
goto out;
length = security_sid_to_context(newsid, &newcon, &len);
if (length)
goto out;
length = -ERANGE;
if (len > SIMPLE_TRANSACTION_LIMIT) {
printk(KERN_ERR "SELinux: %s: context size (%u) exceeds "
"payload max\n", __func__, len);
goto out;
}
memcpy(buf, newcon, len);
length = len;
out:
kfree(newcon);
kfree(tcon);
kfree(scon);
return length;
}
static struct inode *sel_make_inode(struct super_block *sb, int mode)
{
struct inode *ret = new_inode(sb);
if (ret) {
ret->i_mode = mode;
ret->i_atime = ret->i_mtime = ret->i_ctime = CURRENT_TIME;
}
return ret;
}
static ssize_t sel_read_bool(struct file *filep, char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
ssize_t ret;
int cur_enforcing;
struct inode *inode = filep->f_path.dentry->d_inode;
unsigned index = inode->i_ino & SEL_INO_MASK;
const char *name = filep->f_path.dentry->d_name.name;
mutex_lock(&sel_mutex);
ret = -EINVAL;
if (index >= bool_num || strcmp(name, bool_pending_names[index]))
goto out;
ret = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
cur_enforcing = security_get_bool_value(index);
if (cur_enforcing < 0) {
ret = cur_enforcing;
goto out;
}
length = scnprintf(page, PAGE_SIZE, "%d %d", cur_enforcing,
bool_pending_values[index]);
ret = simple_read_from_buffer(buf, count, ppos, page, length);
out:
mutex_unlock(&sel_mutex);
free_page((unsigned long)page);
return ret;
}
static ssize_t sel_write_bool(struct file *filep, const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
int new_value;
struct inode *inode = filep->f_path.dentry->d_inode;
unsigned index = inode->i_ino & SEL_INO_MASK;
const char *name = filep->f_path.dentry->d_name.name;
mutex_lock(&sel_mutex);
length = task_has_security(current, SECURITY__SETBOOL);
if (length)
goto out;
length = -EINVAL;
if (index >= bool_num || strcmp(name, bool_pending_names[index]))
goto out;
length = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
length = -EINVAL;
if (sscanf(page, "%d", &new_value) != 1)
goto out;
if (new_value)
new_value = 1;
bool_pending_values[index] = new_value;
length = count;
out:
mutex_unlock(&sel_mutex);
free_page((unsigned long) page);
return length;
}
static const struct file_operations sel_bool_ops = {
.read = sel_read_bool,
.write = sel_write_bool,
.llseek = generic_file_llseek,
};
static ssize_t sel_commit_bools_write(struct file *filep,
const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t length;
int new_value;
mutex_lock(&sel_mutex);
length = task_has_security(current, SECURITY__SETBOOL);
if (length)
goto out;
length = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
length = -EINVAL;
if (*ppos != 0)
goto out;
length = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
length = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
length = -EINVAL;
if (sscanf(page, "%d", &new_value) != 1)
goto out;
length = 0;
if (new_value && bool_pending_values)
length = security_set_bools(bool_num, bool_pending_values);
if (!length)
length = count;
out:
mutex_unlock(&sel_mutex);
free_page((unsigned long) page);
return length;
}
static const struct file_operations sel_commit_bools_ops = {
.write = sel_commit_bools_write,
.llseek = generic_file_llseek,
};
static void sel_remove_entries(struct dentry *de)
{
struct list_head *node;
spin_lock(&de->d_lock);
node = de->d_subdirs.next;
while (node != &de->d_subdirs) {
struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
spin_lock_nested(&d->d_lock, DENTRY_D_LOCK_NESTED);
list_del_init(node);
if (d->d_inode) {
dget_dlock(d);
spin_unlock(&de->d_lock);
spin_unlock(&d->d_lock);
d_delete(d);
simple_unlink(de->d_inode, d);
dput(d);
spin_lock(&de->d_lock);
} else
spin_unlock(&d->d_lock);
node = de->d_subdirs.next;
}
spin_unlock(&de->d_lock);
}
#define BOOL_DIR_NAME "booleans"
static int sel_make_bools(void)
{
int i, ret;
ssize_t len;
struct dentry *dentry = NULL;
struct dentry *dir = bool_dir;
struct inode *inode = NULL;
struct inode_security_struct *isec;
char **names = NULL, *page;
int num;
int *values = NULL;
u32 sid;
/* remove any existing files */
for (i = 0; i < bool_num; i++)
kfree(bool_pending_names[i]);
kfree(bool_pending_names);
kfree(bool_pending_values);
bool_pending_names = NULL;
bool_pending_values = NULL;
sel_remove_entries(dir);
ret = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
ret = security_get_bools(&num, &names, &values);
if (ret)
goto out;
for (i = 0; i < num; i++) {
ret = -ENOMEM;
dentry = d_alloc_name(dir, names[i]);
if (!dentry)
goto out;
ret = -ENOMEM;
inode = sel_make_inode(dir->d_sb, S_IFREG | S_IRUGO | S_IWUSR);
if (!inode)
goto out;
ret = -EINVAL;
len = snprintf(page, PAGE_SIZE, "/%s/%s", BOOL_DIR_NAME, names[i]);
if (len < 0)
goto out;
ret = -ENAMETOOLONG;
if (len >= PAGE_SIZE)
goto out;
isec = (struct inode_security_struct *)inode->i_security;
ret = security_genfs_sid("selinuxfs", page, SECCLASS_FILE, &sid);
if (ret)
goto out;
isec->sid = sid;
isec->initialized = 1;
inode->i_fop = &sel_bool_ops;
inode->i_ino = i|SEL_BOOL_INO_OFFSET;
d_add(dentry, inode);
}
bool_num = num;
bool_pending_names = names;
bool_pending_values = values;
free_page((unsigned long)page);
return 0;
out:
free_page((unsigned long)page);
if (names) {
for (i = 0; i < num; i++)
kfree(names[i]);
kfree(names);
}
kfree(values);
sel_remove_entries(dir);
return ret;
}
#define NULL_FILE_NAME "null"
struct dentry *selinux_null;
static ssize_t sel_read_avc_cache_threshold(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char tmpbuf[TMPBUFLEN];
ssize_t length;
length = scnprintf(tmpbuf, TMPBUFLEN, "%u", avc_cache_threshold);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static ssize_t sel_write_avc_cache_threshold(struct file *file,
const char __user *buf,
size_t count, loff_t *ppos)
{
char *page = NULL;
ssize_t ret;
int new_value;
ret = task_has_security(current, SECURITY__SETSECPARAM);
if (ret)
goto out;
ret = -ENOMEM;
if (count >= PAGE_SIZE)
goto out;
/* No partial writes. */
ret = -EINVAL;
if (*ppos != 0)
goto out;
ret = -ENOMEM;
page = (char *)get_zeroed_page(GFP_KERNEL);
if (!page)
goto out;
ret = -EFAULT;
if (copy_from_user(page, buf, count))
goto out;
ret = -EINVAL;
if (sscanf(page, "%u", &new_value) != 1)
goto out;
avc_cache_threshold = new_value;
ret = count;
out:
free_page((unsigned long)page);
return ret;
}
static ssize_t sel_read_avc_hash_stats(struct file *filp, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
ssize_t length;
page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
length = avc_get_hash_stats(page);
if (length >= 0)
length = simple_read_from_buffer(buf, count, ppos, page, length);
free_page((unsigned long)page);
return length;
}
static const struct file_operations sel_avc_cache_threshold_ops = {
.read = sel_read_avc_cache_threshold,
.write = sel_write_avc_cache_threshold,
.llseek = generic_file_llseek,
};
static const struct file_operations sel_avc_hash_stats_ops = {
.read = sel_read_avc_hash_stats,
.llseek = generic_file_llseek,
};
#ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
static struct avc_cache_stats *sel_avc_get_stat_idx(loff_t *idx)
{
int cpu;
for (cpu = *idx; cpu < nr_cpu_ids; ++cpu) {
if (!cpu_possible(cpu))
continue;
*idx = cpu + 1;
return &per_cpu(avc_cache_stats, cpu);
}
return NULL;
}
static void *sel_avc_stats_seq_start(struct seq_file *seq, loff_t *pos)
{
loff_t n = *pos - 1;
if (*pos == 0)
return SEQ_START_TOKEN;
return sel_avc_get_stat_idx(&n);
}
static void *sel_avc_stats_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
return sel_avc_get_stat_idx(pos);
}
static int sel_avc_stats_seq_show(struct seq_file *seq, void *v)
{
struct avc_cache_stats *st = v;
if (v == SEQ_START_TOKEN)
seq_printf(seq, "lookups hits misses allocations reclaims "
"frees\n");
else {
unsigned int lookups = st->lookups;
unsigned int misses = st->misses;
unsigned int hits = lookups - misses;
seq_printf(seq, "%u %u %u %u %u %u\n", lookups,
hits, misses, st->allocations,
st->reclaims, st->frees);
}
return 0;
}
static void sel_avc_stats_seq_stop(struct seq_file *seq, void *v)
{ }
static const struct seq_operations sel_avc_cache_stats_seq_ops = {
.start = sel_avc_stats_seq_start,
.next = sel_avc_stats_seq_next,
.show = sel_avc_stats_seq_show,
.stop = sel_avc_stats_seq_stop,
};
static int sel_open_avc_cache_stats(struct inode *inode, struct file *file)
{
return seq_open(file, &sel_avc_cache_stats_seq_ops);
}
static const struct file_operations sel_avc_cache_stats_ops = {
.open = sel_open_avc_cache_stats,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif
static int sel_make_avc_files(struct dentry *dir)
{
int i;
static struct tree_descr files[] = {
{ "cache_threshold",
&sel_avc_cache_threshold_ops, S_IRUGO|S_IWUSR },
{ "hash_stats", &sel_avc_hash_stats_ops, S_IRUGO },
#ifdef CONFIG_SECURITY_SELINUX_AVC_STATS
{ "cache_stats", &sel_avc_cache_stats_ops, S_IRUGO },
#endif
};
for (i = 0; i < ARRAY_SIZE(files); i++) {
struct inode *inode;
struct dentry *dentry;
dentry = d_alloc_name(dir, files[i].name);
if (!dentry)
return -ENOMEM;
inode = sel_make_inode(dir->d_sb, S_IFREG|files[i].mode);
if (!inode)
return -ENOMEM;
inode->i_fop = files[i].ops;
inode->i_ino = ++sel_last_ino;
d_add(dentry, inode);
}
return 0;
}
static ssize_t sel_read_initcon(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
struct inode *inode;
char *con;
u32 sid, len;
ssize_t ret;
inode = file->f_path.dentry->d_inode;
sid = inode->i_ino&SEL_INO_MASK;
ret = security_sid_to_context(sid, &con, &len);
if (ret)
return ret;
ret = simple_read_from_buffer(buf, count, ppos, con, len);
kfree(con);
return ret;
}
static const struct file_operations sel_initcon_ops = {
.read = sel_read_initcon,
.llseek = generic_file_llseek,
};
static int sel_make_initcon_files(struct dentry *dir)
{
int i;
for (i = 1; i <= SECINITSID_NUM; i++) {
struct inode *inode;
struct dentry *dentry;
dentry = d_alloc_name(dir, security_get_initial_sid_context(i));
if (!dentry)
return -ENOMEM;
inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
if (!inode)
return -ENOMEM;
inode->i_fop = &sel_initcon_ops;
inode->i_ino = i|SEL_INITCON_INO_OFFSET;
d_add(dentry, inode);
}
return 0;
}
static inline unsigned int sel_div(unsigned long a, unsigned long b)
{
return a / b - (a % b < 0);
}
static inline unsigned long sel_class_to_ino(u16 class)
{
return (class * (SEL_VEC_MAX + 1)) | SEL_CLASS_INO_OFFSET;
}
static inline u16 sel_ino_to_class(unsigned long ino)
{
return sel_div(ino & SEL_INO_MASK, SEL_VEC_MAX + 1);
}
static inline unsigned long sel_perm_to_ino(u16 class, u32 perm)
{
return (class * (SEL_VEC_MAX + 1) + perm) | SEL_CLASS_INO_OFFSET;
}
static inline u32 sel_ino_to_perm(unsigned long ino)
{
return (ino & SEL_INO_MASK) % (SEL_VEC_MAX + 1);
}
static ssize_t sel_read_class(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
ssize_t rc, len;
char *page;
unsigned long ino = file->f_path.dentry->d_inode->i_ino;
page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_class(ino));
rc = simple_read_from_buffer(buf, count, ppos, page, len);
free_page((unsigned long)page);
return rc;
}
static const struct file_operations sel_class_ops = {
.read = sel_read_class,
.llseek = generic_file_llseek,
};
static ssize_t sel_read_perm(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
ssize_t rc, len;
char *page;
unsigned long ino = file->f_path.dentry->d_inode->i_ino;
page = (char *)__get_free_page(GFP_KERNEL);
if (!page)
return -ENOMEM;
len = snprintf(page, PAGE_SIZE, "%d", sel_ino_to_perm(ino));
rc = simple_read_from_buffer(buf, count, ppos, page, len);
free_page((unsigned long)page);
return rc;
}
static const struct file_operations sel_perm_ops = {
.read = sel_read_perm,
.llseek = generic_file_llseek,
};
static ssize_t sel_read_policycap(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
int value;
char tmpbuf[TMPBUFLEN];
ssize_t length;
unsigned long i_ino = file->f_path.dentry->d_inode->i_ino;
value = security_policycap_supported(i_ino & SEL_INO_MASK);
length = scnprintf(tmpbuf, TMPBUFLEN, "%d", value);
return simple_read_from_buffer(buf, count, ppos, tmpbuf, length);
}
static const struct file_operations sel_policycap_ops = {
.read = sel_read_policycap,
.llseek = generic_file_llseek,
};
static int sel_make_perm_files(char *objclass, int classvalue,
struct dentry *dir)
{
int i, rc, nperms;
char **perms;
rc = security_get_permissions(objclass, &perms, &nperms);
if (rc)
return rc;
for (i = 0; i < nperms; i++) {
struct inode *inode;
struct dentry *dentry;
rc = -ENOMEM;
dentry = d_alloc_name(dir, perms[i]);
if (!dentry)
goto out;
rc = -ENOMEM;
inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
if (!inode)
goto out;
inode->i_fop = &sel_perm_ops;
/* i+1 since perm values are 1-indexed */
inode->i_ino = sel_perm_to_ino(classvalue, i + 1);
d_add(dentry, inode);
}
rc = 0;
out:
for (i = 0; i < nperms; i++)
kfree(perms[i]);
kfree(perms);
return rc;
}
static int sel_make_class_dir_entries(char *classname, int index,
struct dentry *dir)
{
struct dentry *dentry = NULL;
struct inode *inode = NULL;
int rc;
dentry = d_alloc_name(dir, "index");
if (!dentry)
return -ENOMEM;
inode = sel_make_inode(dir->d_sb, S_IFREG|S_IRUGO);
if (!inode)
return -ENOMEM;
inode->i_fop = &sel_class_ops;
inode->i_ino = sel_class_to_ino(index);
d_add(dentry, inode);
dentry = d_alloc_name(dir, "perms");
if (!dentry)
return -ENOMEM;
rc = sel_make_dir(dir->d_inode, dentry, &last_class_ino);
if (rc)
return rc;
rc = sel_make_perm_files(classname, index, dentry);
return rc;
}
static void sel_remove_classes(void)
{
struct list_head *class_node;
list_for_each(class_node, &class_dir->d_subdirs) {
struct dentry *class_subdir = list_entry(class_node,
struct dentry, d_u.d_child);
struct list_head *class_subdir_node;
list_for_each(class_subdir_node, &class_subdir->d_subdirs) {
struct dentry *d = list_entry(class_subdir_node,
struct dentry, d_u.d_child);
if (d->d_inode)
if (d->d_inode->i_mode & S_IFDIR)
sel_remove_entries(d);
}
sel_remove_entries(class_subdir);
}
sel_remove_entries(class_dir);
}
static int sel_make_classes(void)
{
int rc, nclasses, i;
char **classes;
/* delete any existing entries */
sel_remove_classes();
rc = security_get_classes(&classes, &nclasses);
if (rc)
return rc;
/* +2 since classes are 1-indexed */
last_class_ino = sel_class_to_ino(nclasses + 2);
for (i = 0; i < nclasses; i++) {
struct dentry *class_name_dir;
rc = -ENOMEM;
class_name_dir = d_alloc_name(class_dir, classes[i]);
if (!class_name_dir)
goto out;
rc = sel_make_dir(class_dir->d_inode, class_name_dir,
&last_class_ino);
if (rc)
goto out;
/* i+1 since class values are 1-indexed */
rc = sel_make_class_dir_entries(classes[i], i + 1,
class_name_dir);
if (rc)
goto out;
}
rc = 0;
out:
for (i = 0; i < nclasses; i++)
kfree(classes[i]);
kfree(classes);
return rc;
}
static int sel_make_policycap(void)
{
unsigned int iter;
struct dentry *dentry = NULL;
struct inode *inode = NULL;
sel_remove_entries(policycap_dir);
for (iter = 0; iter <= POLICYDB_CAPABILITY_MAX; iter++) {
if (iter < ARRAY_SIZE(policycap_names))
dentry = d_alloc_name(policycap_dir,
policycap_names[iter]);
else
dentry = d_alloc_name(policycap_dir, "unknown");
if (dentry == NULL)
return -ENOMEM;
inode = sel_make_inode(policycap_dir->d_sb, S_IFREG | S_IRUGO);
if (inode == NULL)
return -ENOMEM;
inode->i_fop = &sel_policycap_ops;
inode->i_ino = iter | SEL_POLICYCAP_INO_OFFSET;
d_add(dentry, inode);
}
return 0;
}
static int sel_make_dir(struct inode *dir, struct dentry *dentry,
unsigned long *ino)
{
struct inode *inode;
inode = sel_make_inode(dir->i_sb, S_IFDIR | S_IRUGO | S_IXUGO);
if (!inode)
return -ENOMEM;
inode->i_op = &simple_dir_inode_operations;
inode->i_fop = &simple_dir_operations;
inode->i_ino = ++(*ino);
/* directory inodes start off with i_nlink == 2 (for "." entry) */
inc_nlink(inode);
d_add(dentry, inode);
/* bump link count on parent directory, too */
inc_nlink(dir);
return 0;
}
static int sel_fill_super(struct super_block *sb, void *data, int silent)
{
int ret;
struct dentry *dentry;
struct inode *inode, *root_inode;
struct inode_security_struct *isec;
static struct tree_descr selinux_files[] = {
[SEL_LOAD] = {"load", &sel_load_ops, S_IRUSR|S_IWUSR},
[SEL_ENFORCE] = {"enforce", &sel_enforce_ops, S_IRUGO|S_IWUSR},
[SEL_CONTEXT] = {"context", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_ACCESS] = {"access", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_CREATE] = {"create", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_RELABEL] = {"relabel", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_USER] = {"user", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_POLICYVERS] = {"policyvers", &sel_policyvers_ops, S_IRUGO},
[SEL_COMMIT_BOOLS] = {"commit_pending_bools", &sel_commit_bools_ops, S_IWUSR},
[SEL_MLS] = {"mls", &sel_mls_ops, S_IRUGO},
[SEL_DISABLE] = {"disable", &sel_disable_ops, S_IWUSR},
[SEL_MEMBER] = {"member", &transaction_ops, S_IRUGO|S_IWUGO},
[SEL_CHECKREQPROT] = {"checkreqprot", &sel_checkreqprot_ops, S_IRUGO|S_IWUSR},
[SEL_REJECT_UNKNOWN] = {"reject_unknown", &sel_handle_unknown_ops, S_IRUGO},
[SEL_DENY_UNKNOWN] = {"deny_unknown", &sel_handle_unknown_ops, S_IRUGO},
[SEL_STATUS] = {"status", &sel_handle_status_ops, S_IRUGO},
[SEL_POLICY] = {"policy", &sel_policy_ops, S_IRUSR},
/* last one */ {""}
};
ret = simple_fill_super(sb, SELINUX_MAGIC, selinux_files);
if (ret)
goto err;
root_inode = sb->s_root->d_inode;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, BOOL_DIR_NAME);
if (!dentry)
goto err;
ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
if (ret)
goto err;
bool_dir = dentry;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, NULL_FILE_NAME);
if (!dentry)
goto err;
ret = -ENOMEM;
inode = sel_make_inode(sb, S_IFCHR | S_IRUGO | S_IWUGO);
if (!inode)
goto err;
inode->i_ino = ++sel_last_ino;
isec = (struct inode_security_struct *)inode->i_security;
isec->sid = SECINITSID_DEVNULL;
isec->sclass = SECCLASS_CHR_FILE;
isec->initialized = 1;
init_special_inode(inode, S_IFCHR | S_IRUGO | S_IWUGO, MKDEV(MEM_MAJOR, 3));
d_add(dentry, inode);
selinux_null = dentry;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, "avc");
if (!dentry)
goto err;
ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
if (ret)
goto err;
ret = sel_make_avc_files(dentry);
if (ret)
goto err;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, "initial_contexts");
if (!dentry)
goto err;
ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
if (ret)
goto err;
ret = sel_make_initcon_files(dentry);
if (ret)
goto err;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, "class");
if (!dentry)
goto err;
ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
if (ret)
goto err;
class_dir = dentry;
ret = -ENOMEM;
dentry = d_alloc_name(sb->s_root, "policy_capabilities");
if (!dentry)
goto err;
ret = sel_make_dir(root_inode, dentry, &sel_last_ino);
if (ret)
goto err;
policycap_dir = dentry;
return 0;
err:
printk(KERN_ERR "SELinux: %s: failed while creating inodes\n",
__func__);
return ret;
}
static struct dentry *sel_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_single(fs_type, flags, data, sel_fill_super);
}
static struct file_system_type sel_fs_type = {
.name = "selinuxfs",
.mount = sel_mount,
.kill_sb = kill_litter_super,
};
struct vfsmount *selinuxfs_mount;
static struct kobject *selinuxfs_kobj;
static int __init init_sel_fs(void)
{
int err;
#ifdef CONFIG_ALWAYS_ENFORCE
selinux_enabled = 1;
#endif
if (!selinux_enabled)
return 0;
selinuxfs_kobj = kobject_create_and_add("selinux", fs_kobj);
if (!selinuxfs_kobj)
return -ENOMEM;
err = register_filesystem(&sel_fs_type);
if (err) {
kobject_put(selinuxfs_kobj);
return err;
}
selinuxfs_mount = kern_mount(&sel_fs_type);
if (IS_ERR(selinuxfs_mount)) {
printk(KERN_ERR "selinuxfs: could not mount!\n");
err = PTR_ERR(selinuxfs_mount);
selinuxfs_mount = NULL;
}
return err;
}
__initcall(init_sel_fs);
#ifdef CONFIG_SECURITY_SELINUX_DISABLE
void exit_sel_fs(void)
{
kobject_put(selinuxfs_kobj);
unregister_filesystem(&sel_fs_type);
}
#endif
| gpl-2.0 |
Frontier314/frontkernel35 | drivers/staging/comedi/drivers/skel.c | 50 | 19390 | /*
comedi/drivers/skel.c
Skeleton code for a Comedi driver
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: skel
Description: Skeleton driver, an example for driver writers
Devices:
Author: ds
Updated: Mon, 18 Mar 2002 15:34:01 -0800
Status: works
This driver is a documented example on how Comedi drivers are
written.
Configuration Options:
none
*/
/*
* The previous block comment is used to automatically generate
* documentation in Comedi and Comedilib. The fields:
*
* Driver: the name of the driver
* Description: a short phrase describing the driver. Don't list boards.
* Devices: a full list of the boards that attempt to be supported by
* the driver. Format is "(manufacturer) board name [comedi name]",
* where comedi_name is the name that is used to configure the board.
* See the comment near board_name: in the struct comedi_driver structure
* below. If (manufacturer) or [comedi name] is missing, the previous
* value is used.
* Author: you
* Updated: date when the _documentation_ was last updated. Use 'date -R'
* to get a value for this.
* Status: a one-word description of the status. Valid values are:
* works - driver works correctly on most boards supported, and
* passes comedi_test.
* unknown - unknown. Usually put there by ds.
* experimental - may not work in any particular release. Author
* probably wants assistance testing it.
* bitrotten - driver has not been update in a long time, probably
* doesn't work, and probably is missing support for significant
* Comedi interface features.
* untested - author probably wrote it "blind", and is believed to
* work, but no confirmation.
*
* These headers should be followed by a blank line, and any comments
* you wish to say about the driver. The comment area is the place
* to put any known bugs, limitations, unsupported features, supported
* command triggers, whether or not commands are supported on particular
* subdevices, etc.
*
* Somewhere in the comment should be information about configuration
* options that are used with comedi_config.
*/
#include "../comedidev.h"
#include <linux/pci.h> /* for PCI devices */
/* Imaginary registers for the imaginary board */
#define SKEL_SIZE 0
#define SKEL_START_AI_CONV 0
#define SKEL_AI_READ 0
/*
* Board descriptions for two imaginary boards. Describing the
* boards in this way is optional, and completely driver-dependent.
* Some drivers use arrays such as this, other do not.
*/
struct skel_board {
const char *name;
int ai_chans;
int ai_bits;
int have_dio;
};
static const struct skel_board skel_boards[] = {
{
.name = "skel-100",
.ai_chans = 16,
.ai_bits = 12,
.have_dio = 1,
},
{
.name = "skel-200",
.ai_chans = 8,
.ai_bits = 16,
.have_dio = 0,
},
};
/* This is used by modprobe to translate PCI IDs to drivers. Should
* only be used for PCI and ISA-PnP devices */
/* Please add your PCI vendor ID to comedidev.h, and it will be forwarded
* upstream. */
#define PCI_VENDOR_ID_SKEL 0xdafe
static DEFINE_PCI_DEVICE_TABLE(skel_pci_table) = {
{ PCI_DEVICE(PCI_VENDOR_ID_SKEL, 0x0100) },
{ PCI_DEVICE(PCI_VENDOR_ID_SKEL, 0x0200) },
{ 0 }
};
MODULE_DEVICE_TABLE(pci, skel_pci_table);
/*
* Useful for shorthand access to the particular board structure
*/
#define thisboard ((const struct skel_board *)dev->board_ptr)
/* this structure is for data unique to this hardware driver. If
several hardware drivers keep similar information in this structure,
feel free to suggest moving the variable to the struct comedi_device struct.
*/
struct skel_private {
int data;
/* would be useful for a PCI device */
struct pci_dev *pci_dev;
/* Used for AO readback */
unsigned int ao_readback[2];
};
/*
* most drivers define the following macro to make it easy to
* access the private structure.
*/
#define devpriv ((struct skel_private *)dev->private)
/*
* The struct comedi_driver structure tells the Comedi core module
* which functions to call to configure/deconfigure (attach/detach)
* the board, and also about the kernel module that contains
* the device code.
*/
static int skel_attach(struct comedi_device *dev, struct comedi_devconfig *it);
static void skel_detach(struct comedi_device *dev);
static struct comedi_driver driver_skel = {
.driver_name = "dummy",
.module = THIS_MODULE,
.attach = skel_attach,
.detach = skel_detach,
/* It is not necessary to implement the following members if you are
* writing a driver for a ISA PnP or PCI card */
/* Most drivers will support multiple types of boards by
* having an array of board structures. These were defined
* in skel_boards[] above. Note that the element 'name'
* was first in the structure -- Comedi uses this fact to
* extract the name of the board without knowing any details
* about the structure except for its length.
* When a device is attached (by comedi_config), the name
* of the device is given to Comedi, and Comedi tries to
* match it by going through the list of board names. If
* there is a match, the address of the pointer is put
* into dev->board_ptr and driver->attach() is called.
*
* Note that these are not necessary if you can determine
* the type of board in software. ISA PnP, PCI, and PCMCIA
* devices are such boards.
*/
.board_name = &skel_boards[0].name,
.offset = sizeof(struct skel_board),
.num_names = ARRAY_SIZE(skel_boards),
};
static int skel_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int skel_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int skel_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int skel_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int skel_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data);
static int skel_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd);
static int skel_ns_to_timer(unsigned int *ns, int round);
/*
* Attach is called by the Comedi core to configure the driver
* for a particular board. If you specified a board_name array
* in the driver structure, dev->board_ptr contains that
* address.
*/
static int skel_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
pr_info("comedi%d: skel: ", dev->minor);
/*
* If you can probe the device to determine what device in a series
* it is, this is the place to do it. Otherwise, dev->board_ptr
* should already be initialized.
*/
/* dev->board_ptr = skel_probe(dev, it); */
/*
* Initialize dev->board_name. Note that we can use the "thisboard"
* macro now, since we just initialized it in the last line.
*/
dev->board_name = thisboard->name;
/*
* Allocate the private structure area. alloc_private() is a
* convenient macro defined in comedidev.h.
*/
if (alloc_private(dev, sizeof(struct skel_private)) < 0)
return -ENOMEM;
/*
* Allocate the subdevice structures. alloc_subdevice() is a
* convenient macro defined in comedidev.h.
*/
if (alloc_subdevices(dev, 3) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
/* dev->read_subdev=s; */
/* analog input subdevice */
s->type = COMEDI_SUBD_AI;
/* we support single-ended (ground) and differential */
s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_DIFF;
s->n_chan = thisboard->ai_chans;
s->maxdata = (1 << thisboard->ai_bits) - 1;
s->range_table = &range_bipolar10;
s->len_chanlist = 16; /* This is the maximum chanlist length that
the board can handle */
s->insn_read = skel_ai_rinsn;
/*
* s->subdev_flags |= SDF_CMD_READ;
* s->do_cmd = skel_ai_cmd;
*/
s->do_cmdtest = skel_ai_cmdtest;
s = dev->subdevices + 1;
/* analog output subdevice */
s->type = COMEDI_SUBD_AO;
s->subdev_flags = SDF_WRITABLE;
s->n_chan = 1;
s->maxdata = 0xffff;
s->range_table = &range_bipolar5;
s->insn_write = skel_ao_winsn;
s->insn_read = skel_ao_rinsn;
s = dev->subdevices + 2;
/* digital i/o subdevice */
if (thisboard->have_dio) {
s->type = COMEDI_SUBD_DIO;
s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
s->n_chan = 16;
s->maxdata = 1;
s->range_table = &range_digital;
s->insn_bits = skel_dio_insn_bits;
s->insn_config = skel_dio_insn_config;
} else {
s->type = COMEDI_SUBD_UNUSED;
}
pr_info("attached\n");
return 0;
}
/*
* _detach is called to deconfigure a device. It should deallocate
* resources.
* This function is also called when _attach() fails, so it should be
* careful not to release resources that were not necessarily
* allocated by _attach(). dev->private and dev->subdevices are
* deallocated automatically by the core.
*/
static void skel_detach(struct comedi_device *dev)
{
}
/*
* "instructions" read/write data in "one-shot" or "software-triggered"
* mode.
*/
static int skel_ai_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int n, i;
unsigned int d;
unsigned int status;
/* a typical programming sequence */
/* write channel to multiplexer */
/* outw(chan,dev->iobase + SKEL_MUX); */
/* don't wait for mux to settle */
/* convert n samples */
for (n = 0; n < insn->n; n++) {
/* trigger conversion */
/* outw(0,dev->iobase + SKEL_CONVERT); */
#define TIMEOUT 100
/* wait for conversion to end */
for (i = 0; i < TIMEOUT; i++) {
status = 1;
/* status = inb(dev->iobase + SKEL_STATUS); */
if (status)
break;
}
if (i == TIMEOUT) {
/* printk() should be used instead of printk()
* whenever the code can be called from real-time. */
pr_info("timeout\n");
return -ETIMEDOUT;
}
/* read data */
/* d = inw(dev->iobase + SKEL_AI_DATA); */
d = 0;
/* mangle the data as necessary */
d ^= 1 << (thisboard->ai_bits - 1);
data[n] = d;
}
/* return the number of samples read/written */
return n;
}
static int skel_ai_cmdtest(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_cmd *cmd)
{
int err = 0;
int tmp;
/* cmdtest tests a particular command to see if it is valid.
* Using the cmdtest ioctl, a user can create a valid cmd
* and then have it executes by the cmd ioctl.
*
* cmdtest returns 1,2,3,4 or 0, depending on which tests
* the command passes. */
/* step 1: make sure trigger sources are trivially valid */
tmp = cmd->start_src;
cmd->start_src &= TRIG_NOW;
if (!cmd->start_src || tmp != cmd->start_src)
err++;
tmp = cmd->scan_begin_src;
cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
err++;
tmp = cmd->convert_src;
cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
if (!cmd->convert_src || tmp != cmd->convert_src)
err++;
tmp = cmd->scan_end_src;
cmd->scan_end_src &= TRIG_COUNT;
if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
err++;
tmp = cmd->stop_src;
cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
if (!cmd->stop_src || tmp != cmd->stop_src)
err++;
if (err)
return 1;
/* step 2: make sure trigger sources are unique and mutually compatible
*/
/* note that mutual compatibility is not an issue here */
if (cmd->scan_begin_src != TRIG_TIMER &&
cmd->scan_begin_src != TRIG_EXT)
err++;
if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
err++;
if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
err++;
if (err)
return 2;
/* step 3: make sure arguments are trivially compatible */
if (cmd->start_arg != 0) {
cmd->start_arg = 0;
err++;
}
#define MAX_SPEED 10000 /* in nanoseconds */
#define MIN_SPEED 1000000000 /* in nanoseconds */
if (cmd->scan_begin_src == TRIG_TIMER) {
if (cmd->scan_begin_arg < MAX_SPEED) {
cmd->scan_begin_arg = MAX_SPEED;
err++;
}
if (cmd->scan_begin_arg > MIN_SPEED) {
cmd->scan_begin_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* should be level/edge, hi/lo specification here */
/* should specify multiple external triggers */
if (cmd->scan_begin_arg > 9) {
cmd->scan_begin_arg = 9;
err++;
}
}
if (cmd->convert_src == TRIG_TIMER) {
if (cmd->convert_arg < MAX_SPEED) {
cmd->convert_arg = MAX_SPEED;
err++;
}
if (cmd->convert_arg > MIN_SPEED) {
cmd->convert_arg = MIN_SPEED;
err++;
}
} else {
/* external trigger */
/* see above */
if (cmd->convert_arg > 9) {
cmd->convert_arg = 9;
err++;
}
}
if (cmd->scan_end_arg != cmd->chanlist_len) {
cmd->scan_end_arg = cmd->chanlist_len;
err++;
}
if (cmd->stop_src == TRIG_COUNT) {
if (cmd->stop_arg > 0x00ffffff) {
cmd->stop_arg = 0x00ffffff;
err++;
}
} else {
/* TRIG_NONE */
if (cmd->stop_arg != 0) {
cmd->stop_arg = 0;
err++;
}
}
if (err)
return 3;
/* step 4: fix up any arguments */
if (cmd->scan_begin_src == TRIG_TIMER) {
tmp = cmd->scan_begin_arg;
skel_ns_to_timer(&cmd->scan_begin_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->scan_begin_arg)
err++;
}
if (cmd->convert_src == TRIG_TIMER) {
tmp = cmd->convert_arg;
skel_ns_to_timer(&cmd->convert_arg,
cmd->flags & TRIG_ROUND_MASK);
if (tmp != cmd->convert_arg)
err++;
if (cmd->scan_begin_src == TRIG_TIMER &&
cmd->scan_begin_arg <
cmd->convert_arg * cmd->scan_end_arg) {
cmd->scan_begin_arg =
cmd->convert_arg * cmd->scan_end_arg;
err++;
}
}
if (err)
return 4;
return 0;
}
/* This function doesn't require a particular form, this is just
* what happens to be used in some of the drivers. It should
* convert ns nanoseconds to a counter value suitable for programming
* the device. Also, it should adjust ns so that it cooresponds to
* the actual time that the device will use. */
static int skel_ns_to_timer(unsigned int *ns, int round)
{
/* trivial timer */
/* if your timing is done through two cascaded timers, the
* i8253_cascade_ns_to_timer() function in 8253.h can be
* very helpful. There are also i8254_load() and i8254_mm_load()
* which can be used to load values into the ubiquitous 8254 counters
*/
return *ns;
}
static int skel_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan = CR_CHAN(insn->chanspec);
pr_info("skel_ao_winsn\n");
/* Writing a list of values to an AO channel is probably not
* very useful, but that's how the interface is defined. */
for (i = 0; i < insn->n; i++) {
/* a typical programming sequence */
/* outw(data[i],dev->iobase + SKEL_DA0 + chan); */
devpriv->ao_readback[chan] = data[i];
}
/* return the number of samples read/written */
return i;
}
/* AO subdevices should have a read insn as well as a write insn.
* Usually this means copying a value stored in devpriv. */
static int skel_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int i;
int chan = CR_CHAN(insn->chanspec);
for (i = 0; i < insn->n; i++)
data[i] = devpriv->ao_readback[chan];
return i;
}
/* DIO devices are slightly special. Although it is possible to
* implement the insn_read/insn_write interface, it is much more
* useful to applications if you implement the insn_bits interface.
* This allows packed reading/writing of the DIO channels. The
* comedi core can convert between insn_bits and insn_read/write */
static int skel_dio_insn_bits(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
if (insn->n != 2)
return -EINVAL;
/* The insn data is a mask in data[0] and the new data
* in data[1], each channel cooresponding to a bit. */
if (data[0]) {
s->state &= ~data[0];
s->state |= data[0] & data[1];
/* Write out the new digital output lines */
/* outw(s->state,dev->iobase + SKEL_DIO); */
}
/* on return, data[1] contains the value of the digital
* input and output lines. */
/* data[1]=inw(dev->iobase + SKEL_DIO); */
/* or we could just return the software copy of the output values if
* it was a purely digital output subdevice */
/* data[1]=s->state; */
return 2;
}
static int skel_dio_insn_config(struct comedi_device *dev,
struct comedi_subdevice *s,
struct comedi_insn *insn, unsigned int *data)
{
int chan = CR_CHAN(insn->chanspec);
/* The input or output configuration of each digital line is
* configured by a special insn_config instruction. chanspec
* contains the channel to be changed, and data[0] contains the
* value COMEDI_INPUT or COMEDI_OUTPUT. */
switch (data[0]) {
case INSN_CONFIG_DIO_OUTPUT:
s->io_bits |= 1 << chan;
break;
case INSN_CONFIG_DIO_INPUT:
s->io_bits &= ~(1 << chan);
break;
case INSN_CONFIG_DIO_QUERY:
data[1] =
(s->io_bits & (1 << chan)) ? COMEDI_OUTPUT : COMEDI_INPUT;
return insn->n;
break;
default:
return -EINVAL;
break;
}
/* outw(s->io_bits,dev->iobase + SKEL_DIO_CONFIG); */
return insn->n;
}
#ifdef CONFIG_COMEDI_PCI
static int __devinit driver_skel_pci_probe(struct pci_dev *dev,
const struct pci_device_id *ent)
{
return comedi_pci_auto_config(dev, &driver_skel);
}
static void __devexit driver_skel_pci_remove(struct pci_dev *dev)
{
comedi_pci_auto_unconfig(dev);
}
static struct pci_driver driver_skel_pci_driver = {
.id_table = skel_pci_table,
.probe = &driver_skel_pci_probe,
.remove = __devexit_p(&driver_skel_pci_remove)
};
static int __init driver_skel_init_module(void)
{
int retval;
retval = comedi_driver_register(&driver_skel);
if (retval < 0)
return retval;
driver_skel_pci_driver.name = (char *)driver_skel.driver_name;
return pci_register_driver(&driver_skel_pci_driver);
}
static void __exit driver_skel_cleanup_module(void)
{
pci_unregister_driver(&driver_skel_pci_driver);
comedi_driver_unregister(&driver_skel);
}
module_init(driver_skel_init_module);
module_exit(driver_skel_cleanup_module);
#else
static int __init driver_skel_init_module(void)
{
return comedi_driver_register(&driver_skel);
}
static void __exit driver_skel_cleanup_module(void)
{
comedi_driver_unregister(&driver_skel);
}
module_init(driver_skel_init_module);
module_exit(driver_skel_cleanup_module);
#endif
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
is00hcw/fastsocket | kernel/drivers/staging/otus/wwrap.c | 562 | 31567 | /*
* Copyright (c) 2007-2008 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/* Module Name : wwrap.c */
/* Abstract */
/* This module contains wrapper functions. */
/* */
/* NOTES */
/* Platform dependent. */
/* */
/* Please include your header files here */
#include "oal_dt.h"
#include "usbdrv.h"
#include <linux/netlink.h>
#include <net/iw_handler.h>
extern void zfiRecv80211(zdev_t* dev, zbuf_t* buf, struct zsAdditionInfo* addInfo);
extern void zfCoreRecv(zdev_t* dev, zbuf_t* buf, struct zsAdditionInfo* addInfo);
extern void zfIdlChkRsp(zdev_t* dev, u32_t* rsp, u16_t rspLen);
extern void zfIdlRsp(zdev_t* dev, u32_t *rsp, u16_t rspLen);
//extern struct zsWdsStruct wds[ZM_WDS_PORT_NUMBER];
extern struct zsVapStruct vap[ZM_VAP_PORT_NUMBER];
u32_t zfLnxUsbSubmitTxData(zdev_t* dev);
u32_t zfLnxUsbIn(zdev_t* dev, urb_t *urb, zbuf_t *buf);
u32_t zfLnxSubmitRegInUrb(zdev_t *dev);
u32_t zfLnxUsbSubmitBulkUrb(urb_t *urb, struct usb_device *usb, u16_t epnum, u16_t direction,
void *transfer_buffer, int buffer_length, usb_complete_t complete, void *context);
u32_t zfLnxUsbSubmitIntUrb(urb_t *urb, struct usb_device *usb, u16_t epnum, u16_t direction,
void *transfer_buffer, int buffer_length, usb_complete_t complete, void *context,
u32_t interval);
u16_t zfLnxGetFreeTxUrb(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t idx;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
//idx = ((macp->TxUrbTail + 1) & (ZM_MAX_TX_URB_NUM - 1));
//if (idx != macp->TxUrbHead)
if (macp->TxUrbCnt != 0)
{
idx = macp->TxUrbTail;
macp->TxUrbTail = ((macp->TxUrbTail + 1) & (ZM_MAX_TX_URB_NUM - 1));
macp->TxUrbCnt--;
}
else
{
//printk(KERN_ERR "macp->TxUrbCnt: %d\n", macp->TxUrbCnt);
idx = 0xffff;
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return idx;
}
void zfLnxPutTxUrb(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t idx;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
idx = ((macp->TxUrbHead + 1) & (ZM_MAX_TX_URB_NUM - 1));
//if (idx != macp->TxUrbTail)
if (macp->TxUrbCnt < ZM_MAX_TX_URB_NUM)
{
macp->TxUrbHead = idx;
macp->TxUrbCnt++;
}
else
{
printk("UsbTxUrbQ inconsistent: TxUrbHead: %d, TxUrbTail: %d\n",
macp->TxUrbHead, macp->TxUrbTail);
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
}
u16_t zfLnxCheckTxBufferCnt(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t TxBufCnt;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
TxBufCnt = macp->TxBufCnt;
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return TxBufCnt;
}
UsbTxQ_t *zfLnxGetUsbTxBuffer(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t idx;
UsbTxQ_t *TxQ;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
idx = ((macp->TxBufHead+1) & (ZM_MAX_TX_BUF_NUM - 1));
//if (idx != macp->TxBufTail)
if (macp->TxBufCnt > 0)
{
//printk("CWY - zfwGetUsbTxBuffer ,macp->TxBufCnt = %d\n", macp->TxBufCnt);
TxQ = (UsbTxQ_t *)&(macp->UsbTxBufQ[macp->TxBufHead]);
macp->TxBufHead = ((macp->TxBufHead+1) & (ZM_MAX_TX_BUF_NUM - 1));
macp->TxBufCnt--;
}
else
{
if (macp->TxBufHead != macp->TxBufTail)
{
printk(KERN_ERR "zfwGetUsbTxBuf UsbTxBufQ inconsistent: TxBufHead: %d, TxBufTail: %d\n",
macp->TxBufHead, macp->TxBufTail);
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return NULL;
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return TxQ;
}
u16_t zfLnxPutUsbTxBuffer(zdev_t *dev, u8_t *hdr, u16_t hdrlen,
u8_t *snap, u16_t snapLen, u8_t *tail, u16_t tailLen,
zbuf_t *buf, u16_t offset)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t idx;
UsbTxQ_t *TxQ;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
idx = ((macp->TxBufTail+1) & (ZM_MAX_TX_BUF_NUM - 1));
/* For Tx debug */
//zm_assert(macp->TxBufCnt >= 0); // deleted because of always true
//if (idx != macp->TxBufHead)
if (macp->TxBufCnt < ZM_MAX_TX_BUF_NUM)
{
//printk("CWY - zfwPutUsbTxBuffer ,macp->TxBufCnt = %d\n", macp->TxBufCnt);
TxQ = (UsbTxQ_t *)&(macp->UsbTxBufQ[macp->TxBufTail]);
memcpy(TxQ->hdr, hdr, hdrlen);
TxQ->hdrlen = hdrlen;
memcpy(TxQ->snap, snap, snapLen);
TxQ->snapLen = snapLen;
memcpy(TxQ->tail, tail, tailLen);
TxQ->tailLen = tailLen;
TxQ->buf = buf;
TxQ->offset = offset;
macp->TxBufTail = ((macp->TxBufTail+1) & (ZM_MAX_TX_BUF_NUM - 1));
macp->TxBufCnt++;
}
else
{
printk(KERN_ERR "zfLnxPutUsbTxBuffer UsbTxBufQ inconsistent: TxBufHead: %d, TxBufTail: %d, TxBufCnt: %d\n",
macp->TxBufHead, macp->TxBufTail, macp->TxBufCnt);
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return 0xffff;
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return 0;
}
zbuf_t *zfLnxGetUsbRxBuffer(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
//u16_t idx;
zbuf_t *buf;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
//idx = ((macp->RxBufHead+1) & (ZM_MAX_RX_URB_NUM - 1));
//if (idx != macp->RxBufTail)
if (macp->RxBufCnt != 0)
{
buf = macp->UsbRxBufQ[macp->RxBufHead];
macp->RxBufHead = ((macp->RxBufHead+1) & (ZM_MAX_RX_URB_NUM - 1));
macp->RxBufCnt--;
}
else
{
printk("RxBufQ inconsistent: RxBufHead: %d, RxBufTail: %d\n",
macp->RxBufHead, macp->RxBufTail);
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return NULL;
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return buf;
}
u32_t zfLnxPutUsbRxBuffer(zdev_t *dev, zbuf_t *buf)
{
struct usbdrv_private *macp = dev->ml_priv;
u16_t idx;
unsigned long irqFlag;
spin_lock_irqsave(&macp->cs_lock, irqFlag);
idx = ((macp->RxBufTail+1) & (ZM_MAX_RX_URB_NUM - 1));
//if (idx != macp->RxBufHead)
if (macp->RxBufCnt != ZM_MAX_RX_URB_NUM)
{
macp->UsbRxBufQ[macp->RxBufTail] = buf;
macp->RxBufTail = idx;
macp->RxBufCnt++;
}
else
{
printk("RxBufQ inconsistent: RxBufHead: %d, RxBufTail: %d\n",
macp->RxBufHead, macp->RxBufTail);
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return 0xffff;
}
spin_unlock_irqrestore(&macp->cs_lock, irqFlag);
return 0;
}
void zfLnxUsbDataOut_callback(urb_t *urb)
{
zdev_t* dev = urb->context;
//UsbTxQ_t *TxData;
/* Give the urb back */
zfLnxPutTxUrb(dev);
/* Check whether there is any pending buffer needed */
/* to be sent */
if (zfLnxCheckTxBufferCnt(dev) != 0)
{
//TxData = zfwGetUsbTxBuffer(dev);
//if (TxData == NULL)
//{
// printk("Get a NULL buffer from zfwGetUsbTxBuffer\n");
// return;
//}
//else
//{
zfLnxUsbSubmitTxData(dev);
//}
}
}
void zfLnxUsbDataIn_callback(urb_t *urb)
{
zdev_t* dev = urb->context;
struct usbdrv_private *macp = dev->ml_priv;
zbuf_t *buf;
zbuf_t *new_buf;
int status;
#if ZM_USB_STREAM_MODE == 1
static int remain_len = 0, check_pad = 0, check_len = 0;
int index = 0;
int chk_idx;
u16_t pkt_len;
u16_t pkt_tag;
u16_t ii;
zbuf_t *rxBufPool[8];
u16_t rxBufPoolIndex = 0;
#endif
/* Check status for URB */
if (urb->status != 0){
printk("zfLnxUsbDataIn_callback() : status=0x%x\n", urb->status);
if ((urb->status != -ENOENT) && (urb->status != -ECONNRESET)
&& (urb->status != -ESHUTDOWN))
{
if (urb->status == -EPIPE){
//printk(KERN_ERR "nonzero read bulk status received: -EPIPE");
status = -1;
}
if (urb->status == -EPROTO){
//printk(KERN_ERR "nonzero read bulk status received: -EPROTO");
status = -1;
}
}
//printk(KERN_ERR "urb->status: 0x%08x\n", urb->status);
/* Dequeue skb buffer */
buf = zfLnxGetUsbRxBuffer(dev);
dev_kfree_skb_any(buf);
#if 0
/* Enqueue skb buffer */
zfLnxPutUsbRxBuffer(dev, buf);
/* Submit a Rx urb */
zfLnxUsbIn(dev, urb, buf);
#endif
return;
}
if (urb->actual_length == 0)
{
printk(KERN_ERR "Get an URB whose length is zero");
status = -1;
}
/* Dequeue skb buffer */
buf = zfLnxGetUsbRxBuffer(dev);
//zfwBufSetSize(dev, buf, urb->actual_length);
#ifdef NET_SKBUFF_DATA_USES_OFFSET
buf->tail = 0;
buf->len = 0;
#else
buf->tail = buf->data;
buf->len = 0;
#endif
BUG_ON((buf->tail + urb->actual_length) > buf->end);
skb_put(buf, urb->actual_length);
#if ZM_USB_STREAM_MODE == 1
if (remain_len != 0)
{
zbuf_t *remain_buf = macp->reamin_buf;
index = remain_len;
remain_len -= check_pad;
/* Copy data */
memcpy(&(remain_buf->data[check_len]), buf->data, remain_len);
check_len += remain_len;
remain_len = 0;
rxBufPool[rxBufPoolIndex++] = remain_buf;
}
while(index < urb->actual_length)
{
pkt_len = buf->data[index] + (buf->data[index+1] << 8);
pkt_tag = buf->data[index+2] + (buf->data[index+3] << 8);
if (pkt_tag == 0x4e00)
{
int pad_len;
//printk("Get a packet, index: %d, pkt_len: 0x%04x\n", index, pkt_len);
#if 0
/* Dump data */
for (ii = index; ii < pkt_len+4;)
{
printk("%02x ", (buf->data[ii] & 0xff));
if ((++ii % 16) == 0)
printk("\n");
}
printk("\n");
#endif
pad_len = 4 - (pkt_len & 0x3);
if(pad_len == 4)
pad_len = 0;
chk_idx = index;
index = index + 4 + pkt_len + pad_len;
if (index > ZM_MAX_RX_BUFFER_SIZE)
{
remain_len = index - ZM_MAX_RX_BUFFER_SIZE; // - pad_len;
check_len = ZM_MAX_RX_BUFFER_SIZE - chk_idx - 4;
check_pad = pad_len;
/* Allocate a skb buffer */
//new_buf = zfwBufAllocate(dev, ZM_MAX_RX_BUFFER_SIZE);
new_buf = dev_alloc_skb(ZM_MAX_RX_BUFFER_SIZE);
/* Set skb buffer length */
#ifdef NET_SKBUFF_DATA_USES_OFFSET
new_buf->tail = 0;
new_buf->len = 0;
#else
new_buf->tail = new_buf->data;
new_buf->len = 0;
#endif
skb_put(new_buf, pkt_len);
/* Copy the buffer */
memcpy(new_buf->data, &(buf->data[chk_idx+4]), check_len);
/* Record the buffer pointer */
macp->reamin_buf = new_buf;
}
else
{
#ifdef ZM_DONT_COPY_RX_BUFFER
if (rxBufPoolIndex == 0)
{
new_buf = skb_clone(buf, GFP_ATOMIC);
new_buf->data = &(buf->data[chk_idx+4]);
new_buf->len = pkt_len;
}
else
{
#endif
/* Allocate a skb buffer */
new_buf = dev_alloc_skb(ZM_MAX_RX_BUFFER_SIZE);
/* Set skb buffer length */
#ifdef NET_SKBUFF_DATA_USES_OFFSET
new_buf->tail = 0;
new_buf->len = 0;
#else
new_buf->tail = new_buf->data;
new_buf->len = 0;
#endif
skb_put(new_buf, pkt_len);
/* Copy the buffer */
memcpy(new_buf->data, &(buf->data[chk_idx+4]), pkt_len);
#ifdef ZM_DONT_COPY_RX_BUFFER
}
#endif
rxBufPool[rxBufPoolIndex++] = new_buf;
}
}
else
{
printk(KERN_ERR "Can't find tag, pkt_len: 0x%04x, tag: 0x%04x\n", pkt_len, pkt_tag);
/* Free buffer */
dev_kfree_skb_any(buf);
/* Allocate a skb buffer */
new_buf = dev_alloc_skb(ZM_MAX_RX_BUFFER_SIZE);
/* Enqueue skb buffer */
zfLnxPutUsbRxBuffer(dev, new_buf);
/* Submit a Rx urb */
zfLnxUsbIn(dev, urb, new_buf);
return;
}
}
/* Free buffer */
dev_kfree_skb_any(buf);
#endif
/* Allocate a skb buffer */
new_buf = dev_alloc_skb(ZM_MAX_RX_BUFFER_SIZE);
/* Enqueue skb buffer */
zfLnxPutUsbRxBuffer(dev, new_buf);
/* Submit a Rx urb */
zfLnxUsbIn(dev, urb, new_buf);
#if ZM_USB_STREAM_MODE == 1
for(ii = 0; ii < rxBufPoolIndex; ii++)
{
macp->usbCbFunctions.zfcbUsbRecv(dev, rxBufPool[ii]);
}
#else
/* pass data to upper layer */
macp->usbCbFunctions.zfcbUsbRecv(dev, buf);
#endif
}
void zfLnxUsbRegOut_callback(urb_t *urb)
{
//dev_t* dev = urb->context;
//printk(KERN_ERR "zfwUsbRegOut_callback\n");
}
void zfLnxUsbRegIn_callback(urb_t *urb)
{
zdev_t* dev = urb->context;
u32_t rsp[64/4];
int status;
struct usbdrv_private *macp = dev->ml_priv;
/* Check status for URB */
if (urb->status != 0){
printk("zfLnxUsbRegIn_callback() : status=0x%x\n", urb->status);
if ((urb->status != -ENOENT) && (urb->status != -ECONNRESET)
&& (urb->status != -ESHUTDOWN))
{
if (urb->status == -EPIPE){
//printk(KERN_ERR "nonzero read bulk status received: -EPIPE");
status = -1;
}
if (urb->status == -EPROTO){
//printk(KERN_ERR "nonzero read bulk status received: -EPROTO");
status = -1;
}
}
//printk(KERN_ERR "urb->status: 0x%08x\n", urb->status);
return;
}
if (urb->actual_length == 0)
{
printk(KERN_ERR "Get an URB whose length is zero");
status = -1;
}
/* Copy data into respone buffer */
memcpy(rsp, macp->regUsbReadBuf, urb->actual_length);
/* Notify to upper layer */
//zfIdlChkRsp(dev, rsp, (u16_t)urb->actual_length);
//zfiUsbRegIn(dev, rsp, (u16_t)urb->actual_length);
macp->usbCbFunctions.zfcbUsbRegIn(dev, rsp, (u16_t)urb->actual_length);
/* Issue another USB IN URB */
zfLnxSubmitRegInUrb(dev);
}
u32_t zfLnxSubmitRegInUrb(zdev_t *dev)
{
u32_t ret;
struct usbdrv_private *macp = dev->ml_priv;
/* Submit a rx urb */
//ret = zfLnxUsbSubmitBulkUrb(macp->RegInUrb, macp->udev,
// USB_REG_IN_PIPE, USB_DIR_IN, macp->regUsbReadBuf,
// ZM_USB_REG_MAX_BUF_SIZE, zfLnxUsbRegIn_callback, dev);
//CWYang(-)
//if (ret != 0)
// printk("zfwUsbSubmitBulkUrb fail, status: 0x%08x\n", (int)ret);
ret = zfLnxUsbSubmitIntUrb(macp->RegInUrb, macp->udev,
USB_REG_IN_PIPE, USB_DIR_IN, macp->regUsbReadBuf,
ZM_USB_REG_MAX_BUF_SIZE, zfLnxUsbRegIn_callback, dev, 1);
return ret;
}
u32_t zfLnxUsbSubmitTxData(zdev_t* dev)
{
u32_t i;
u32_t ret;
u16_t freeTxUrb;
u8_t *puTxBuf = NULL;
UsbTxQ_t *TxData;
int len = 0;
struct usbdrv_private *macp = dev->ml_priv;
#if ZM_USB_TX_STREAM_MODE == 1
u8_t ii;
u16_t offset = 0;
u16_t usbTxAggCnt;
u16_t *pUsbTxHdr;
UsbTxQ_t *TxQPool[ZM_MAX_TX_AGGREGATE_NUM];
#endif
/* First check whether there is a free URB */
freeTxUrb = zfLnxGetFreeTxUrb(dev);
/* If there is no any free Tx Urb */
if (freeTxUrb == 0xffff)
{
//printk(KERN_ERR "Can't get free Tx Urb\n");
//printk("CWY - Can't get free Tx Urb\n");
return 0xffff;
}
#if ZM_USB_TX_STREAM_MODE == 1
usbTxAggCnt = zfLnxCheckTxBufferCnt(dev);
if (usbTxAggCnt >= ZM_MAX_TX_AGGREGATE_NUM)
{
usbTxAggCnt = ZM_MAX_TX_AGGREGATE_NUM;
}
else
{
usbTxAggCnt = 1;
}
//printk("usbTxAggCnt: %d\n", usbTxAggCnt);
#endif
#if ZM_USB_TX_STREAM_MODE == 1
for(ii = 0; ii < usbTxAggCnt; ii++)
{
#endif
/* Dequeue the packet from UsbTxBufQ */
TxData = zfLnxGetUsbTxBuffer(dev);
if (TxData == NULL)
{
/* Give the urb back */
zfLnxPutTxUrb(dev);
return 0xffff;
}
/* Point to the freeTxUrb buffer */
puTxBuf = macp->txUsbBuf[freeTxUrb];
#if ZM_USB_TX_STREAM_MODE == 1
puTxBuf += offset;
pUsbTxHdr = (u16_t *)puTxBuf;
/* Add the packet length and tag information */
*pUsbTxHdr++ = TxData->hdrlen + TxData->snapLen +
(TxData->buf->len - TxData->offset) + TxData->tailLen;
*pUsbTxHdr++ = 0x697e;
puTxBuf += 4;
#endif // #ifdef ZM_USB_TX_STREAM_MODE
/* Copy WLAN header and packet buffer into USB buffer */
for(i = 0; i < TxData->hdrlen; i++)
{
*puTxBuf++ = TxData->hdr[i];
}
/* Copy SNAP header */
for(i = 0; i < TxData->snapLen; i++)
{
*puTxBuf++ = TxData->snap[i];
}
/* Copy packet buffer */
for(i = 0; i < TxData->buf->len - TxData->offset; i++)
{
//*puTxBuf++ = zmw_rx_buf_readb(dev, TxData->buf, i);
*puTxBuf++ = *(u8_t*)((u8_t*)TxData->buf->data+i+TxData->offset);
}
/* Copy tail */
for(i = 0; i < TxData->tailLen; i++)
{
*puTxBuf++ = TxData->tail[i];
}
len = TxData->hdrlen+TxData->snapLen+TxData->buf->len+TxData->tailLen-TxData->offset;
#if 0
if (TxData->hdrlen != 0)
{
puTxBuf = macp->txUsbBuf[freeTxUrb];
for (i = 0; i < len; i++)
{
printk("%02x ", puTxBuf[i]);
if (i % 16 == 15)
printk("\n");
}
printk("\n");
}
#endif
#if 0
/* For debug purpose */
if(TxData->hdr[9] & 0x40)
{
int i;
u16_t ctrlLen = TxData->hdr[0] + (TxData->hdr[1] << 8);
if (ctrlLen != len + 4)
{
/* Dump control setting */
for(i = 0; i < 8; i++)
{
printk(KERN_ERR "0x%02x ", TxData->hdr[i]);
}
printk(KERN_ERR "\n");
printk(KERN_ERR "ctrLen: %d, hdrLen: %d, snapLen: %d\n", ctrlLen, TxData->hdrlen, TxData->snapLen);
printk(KERN_ERR "bufLen: %d, tailLen: %d, len: %d\n", TxData->buf->len, TxData->tailLen, len);
}
}
#endif
#if ZM_USB_TX_STREAM_MODE == 1
// Add the Length and Tag
len += 4;
//printk("%d packet, length: %d\n", ii+1, len);
if (ii < (ZM_MAX_TX_AGGREGATE_NUM-1))
{
/* Pad the buffer to firmware descriptor boundary */
offset += (((len-1) / 4) + 1) * 4;
}
if (ii == (ZM_MAX_TX_AGGREGATE_NUM-1))
{
len += offset;
}
TxQPool[ii] = TxData;
//DbgPrint("%d packet, offset: %d\n", ii+1, pUsbTxTransfer->offset);
/* free packet */
//zfBufFree(dev, txData->buf);
}
#endif
//printk("CWY - call zfwUsbSubmitBulkUrb(), len = 0x%d\n", len);
/* Submit a tx urb */
ret = zfLnxUsbSubmitBulkUrb(macp->WlanTxDataUrb[freeTxUrb], macp->udev,
USB_WLAN_TX_PIPE, USB_DIR_OUT, macp->txUsbBuf[freeTxUrb],
len, zfLnxUsbDataOut_callback, dev);
//CWYang(-)
//if (ret != 0)
// printk("zfwUsbSubmitBulkUrb fail, status: 0x%08x\n", (int)ret);
/* free packet */
//dev_kfree_skb_any(TxData->buf);
#if ZM_USB_TX_STREAM_MODE == 1
for(ii = 0; ii < usbTxAggCnt; ii++)
macp->usbCbFunctions.zfcbUsbOutComplete(dev, TxQPool[ii]->buf, 1, TxQPool[ii]->hdr);
#else
macp->usbCbFunctions.zfcbUsbOutComplete(dev, TxData->buf, 1, TxData->hdr);
#endif
return ret;
}
u32_t zfLnxUsbIn(zdev_t* dev, urb_t *urb, zbuf_t *buf)
{
u32_t ret;
struct usbdrv_private *macp = dev->ml_priv;
/* Submit a rx urb */
ret = zfLnxUsbSubmitBulkUrb(urb, macp->udev, USB_WLAN_RX_PIPE,
USB_DIR_IN, buf->data, ZM_MAX_RX_BUFFER_SIZE,
zfLnxUsbDataIn_callback, dev);
//CWYang(-)
//if (ret != 0)
// printk("zfwUsbSubmitBulkUrb fail, status: 0x%08x\n", (int)ret);
return ret;
}
u32_t zfLnxUsbWriteReg(zdev_t* dev, u32_t* cmd, u16_t cmdLen)
{
struct usbdrv_private *macp = dev->ml_priv;
u32_t ret;
#ifdef ZM_CONFIG_BIG_ENDIAN
int ii = 0;
for(ii=0; ii<(cmdLen>>2); ii++)
cmd[ii] = cpu_to_le32(cmd[ii]);
#endif
memcpy(macp->regUsbWriteBuf, cmd, cmdLen);
/* Issue an USB Out transfer */
/* Submit a tx urb */
ret = zfLnxUsbSubmitIntUrb(macp->RegOutUrb, macp->udev,
USB_REG_OUT_PIPE, USB_DIR_OUT, macp->regUsbWriteBuf,
cmdLen, zfLnxUsbRegOut_callback, dev, 1);
return ret;
}
u32_t zfLnxUsbOut(zdev_t* dev, u8_t *hdr, u16_t hdrlen, u8_t *snap, u16_t snapLen,
u8_t *tail, u16_t tailLen, zbuf_t *buf, u16_t offset)
{
u32_t ret;
struct usbdrv_private *macp = dev->ml_priv;
/* Check length of tail buffer */
//zm_assert((tailLen <= 16));
/* Enqueue the packet into UsbTxBufQ */
if (zfLnxPutUsbTxBuffer(dev, hdr, hdrlen, snap, snapLen, tail, tailLen, buf, offset) == 0xffff)
{
/* free packet */
//printk("CWY - zfwPutUsbTxBuffer Error, free packet\n");
//dev_kfree_skb_any(buf);
macp->usbCbFunctions.zfcbUsbOutComplete(dev, buf, 0, hdr);
return 0xffff;
}
//return 0;
//printk("CWY - call zfwUsbSubmitTxData()\n");
ret = zfLnxUsbSubmitTxData(dev);
return ret;
}
void zfLnxInitUsbTxQ(zdev_t* dev)
{
struct usbdrv_private *macp = dev->ml_priv;
printk(KERN_ERR "zfwInitUsbTxQ\n");
/* Zero memory for UsbTxBufQ */
memset(macp->UsbTxBufQ, 0, sizeof(UsbTxQ_t) * ZM_MAX_TX_URB_NUM);
macp->TxBufHead = 0;
macp->TxBufTail = 0;
macp->TxUrbHead = 0;
macp->TxUrbTail = 0;
macp->TxUrbCnt = ZM_MAX_TX_URB_NUM;
}
void zfLnxInitUsbRxQ(zdev_t* dev)
{
u16_t i;
zbuf_t *buf;
struct usbdrv_private *macp = dev->ml_priv;
/* Zero memory for UsbRxBufQ */
memset(macp->UsbRxBufQ, 0, sizeof(zbuf_t *) * ZM_MAX_RX_URB_NUM);
macp->RxBufHead = 0;
for (i = 0; i < ZM_MAX_RX_URB_NUM; i++)
{
//buf = zfwBufAllocate(dev, ZM_MAX_RX_BUFFER_SIZE);
buf = dev_alloc_skb(ZM_MAX_RX_BUFFER_SIZE);
macp->UsbRxBufQ[i] = buf;
}
//macp->RxBufTail = ZM_MAX_RX_URB_NUM - 1;
macp->RxBufTail = 0;
/* Submit all Rx urbs */
for (i = 0; i < ZM_MAX_RX_URB_NUM; i++)
{
zfLnxPutUsbRxBuffer(dev, macp->UsbRxBufQ[i]);
zfLnxUsbIn(dev, macp->WlanRxDataUrb[i], macp->UsbRxBufQ[i]);
}
}
u32_t zfLnxUsbSubmitBulkUrb(urb_t *urb, struct usb_device *usb, u16_t epnum, u16_t direction,
void *transfer_buffer, int buffer_length, usb_complete_t complete, void *context)
{
u32_t ret;
if(direction == USB_DIR_OUT)
{
usb_fill_bulk_urb(urb, usb, usb_sndbulkpipe(usb, epnum),
transfer_buffer, buffer_length, complete, context);
urb->transfer_flags |= URB_ZERO_PACKET;
}
else
{
usb_fill_bulk_urb(urb, usb, usb_rcvbulkpipe(usb, epnum),
transfer_buffer, buffer_length, complete, context);
}
if (epnum == 4)
{
if (urb->hcpriv)
{
//printk("CWY - urb->hcpriv set by unknown reason, reset it\n");
//urb->hcpriv = 0;
}
}
ret = usb_submit_urb(urb, GFP_ATOMIC);
if ((epnum == 4) & (ret != 0))
{
//printk("CWY - ret = %x\n", ret);
}
return ret;
}
u32_t zfLnxUsbSubmitIntUrb(urb_t *urb, struct usb_device *usb, u16_t epnum, u16_t direction,
void *transfer_buffer, int buffer_length, usb_complete_t complete, void *context,
u32_t interval)
{
u32_t ret;
if(direction == USB_DIR_OUT)
{
usb_fill_int_urb(urb, usb, usb_sndbulkpipe(usb, epnum),
transfer_buffer, buffer_length, complete, context, interval);
}
else
{
usb_fill_int_urb(urb, usb, usb_rcvbulkpipe(usb, epnum),
transfer_buffer, buffer_length, complete, context, interval);
}
ret = usb_submit_urb(urb, GFP_ATOMIC);
return ret;
}
#ifdef ZM_ENABLE_CENC
int zfLnxCencSendMsg(struct sock *netlink_sk, u_int8_t *msg, int len)
{
#define COMMTYPE_GROUP 8
#define WAI_K_MSG 0x11
int ret = -1;
int size;
unsigned char *old_tail;
struct sk_buff *skb;
struct nlmsghdr *nlh;
char *pos = NULL;
size = NLMSG_SPACE(len);
skb = alloc_skb(size, GFP_ATOMIC);
if(skb == NULL)
{
printk("dev_alloc_skb failure \n");
goto out;
}
old_tail = skb->tail;
/*ÌîдÊý¾Ý±¨Ïà¹ØÐÅÏ¢*/
nlh = NLMSG_PUT(skb, 0, 0, WAI_K_MSG, size-sizeof(*nlh));
pos = NLMSG_DATA(nlh);
memset(pos, 0, len);
/*´«Êäµ½Óû§¿Õ¼äµÄÊý¾Ý*/
memcpy(pos, msg, len);
/*¼ÆËã¾¹ý×Ö½Ú¶ÔÆäºóµÄÊý¾Ýʵ¼Ê³¤¶È*/
nlh->nlmsg_len = skb->tail - old_tail;
NETLINK_CB(skb).dst_group = COMMTYPE_GROUP;
netlink_broadcast(netlink_sk, skb, 0, COMMTYPE_GROUP, GFP_ATOMIC);
ret = 0;
out:
return ret;
nlmsg_failure: /*NLMSG_PUT ʧ°Ü£¬Ôò³·ÏúÌ×½Ó×Ö»º´æ*/
kfree_skb(skb);
goto out;
#undef COMMTYPE_GROUP
#undef WAI_K_MSG
}
#endif //ZM_ENABLE_CENC
/* Simply return 0xffff if VAP function is not supported */
u16_t zfLnxGetVapId(zdev_t* dev)
{
u16_t i;
for (i=0; i<ZM_VAP_PORT_NUMBER; i++)
{
if (vap[i].dev == dev)
{
return i;
}
}
return 0xffff;
}
u32_t zfwReadReg(zdev_t* dev, u32_t offset)
{
return 0;
}
#ifndef INIT_WORK
#define work_struct tq_struct
#define schedule_work(a) schedule_task(a)
#define flush_scheduled_work flush_scheduled_tasks
#define INIT_WORK(_wq, _routine, _data) INIT_TQUEUE(_wq, _routine, _data)
#define PREPARE_WORK(_wq, _routine, _data) PREPARE_TQUEUE(_wq, _routine, _data)
#endif
#define KEVENT_WATCHDOG 0x00000001
u32_t smp_kevent_Lock = 0;
void kevent(struct work_struct *work)
{
struct usbdrv_private *macp =
container_of(work, struct usbdrv_private, kevent);
zdev_t *dev = macp->device;
if (test_and_set_bit(0, (void *)&smp_kevent_Lock))
{
//schedule_work(&macp->kevent);
return;
}
down(&macp->ioctl_sem);
if (test_and_clear_bit(KEVENT_WATCHDOG, &macp->kevent_flags))
{
extern u16_t zfHpStartRecv(zdev_t *dev);
//zfiHwWatchDogReinit(dev);
printk(("\n ************ Hw watchDog occur!! ************** \n"));
zfiWlanSuspend(dev);
zfiWlanResume(dev,0);
zfHpStartRecv(dev);
}
clear_bit(0, (void *)&smp_kevent_Lock);
up(&macp->ioctl_sem);
}
/************************************************************************/
/* */
/* FUNCTION DESCRIPTION zfLnxCreateThread */
/* Create a Thread */
/* */
/* INPUTS */
/* dev : device pointer */
/* */
/* OUTPUTS */
/* always 0 */
/* */
/* AUTHOR */
/* Yuan-Gu Wei Atheros Communications, INC. 2007.3 */
/* */
/************************************************************************/
u8_t zfLnxCreateThread(zdev_t *dev)
{
struct usbdrv_private *macp = dev->ml_priv;
/* Create Mutex and keventd */
INIT_WORK(&macp->kevent, kevent);
init_MUTEX(&macp->ioctl_sem);
return 0;
}
/************************************************************************/
/* */
/* FUNCTION DESCRIPTION zfLnxSignalThread */
/* Signal Thread with Flag */
/* */
/* INPUTS */
/* dev : device pointer */
/* flag : signal thread flag */
/* */
/* OUTPUTS */
/* none */
/* */
/* AUTHOR */
/* Yuan-Gu Wei Atheros Communications, INC. 2007.3 */
/* */
/************************************************************************/
void zfLnxSignalThread(zdev_t *dev, int flag)
{
struct usbdrv_private *macp = dev->ml_priv;
if (macp == NULL)
{
printk("macp is NULL\n");
return;
}
if (0 && macp->kevent_ready != 1)
{
printk("Kevent not ready\n");
return;
}
set_bit(flag, &macp->kevent_flags);
if (!schedule_work(&macp->kevent))
{
//Fails is Normal
//printk(KERN_ERR "schedule_task failed, flag = %x\n", flag);
}
}
/* Notify wrapper todo redownload firmware and reinit procedure when */
/* hardware watchdog occur : zfiHwWatchDogReinit() */
void zfLnxWatchDogNotify(zdev_t* dev)
{
zfLnxSignalThread(dev, KEVENT_WATCHDOG);
}
/* Query Durantion of Active Scan */
void zfwGetActiveScanDur(zdev_t* dev, u8_t* Dur)
{
*Dur = 30; // default 30 ms
}
void zfwGetShowZeroLengthSSID(zdev_t* dev, u8_t* Dur)
{
*Dur = 0;
}
| gpl-2.0 |
sktjdgns1189/android_kernel_lge_f180k | arch/arm/mach-msm/board-mahimahi-panel.c | 3634 | 22498 | /* linux/arch/arm/mach-msm/board-mahimahi-panel.c
*
* Copyright (c) 2009 Google Inc.
* Author: Dima Zavin <dima@android.com>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/gpio.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/leds.h>
#include <linux/platform_device.h>
#include <linux/workqueue.h>
#include <asm/io.h>
#include <asm/mach-types.h>
#include <mach/msm_fb.h>
#include <mach/msm_iomap.h>
#include <mach/vreg.h>
#include <mach/proc_comm.h>
#include "board-mahimahi.h"
#include "devices.h"
#define SPI_CONFIG (0x00000000)
#define SPI_IO_CONTROL (0x00000004)
#define SPI_OPERATIONAL (0x00000030)
#define SPI_ERROR_FLAGS_EN (0x00000038)
#define SPI_ERROR_FLAGS (0x00000038)
#define SPI_OUTPUT_FIFO (0x00000100)
static void __iomem *spi_base;
static struct clk *spi_clk ;
static struct vreg *vreg_lcm_rftx_2v6;
static struct vreg *vreg_lcm_aux_2v6;
static int qspi_send(uint32_t id, uint8_t data)
{
uint32_t err;
/* bit-5: OUTPUT_FIFO_NOT_EMPTY */
while (readl(spi_base + SPI_OPERATIONAL) & (1<<5)) {
if ((err = readl(spi_base + SPI_ERROR_FLAGS))) {
pr_err("%s: ERROR: SPI_ERROR_FLAGS=0x%08x\n", __func__,
err);
return -EIO;
}
}
writel((0x7000 | (id << 9) | data) << 16, spi_base + SPI_OUTPUT_FIFO);
udelay(100);
return 0;
}
static int qspi_send_9bit(uint32_t id, uint8_t data)
{
uint32_t err;
while (readl(spi_base + SPI_OPERATIONAL) & (1<<5)) {
err = readl(spi_base + SPI_ERROR_FLAGS);
if (err) {
pr_err("%s: ERROR: SPI_ERROR_FLAGS=0x%08x\n", __func__,
err);
return -EIO;
}
}
writel(((id << 8) | data) << 23, spi_base + SPI_OUTPUT_FIFO);
udelay(100);
return 0;
}
static int lcm_writeb(uint8_t reg, uint8_t val)
{
qspi_send(0x0, reg);
qspi_send(0x1, val);
return 0;
}
static int lcm_writew(uint8_t reg, uint16_t val)
{
qspi_send(0x0, reg);
qspi_send(0x1, val >> 8);
qspi_send(0x1, val & 0xff);
return 0;
}
static struct resource resources_msm_fb[] = {
{
.start = MSM_FB_BASE,
.end = MSM_FB_BASE + MSM_FB_SIZE - 1,
.flags = IORESOURCE_MEM,
},
};
struct lcm_tbl {
uint8_t reg;
uint8_t val;
};
static struct lcm_tbl samsung_oled_rgb565_init_table[] = {
{ 0x31, 0x08 },
{ 0x32, 0x14 },
{ 0x30, 0x2 },
{ 0x27, 0x1 },
{ 0x12, 0x8 },
{ 0x13, 0x8 },
{ 0x15, 0x0 },
{ 0x16, 0x02 },
{ 0x39, 0x24 },
{ 0x17, 0x22 },
{ 0x18, 0x33 },
{ 0x19, 0x3 },
{ 0x1A, 0x1 },
{ 0x22, 0xA4 },
{ 0x23, 0x0 },
{ 0x26, 0xA0 },
};
static struct lcm_tbl samsung_oled_rgb666_init_table[] = {
{ 0x31, 0x08 },
{ 0x32, 0x14 },
{ 0x30, 0x2 },
{ 0x27, 0x1 },
{ 0x12, 0x8 },
{ 0x13, 0x8 },
{ 0x15, 0x0 },
{ 0x16, 0x01 },
{ 0x39, 0x24 },
{ 0x17, 0x22 },
{ 0x18, 0x33 },
{ 0x19, 0x3 },
{ 0x1A, 0x1 },
{ 0x22, 0xA4 },
{ 0x23, 0x0 },
{ 0x26, 0xA0 },
};
static struct lcm_tbl *init_tablep = samsung_oled_rgb565_init_table;
static size_t init_table_sz = ARRAY_SIZE(samsung_oled_rgb565_init_table);
#define OLED_GAMMA_TABLE_SIZE (7 * 3)
static struct lcm_tbl samsung_oled_gamma_table[][OLED_GAMMA_TABLE_SIZE] = {
/* level 10 */
{
/* Gamma-R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x3f },
{ 0x43, 0x35 },
{ 0x44, 0x30 },
{ 0x45, 0x2c },
{ 0x46, 0x13 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x0 },
{ 0x53, 0x0 },
{ 0x54, 0x27 },
{ 0x55, 0x2b },
{ 0x56, 0x12 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x3f },
{ 0x63, 0x34 },
{ 0x64, 0x2f },
{ 0x65, 0x2b },
{ 0x66, 0x1b },
},
/* level 40 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x3e },
{ 0x43, 0x2e },
{ 0x44, 0x2d },
{ 0x45, 0x28 },
{ 0x46, 0x21 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x0 },
{ 0x53, 0x21 },
{ 0x54, 0x2a },
{ 0x55, 0x28 },
{ 0x56, 0x20 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x3e },
{ 0x63, 0x2d },
{ 0x64, 0x2b },
{ 0x65, 0x26 },
{ 0x66, 0x2d },
},
/* level 70 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x35 },
{ 0x43, 0x2c },
{ 0x44, 0x2b },
{ 0x45, 0x26 },
{ 0x46, 0x29 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x0 },
{ 0x53, 0x25 },
{ 0x54, 0x29 },
{ 0x55, 0x26 },
{ 0x56, 0x28 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x34 },
{ 0x63, 0x2b },
{ 0x64, 0x2a },
{ 0x65, 0x23 },
{ 0x66, 0x37 },
},
/* level 100 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x30 },
{ 0x43, 0x2a },
{ 0x44, 0x2b },
{ 0x45, 0x24 },
{ 0x46, 0x2f },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x0 },
{ 0x53, 0x25 },
{ 0x54, 0x29 },
{ 0x55, 0x24 },
{ 0x56, 0x2e },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x2f },
{ 0x63, 0x29 },
{ 0x64, 0x29 },
{ 0x65, 0x21 },
{ 0x66, 0x3f },
},
/* level 130 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x2e },
{ 0x43, 0x29 },
{ 0x44, 0x2a },
{ 0x45, 0x23 },
{ 0x46, 0x34 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0xa },
{ 0x53, 0x25 },
{ 0x54, 0x28 },
{ 0x55, 0x23 },
{ 0x56, 0x33 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x2d },
{ 0x63, 0x28 },
{ 0x64, 0x27 },
{ 0x65, 0x20 },
{ 0x66, 0x46 },
},
/* level 160 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x2b },
{ 0x43, 0x29 },
{ 0x44, 0x28 },
{ 0x45, 0x23 },
{ 0x46, 0x38 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0xb },
{ 0x53, 0x25 },
{ 0x54, 0x27 },
{ 0x55, 0x23 },
{ 0x56, 0x37 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x29 },
{ 0x63, 0x28 },
{ 0x64, 0x25 },
{ 0x65, 0x20 },
{ 0x66, 0x4b },
},
/* level 190 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x29 },
{ 0x43, 0x29 },
{ 0x44, 0x27 },
{ 0x45, 0x22 },
{ 0x46, 0x3c },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x10 },
{ 0x53, 0x26 },
{ 0x54, 0x26 },
{ 0x55, 0x22 },
{ 0x56, 0x3b },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x28 },
{ 0x63, 0x28 },
{ 0x64, 0x24 },
{ 0x65, 0x1f },
{ 0x66, 0x50 },
},
/* level 220 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x28 },
{ 0x43, 0x28 },
{ 0x44, 0x28 },
{ 0x45, 0x20 },
{ 0x46, 0x40 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x11 },
{ 0x53, 0x25 },
{ 0x54, 0x27 },
{ 0x55, 0x20 },
{ 0x56, 0x3f },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x27 },
{ 0x63, 0x26 },
{ 0x64, 0x26 },
{ 0x65, 0x1c },
{ 0x66, 0x56 },
},
/* level 250 */
{
/* Gamma -R */
{ 0x40, 0x0 },
{ 0x41, 0x3f },
{ 0x42, 0x2a },
{ 0x43, 0x27 },
{ 0x44, 0x27 },
{ 0x45, 0x1f },
{ 0x46, 0x44 },
/* Gamma -G */
{ 0x50, 0x0 },
{ 0x51, 0x0 },
{ 0x52, 0x17 },
{ 0x53, 0x24 },
{ 0x54, 0x26 },
{ 0x55, 0x1f },
{ 0x56, 0x43 },
/* Gamma -B */
{ 0x60, 0x0 },
{ 0x61, 0x3f },
{ 0x62, 0x2a },
{ 0x63, 0x25 },
{ 0x64, 0x24 },
{ 0x65, 0x1b },
{ 0x66, 0x5c },
},
};
#define SAMSUNG_OLED_NUM_LEVELS ARRAY_SIZE(samsung_oled_gamma_table)
#define SAMSUNG_OLED_MIN_VAL 10
#define SAMSUNG_OLED_MAX_VAL 250
#define SAMSUNG_OLED_DEFAULT_VAL (SAMSUNG_OLED_MIN_VAL + \
(SAMSUNG_OLED_MAX_VAL - \
SAMSUNG_OLED_MIN_VAL) / 2)
#define SAMSUNG_OLED_LEVEL_STEP ((SAMSUNG_OLED_MAX_VAL - \
SAMSUNG_OLED_MIN_VAL) / \
(SAMSUNG_OLED_NUM_LEVELS - 1))
#define SONY_TFT_DEF_USER_VAL 102
#define SONY_TFT_MIN_USER_VAL 30
#define SONY_TFT_MAX_USER_VAL 255
#define SONY_TFT_DEF_PANEL_VAL 155
#define SONY_TFT_MIN_PANEL_VAL 26
#define SONY_TFT_MAX_PANEL_VAL 255
static DEFINE_MUTEX(panel_lock);
static struct work_struct brightness_delayed_work;
static DEFINE_SPINLOCK(brightness_lock);
static uint8_t new_val = SAMSUNG_OLED_DEFAULT_VAL;
static uint8_t last_val = SAMSUNG_OLED_DEFAULT_VAL;
static uint8_t table_sel_vals[] = { 0x43, 0x34 };
static int table_sel_idx = 0;
static uint8_t tft_panel_on;
static void gamma_table_bank_select(void)
{
lcm_writeb(0x39, table_sel_vals[table_sel_idx]);
table_sel_idx ^= 1;
}
static void samsung_oled_set_gamma_val(int val)
{
int i;
int level;
int frac;
val = clamp(val, SAMSUNG_OLED_MIN_VAL, SAMSUNG_OLED_MAX_VAL);
val = (val / 2) * 2;
level = (val - SAMSUNG_OLED_MIN_VAL) / SAMSUNG_OLED_LEVEL_STEP;
frac = (val - SAMSUNG_OLED_MIN_VAL) % SAMSUNG_OLED_LEVEL_STEP;
clk_enable(spi_clk);
for (i = 0; i < OLED_GAMMA_TABLE_SIZE; ++i) {
unsigned int v1;
unsigned int v2 = 0;
u8 v;
if (frac == 0) {
v = samsung_oled_gamma_table[level][i].val;
} else {
v1 = samsung_oled_gamma_table[level][i].val;
v2 = samsung_oled_gamma_table[level+1][i].val;
v = (v1 * (SAMSUNG_OLED_LEVEL_STEP - frac) +
v2 * frac) / SAMSUNG_OLED_LEVEL_STEP;
}
lcm_writeb(samsung_oled_gamma_table[level][i].reg, v);
}
gamma_table_bank_select();
clk_disable(spi_clk);
last_val = val;
}
static int samsung_oled_panel_init(struct msm_lcdc_panel_ops *ops)
{
pr_info("%s: +()\n", __func__);
mutex_lock(&panel_lock);
clk_enable(spi_clk);
/* Set the gamma write target to 4, leave the current gamma set at 2 */
lcm_writeb(0x39, 0x24);
clk_disable(spi_clk);
mutex_unlock(&panel_lock);
pr_info("%s: -()\n", __func__);
return 0;
}
static int samsung_oled_panel_unblank(struct msm_lcdc_panel_ops *ops)
{
int i;
pr_info("%s: +()\n", __func__);
mutex_lock(&panel_lock);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 1);
udelay(50);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 0);
udelay(20);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 1);
msleep(20);
clk_enable(spi_clk);
for (i = 0; i < init_table_sz; i++)
lcm_writeb(init_tablep[i].reg, init_tablep[i].val);
lcm_writew(0xef, 0xd0e8);
lcm_writeb(0x1d, 0xa0);
table_sel_idx = 0;
gamma_table_bank_select();
samsung_oled_set_gamma_val(last_val);
msleep(250);
lcm_writeb(0x14, 0x03);
clk_disable(spi_clk);
mutex_unlock(&panel_lock);
pr_info("%s: -()\n", __func__);
return 0;
}
static int samsung_oled_panel_blank(struct msm_lcdc_panel_ops *ops)
{
pr_info("%s: +()\n", __func__);
mutex_lock(&panel_lock);
clk_enable(spi_clk);
lcm_writeb(0x14, 0x0);
mdelay(1);
lcm_writeb(0x1d, 0xa1);
clk_disable(spi_clk);
msleep(200);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 0);
mutex_unlock(&panel_lock);
pr_info("%s: -()\n", __func__);
return 0;
}
struct lcm_cmd {
int reg;
uint32_t val;
unsigned delay;
};
#define LCM_GPIO_CFG(gpio, func, str) \
PCOM_GPIO_CFG(gpio, func, GPIO_OUTPUT, GPIO_NO_PULL, str)
static uint32_t sony_tft_display_on_gpio_table[] = {
LCM_GPIO_CFG(MAHIMAHI_LCD_R1, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R2, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R3, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R4, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R5, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G0, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G1, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G2, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G3, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G4, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G5, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B1, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B2, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B3, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B4, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B5, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_PCLK, 1, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_VSYNC, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_HSYNC, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_DE, 1, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_CLK, 1, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_DO, 1, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_CSz, 1, GPIO_4MA),
};
static uint32_t sony_tft_display_off_gpio_table[] = {
LCM_GPIO_CFG(MAHIMAHI_LCD_R1, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R2, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R3, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R4, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_R5, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G0, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G1, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G2, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G3, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G4, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_G5, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B1, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B2, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B3, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B4, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_B5, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_PCLK, 0, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_VSYNC, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_HSYNC, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_DE, 0, GPIO_8MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_CLK, 0, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_DO, 0, GPIO_4MA),
LCM_GPIO_CFG(MAHIMAHI_LCD_SPI_CSz, 0, GPIO_4MA),
};
#undef LCM_GPIO_CFG
#define SONY_TFT_DEF_PANEL_DELTA \
(SONY_TFT_DEF_PANEL_VAL - SONY_TFT_MIN_PANEL_VAL)
#define SONY_TFT_DEF_USER_DELTA \
(SONY_TFT_DEF_USER_VAL - SONY_TFT_MIN_USER_VAL)
static void sony_tft_set_pwm_val(int val)
{
pr_info("%s: %d\n", __func__, val);
last_val = val;
if (!tft_panel_on)
return;
if (val <= SONY_TFT_DEF_USER_VAL) {
if (val <= SONY_TFT_MIN_USER_VAL)
val = SONY_TFT_MIN_PANEL_VAL;
else
val = SONY_TFT_DEF_PANEL_DELTA *
(val - SONY_TFT_MIN_USER_VAL) /
SONY_TFT_DEF_USER_DELTA +
SONY_TFT_MIN_PANEL_VAL;
} else
val = (SONY_TFT_MAX_PANEL_VAL - SONY_TFT_DEF_PANEL_VAL) *
(val - SONY_TFT_DEF_USER_VAL) /
(SONY_TFT_MAX_USER_VAL - SONY_TFT_DEF_USER_VAL) +
SONY_TFT_DEF_PANEL_VAL;
clk_enable(spi_clk);
qspi_send_9bit(0x0, 0x51);
qspi_send_9bit(0x1, val);
qspi_send_9bit(0x0, 0x53);
qspi_send_9bit(0x1, 0x24);
clk_disable(spi_clk);
}
#undef SONY_TFT_DEF_PANEL_DELTA
#undef SONY_TFT_DEF_USER_DELTA
static void sony_tft_panel_config_gpio_table(uint32_t *table, int len)
{
int n;
unsigned id;
for (n = 0; n < len; n++) {
id = table[n];
msm_proc_comm(PCOM_RPC_GPIO_TLMM_CONFIG_EX, &id, 0);
}
}
static int sony_tft_panel_power(int on)
{
unsigned id, on_off;
if (on) {
on_off = 0;
vreg_enable(vreg_lcm_aux_2v6);
vreg_enable(vreg_lcm_rftx_2v6);
id = PM_VREG_PDOWN_AUX_ID;
msm_proc_comm(PCOM_VREG_PULLDOWN, &on_off, &id);
id = PM_VREG_PDOWN_RFTX_ID;
msm_proc_comm(PCOM_VREG_PULLDOWN, &on_off, &id);
mdelay(10);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 1);
mdelay(10);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 0);
udelay(500);
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 1);
mdelay(10);
sony_tft_panel_config_gpio_table(
sony_tft_display_on_gpio_table,
ARRAY_SIZE(sony_tft_display_on_gpio_table));
} else {
on_off = 1;
gpio_set_value(MAHIMAHI_GPIO_LCD_RST_N, 0);
mdelay(120);
vreg_disable(vreg_lcm_rftx_2v6);
vreg_disable(vreg_lcm_aux_2v6);
id = PM_VREG_PDOWN_RFTX_ID;
msm_proc_comm(PCOM_VREG_PULLDOWN, &on_off, &id);
id = PM_VREG_PDOWN_AUX_ID;
msm_proc_comm(PCOM_VREG_PULLDOWN, &on_off, &id);
sony_tft_panel_config_gpio_table(
sony_tft_display_off_gpio_table,
ARRAY_SIZE(sony_tft_display_off_gpio_table));
}
return 0;
}
static int sony_tft_panel_init(struct msm_lcdc_panel_ops *ops)
{
return 0;
}
static int sony_tft_panel_unblank(struct msm_lcdc_panel_ops *ops)
{
pr_info("%s: +()\n", __func__);
mutex_lock(&panel_lock);
if (tft_panel_on) {
pr_info("%s: -() already unblanked\n", __func__);
goto done;
}
sony_tft_panel_power(1);
msleep(45);
clk_enable(spi_clk);
qspi_send_9bit(0x0, 0x11);
msleep(5);
qspi_send_9bit(0x0, 0x3a);
qspi_send_9bit(0x1, 0x05);
msleep(100);
qspi_send_9bit(0x0, 0x29);
/* unlock register page for pwm setting */
qspi_send_9bit(0x0, 0xf0);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x0, 0xf1);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x0, 0xd0);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x1, 0x5a);
qspi_send_9bit(0x0, 0xc2);
qspi_send_9bit(0x1, 0x53);
qspi_send_9bit(0x1, 0x12);
clk_disable(spi_clk);
msleep(100);
tft_panel_on = 1;
sony_tft_set_pwm_val(last_val);
pr_info("%s: -()\n", __func__);
done:
mutex_unlock(&panel_lock);
return 0;
}
static int sony_tft_panel_blank(struct msm_lcdc_panel_ops *ops)
{
pr_info("%s: +()\n", __func__);
mutex_lock(&panel_lock);
clk_enable(spi_clk);
qspi_send_9bit(0x0, 0x28);
qspi_send_9bit(0x0, 0x10);
clk_disable(spi_clk);
msleep(40);
sony_tft_panel_power(0);
tft_panel_on = 0;
mutex_unlock(&panel_lock);
pr_info("%s: -()\n", __func__);
return 0;
}
static struct msm_lcdc_panel_ops mahimahi_lcdc_amoled_panel_ops = {
.init = samsung_oled_panel_init,
.blank = samsung_oled_panel_blank,
.unblank = samsung_oled_panel_unblank,
};
static struct msm_lcdc_panel_ops mahimahi_lcdc_tft_panel_ops = {
.init = sony_tft_panel_init,
.blank = sony_tft_panel_blank,
.unblank = sony_tft_panel_unblank,
};
static struct msm_lcdc_timing mahimahi_lcdc_amoled_timing = {
.clk_rate = 24576000,
.hsync_pulse_width = 4,
.hsync_back_porch = 8,
.hsync_front_porch = 8,
.hsync_skew = 0,
.vsync_pulse_width = 2,
.vsync_back_porch = 8,
.vsync_front_porch = 8,
.vsync_act_low = 1,
.hsync_act_low = 1,
.den_act_low = 1,
};
static struct msm_lcdc_timing mahimahi_lcdc_tft_timing = {
.clk_rate = 24576000,
.hsync_pulse_width = 2,
.hsync_back_porch = 20,
.hsync_front_porch = 20,
.hsync_skew = 0,
.vsync_pulse_width = 2,
.vsync_back_porch = 6,
.vsync_front_porch = 4,
.vsync_act_low = 1,
.hsync_act_low = 1,
.den_act_low = 0,
};
static struct msm_fb_data mahimahi_lcdc_fb_data = {
.xres = 480,
.yres = 800,
.width = 48,
.height = 80,
.output_format = MSM_MDP_OUT_IF_FMT_RGB565,
};
static struct msm_lcdc_platform_data mahimahi_lcdc_amoled_platform_data = {
.panel_ops = &mahimahi_lcdc_amoled_panel_ops,
.timing = &mahimahi_lcdc_amoled_timing,
.fb_id = 0,
.fb_data = &mahimahi_lcdc_fb_data,
.fb_resource = &resources_msm_fb[0],
};
static struct msm_lcdc_platform_data mahimahi_lcdc_tft_platform_data = {
.panel_ops = &mahimahi_lcdc_tft_panel_ops,
.timing = &mahimahi_lcdc_tft_timing,
.fb_id = 0,
.fb_data = &mahimahi_lcdc_fb_data,
.fb_resource = &resources_msm_fb[0],
};
static struct platform_device mahimahi_lcdc_amoled_device = {
.name = "msm_mdp_lcdc",
.id = -1,
.dev = {
.platform_data = &mahimahi_lcdc_amoled_platform_data,
},
};
static struct platform_device mahimahi_lcdc_tft_device = {
.name = "msm_mdp_lcdc",
.id = -1,
.dev = {
.platform_data = &mahimahi_lcdc_tft_platform_data,
},
};
static int mahimahi_init_spi_hack(void)
{
int ret;
spi_base = ioremap(MSM_SPI_PHYS, MSM_SPI_SIZE);
if (!spi_base)
return -1;
spi_clk = clk_get(&msm_device_spi.dev, "spi_clk");
if (IS_ERR(spi_clk)) {
pr_err("%s: unable to get spi_clk\n", __func__);
ret = PTR_ERR(spi_clk);
goto err_clk_get;
}
clk_enable(spi_clk);
printk("spi: SPI_CONFIG=%x\n", readl(spi_base + SPI_CONFIG));
printk("spi: SPI_IO_CONTROL=%x\n", readl(spi_base + SPI_IO_CONTROL));
printk("spi: SPI_OPERATIONAL=%x\n", readl(spi_base + SPI_OPERATIONAL));
printk("spi: SPI_ERROR_FLAGS_EN=%x\n",
readl(spi_base + SPI_ERROR_FLAGS_EN));
printk("spi: SPI_ERROR_FLAGS=%x\n", readl(spi_base + SPI_ERROR_FLAGS));
printk("-%s()\n", __FUNCTION__);
clk_disable(spi_clk);
return 0;
err_clk_get:
iounmap(spi_base);
return ret;
}
static void mahimahi_brightness_set(struct led_classdev *led_cdev,
enum led_brightness val)
{
unsigned long flags;
led_cdev->brightness = val;
spin_lock_irqsave(&brightness_lock, flags);
new_val = val;
spin_unlock_irqrestore(&brightness_lock, flags);
schedule_work(&brightness_delayed_work);
}
static void mahimahi_brightness_amoled_set_work(struct work_struct *work_ptr)
{
unsigned long flags;
uint8_t val;
spin_lock_irqsave(&brightness_lock, flags);
val = new_val;
spin_unlock_irqrestore(&brightness_lock, flags);
mutex_lock(&panel_lock);
samsung_oled_set_gamma_val(val);
mutex_unlock(&panel_lock);
}
static void mahimahi_brightness_tft_set_work(struct work_struct *work_ptr)
{
unsigned long flags;
uint8_t val;
spin_lock_irqsave(&brightness_lock, flags);
val = new_val;
spin_unlock_irqrestore(&brightness_lock, flags);
mutex_lock(&panel_lock);
sony_tft_set_pwm_val(val);
mutex_unlock(&panel_lock);
}
static struct led_classdev mahimahi_brightness_led = {
.name = "lcd-backlight",
.brightness = LED_FULL,
.brightness_set = mahimahi_brightness_set,
};
int __init mahimahi_init_panel(void)
{
int ret;
if (!machine_is_mahimahi())
return 0;
if (system_rev > 0xC0) {
/* CDMA version (except for EVT1) supports RGB666 */
init_tablep = samsung_oled_rgb666_init_table;
init_table_sz = ARRAY_SIZE(samsung_oled_rgb666_init_table);
mahimahi_lcdc_fb_data.output_format = MSM_MDP_OUT_IF_FMT_RGB666;
}
ret = platform_device_register(&msm_device_mdp);
if (ret != 0)
return ret;
ret = mahimahi_init_spi_hack();
if (ret != 0)
return ret;
if (gpio_get_value(MAHIMAHI_GPIO_LCD_ID0)) {
pr_info("%s: tft panel\n", __func__);
vreg_lcm_rftx_2v6 = vreg_get(0, "rftx");
if (IS_ERR(vreg_lcm_rftx_2v6))
return PTR_ERR(vreg_lcm_rftx_2v6);
vreg_set_level(vreg_lcm_rftx_2v6, 2600);
vreg_lcm_aux_2v6 = vreg_get(0, "gp4");
if (IS_ERR(vreg_lcm_aux_2v6))
return PTR_ERR(vreg_lcm_aux_2v6);
if (gpio_get_value(MAHIMAHI_GPIO_LCD_RST_N))
tft_panel_on = 1;
ret = platform_device_register(&mahimahi_lcdc_tft_device);
INIT_WORK(&brightness_delayed_work, mahimahi_brightness_tft_set_work);
} else {
pr_info("%s: amoled panel\n", __func__);
ret = platform_device_register(&mahimahi_lcdc_amoled_device);
INIT_WORK(&brightness_delayed_work, mahimahi_brightness_amoled_set_work);
}
if (ret != 0)
return ret;
ret = led_classdev_register(NULL, &mahimahi_brightness_led);
if (ret != 0) {
pr_err("%s: Cannot register brightness led\n", __func__);
return ret;
}
return 0;
}
device_initcall(mahimahi_init_panel);
| gpl-2.0 |
KAsp3rd/android_kernel_lge_v496 | arch/arm/mach-msm/board-halibut-panel.c | 3634 | 1469 | /* linux/arch/arm/mach-msm/board-halibut-mddi.c
** Author: Brian Swetland <swetland@google.com>
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/leds.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <linux/bootmem.h>
#include <asm/io.h>
#include <asm/gpio.h>
#include <asm/mach-types.h>
#include <mach/msm_fb.h>
#include <mach/vreg.h>
#include <mach/proc_comm.h>
#include "devices.h"
#include "board-halibut.h"
static void halibut_mddi_power_client(struct msm_mddi_client_data *mddi,
int on)
{
}
static struct resource resources_msm_fb = {
.start = MSM_FB_BASE,
.end = MSM_FB_BASE + MSM_FB_SIZE - 1,
.flags = IORESOURCE_MEM,
};
static struct msm_fb_data fb_data = {
.xres = 800,
.yres = 480,
.output_format = 0,
};
static struct msm_mddi_platform_data mddi_pdata = {
.clk_rate = 122880000,
.power_client = halibut_mddi_power_client,
.fb_resource = &resources_msm_fb,
.num_clients = 1,
.client_platform_data = {
{
.product_id = (0x4474 << 16 | 0xc065),
.name = "mddi_c_dummy",
.id = 0,
.client_data = &fb_data,
.clk_rate = 0,
},
},
};
int __init halibut_init_panel(void)
{
int rc;
if (!machine_is_halibut())
return 0;
rc = platform_device_register(&msm_device_mdp);
if (rc)
return rc;
msm_device_mddi0.dev.platform_data = &mddi_pdata;
return platform_device_register(&msm_device_mddi0);
}
device_initcall(halibut_init_panel);
| gpl-2.0 |
baolfire/aries_kernel_pexcn | arch/arm/mach-s3c24xx/irq-s3c2443.c | 4914 | 7147 | /* linux/arch/arm/mach-s3c2443/irq.c
*
* Copyright (c) 2007 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/ioport.h>
#include <linux/device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/mach/irq.h>
#include <mach/regs-irq.h>
#include <mach/regs-gpio.h>
#include <plat/cpu.h>
#include <plat/pm.h>
#include <plat/irq.h>
#define INTMSK(start, end) ((1 << ((end) + 1 - (start))) - 1)
static inline void s3c2443_irq_demux(unsigned int irq, unsigned int len)
{
unsigned int subsrc, submsk;
unsigned int end;
/* read the current pending interrupts, and the mask
* for what it is available */
subsrc = __raw_readl(S3C2410_SUBSRCPND);
submsk = __raw_readl(S3C2410_INTSUBMSK);
subsrc &= ~submsk;
subsrc >>= (irq - S3C2410_IRQSUB(0));
subsrc &= (1 << len)-1;
end = len + irq;
for (; irq < end && subsrc; irq++) {
if (subsrc & 1)
generic_handle_irq(irq);
subsrc >>= 1;
}
}
/* WDT/AC97 sub interrupts */
static void s3c2443_irq_demux_wdtac97(unsigned int irq, struct irq_desc *desc)
{
s3c2443_irq_demux(IRQ_S3C2443_WDT, 4);
}
#define INTMSK_WDTAC97 (1UL << (IRQ_WDT - IRQ_EINT0))
#define SUBMSK_WDTAC97 INTMSK(IRQ_S3C2443_WDT, IRQ_S3C2443_AC97)
static void s3c2443_irq_wdtac97_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_WDTAC97, SUBMSK_WDTAC97);
}
static void s3c2443_irq_wdtac97_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_WDTAC97);
}
static void s3c2443_irq_wdtac97_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_WDTAC97, SUBMSK_WDTAC97);
}
static struct irq_chip s3c2443_irq_wdtac97 = {
.irq_mask = s3c2443_irq_wdtac97_mask,
.irq_unmask = s3c2443_irq_wdtac97_unmask,
.irq_ack = s3c2443_irq_wdtac97_ack,
};
/* LCD sub interrupts */
static void s3c2443_irq_demux_lcd(unsigned int irq, struct irq_desc *desc)
{
s3c2443_irq_demux(IRQ_S3C2443_LCD1, 4);
}
#define INTMSK_LCD (1UL << (IRQ_LCD - IRQ_EINT0))
#define SUBMSK_LCD INTMSK(IRQ_S3C2443_LCD1, IRQ_S3C2443_LCD4)
static void s3c2443_irq_lcd_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_LCD, SUBMSK_LCD);
}
static void s3c2443_irq_lcd_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_LCD);
}
static void s3c2443_irq_lcd_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_LCD, SUBMSK_LCD);
}
static struct irq_chip s3c2443_irq_lcd = {
.irq_mask = s3c2443_irq_lcd_mask,
.irq_unmask = s3c2443_irq_lcd_unmask,
.irq_ack = s3c2443_irq_lcd_ack,
};
/* DMA sub interrupts */
static void s3c2443_irq_demux_dma(unsigned int irq, struct irq_desc *desc)
{
s3c2443_irq_demux(IRQ_S3C2443_DMA0, 6);
}
#define INTMSK_DMA (1UL << (IRQ_S3C2443_DMA - IRQ_EINT0))
#define SUBMSK_DMA INTMSK(IRQ_S3C2443_DMA0, IRQ_S3C2443_DMA5)
static void s3c2443_irq_dma_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_DMA, SUBMSK_DMA);
}
static void s3c2443_irq_dma_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_DMA);
}
static void s3c2443_irq_dma_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_DMA, SUBMSK_DMA);
}
static struct irq_chip s3c2443_irq_dma = {
.irq_mask = s3c2443_irq_dma_mask,
.irq_unmask = s3c2443_irq_dma_unmask,
.irq_ack = s3c2443_irq_dma_ack,
};
/* UART3 sub interrupts */
static void s3c2443_irq_demux_uart3(unsigned int irq, struct irq_desc *desc)
{
s3c2443_irq_demux(IRQ_S3C2443_RX3, 3);
}
#define INTMSK_UART3 (1UL << (IRQ_S3C2443_UART3 - IRQ_EINT0))
#define SUBMSK_UART3 (0x7 << (IRQ_S3C2443_RX3 - S3C2410_IRQSUB(0)))
static void s3c2443_irq_uart3_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_UART3, SUBMSK_UART3);
}
static void s3c2443_irq_uart3_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_UART3);
}
static void s3c2443_irq_uart3_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_UART3, SUBMSK_UART3);
}
static struct irq_chip s3c2443_irq_uart3 = {
.irq_mask = s3c2443_irq_uart3_mask,
.irq_unmask = s3c2443_irq_uart3_unmask,
.irq_ack = s3c2443_irq_uart3_ack,
};
/* CAM sub interrupts */
static void s3c2443_irq_demux_cam(unsigned int irq, struct irq_desc *desc)
{
s3c2443_irq_demux(IRQ_S3C2440_CAM_C, 4);
}
#define INTMSK_CAM (1UL << (IRQ_CAM - IRQ_EINT0))
#define SUBMSK_CAM INTMSK(IRQ_S3C2440_CAM_C, IRQ_S3C2440_CAM_P)
static void s3c2443_irq_cam_mask(struct irq_data *data)
{
s3c_irqsub_mask(data->irq, INTMSK_CAM, SUBMSK_CAM);
}
static void s3c2443_irq_cam_unmask(struct irq_data *data)
{
s3c_irqsub_unmask(data->irq, INTMSK_CAM);
}
static void s3c2443_irq_cam_ack(struct irq_data *data)
{
s3c_irqsub_maskack(data->irq, INTMSK_CAM, SUBMSK_CAM);
}
static struct irq_chip s3c2443_irq_cam = {
.irq_mask = s3c2443_irq_cam_mask,
.irq_unmask = s3c2443_irq_cam_unmask,
.irq_ack = s3c2443_irq_cam_ack,
};
/* IRQ initialisation code */
static int __init s3c2443_add_sub(unsigned int base,
void (*demux)(unsigned int,
struct irq_desc *),
struct irq_chip *chip,
unsigned int start, unsigned int end)
{
unsigned int irqno;
irq_set_chip_and_handler(base, &s3c_irq_level_chip, handle_level_irq);
irq_set_chained_handler(base, demux);
for (irqno = start; irqno <= end; irqno++) {
irq_set_chip_and_handler(irqno, chip, handle_level_irq);
set_irq_flags(irqno, IRQF_VALID);
}
return 0;
}
static int __init s3c2443_irq_add(struct device *dev,
struct subsys_interface *sif)
{
printk("S3C2443: IRQ Support\n");
s3c2443_add_sub(IRQ_CAM, s3c2443_irq_demux_cam, &s3c2443_irq_cam,
IRQ_S3C2440_CAM_C, IRQ_S3C2440_CAM_P);
s3c2443_add_sub(IRQ_LCD, s3c2443_irq_demux_lcd, &s3c2443_irq_lcd,
IRQ_S3C2443_LCD1, IRQ_S3C2443_LCD4);
s3c2443_add_sub(IRQ_S3C2443_DMA, s3c2443_irq_demux_dma,
&s3c2443_irq_dma, IRQ_S3C2443_DMA0, IRQ_S3C2443_DMA5);
s3c2443_add_sub(IRQ_S3C2443_UART3, s3c2443_irq_demux_uart3,
&s3c2443_irq_uart3,
IRQ_S3C2443_RX3, IRQ_S3C2443_ERR3);
s3c2443_add_sub(IRQ_WDT, s3c2443_irq_demux_wdtac97,
&s3c2443_irq_wdtac97,
IRQ_S3C2443_WDT, IRQ_S3C2443_AC97);
return 0;
}
static struct subsys_interface s3c2443_irq_interface = {
.name = "s3c2443_irq",
.subsys = &s3c2443_subsys,
.add_dev = s3c2443_irq_add,
};
static int __init s3c2443_irq_init(void)
{
return subsys_interface_register(&s3c2443_irq_interface);
}
arch_initcall(s3c2443_irq_init);
| gpl-2.0 |
Vegaviet-DevTeam/android_kernel_pantech_ef63 | sound/soc/codecs/stac9766.c | 4914 | 12581 | /*
* stac9766.c -- ALSA SoC STAC9766 codec support
*
* Copyright 2009 Jon Smirl, Digispeaker
* Author: Jon Smirl <jonsmirl@gmail.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Features:-
*
* o Support for AC97 Codec, S/PDIF
*/
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/ac97_codec.h>
#include <sound/initval.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#include <sound/tlv.h>
#include "stac9766.h"
#define STAC9766_VERSION "0.10"
/*
* STAC9766 register cache
*/
static const u16 stac9766_reg[] = {
0x6A90, 0x8000, 0x8000, 0x8000, /* 6 */
0x0000, 0x0000, 0x8008, 0x8008, /* e */
0x8808, 0x8808, 0x8808, 0x8808, /* 16 */
0x8808, 0x0000, 0x8000, 0x0000, /* 1e */
0x0000, 0x0000, 0x0000, 0x000f, /* 26 */
0x0a05, 0x0400, 0xbb80, 0x0000, /* 2e */
0x0000, 0xbb80, 0x0000, 0x0000, /* 36 */
0x0000, 0x2000, 0x0000, 0x0100, /* 3e */
0x0000, 0x0000, 0x0080, 0x0000, /* 46 */
0x0000, 0x0000, 0x0003, 0xffff, /* 4e */
0x0000, 0x0000, 0x0000, 0x0000, /* 56 */
0x4000, 0x0000, 0x0000, 0x0000, /* 5e */
0x1201, 0xFFFF, 0xFFFF, 0x0000, /* 66 */
0x0000, 0x0000, 0x0000, 0x0000, /* 6e */
0x0000, 0x0000, 0x0000, 0x0006, /* 76 */
0x0000, 0x0000, 0x0000, 0x0000, /* 7e */
};
static const char *stac9766_record_mux[] = {"Mic", "CD", "Video", "AUX",
"Line", "Stereo Mix", "Mono Mix", "Phone"};
static const char *stac9766_mono_mux[] = {"Mix", "Mic"};
static const char *stac9766_mic_mux[] = {"Mic1", "Mic2"};
static const char *stac9766_SPDIF_mux[] = {"PCM", "ADC Record"};
static const char *stac9766_popbypass_mux[] = {"Normal", "Bypass Mixer"};
static const char *stac9766_record_all_mux[] = {"All analog",
"Analog plus DAC"};
static const char *stac9766_boost1[] = {"0dB", "10dB"};
static const char *stac9766_boost2[] = {"0dB", "20dB"};
static const char *stac9766_stereo_mic[] = {"Off", "On"};
static const struct soc_enum stac9766_record_enum =
SOC_ENUM_DOUBLE(AC97_REC_SEL, 8, 0, 8, stac9766_record_mux);
static const struct soc_enum stac9766_mono_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 9, 2, stac9766_mono_mux);
static const struct soc_enum stac9766_mic_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 8, 2, stac9766_mic_mux);
static const struct soc_enum stac9766_SPDIF_enum =
SOC_ENUM_SINGLE(AC97_STAC_DA_CONTROL, 1, 2, stac9766_SPDIF_mux);
static const struct soc_enum stac9766_popbypass_enum =
SOC_ENUM_SINGLE(AC97_GENERAL_PURPOSE, 15, 2, stac9766_popbypass_mux);
static const struct soc_enum stac9766_record_all_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 12, 2,
stac9766_record_all_mux);
static const struct soc_enum stac9766_boost1_enum =
SOC_ENUM_SINGLE(AC97_MIC, 6, 2, stac9766_boost1); /* 0/10dB */
static const struct soc_enum stac9766_boost2_enum =
SOC_ENUM_SINGLE(AC97_STAC_ANALOG_SPECIAL, 2, 2, stac9766_boost2); /* 0/20dB */
static const struct soc_enum stac9766_stereo_mic_enum =
SOC_ENUM_SINGLE(AC97_STAC_STEREO_MIC, 2, 1, stac9766_stereo_mic);
static const DECLARE_TLV_DB_LINEAR(master_tlv, -4600, 0);
static const DECLARE_TLV_DB_LINEAR(record_tlv, 0, 2250);
static const DECLARE_TLV_DB_LINEAR(beep_tlv, -4500, 0);
static const DECLARE_TLV_DB_LINEAR(mix_tlv, -3450, 1200);
static const struct snd_kcontrol_new stac9766_snd_ac97_controls[] = {
SOC_DOUBLE_TLV("Speaker Volume", AC97_MASTER, 8, 0, 31, 1, master_tlv),
SOC_SINGLE("Speaker Switch", AC97_MASTER, 15, 1, 1),
SOC_DOUBLE_TLV("Headphone Volume", AC97_HEADPHONE, 8, 0, 31, 1,
master_tlv),
SOC_SINGLE("Headphone Switch", AC97_HEADPHONE, 15, 1, 1),
SOC_SINGLE_TLV("Mono Out Volume", AC97_MASTER_MONO, 0, 31, 1,
master_tlv),
SOC_SINGLE("Mono Out Switch", AC97_MASTER_MONO, 15, 1, 1),
SOC_DOUBLE_TLV("Record Volume", AC97_REC_GAIN, 8, 0, 15, 0, record_tlv),
SOC_SINGLE("Record Switch", AC97_REC_GAIN, 15, 1, 1),
SOC_SINGLE_TLV("Beep Volume", AC97_PC_BEEP, 1, 15, 1, beep_tlv),
SOC_SINGLE("Beep Switch", AC97_PC_BEEP, 15, 1, 1),
SOC_SINGLE("Beep Frequency", AC97_PC_BEEP, 5, 127, 1),
SOC_SINGLE_TLV("Phone Volume", AC97_PHONE, 0, 31, 1, mix_tlv),
SOC_SINGLE("Phone Switch", AC97_PHONE, 15, 1, 1),
SOC_ENUM("Mic Boost1", stac9766_boost1_enum),
SOC_ENUM("Mic Boost2", stac9766_boost2_enum),
SOC_SINGLE_TLV("Mic Volume", AC97_MIC, 0, 31, 1, mix_tlv),
SOC_SINGLE("Mic Switch", AC97_MIC, 15, 1, 1),
SOC_ENUM("Stereo Mic", stac9766_stereo_mic_enum),
SOC_DOUBLE_TLV("Line Volume", AC97_LINE, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Line Switch", AC97_LINE, 15, 1, 1),
SOC_DOUBLE_TLV("CD Volume", AC97_CD, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("CD Switch", AC97_CD, 15, 1, 1),
SOC_DOUBLE_TLV("AUX Volume", AC97_AUX, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("AUX Switch", AC97_AUX, 15, 1, 1),
SOC_DOUBLE_TLV("Video Volume", AC97_VIDEO, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("Video Switch", AC97_VIDEO, 15, 1, 1),
SOC_DOUBLE_TLV("DAC Volume", AC97_PCM, 8, 0, 31, 1, mix_tlv),
SOC_SINGLE("DAC Switch", AC97_PCM, 15, 1, 1),
SOC_SINGLE("Loopback Test Switch", AC97_GENERAL_PURPOSE, 7, 1, 0),
SOC_SINGLE("3D Volume", AC97_3D_CONTROL, 3, 2, 1),
SOC_SINGLE("3D Switch", AC97_GENERAL_PURPOSE, 13, 1, 0),
SOC_ENUM("SPDIF Mux", stac9766_SPDIF_enum),
SOC_ENUM("Mic1/2 Mux", stac9766_mic_enum),
SOC_ENUM("Record All Mux", stac9766_record_all_enum),
SOC_ENUM("Record Mux", stac9766_record_enum),
SOC_ENUM("Mono Mux", stac9766_mono_enum),
SOC_ENUM("Pop Bypass Mux", stac9766_popbypass_enum),
};
static int stac9766_ac97_write(struct snd_soc_codec *codec, unsigned int reg,
unsigned int val)
{
u16 *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
soc_ac97_ops.write(codec->ac97, reg, val);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return 0;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
soc_ac97_ops.write(codec->ac97, reg, val);
cache[reg / 2] = val;
return 0;
}
static unsigned int stac9766_ac97_read(struct snd_soc_codec *codec,
unsigned int reg)
{
u16 val = 0, *cache = codec->reg_cache;
if (reg > AC97_STAC_PAGE0) {
stac9766_ac97_write(codec, AC97_INT_PAGING, 0);
val = soc_ac97_ops.read(codec->ac97, reg - AC97_STAC_PAGE0);
stac9766_ac97_write(codec, AC97_INT_PAGING, 1);
return val;
}
if (reg / 2 >= ARRAY_SIZE(stac9766_reg))
return -EIO;
if (reg == AC97_RESET || reg == AC97_GPIO_STATUS ||
reg == AC97_INT_PAGING || reg == AC97_VENDOR_ID1 ||
reg == AC97_VENDOR_ID2) {
val = soc_ac97_ops.read(codec->ac97, reg);
return val;
}
return cache[reg / 2];
}
static int ac97_analog_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x1; /* enable variable rate audio */
vra &= ~0x4; /* disable SPDIF output */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK)
reg = AC97_PCM_FRONT_DAC_RATE;
else
reg = AC97_PCM_LR_ADC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int ac97_digital_prepare(struct snd_pcm_substream *substream,
struct snd_soc_dai *dai)
{
struct snd_soc_codec *codec = dai->codec;
struct snd_pcm_runtime *runtime = substream->runtime;
unsigned short reg, vra;
stac9766_ac97_write(codec, AC97_SPDIF, 0x2002);
vra = stac9766_ac97_read(codec, AC97_EXTENDED_STATUS);
vra |= 0x5; /* Enable VRA and SPDIF out */
stac9766_ac97_write(codec, AC97_EXTENDED_STATUS, vra);
reg = AC97_PCM_FRONT_DAC_RATE;
return stac9766_ac97_write(codec, reg, runtime->rate);
}
static int stac9766_set_bias_level(struct snd_soc_codec *codec,
enum snd_soc_bias_level level)
{
switch (level) {
case SND_SOC_BIAS_ON: /* full On */
case SND_SOC_BIAS_PREPARE: /* partial On */
case SND_SOC_BIAS_STANDBY: /* Off, with power */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0x0000);
break;
case SND_SOC_BIAS_OFF: /* Off, without power */
/* disable everything including AC link */
stac9766_ac97_write(codec, AC97_POWERDOWN, 0xffff);
break;
}
codec->dapm.bias_level = level;
return 0;
}
static int stac9766_reset(struct snd_soc_codec *codec, int try_warm)
{
if (try_warm && soc_ac97_ops.warm_reset) {
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) == stac9766_reg[0])
return 1;
}
soc_ac97_ops.reset(codec->ac97);
if (soc_ac97_ops.warm_reset)
soc_ac97_ops.warm_reset(codec->ac97);
if (stac9766_ac97_read(codec, 0) != stac9766_reg[0])
return -EIO;
return 0;
}
static int stac9766_codec_suspend(struct snd_soc_codec *codec)
{
stac9766_set_bias_level(codec, SND_SOC_BIAS_OFF);
return 0;
}
static int stac9766_codec_resume(struct snd_soc_codec *codec)
{
u16 id, reset;
reset = 0;
/* give the codec an AC97 warm reset to start the link */
reset:
if (reset > 5) {
printk(KERN_ERR "stac9766 failed to resume");
return -EIO;
}
codec->ac97->bus->ops->warm_reset(codec->ac97);
id = soc_ac97_ops.read(codec->ac97, AC97_VENDOR_ID2);
if (id != 0x4c13) {
stac9766_reset(codec, 0);
reset++;
goto reset;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
return 0;
}
static const struct snd_soc_dai_ops stac9766_dai_ops_analog = {
.prepare = ac97_analog_prepare,
};
static const struct snd_soc_dai_ops stac9766_dai_ops_digital = {
.prepare = ac97_digital_prepare,
};
static struct snd_soc_dai_driver stac9766_dai[] = {
{
.name = "stac9766-hifi-analog",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
.capture = {
.stream_name = "stac9766 analog",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_8000_48000,
.formats = SND_SOC_STD_AC97_FMTS,
},
/* alsa ops */
.ops = &stac9766_dai_ops_analog,
},
{
.name = "stac9766-hifi-IEC958",
.ac97_control = 1,
/* stream cababilities */
.playback = {
.stream_name = "stac9766 IEC958",
.channels_min = 1,
.channels_max = 2,
.rates = SNDRV_PCM_RATE_32000 | \
SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000,
.formats = SNDRV_PCM_FORMAT_IEC958_SUBFRAME_BE,
},
/* alsa ops */
.ops = &stac9766_dai_ops_digital,
}
};
static int stac9766_codec_probe(struct snd_soc_codec *codec)
{
int ret = 0;
printk(KERN_INFO "STAC9766 SoC Audio Codec %s\n", STAC9766_VERSION);
ret = snd_soc_new_ac97_codec(codec, &soc_ac97_ops, 0);
if (ret < 0)
goto codec_err;
/* do a cold reset for the controller and then try
* a warm reset followed by an optional cold reset for codec */
stac9766_reset(codec, 0);
ret = stac9766_reset(codec, 1);
if (ret < 0) {
printk(KERN_ERR "Failed to reset STAC9766: AC97 link error\n");
goto codec_err;
}
stac9766_set_bias_level(codec, SND_SOC_BIAS_STANDBY);
snd_soc_add_codec_controls(codec, stac9766_snd_ac97_controls,
ARRAY_SIZE(stac9766_snd_ac97_controls));
return 0;
codec_err:
snd_soc_free_ac97_codec(codec);
return ret;
}
static int stac9766_codec_remove(struct snd_soc_codec *codec)
{
snd_soc_free_ac97_codec(codec);
return 0;
}
static struct snd_soc_codec_driver soc_codec_dev_stac9766 = {
.write = stac9766_ac97_write,
.read = stac9766_ac97_read,
.set_bias_level = stac9766_set_bias_level,
.probe = stac9766_codec_probe,
.remove = stac9766_codec_remove,
.suspend = stac9766_codec_suspend,
.resume = stac9766_codec_resume,
.reg_cache_size = ARRAY_SIZE(stac9766_reg),
.reg_word_size = sizeof(u16),
.reg_cache_step = 2,
.reg_cache_default = stac9766_reg,
};
static __devinit int stac9766_probe(struct platform_device *pdev)
{
return snd_soc_register_codec(&pdev->dev,
&soc_codec_dev_stac9766, stac9766_dai, ARRAY_SIZE(stac9766_dai));
}
static int __devexit stac9766_remove(struct platform_device *pdev)
{
snd_soc_unregister_codec(&pdev->dev);
return 0;
}
static struct platform_driver stac9766_codec_driver = {
.driver = {
.name = "stac9766-codec",
.owner = THIS_MODULE,
},
.probe = stac9766_probe,
.remove = __devexit_p(stac9766_remove),
};
module_platform_driver(stac9766_codec_driver);
MODULE_DESCRIPTION("ASoC stac9766 driver");
MODULE_AUTHOR("Jon Smirl <jonsmirl@gmail.com>");
MODULE_LICENSE("GPL");
| gpl-2.0 |
atwilc3000/linux4sam | drivers/misc/eeprom/eeprom.c | 7474 | 6645 | /*
* Copyright (C) 1998, 1999 Frodo Looijaard <frodol@dds.nl> and
* Philip Edelbrock <phil@netroedge.com>
* Copyright (C) 2003 Greg Kroah-Hartman <greg@kroah.com>
* Copyright (C) 2003 IBM Corp.
* Copyright (C) 2004 Jean Delvare <khali@linux-fr.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/i2c.h>
#include <linux/mutex.h>
/* Addresses to scan */
static const unsigned short normal_i2c[] = { 0x50, 0x51, 0x52, 0x53, 0x54,
0x55, 0x56, 0x57, I2C_CLIENT_END };
/* Size of EEPROM in bytes */
#define EEPROM_SIZE 256
/* possible types of eeprom devices */
enum eeprom_nature {
UNKNOWN,
VAIO,
};
/* Each client has this additional data */
struct eeprom_data {
struct mutex update_lock;
u8 valid; /* bitfield, bit!=0 if slice is valid */
unsigned long last_updated[8]; /* In jiffies, 8 slices */
u8 data[EEPROM_SIZE]; /* Register values */
enum eeprom_nature nature;
};
static void eeprom_update_client(struct i2c_client *client, u8 slice)
{
struct eeprom_data *data = i2c_get_clientdata(client);
int i;
mutex_lock(&data->update_lock);
if (!(data->valid & (1 << slice)) ||
time_after(jiffies, data->last_updated[slice] + 300 * HZ)) {
dev_dbg(&client->dev, "Starting eeprom update, slice %u\n", slice);
if (i2c_check_functionality(client->adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK)) {
for (i = slice << 5; i < (slice + 1) << 5; i += 32)
if (i2c_smbus_read_i2c_block_data(client, i,
32, data->data + i)
!= 32)
goto exit;
} else {
for (i = slice << 5; i < (slice + 1) << 5; i += 2) {
int word = i2c_smbus_read_word_data(client, i);
if (word < 0)
goto exit;
data->data[i] = word & 0xff;
data->data[i + 1] = word >> 8;
}
}
data->last_updated[slice] = jiffies;
data->valid |= (1 << slice);
}
exit:
mutex_unlock(&data->update_lock);
}
static ssize_t eeprom_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buf, loff_t off, size_t count)
{
struct i2c_client *client = to_i2c_client(container_of(kobj, struct device, kobj));
struct eeprom_data *data = i2c_get_clientdata(client);
u8 slice;
if (off > EEPROM_SIZE)
return 0;
if (off + count > EEPROM_SIZE)
count = EEPROM_SIZE - off;
/* Only refresh slices which contain requested bytes */
for (slice = off >> 5; slice <= (off + count - 1) >> 5; slice++)
eeprom_update_client(client, slice);
/* Hide Vaio private settings to regular users:
- BIOS passwords: bytes 0x00 to 0x0f
- UUID: bytes 0x10 to 0x1f
- Serial number: 0xc0 to 0xdf */
if (data->nature == VAIO && !capable(CAP_SYS_ADMIN)) {
int i;
for (i = 0; i < count; i++) {
if ((off + i <= 0x1f) ||
(off + i >= 0xc0 && off + i <= 0xdf))
buf[i] = 0;
else
buf[i] = data->data[off + i];
}
} else {
memcpy(buf, &data->data[off], count);
}
return count;
}
static struct bin_attribute eeprom_attr = {
.attr = {
.name = "eeprom",
.mode = S_IRUGO,
},
.size = EEPROM_SIZE,
.read = eeprom_read,
};
/* Return 0 if detection is successful, -ENODEV otherwise */
static int eeprom_detect(struct i2c_client *client, struct i2c_board_info *info)
{
struct i2c_adapter *adapter = client->adapter;
/* EDID EEPROMs are often 24C00 EEPROMs, which answer to all
addresses 0x50-0x57, but we only care about 0x50. So decline
attaching to addresses >= 0x51 on DDC buses */
if (!(adapter->class & I2C_CLASS_SPD) && client->addr >= 0x51)
return -ENODEV;
/* There are four ways we can read the EEPROM data:
(1) I2C block reads (faster, but unsupported by most adapters)
(2) Word reads (128% overhead)
(3) Consecutive byte reads (88% overhead, unsafe)
(4) Regular byte data reads (265% overhead)
The third and fourth methods are not implemented by this driver
because all known adapters support one of the first two. */
if (!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_WORD_DATA)
&& !i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_I2C_BLOCK))
return -ENODEV;
strlcpy(info->type, "eeprom", I2C_NAME_SIZE);
return 0;
}
static int eeprom_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct i2c_adapter *adapter = client->adapter;
struct eeprom_data *data;
int err;
if (!(data = kzalloc(sizeof(struct eeprom_data), GFP_KERNEL))) {
err = -ENOMEM;
goto exit;
}
memset(data->data, 0xff, EEPROM_SIZE);
i2c_set_clientdata(client, data);
mutex_init(&data->update_lock);
data->nature = UNKNOWN;
/* Detect the Vaio nature of EEPROMs.
We use the "PCG-" or "VGN-" prefix as the signature. */
if (client->addr == 0x57
&& i2c_check_functionality(adapter, I2C_FUNC_SMBUS_READ_BYTE_DATA)) {
char name[4];
name[0] = i2c_smbus_read_byte_data(client, 0x80);
name[1] = i2c_smbus_read_byte_data(client, 0x81);
name[2] = i2c_smbus_read_byte_data(client, 0x82);
name[3] = i2c_smbus_read_byte_data(client, 0x83);
if (!memcmp(name, "PCG-", 4) || !memcmp(name, "VGN-", 4)) {
dev_info(&client->dev, "Vaio EEPROM detected, "
"enabling privacy protection\n");
data->nature = VAIO;
}
}
/* create the sysfs eeprom file */
err = sysfs_create_bin_file(&client->dev.kobj, &eeprom_attr);
if (err)
goto exit_kfree;
return 0;
exit_kfree:
kfree(data);
exit:
return err;
}
static int eeprom_remove(struct i2c_client *client)
{
sysfs_remove_bin_file(&client->dev.kobj, &eeprom_attr);
kfree(i2c_get_clientdata(client));
return 0;
}
static const struct i2c_device_id eeprom_id[] = {
{ "eeprom", 0 },
{ }
};
static struct i2c_driver eeprom_driver = {
.driver = {
.name = "eeprom",
},
.probe = eeprom_probe,
.remove = eeprom_remove,
.id_table = eeprom_id,
.class = I2C_CLASS_DDC | I2C_CLASS_SPD,
.detect = eeprom_detect,
.address_list = normal_i2c,
};
module_i2c_driver(eeprom_driver);
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl> and "
"Philip Edelbrock <phil@netroedge.com> and "
"Greg Kroah-Hartman <greg@kroah.com>");
MODULE_DESCRIPTION("I2C EEPROM driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
mstanovich/polling_server | drivers/staging/comedi/drivers/mpc624.c | 7986 | 12985 | /*
comedi/drivers/mpc624.c
Hardware driver for a Micro/sys inc. MPC-624 PC/104 board
COMEDI - Linux Control and Measurement Device Interface
Copyright (C) 2000 David A. Schleef <ds@schleef.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Driver: mpc624
Description: Micro/sys MPC-624 PC/104 board
Devices: [Micro/sys] MPC-624 (mpc624)
Author: Stanislaw Raczynski <sraczynski@op.pl>
Updated: Thu, 15 Sep 2005 12:01:18 +0200
Status: working
The Micro/sys MPC-624 board is based on the LTC2440 24-bit sigma-delta
ADC chip.
Subdevices supported by the driver:
- Analog In: supported
- Digital I/O: not supported
- LEDs: not supported
- EEPROM: not supported
Configuration Options:
[0] - I/O base address
[1] - conversion rate
Conversion rate RMS noise Effective Number Of Bits
0 3.52kHz 23uV 17
1 1.76kHz 3.5uV 20
2 880Hz 2uV 21.3
3 440Hz 1.4uV 21.8
4 220Hz 1uV 22.4
5 110Hz 750uV 22.9
6 55Hz 510nV 23.4
7 27.5Hz 375nV 24
8 13.75Hz 250nV 24.4
9 6.875Hz 200nV 24.6
[2] - voltage range
0 -1.01V .. +1.01V
1 -10.1V .. +10.1V
*/
#include "../comedidev.h"
#include <linux/ioport.h>
#include <linux/delay.h>
/* Consecutive I/O port addresses */
#define MPC624_SIZE 16
/* Offsets of different ports */
#define MPC624_MASTER_CONTROL 0 /* not used */
#define MPC624_GNMUXCH 1 /* Gain, Mux, Channel of ADC */
#define MPC624_ADC 2 /* read/write to/from ADC */
#define MPC624_EE 3 /* read/write to/from serial EEPROM via I2C */
#define MPC624_LEDS 4 /* write to LEDs */
#define MPC624_DIO 5 /* read/write to/from digital I/O ports */
#define MPC624_IRQ_MASK 6 /* IRQ masking enable/disable */
/* Register bits' names */
#define MPC624_ADBUSY (1<<5)
#define MPC624_ADSDO (1<<4)
#define MPC624_ADFO (1<<3)
#define MPC624_ADCS (1<<2)
#define MPC624_ADSCK (1<<1)
#define MPC624_ADSDI (1<<0)
/* SDI Speed/Resolution Programming bits */
#define MPC624_OSR4 (1<<31)
#define MPC624_OSR3 (1<<30)
#define MPC624_OSR2 (1<<29)
#define MPC624_OSR1 (1<<28)
#define MPC624_OSR0 (1<<27)
/* 32-bit output value bits' names */
#define MPC624_EOC_BIT (1<<31)
#define MPC624_DMY_BIT (1<<30)
#define MPC624_SGN_BIT (1<<29)
/* Conversion speeds */
/* OSR4 OSR3 OSR2 OSR1 OSR0 Conversion rate RMS noise ENOB^
* X 0 0 0 1 3.52kHz 23uV 17
* X 0 0 1 0 1.76kHz 3.5uV 20
* X 0 0 1 1 880Hz 2uV 21.3
* X 0 1 0 0 440Hz 1.4uV 21.8
* X 0 1 0 1 220Hz 1uV 22.4
* X 0 1 1 0 110Hz 750uV 22.9
* X 0 1 1 1 55Hz 510nV 23.4
* X 1 0 0 0 27.5Hz 375nV 24
* X 1 0 0 1 13.75Hz 250nV 24.4
* X 1 1 1 1 6.875Hz 200nV 24.6
*
* ^ - Effective Number Of Bits
*/
#define MPC624_SPEED_3_52_kHz (MPC624_OSR4 | MPC624_OSR0)
#define MPC624_SPEED_1_76_kHz (MPC624_OSR4 | MPC624_OSR1)
#define MPC624_SPEED_880_Hz (MPC624_OSR4 | MPC624_OSR1 | MPC624_OSR0)
#define MPC624_SPEED_440_Hz (MPC624_OSR4 | MPC624_OSR2)
#define MPC624_SPEED_220_Hz (MPC624_OSR4 | MPC624_OSR2 | MPC624_OSR0)
#define MPC624_SPEED_110_Hz (MPC624_OSR4 | MPC624_OSR2 | MPC624_OSR1)
#define MPC624_SPEED_55_Hz \
(MPC624_OSR4 | MPC624_OSR2 | MPC624_OSR1 | MPC624_OSR0)
#define MPC624_SPEED_27_5_Hz (MPC624_OSR4 | MPC624_OSR3)
#define MPC624_SPEED_13_75_Hz (MPC624_OSR4 | MPC624_OSR3 | MPC624_OSR0)
#define MPC624_SPEED_6_875_Hz \
(MPC624_OSR4 | MPC624_OSR3 | MPC624_OSR2 | MPC624_OSR1 | MPC624_OSR0)
/* -------------------------------------------------------------------------- */
struct skel_private {
/* set by mpc624_attach() from driver's parameters */
unsigned long int ulConvertionRate;
};
#define devpriv ((struct skel_private *)dev->private)
/* -------------------------------------------------------------------------- */
static const struct comedi_lrange range_mpc624_bipolar1 = {
1,
{
/* BIP_RANGE(1.01) this is correct, */
/* but my MPC-624 actually seems to have a range of 2.02 */
BIP_RANGE(2.02)
}
};
static const struct comedi_lrange range_mpc624_bipolar10 = {
1,
{
/* BIP_RANGE(10.1) this is correct, */
/* but my MPC-624 actually seems to have a range of 20.2 */
BIP_RANGE(20.2)
}
};
/* -------------------------------------------------------------------------- */
static int mpc624_attach(struct comedi_device *dev,
struct comedi_devconfig *it);
static int mpc624_detach(struct comedi_device *dev);
/* -------------------------------------------------------------------------- */
static struct comedi_driver driver_mpc624 = {
.driver_name = "mpc624",
.module = THIS_MODULE,
.attach = mpc624_attach,
.detach = mpc624_detach
};
/* -------------------------------------------------------------------------- */
static int mpc624_ai_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data);
/* -------------------------------------------------------------------------- */
static int mpc624_attach(struct comedi_device *dev, struct comedi_devconfig *it)
{
struct comedi_subdevice *s;
unsigned long iobase;
iobase = it->options[0];
printk(KERN_INFO "comedi%d: mpc624 [0x%04lx, ", dev->minor, iobase);
if (request_region(iobase, MPC624_SIZE, "mpc624") == NULL) {
printk(KERN_ERR "I/O port(s) in use\n");
return -EIO;
}
dev->iobase = iobase;
dev->board_name = "mpc624";
/* Private structure initialization */
if (alloc_private(dev, sizeof(struct skel_private)) < 0)
return -ENOMEM;
switch (it->options[1]) {
case 0:
devpriv->ulConvertionRate = MPC624_SPEED_3_52_kHz;
printk(KERN_INFO "3.52 kHz, ");
break;
case 1:
devpriv->ulConvertionRate = MPC624_SPEED_1_76_kHz;
printk(KERN_INFO "1.76 kHz, ");
break;
case 2:
devpriv->ulConvertionRate = MPC624_SPEED_880_Hz;
printk(KERN_INFO "880 Hz, ");
break;
case 3:
devpriv->ulConvertionRate = MPC624_SPEED_440_Hz;
printk(KERN_INFO "440 Hz, ");
break;
case 4:
devpriv->ulConvertionRate = MPC624_SPEED_220_Hz;
printk(KERN_INFO "220 Hz, ");
break;
case 5:
devpriv->ulConvertionRate = MPC624_SPEED_110_Hz;
printk(KERN_INFO "110 Hz, ");
break;
case 6:
devpriv->ulConvertionRate = MPC624_SPEED_55_Hz;
printk(KERN_INFO "55 Hz, ");
break;
case 7:
devpriv->ulConvertionRate = MPC624_SPEED_27_5_Hz;
printk(KERN_INFO "27.5 Hz, ");
break;
case 8:
devpriv->ulConvertionRate = MPC624_SPEED_13_75_Hz;
printk(KERN_INFO "13.75 Hz, ");
break;
case 9:
devpriv->ulConvertionRate = MPC624_SPEED_6_875_Hz;
printk(KERN_INFO "6.875 Hz, ");
break;
default:
printk
(KERN_ERR "illegal conversion rate setting!"
" Valid numbers are 0..9. Using 9 => 6.875 Hz, ");
devpriv->ulConvertionRate = MPC624_SPEED_3_52_kHz;
}
/* Subdevices structures */
if (alloc_subdevices(dev, 1) < 0)
return -ENOMEM;
s = dev->subdevices + 0;
s->type = COMEDI_SUBD_AI;
s->subdev_flags = SDF_READABLE | SDF_DIFF;
s->n_chan = 8;
switch (it->options[1]) {
default:
s->maxdata = 0x3FFFFFFF;
printk(KERN_INFO "30 bit, ");
}
switch (it->options[1]) {
case 0:
s->range_table = &range_mpc624_bipolar1;
printk(KERN_INFO "1.01V]: ");
break;
default:
s->range_table = &range_mpc624_bipolar10;
printk(KERN_INFO "10.1V]: ");
}
s->len_chanlist = 1;
s->insn_read = mpc624_ai_rinsn;
printk(KERN_INFO "attached\n");
return 1;
}
static int mpc624_detach(struct comedi_device *dev)
{
printk(KERN_INFO "comedi%d: mpc624: remove\n", dev->minor);
if (dev->iobase)
release_region(dev->iobase, MPC624_SIZE);
return 0;
}
/* Timeout 200ms */
#define TIMEOUT 200
static int mpc624_ai_rinsn(struct comedi_device *dev,
struct comedi_subdevice *s, struct comedi_insn *insn,
unsigned int *data)
{
int n, i;
unsigned long int data_in, data_out;
unsigned char ucPort;
/*
* WARNING:
* We always write 0 to GNSWA bit, so the channel range is +-/10.1Vdc
*/
outb(insn->chanspec, dev->iobase + MPC624_GNMUXCH);
/* printk("Channel %d:\n", insn->chanspec); */
if (!insn->n) {
printk(KERN_INFO "MPC624: Warning, no data to acquire\n");
return 0;
}
for (n = 0; n < insn->n; n++) {
/* Trigger the conversion */
outb(MPC624_ADSCK, dev->iobase + MPC624_ADC);
udelay(1);
outb(MPC624_ADCS | MPC624_ADSCK, dev->iobase + MPC624_ADC);
udelay(1);
outb(0, dev->iobase + MPC624_ADC);
udelay(1);
/* Wait for the conversion to end */
for (i = 0; i < TIMEOUT; i++) {
ucPort = inb(dev->iobase + MPC624_ADC);
if (ucPort & MPC624_ADBUSY)
udelay(1000);
else
break;
}
if (i == TIMEOUT) {
printk(KERN_ERR "MPC624: timeout (%dms)\n", TIMEOUT);
data[n] = 0;
return -ETIMEDOUT;
}
/* Start reading data */
data_in = 0;
data_out = devpriv->ulConvertionRate;
udelay(1);
for (i = 0; i < 32; i++) {
/* Set the clock low */
outb(0, dev->iobase + MPC624_ADC);
udelay(1);
if (data_out & (1 << 31)) { /* the next bit is a 1 */
/* Set the ADSDI line (send to MPC624) */
outb(MPC624_ADSDI, dev->iobase + MPC624_ADC);
udelay(1);
/* Set the clock high */
outb(MPC624_ADSCK | MPC624_ADSDI,
dev->iobase + MPC624_ADC);
} else { /* the next bit is a 0 */
/* Set the ADSDI line (send to MPC624) */
outb(0, dev->iobase + MPC624_ADC);
udelay(1);
/* Set the clock high */
outb(MPC624_ADSCK, dev->iobase + MPC624_ADC);
}
/* Read ADSDO on high clock (receive from MPC624) */
udelay(1);
data_in <<= 1;
data_in |=
(inb(dev->iobase + MPC624_ADC) & MPC624_ADSDO) >> 4;
udelay(1);
data_out <<= 1;
}
/*
* Received 32-bit long value consist of:
* 31: EOC -
* (End Of Transmission) bit - should be 0
* 30: DMY
* (Dummy) bit - should be 0
* 29: SIG
* (Sign) bit- 1 if the voltage is positive,
* 0 if negative
* 28: MSB
* (Most Significant Bit) - the first bit of
* the conversion result
* ....
* 05: LSB
* (Least Significant Bit)- the last bit of the
* conversion result
* 04-00: sub-LSB
* - sub-LSBs are basically noise, but when
* averaged properly, they can increase conversion
* precision up to 29 bits; they can be discarded
* without loss of resolution.
*/
if (data_in & MPC624_EOC_BIT)
printk(KERN_INFO "MPC624:EOC bit is set (data_in=%lu)!",
data_in);
if (data_in & MPC624_DMY_BIT)
printk(KERN_INFO "MPC624:DMY bit is set (data_in=%lu)!",
data_in);
if (data_in & MPC624_SGN_BIT) { /* Volatge is positive */
/*
* comedi operates on unsigned numbers, so mask off EOC
* and DMY and don't clear the SGN bit
*/
data_in &= 0x3FFFFFFF;
data[n] = data_in;
} else { /* The voltage is negative */
/*
* data_in contains a number in 30-bit two's complement
* code and we must deal with it
*/
data_in |= MPC624_SGN_BIT;
data_in = ~data_in;
data_in += 1;
data_in &= ~(MPC624_EOC_BIT | MPC624_DMY_BIT);
/* clear EOC and DMY bits */
data_in = 0x20000000 - data_in;
data[n] = data_in;
}
}
/* Return the number of samples read/written */
return n;
}
static int __init driver_mpc624_init_module(void)
{
return comedi_driver_register(&driver_mpc624);
}
static void __exit driver_mpc624_cleanup_module(void)
{
comedi_driver_unregister(&driver_mpc624);
}
module_init(driver_mpc624_init_module);
module_exit(driver_mpc624_cleanup_module);
MODULE_AUTHOR("Comedi http://www.comedi.org");
MODULE_DESCRIPTION("Comedi low-level driver");
MODULE_LICENSE("GPL");
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.