code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
!
! Copyright (C) 2002-2010 Quantum ESPRESSO group
! This file is distributed under the terms of the
! GNU General Public License. See the file `License'
! in the root directory of the present distribution,
! or http://www.gnu.org/copyleft/gpl.txt .
!=----------------------------------------------------------------------------=!
SUBROUTINE ecutoffs_setup( ecutwfc_, ecutrho_, ecfixed_, qcutz_, &
q2sigma_, refg_ )
!------------------------------------------------------------------------------!
USE kinds, ONLY: DP
USE constants, ONLY: eps8
USE gvecw, ONLY: ecutwfc
USE gvecw, ONLY: ecfixed, qcutz, q2sigma
USE gvect, ONLY: ecutrho
USE gvecs, ONLY: ecuts, dual, doublegrid
USE pseudopotential, only: tpstab
USE io_global, only: stdout, ionode
USE uspp, only: okvan
use betax, only: mmx, refg
IMPLICIT NONE
REAL(DP), INTENT(IN) :: ecutwfc_, ecutrho_, ecfixed_, qcutz_, &
q2sigma_, refg_
ecutwfc = ecutwfc_
IF ( ecutrho_ <= 0.D0 ) THEN
!
dual = 4.D0
!
ELSE
!
dual = ecutrho_ / ecutwfc
!
IF ( dual <= 1.D0 ) &
CALL errore( ' ecutoffs_setup ', ' invalid dual? ', 1 )
!
END IF
doublegrid = ( dual > 4.0_dp + eps8 )
IF ( doublegrid .AND. .NOT. okvan ) &
CALL errore( 'setup', 'No USPP: set ecutrho=4*ecutwfc', 1 )
ecutrho = dual * ecutwfc
!
IF ( doublegrid ) THEN
!
ecuts = 4.D0 * ecutwfc
!
ELSE
!
ecuts = ecutrho
!
END IF
!
ecfixed = ecfixed_
qcutz = qcutz_
q2sigma = q2sigma_
IF( refg_ < 0.0001d0 ) THEN
tpstab = .FALSE.
refg = 0.05d0
ELSE
refg = refg_
END IF
CALL set_interpolation_table_size( mmx, refg, ecutrho )
RETURN
END SUBROUTINE ecutoffs_setup
SUBROUTINE set_interpolation_table_size( mmx, refg, gmax )
USE control_flags, only: thdyn
USE kinds, only: DP
IMPLICIT NONE
INTEGER, INTENT(OUT) :: mmx
REAL(DP), INTENT(IN) :: refg
REAL(DP), INTENT(IN) :: gmax
IF( thdyn ) THEN
! ... a larger table is used when cell is moving to allow
! ... large volume fluctuation
mmx = NINT( 2.0d0 * gmax / refg )
ELSE
mmx = NINT( 1.2d0 * gmax / refg )
END IF
RETURN
END SUBROUTINE set_interpolation_table_size
SUBROUTINE gcutoffs_setup( alat, tk_inp, nk_inp, kpoints_inp )
! (describe briefly what this routine does...)
! ----------------------------------------------
USE kinds, ONLY: DP
USE gvecw, ONLY: ecutwfc, gcutw
USE gvect, ONLY: ecutrho, gcutm
USE gvecs, ONLY: ecuts, gcutms
USE gvecw, ONLY: ekcut, gkcut
USE constants, ONLY: eps8, pi
IMPLICIT NONE
! ... declare subroutine arguments
REAL(DP), INTENT(IN) :: alat
LOGICAL, INTENT(IN) :: tk_inp
INTEGER, INTENT(IN) :: nk_inp
REAL(DP), INTENT(IN) :: kpoints_inp(3,*)
! ... declare other variables
INTEGER :: i
REAL(DP) :: kcut, ksq
REAL(DP) :: tpiba
! end of declarations
! ----------------------------------------------
! ... Set Values for the cutoff
IF( alat < eps8 ) THEN
CALL errore(' cut-off setup ', ' alat too small ', 0)
END IF
tpiba = 2.0d0 * pi / alat
! ... Constant cutoff simulation parameters
gcutw = ecutwfc / tpiba**2 ! wave function cut-off
gcutm = ecutrho / tpiba**2 ! potential cut-off
gcutms= ecuts / tpiba**2 ! smooth mesh cut-off
kcut = 0.0_DP
IF ( tk_inp ) THEN
! ... augment plane wave cutoff to include all k+G's
DO i = 1, nk_inp
! ... calculate modulus
ksq = kpoints_inp( 1, i ) ** 2 + kpoints_inp( 2, i ) ** 2 + kpoints_inp( 3, i ) ** 2
IF ( ksq > kcut ) kcut = ksq
END DO
END IF
gkcut = ( sqrt( kcut ) + sqrt( gcutw ) ) ** 2
ekcut = gkcut * tpiba ** 2
RETURN
END SUBROUTINE gcutoffs_setup
! ----------------------------------------------
SUBROUTINE cutoffs_print_info()
! Print out information about different cut-offs
USE gvecw, ONLY: ecutwfc, gcutw
USE gvect, ONLY: ecutrho, gcutm
USE gvecw, ONLY: ecfixed, qcutz, q2sigma
USE gvecw, ONLY: ekcut, gkcut
USE gvecs, ONLY: ecuts, gcutms
use betax, only: mmx, refg
USE io_global, ONLY: stdout
USE input_parameters, ONLY: ref_cell, ref_alat
WRITE( stdout, 100 ) ecutwfc, ecutrho, ecuts, sqrt(gcutw), &
sqrt(gcutm), sqrt(gcutms)
IF(ref_cell) WRITE( stdout,'(3X,"Reference Cell alat is",F14.8,1X,"A.U is used to Compute Gcutoffs:")') ref_alat ! BS : debug
IF( qcutz > 0.0d0 ) THEN
WRITE( stdout, 150 ) qcutz, q2sigma, ecfixed
END IF
WRITE( stdout,200) refg, mmx
100 FORMAT(/,3X,'Energy Cut-offs',/ &
,3X,'---------------',/ &
,3X,'Ecutwfc = ',F6.1,' Ry, ', 3X,'Ecutrho = ',F6.1,' Ry, ', 3X,'Ecuts = ',F6.1,' Ry',/ &
,3X,'Gcutwfc = ',F6.1,' , ', 3X,'Gcutrho = ',F6.1,' ', 3X,'Gcuts = ',F6.1)
150 FORMAT( 3X,'modified kinetic energy functional, with parameters:',/, &
3X,'ecutz = ',f8.4,' ecsig = ', f7.4,' ecfix = ',f6.2)
200 FORMAT( 3X,'NOTA BENE: refg, mmx = ', f10.6,I6 )
RETURN
END SUBROUTINE cutoffs_print_info
! ----------------------------------------------
SUBROUTINE orthogonalize_info( )
USE control_flags, ONLY: ortho_eps, ortho_max
USE io_global, ONLY: stdout
IMPLICIT NONE
WRITE(stdout, 585)
WRITE(stdout, 511) ortho_eps, ortho_max
511 FORMAT( 3X,'Orthog. with lagrange multipliers : eps = ',E10.2, ', max = ',I3)
585 FORMAT( 3X,'Eigenvalues calculated without the kinetic term contribution')
RETURN
END SUBROUTINE orthogonalize_info
! ----------------------------------------------
SUBROUTINE electrons_print_info( )
USE kinds, ONLY: DP
USE electrons_base, ONLY: nbnd, nspin, nel, nelt, nupdwn, iupdwn, &
f, qbac
USE io_global, ONLY: stdout
USE ions_base, ONLY: zv, nsp, na
IMPLICIT NONE
INTEGER :: i,is
IF( nspin == 1) THEN
WRITE(stdout,6) nelt, nbnd
WRITE(stdout,7) ( f( i ), i = 1, nbnd )
ELSE
WRITE(stdout,8) nelt
WRITE(stdout,9) nel(1)
WRITE(stdout,7) ( f( i ), i = 1, nupdwn(1))
WRITE(stdout,10) nel(2)
WRITE(stdout,7) ( f( i ), i = iupdwn(2), ( iupdwn(2) + nupdwn(2) - 1 ) )
END IF
qbac=0.
do is=1,nsp
qbac=qbac+na(is)*zv(is)
end do
qbac=qbac-nelt
if(qbac.ne.0) write(stdout,11) qbac
6 FORMAT(/,3X,'Electronic states',/ &
,3X,'-----------------',/ &
,3X,'Number of Electrons= ',I5,', of States = ',I5,/ &
,3X,'Occupation numbers :')
7 FORMAT(2X,10F5.2)
8 FORMAT(/,3X,'Electronic states',/ &
,3X,'-----------------',/ &
,3X,'Local Spin Density calculation',/ &
,3X,'Number of Electrons= ',I5)
9 FORMAT( 3X,'Spins up = ', I5, ', occupations: ')
10 FORMAT( 3X,'Spins down = ', I5, ', occupations: ')
11 FORMAT(/,3X,'WARNING: system charge = ',F12.6)
RETURN
END SUBROUTINE electrons_print_info
! ----------------------------------------------
SUBROUTINE exch_corr_print_info()
USE funct, ONLY: write_dft_name
USE io_global, ONLY: stdout
IMPLICIT NONE
WRITE(stdout,800)
call write_dft_name ( )
800 FORMAT(//,3X,'Exchange and correlations functionals',/ &
,3X,'-------------------------------------')
RETURN
END SUBROUTINE exch_corr_print_info
! ----------------------------------------------
SUBROUTINE ions_print_info( )
! Print info about input parameter for ion dynamic
USE io_global, ONLY: ionode, stdout
USE control_flags, ONLY: tranp, amprp, tnosep, tolp, tfor, tsdp, &
tzerop, tv0rd, taurdr, nbeg, tcp, tcap
USE ions_base, ONLY: if_pos, nsp, na, tau, ityp, &
amass, nat, fricp, greasp, rcmax
USE ions_nose, ONLY: tempw, ndega
USE constants, ONLY: amu_au
IMPLICIT NONE
integer is, ia, k, ic
LOGICAL :: ismb( 3 )
WRITE( stdout, 50 )
IF( .NOT. tfor ) THEN
WRITE( stdout, 518 )
ELSE
WRITE( stdout, 520 )
IF( tsdp ) THEN
WRITE( stdout, 521 )
ELSE
WRITE( stdout, 522 )
END IF
WRITE( stdout, 523 ) ndega
WRITE( stdout, 524 ) fricp, greasp
IF( tv0rd ) THEN
WRITE( stdout, 850 )
ELSE IF ( tzerop ) THEN
WRITE( stdout, 635 )
ENDIF
END IF
DO is = 1, nsp
IF( tranp(is) ) THEN
WRITE( stdout,510)
WRITE( stdout,512) is, amprp(is)
END IF
END DO
WRITE(stdout,660)
DO is = 1, nsp
WRITE(stdout,1000) is, na(is), amass(is)*amu_au, amass(is), rcmax(is)
DO ia = 1, nat
IF( ityp(ia) == is ) THEN
WRITE(stdout,1010) ( tau(k,ia), K = 1,3 )
END IF
END DO
END DO
IF ( ( nbeg > -1 ) .AND. ( .NOT. taurdr ) ) THEN
WRITE(stdout,661)
ELSE
WRITE(stdout,662)
ENDIF
IF( tfor ) THEN
IF( ANY( ( if_pos( 1:3, 1:nat ) == 0 ) ) ) THEN
WRITE(stdout,1020)
WRITE(stdout,1022)
DO ia = 1, nat
ismb( 1 ) = ( if_pos(1,ia) /= 0 )
ismb( 2 ) = ( if_pos(2,ia) /= 0 )
ismb( 3 ) = ( if_pos(3,ia) /= 0 )
IF( .NOT. ALL( ismb ) ) THEN
WRITE( stdout, 1023 ) ia, ( ismb(k), K = 1, 3 )
END IF
END DO
ELSE
WRITE(stdout,1021)
END IF
END IF
IF( tfor ) THEN
if( ( tcp .or. tcap .or. tnosep ) .and. tsdp ) then
call errore(' ions_print_info', &
' Temperature control not allowed with steepest descent',1)
endif
IF(.not. tcp .and. .not. tcap .and. .not. tnosep ) THEN
WRITE( stdout,550)
ELSE IF( tcp .and. tcap ) then
call errore(' ions_print_info', ' Velocity rescaling not' &
//' compatible with random velocity initialization',1)
ELSE IF( tcp .and. tnosep ) then
call errore(' ions_print_info', ' Velocity rescaling and' &
//' Nose thermostat are incompatible',1)
ELSE IF(tcap .and. tnosep ) then
call errore(' ions_print_info', ' Nose thermostat not' &
//' compatible with random velocity initialization',1)
ELSE IF(tcp) THEN
WRITE( stdout,555) tempw,tolp
!ELSE IF(tcap) THEN !tcap is random velocity initialization!
! WRITE( stdout,560) tempw,tolp
ELSE IF(tnosep) THEN
WRITE( stdout,595)
ELSE
WRITE( stdout,550)
END IF
END IF
50 FORMAT(//,3X,'Ions Simulation Parameters',/ &
,3X,'--------------------------')
510 FORMAT( 3X,'Initial random displacement of ionic coordinates',/, &
3X,' specie amplitude')
512 FORMAT( 3X,I7,2X,F9.6)
518 FORMAT( 3X,'Ions are not allowed to move')
520 FORMAT( 3X,'Ions are allowed to move')
521 FORMAT( 3X,'Ions dynamics with steepest descent')
522 FORMAT( 3X,'Ions dynamics with newton equations')
523 format( 3X,'the temperature is computed for ',i5,' degrees of freedom')
524 format( 3X,'ion dynamics with fricp = ',f7.4,' and greasp = ',f7.4)
550 FORMAT( 3X,'Ionic temperature is not controlled')
555 FORMAT( 3X,'Ionic temperature control via ', &
'rescaling of velocities :',/ &
,3X,'temperature required = ',F10.5,'K, ', &
'tolerance = ',F10.5,'K')
560 FORMAT( 3X,'Ionic temperature control via ', &
'canonical velocities rescaling :',/ &
,3X,'temperature required = ',F10.5,'K, ', &
'tolerance = ',F10.5,'K')
595 FORMAT( 3X,'Ionic temperature control via nose thermostat')
635 FORMAT( 3X,'Zero initial momentum for ions')
660 FORMAT( 3X,'Ionic position (from input)', /, &
3X,'sorted by specie, and converted to real a.u. coordinates')
661 FORMAT( 3X,'Ionic position will be re-read from restart file')
662 FORMAT( 3X,'Ionic position read from input file')
850 FORMAT( 3X,'Initial ion velocities read from input')
1000 FORMAT(3X,'Species ',I3,' atoms = ',I4,' mass = ',F12.2, ' (a.u.), ', &
& F12.2, ' (amu)', ' rcmax = ', F6.2, ' (a.u.)' )
1010 FORMAT(3X,3(1X,F12.6))
1020 FORMAT(/,3X,'NOT all atoms are allowed to move ')
1021 FORMAT(/,3X,'All atoms are allowed to move')
1022 FORMAT( 3X,' indx ..x.. ..y.. ..z..')
1023 FORMAT( 3X,I4,3(1X,L5))
RETURN
END SUBROUTINE ions_print_info
! ----------------------------------------------
subroutine cell_print_info( )
USE constants, ONLY: au_gpa
USE control_flags, ONLY: thdyn, tsdc, tzeroc, tbeg, nbeg, tpre
USE control_flags, ONLY: tnoseh
USE io_global, ONLY: stdout
USE cell_base, ONLY: press, frich, greash, wmass
IMPLICIT NONE
WRITE(stdout,545 )
IF ( tpre ) WRITE( stdout, 600 )
IF ( tbeg ) THEN
WRITE(stdout,546)
ELSE
WRITE(stdout,547)
IF( nbeg > -1 ) WRITE( stdout, 548 )
END IF
IF( .NOT. thdyn ) THEN
WRITE( stdout,525)
WRITE( stdout,606)
ELSE
IF( tsdc ) THEN
WRITE( stdout,526)
ELSE
IF( frich /= 0.0d0 ) THEN
WRITE( stdout,602) frich, greash
ELSE
WRITE( stdout,527)
END IF
IF( tnoseh ) then
WRITE( stdout,604)
ELSE
WRITE( stdout,565)
END IF
IF( tzeroc ) THEN
WRITE( stdout,563)
ENDIF
END IF
WRITE( stdout,530) press * au_gpa, wmass
END IF
545 FORMAT(//,3X,'Cell Dynamics Parameters (from STDIN)',/ &
,3X,'-------------------------------------')
546 FORMAT( 3X,'Simulation cell read from STDIN')
547 FORMAT( 3X,'Starting cell generated from CELLDM')
548 FORMAT( 3X,'Cell parameters will be re-read from restart file')
525 FORMAT( 3X,'Constant VOLUME Molecular dynamics')
606 format( 3X,'cell parameters are not allowed to move')
526 FORMAT( 3X,'Volume dynamics with steepest descent')
527 FORMAT( 3X,'Volume dynamics with newton equations')
530 FORMAT( 3X,'Constant PRESSURE Molecular dynamics:',/ &
,3X,'External pressure (GPa) = ',F11.2,/ &
,3X,'Volume mass = ',F11.2)
563 FORMAT( 3X,'Zero initial momentum for cell variables')
565 FORMAT( 3X,'Volume dynamics: the temperature is not controlled')
604 format( 3X,'cell parameters dynamics with nose` temp. control' )
600 format( 3X, 'internal stress tensor calculated')
602 format( 3X, 'cell parameters dynamics with frich = ',f7.4, &
& 3X, 'and greash = ',f7.4 )
return
end subroutine cell_print_info
!----------------------------------------------
SUBROUTINE gmeshinfo( )
!----------------------------------------------
!
! Print out the number of g vectors for the different mesh
!
USE kinds, ONLY: DP
USE mp_global, ONLY: nproc_bgrp, intra_bgrp_comm
USE io_global, ONLY: ionode, ionode_id, stdout
USE mp, ONLY: mp_max, mp_gather
use smallbox_gvec, only: ngb
USE gvecw, only: ngw_g, ngw, ngwx
USE gvecs, only: ngms_g, ngms, ngsx
USE gvect, only: ngm, ngm_g, ngmx
USE fft_base, ONLY: dfftp, dffts
IMPLICIT NONE
INTEGER :: ip, ng_snd(3), ng_rcv( 3, nproc_bgrp )
INTEGER :: ierr, min_val, max_val, i
REAL(DP) :: avg_val
IF( ngm /= dfftp%ngm ) THEN
CALL errore( " gmeshinfo ", " number of G-vectors in module gvect not consistent with FFT descriptor ", 1 )
END IF
IF( ngms /= dffts%ngm ) THEN
CALL errore( " gmeshinfo ", " number of G-vectors in module gvecs not consistent with FFT descriptor ", 2 )
END IF
IF( ngw /= dffts%ngw ) THEN
CALL errore( " gmeshinfo ", " number of G-vectors in module gvecw not consistent with FFT descriptor ", 2 )
END IF
IF(ionode) THEN
WRITE( stdout,*)
WRITE( stdout,*) ' Reciprocal Space Mesh'
WRITE( stdout,*) ' ---------------------'
END IF
ng_snd(1) = ngm_g
ng_snd(2) = ngm
ng_snd(3) = ngmx
CALL mp_gather(ng_snd, ng_rcv, ionode_id, intra_bgrp_comm)
!
IF(ionode) THEN
min_val = MINVAL( ng_rcv(2,:) )
max_val = MAXVAL( ng_rcv(2,:) )
avg_val = REAL(SUM( ng_rcv(2,:) ))/nproc_bgrp
WRITE( stdout,1000)
WRITE( stdout,1011) ng_snd(1), min_val, max_val, avg_val
END IF
!
ng_snd(1) = ngms_g
ng_snd(2) = ngms
ng_snd(3) = ngsx
CALL mp_gather(ng_snd, ng_rcv, ionode_id, intra_bgrp_comm)
!
ierr = 0
!
IF(ionode) THEN
WRITE( stdout,1001)
min_val = MINVAL( ng_rcv(2,:) )
max_val = MAXVAL( ng_rcv(2,:) )
avg_val = REAL(SUM( ng_rcv(2,:) ))/nproc_bgrp
WRITE( stdout,1011) ng_snd(1), min_val, max_val, avg_val
IF( min_val < 1 ) ierr = ip
END IF
!
CALL mp_max( ierr, intra_bgrp_comm )
!
IF( ierr > 0 ) &
CALL errore( " gmeshinfo ", " Wow! some processors have no G-vectors ", ierr )
!
ng_snd(1) = ngw_g
ng_snd(2) = ngw
ng_snd(3) = ngwx
CALL mp_gather(ng_snd, ng_rcv, ionode_id, intra_bgrp_comm)
!
IF(ionode) THEN
WRITE( stdout,1002)
min_val = MINVAL( ng_rcv(2,:) )
max_val = MAXVAL( ng_rcv(2,:) )
avg_val = REAL(SUM( ng_rcv(2,:) ))/nproc_bgrp
WRITE( stdout,1011) ng_snd(1), min_val, max_val, avg_val
IF( min_val < 1 ) ierr = ip
END IF
!
CALL mp_max( ierr, intra_bgrp_comm )
!
IF( ierr > 0 ) &
CALL errore( " gmeshinfo ", " Wow! some processors have no G-vectors ", ierr )
!
IF(ionode .AND. ngb > 0 ) THEN
WRITE( stdout,1050)
WRITE( stdout,1060) ngb
END IF
1000 FORMAT(3X,'Large Mesh',/, &
' Global(ngm_g) MinLocal MaxLocal Average')
1001 FORMAT(3X,'Smooth Mesh',/, &
' Global(ngms_g) MinLocal MaxLocal Average')
1002 FORMAT(3X,'Wave function Mesh',/, &
' Global(ngw_g) MinLocal MaxLocal Average')
1011 FORMAT( 3I15, F15.2 )
1050 FORMAT(/,3X,'Small box Mesh')
1060 FORMAT( 3X, 'ngb = ', I12, ' not distributed to processors' )
RETURN
END SUBROUTINE gmeshinfo
!----------------------------------------------
SUBROUTINE constraint_info()
!----------------------------------------------
USE kinds, ONLY: DP
USE constraints_module, ONLY: nconstr, constr_tol, &
constr_type, constr, constr_target
USE io_global, ONLY: ionode, stdout
USE control_flags, ONLY: lconstrain
!
IMPLICIT NONE
!
INTEGER :: ic
!
IF( lconstrain .AND. ionode ) THEN
!
WRITE( stdout, 10 )
WRITE( stdout, 20 ) nconstr, constr_tol
!
DO ic = 1, nconstr
!
IF( constr_type( ic ) == 3 ) THEN
!
! distance
!
WRITE( stdout, 30 ) ic
WRITE( stdout, 40 ) NINT( constr(1,ic) ), &
NINT( constr(2,ic) ), constr_target(ic)
!
END IF
!
END DO
!
END IF
!
10 FORMAT( 3X, "Using constrained dynamics")
20 FORMAT( 3X, "number of constrain and tolerance: ", I5, D10.2)
30 FORMAT( 3X, "constrain ", I5, " type distance ")
40 FORMAT( 3X, " atoms ", I5, I5, " target dist ", F10.5)
!
END SUBROUTINE constraint_info
SUBROUTINE new_atomind_constraints()
!
USE kinds, ONLY: DP
USE constraints_module, ONLY: constr
!
IMPLICIT NONE
!
INTEGER :: ic, ia
INTEGER :: iaa
REAL(DP) :: aa
!
! Substitute the atom index given in the input file
! with the new atom index, after the sort in the
! atomic coordinates.
!
DO ic = 1, SIZE( constr, 2 )
DO ia = 1, SIZE( constr, 1 )
IF( constr( ia, ic ) > 0.0d0 ) THEN
iaa = NINT( constr( ia, ic ) )
aa = DBLE( iaa )
constr( ia, ic ) = aa
END IF
END DO
END DO
!
RETURN
!
END SUBROUTINE new_atomind_constraints
SUBROUTINE compute_stress_x( stress, detot, h, omega )
USE kinds, ONLY : DP
IMPLICIT NONE
REAL(DP), INTENT(OUT) :: stress(3,3)
REAL(DP), INTENT(IN) :: detot(3,3), h(3,3), omega
integer :: i, j
do i=1,3
do j=1,3
stress(i,j)=-1.d0/omega*(detot(i,1)*h(j,1)+ &
& detot(i,2)*h(j,2)+detot(i,3)*h(j,3))
enddo
enddo
return
END SUBROUTINE compute_stress_x
!-----------------------------------------------------------------------
subroutine formf( tfirst, eself )
!-----------------------------------------------------------------------
!computes (a) the self-energy eself of the ionic pseudocharges;
! (b) the form factors of: (i) pseudopotential (vps),
! (ii) ionic pseudocharge (rhops)
! also calculated the derivative of vps with respect to
! g^2 (dvps)
!
USE kinds, ONLY : DP
use mp, ONLY : mp_sum
use control_flags, ONLY : iprint, tpre, iverbosity
use io_global, ONLY : stdout
use mp_global, ONLY : intra_bgrp_comm
USE fft_base, ONLY : dffts
use cell_base, ONLY : omega, tpiba2, tpiba
use ions_base, ONLY : rcmax, zv, nsp, na
use local_pseudo, ONLY : vps, vps0, rhops, dvps, drhops
use atom, ONLY : rgrid
use uspp_param, ONLY : upf
use pseudo_base, ONLY : compute_rhops, formfn, formfa, compute_eself
use pseudopotential, ONLY : tpstab, vps_sp, dvps_sp
use splines, ONLY : spline
use gvect, ONLY : gstart, gg
use constants, ONLY : autoev
!
implicit none
logical :: tfirst
real(DP) :: eself, DeltaV0
!
real(DP) :: vpsum, rhopsum
integer :: is, ig
REAL(DP) :: cost1, xg
call start_clock( 'formf' )
!
IF( .NOT. ALLOCATED( rgrid ) ) &
CALL errore( ' formf ', ' rgrid not allocated ', 1 )
IF( .NOT. ALLOCATED( upf ) ) &
CALL errore( ' formf ', ' upf not allocated ', 1 )
!
! calculation of gaussian selfinteraction
!
eself = compute_eself( na, zv, rcmax, nsp )
if( tfirst .or. ( iverbosity > 2 ) )then
WRITE( stdout, 1200 ) eself
endif
!
1200 format(/,3x,'formf: eself=',f12.5)
!
do is = 1, nsp
IF( tpstab ) THEN
!
! Use interpolation table, with cubic spline
!
cost1 = 1.0d0/omega
!
IF( gstart == 2 ) THEN
vps (1,is) = vps_sp(is)%y(1) * cost1
dvps(1,is) = dvps_sp(is)%y(1) * cost1
END IF
!
DO ig = gstart, dffts%ngm
xg = SQRT( gg(ig) ) * tpiba
vps (ig,is) = spline( vps_sp(is), xg ) * cost1
dvps(ig,is) = spline( dvps_sp(is), xg ) * cost1
END DO
!
ELSE
call formfn( rgrid(is)%r, rgrid(is)%rab, &
upf(is)%vloc(1:rgrid(is)%mesh), zv(is), rcmax(is), gg, &
omega, tpiba2, rgrid(is)%mesh, dffts%ngm, tpre, &
vps(:,is), vps0(is), dvps(:,is) )
! obsolete BHS form
! call formfa( vps(:,is), dvps(:,is), rc1(is), rc2(is), wrc1(is), wrc2(is), &
! rcl(:,is,lloc(is)), al(:,is,lloc(is)), bl(:,is,lloc(is)), &
! zv(is), rcmax(is), g, omega, tpiba2, dffts%ngm, gstart, tpre )
END IF
!
! fourier transform of local pp and gaussian nuclear charge
!
call compute_rhops( rhops(:,is), drhops(:,is), zv(is), rcmax(is), gg, &
omega, tpiba2, dffts%ngm, tpre )
if( tfirst .or. ( iverbosity > 2 ) )then
vpsum = SUM( vps( 1:dffts%ngm, is ) )
rhopsum = SUM( rhops( 1:dffts%ngm, is ) )
call mp_sum( vpsum, intra_bgrp_comm )
call mp_sum( rhopsum, intra_bgrp_comm )
WRITE( stdout,1250) (vps(ig,is),rhops(ig,is),ig=1,5)
WRITE( stdout,1300) vpsum,rhopsum
endif
!
end do
!
! ... DeltaV0 is the shift to be applied to eigenvalues
! ... in order to align them to other plane wave codes
!
DeltaV0 = 0.0_dp
DO is = 1, nsp
!
! ... na(is)/omega is the structure factor at G=0
!
DeltaV0 = DeltaV0 + na(is) / omega * vps0(is)
END DO
!
IF ( tfirst .or. ( iverbosity > 2 ) ) THEN
write(6,'(" Delta V(G=0): ",f10.6,"Ry, ",f11.6,"eV")') &
deltaV0, deltaV0*autoev
END IF
!
call stop_clock( 'formf' )
!
1250 format(3x,'formf: vps(g=0)=',f12.7,' rhops(g=0)=',f12.7)
1300 format(3x,'formf: sum_g vps(g)=',f12.7,' sum_g rhops(g)=',f12.7)
!
return
end subroutine formf
!
!-----------------------------------------------------------------------
SUBROUTINE newnlinit()
!-----------------------------------------------------------------------
!
! ... this routine calculates arrays beta, qq, qgb, rhocb
! ... and derivatives w.r.t. cell parameters dbeta
! ... See also comments in nlinit
!
use control_flags, ONLY : tpre
use pseudopotential, ONLY : tpstab
use cp_interfaces, ONLY : interpolate_beta, interpolate_qradb, compute_qradx, compute_betagx, &
exact_beta, check_tables, exact_qradb, build_pstab, build_cctab
use betax, only : mmx, refg
use kinds, only : dp
use io_global, only : ionode, stdout
!
IMPLICIT NONE
!
LOGICAL :: recompute_table
REAL(DP) :: gmax
!
! ... initialization for vanderbilt species
!
CALL start_clock( 'newnlinit' )
IF( tpstab ) THEN
recompute_table = tpre .AND. check_tables( gmax )
!
IF ( recompute_table ) THEN
IF( ionode ) &
WRITE( stdout, * ) "newnliinit: recomputing the pseudopotentials tables"
!"!
CALL set_interpolation_table_size( mmx, refg, gmax )
CALL compute_qradx( tpre )
call compute_betagx( tpre )
call build_pstab()
!
call build_cctab()
END IF
!
! initialization that is common to all species
!
CALL interpolate_beta( tpre )
!
CALL interpolate_qradb( tpre )
!
ELSE
!
! ... this is mainly for testing
!
CALL exact_beta( tpre )
!
CALL exact_qradb( tpre )
!
END IF
!
! ... non-linear core-correction ( rhocb(ig,is) )
!
CALL core_charge_ftr( tpre )
CALL stop_clock( 'newnlinit' )
!
RETURN
!
END SUBROUTINE newnlinit
!
!-----------------------------------------------------------------------
subroutine nlfh_x( stress, bec_bgrp, dbec, lambda, idesc )
!-----------------------------------------------------------------------
!
! contribution to the internal stress tensor due to the constraints
!
USE kinds, ONLY : DP
use uspp, ONLY : nkb, qq_nt, ofsbeta
use uspp_param, ONLY : nh, nhm, upf
use ions_base, ONLY : nat, ityp
use electrons_base, ONLY : nbspx, nbsp, nudx, nspin, nupdwn, iupdwn, ibgrp_g2l
use cell_base, ONLY : omega, h
use constants, ONLY : pi, fpi, au_gpa
use io_global, ONLY : stdout
use control_flags, ONLY : iverbosity
USE mp, ONLY : mp_sum
USE mp_global, ONLY : intra_bgrp_comm, inter_bgrp_comm
!
implicit none
include 'laxlib.fh'
INTEGER, INTENT(IN) :: idesc(:,:)
REAL(DP), INTENT(INOUT) :: stress(3,3)
REAL(DP), INTENT(IN) :: bec_bgrp( :, : ), dbec( :, :, :, : )
REAL(DP), INTENT(IN) :: lambda( :, :, : )
!
INTEGER :: i, j, ii, jj, inl, iv, jv, ia, is, iss, nss, istart
INTEGER :: jnl, ir, ic, nr, nc, ibgrp_i, nrcx
REAL(DP) :: fpre(3,3), TT, T1, T2
!
REAL(DP), ALLOCATABLE :: tmpbec(:,:), tmpdh(:,:), temp(:,:), bec(:,:,:)
!
nrcx = MAXVAL( idesc( LAX_DESC_NRCX, : ) )
!
ALLOCATE( bec( nkb, nrcx, nspin ) )
!
DO iss = 1, nspin
IF( idesc( LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
nss = nupdwn( iss )
istart = iupdwn( iss )
ic = idesc( LAX_DESC_IC, iss )
nc = idesc( LAX_DESC_NC, iss )
DO i=1,nc
ibgrp_i = ibgrp_g2l( i+istart-1+ic-1 )
IF( ibgrp_i > 0 ) THEN
bec( :, i, iss ) = bec_bgrp( :, ibgrp_i )
ELSE
bec( :, i, iss ) = 0.0d0
END IF
END DO
ELSE
bec(:,:,iss) = 0.0d0
END IF
END DO
CALL mp_sum( bec, inter_bgrp_comm )
!
IF (nspin == 1) THEN
IF( ( idesc( LAX_DESC_ACTIVE_NODE, 1 ) > 0 ) ) THEN
ALLOCATE ( tmpbec(nhm,nrcx), tmpdh(nrcx,nhm), temp(nrcx,nrcx) )
ENDIF
ELSEIF (nspin == 2) THEN
IF( ( idesc( LAX_DESC_ACTIVE_NODE, 1 ) > 0 ) .OR. ( idesc( LAX_DESC_ACTIVE_NODE, 2 ) > 0 ) ) THEN
ALLOCATE ( tmpbec(nhm,nrcx), tmpdh(nrcx,nhm), temp(nrcx,nrcx) )
END IF
ENDIF
!
fpre = 0.d0
!
do ii=1,3
do jj=1,3
do ia=1,nat
is = ityp(ia)
IF( upf(is)%tvanp ) THEN
do iss = 1, nspin
!
istart = iupdwn( iss )
nss = nupdwn( iss )
!
IF( idesc( LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
ic = idesc( LAX_DESC_IC, iss )
nc = idesc( LAX_DESC_NC, iss )
ir = idesc( LAX_DESC_IR, iss )
nr = idesc( LAX_DESC_NR, iss )
tmpbec = 0.d0
tmpdh = 0.d0
!
do iv=1,nh(is)
do jv=1,nh(is)
inl=ofsbeta(ia) + jv
if(abs(qq_nt(iv,jv,is)).gt.1.e-5) then
do i = 1, nc
tmpbec(iv,i) = tmpbec(iv,i) + qq_nt(iv,jv,is) * bec( inl, i, iss )
end do
endif
end do
end do
do iv=1,nh(is)
inl=ofsbeta(ia) + iv
do i = 1, nr
tmpdh(i,iv) = dbec( inl, i + (iss-1)*nrcx, ii, jj )
end do
end do
if(nh(is).gt.0)then
CALL dgemm &
( 'N', 'N', nr, nc, nh(is), 1.0d0, tmpdh, nrcx, tmpbec, nhm, 0.0d0, temp, nrcx )
do j = 1, nc
do i = 1, nr
fpre(ii,jj) = fpre(ii,jj) + 2D0 * temp( i, j ) * lambda(i,j,iss)
end do
end do
endif
END IF
!
end do
!
END IF
!
end do
!
end do
!
end do
CALL mp_sum( fpre, intra_bgrp_comm )
do i=1,3
do j=1,3
stress(i,j)=stress(i,j)+ &
(fpre(i,1)*h(j,1)+fpre(i,2)*h(j,2)+fpre(i,3)*h(j,3))/omega
enddo
enddo
IF (allocated(tmpbec)) THEN
DEALLOCATE ( tmpbec, tmpdh, temp )
END IF
DEALLOCATE( bec )
IF( iverbosity > 1 ) THEN
WRITE( stdout,*)
WRITE( stdout,*) "constraints contribution to stress"
WRITE( stdout,5555) ((-fpre(i,j),j=1,3),i=1,3)
fpre = MATMUL( fpre, TRANSPOSE( h ) ) / omega * au_gpa * 10.0d0
WRITE( stdout,5555) ((fpre(i,j),j=1,3),i=1,3)
WRITE( stdout,*)
END IF
!
5555 FORMAT(1x,f12.5,1x,f12.5,1x,f12.5/ &
& 1x,f12.5,1x,f12.5,1x,f12.5/ &
& 1x,f12.5,1x,f12.5,1x,f12.5//)
return
end subroutine nlfh_x
!-----------------------------------------------------------------------
subroutine nlinit
!-----------------------------------------------------------------------
!
! this routine allocates and initializes arrays beta, qq, qgb,
! rhocb, and derivatives w.r.t. cell parameters dbeta
!
! beta(ig,l,is) = 4pi/sqrt(omega) y^r(l,q^)
! int_0^inf dr r^2 j_l(qr) betar(l,is,r)
!
! Note that beta(g)_lm,is = (-i)^l*beta(ig,l,is) (?)
!
! qq_ij=int_0^r q_ij(r)=omega*qg(g=0)
!
! beta and qradb are first calculated on a fixed linear grid in |G|
! (betax, qradx) then calculated on the box grid by interpolation
! (this is done in routine newnlinit)
!
use kinds, ONLY : dp
use control_flags, ONLY : iprint, tpre
use io_global, ONLY : stdout, ionode
use gvecw, ONLY : ngw
use core, ONLY : rhocb, allocate_core
use constants, ONLY : pi, fpi
use ions_base, ONLY : na, nsp
use uspp, ONLY : aainit, beta, qq_nt, dvan, nhtol, nhtolm, indv,&
dbeta, qq_nt_d
use uspp_param, ONLY : upf, lmaxq, nbetam, lmaxkb, nhm, nh
use atom, ONLY : rgrid
use qgb_mod, ONLY : qgb, dqgb
use smallbox_gvec, ONLY : ngb
use cp_interfaces, ONLY : pseudopotential_indexes, compute_dvan, &
compute_betagx, compute_qradx, build_pstab, build_cctab
USE fft_base, ONLY : dfftp
use pseudopotential, ONLY : tpstab
!
implicit none
!
integer is, il, l, ir, iv, jv, lm, ind, ltmp, i0
real(dp), allocatable:: fint(:), jl(:), jltmp(:), djl(:), &
& dfint(:)
real(dp) xg, xrg, fac
CALL start_clock( 'nlinit' )
IF( ionode ) THEN
WRITE( stdout, 100 )
100 FORMAT( //, &
3X,'Pseudopotentials initialization',/, &
3X,'-------------------------------' )
END IF
IF( .NOT. ALLOCATED( rgrid ) ) &
CALL errore( ' nlinit ', ' rgrid not allocated ', 1 )
IF( .NOT. ALLOCATED( upf ) ) &
CALL errore( ' nlinit ', ' upf not allocated ', 1 )
!
! initialize indexes
!
CALL pseudopotential_indexes( )
!
! initialize array ap
!
call aainit( lmaxkb + 1 )
!
CALL allocate_core( dfftp%nnr, dfftp%ngm, ngb, nsp )
!
!
allocate( beta( ngw, nhm, nsp ) )
allocate( qgb( ngb, nhm*(nhm+1)/2, nsp ) )
allocate( qq_nt( nhm, nhm, nsp ) )
qq_nt (:,:,:) =0.d0
IF (tpre) THEN
allocate( dqgb( ngb, nhm*(nhm+1)/2, nsp, 3, 3 ) )
allocate( dbeta( ngw, nhm, nsp, 3, 3 ) )
END IF
#ifdef __CUDA
ALLOCATE( qq_nt_d(nhm,nhm,nsp) )
#endif
!
! initialization for vanderbilt species
!
CALL compute_qradx( tpre )
!
! initialization that is common to all species
!
WRITE( stdout, fmt="(//,3X,'Common initialization' )" )
do is = 1, nsp
WRITE( stdout, fmt="(/,3X,'Specie: ',I5)" ) is
! fac converts ry to hartree
fac=0.5d0
do iv = 1, nh(is)
WRITE( stdout,901) iv, indv(iv,is), nhtol(iv,is)
end do
901 format(2x,i2,' indv= ',i2,' ang. mom= ',i2)
!
WRITE( stdout,*)
WRITE( stdout,'(20x,a)') ' dion '
do iv = 1, upf(is)%nbeta
WRITE( stdout,'(8f9.4)') ( fac*upf(is)%dion(iv,jv), jv = 1, upf(is)%nbeta )
end do
!
end do
!
! calculation of array betagx(ig,iv,is)
!
call compute_betagx( tpre )
!
! calculate array dvan(iv,jv,is)
!
call compute_dvan()
!
IF( tpstab ) THEN
call build_pstab()
!
call build_cctab()
!
END IF
!
! newnlinit stores qgb and qq, calculates arrays beta rhocb
! and derivatives wrt cell dbeta
!
call newnlinit()
CALL stop_clock( 'nlinit' )
return
end subroutine nlinit
!-------------------------------------------------------------------------
subroutine qvan2b(ngy,iv,jv,is,ylm,qg,qradb)
!--------------------------------------------------------------------------
!
! q(g,l,k) = sum_lm (-i)^l ap(lm,l,k) yr_lm(g^) qrad(g,l,l,k)
!
USE kinds, ONLY : DP
use control_flags, ONLY : iprint, tpre
use uspp, ONLY : nlx, lpx, lpl, ap, indv, nhtolm
use smallbox_gvec, ONLY : ngb
use uspp_param, ONLY : lmaxq, nbetam
use ions_base, ONLY : nsp
!
implicit none
!
integer, intent(in) :: ngy, iv, jv, is
real(DP), intent(in) :: ylm( ngb, lmaxq*lmaxq )
real(DP), intent(in) :: qradb( ngb, nbetam*(nbetam+1)/2, lmaxq, nsp )
complex(DP), intent(out) :: qg( ngb )
!
integer :: ivs, jvs, ijvs, ivl, jvl, i, ii, ij, l, lp, ig
complex(DP) :: sig
!
! iv = 1..8 s_1 p_x1 p_z1 p_y1 s_2 p_x2 p_z2 p_y2
! ivs = 1..4 s_1 s_2 p_1 p_2
! ivl = 1..4 s p_x p_z p_y
!
ivs=indv(iv,is)
jvs=indv(jv,is)
if (ivs >= jvs) then
ijvs = ivs*(ivs-1)/2 + jvs
else
ijvs = jvs*(jvs-1)/2 + ivs
end if
! ijvs is the packed index for (ivs,jvs)
ivl=nhtolm(iv,is)
jvl=nhtolm(jv,is)
if (ivl > nlx .OR. jvl > nlx) &
call errore (' qvan2b ', ' wrong dimensions', MAX(ivl,jvl))
!
qg(:) = (0.d0, 0.d0)
!
! lpx = max number of allowed y_lm
! lp = composite lm to indentify them
!
do i=1,lpx(ivl,jvl)
lp=lpl(ivl,jvl,i)
if (lp > lmaxq*lmaxq) call errore(' qvan2b ',' lp out of bounds ',lp)
!
! extraction of angular momentum l from lp:
! l = int ( sqrt( DBLE(l-1) + epsilon) ) + 1
!
if (lp == 1) then
l=1
else if ((lp >= 2) .and. (lp <= 4)) then
l=2
else if ((lp >= 5) .and. (lp <= 9)) then
l=3
else if ((lp >= 10).and.(lp <= 16)) then
l=4
else if ((lp >= 17).and.(lp <= 25)) then
l=5
else if ((lp >= 26).and.(lp <= 36)) then
l=6
else if ((lp >= 37).and.(lp <= 49)) then
l=7
else
call errore(' qvan2b ',' not implemented ',lp)
endif
!
! sig= (-i)^l
!
sig=(0.d0,-1.d0)**(l-1)
sig=sig*ap(lp,ivl,jvl)
do ig=1,ngy
qg(ig)=qg(ig)+sig*ylm(ig,lp)*qradb(ig,ijvs,l,is)
end do
end do
return
end subroutine qvan2b
!-------------------------------------------------------------------------
subroutine dqvan2b(ngy,iv,jv,is,ylm,dylm,dqg,dqrad,qradb)
!--------------------------------------------------------------------------
!
! dq(i,j) derivatives wrt to h(i,j) of q(g,l,k) calculated in qvan2b
!
USE kinds, ONLY : DP
use control_flags, ONLY : iprint, tpre
use uspp, ONLY : nlx, lpx, lpl, ap, indv, nhtolm
use smallbox_gvec, ONLY : ngb
use uspp_param, ONLY : lmaxq, nbetam
use ions_base, ONLY : nsp
implicit none
integer, intent(in) :: ngy, iv, jv, is
REAL(DP), INTENT(IN) :: ylm( ngb, lmaxq*lmaxq ), dylm( ngb, lmaxq*lmaxq, 3, 3 )
complex(DP), intent(out) :: dqg( ngb, 3, 3 )
REAL(DP), INTENT(IN) :: dqrad( ngb, nbetam*(nbetam+1)/2, lmaxq, nsp, 3, 3 )
real(DP), intent(in) :: qradb( ngb, nbetam*(nbetam+1)/2, lmaxq, nsp )
integer :: ivs, jvs, ijvs, ivl, jvl, i, ii, ij, l, lp, ig
complex(DP) :: sig, z1, z2, zfac
!
!
! iv = 1..8 s_1 p_x1 p_z1 p_y1 s_2 p_x2 p_z2 p_y2
! ivs = 1..4 s_1 s_2 p_1 p_2
! ivl = 1..4 s p_x p_z p_y
!
ivs=indv(iv,is)
jvs=indv(jv,is)
!
if (ivs >= jvs) then
ijvs = ivs*(ivs-1)/2 + jvs
else
ijvs = jvs*(jvs-1)/2 + ivs
end if
!
! ijvs is the packed index for (ivs,jvs)
!
ivl=nhtolm(iv,is)
jvl=nhtolm(jv,is)
!
if (ivl > nlx .OR. jvl > nlx) &
call errore (' qvan2 ', ' wrong dimensions (2)', MAX(ivl,jvl))
!
dqg(:,:,:) = (0.d0, 0.d0)
! lpx = max number of allowed y_lm
! lp = composite lm to indentify them
z1 = 0.0d0
z2 = 0.0d0
do i=1,lpx(ivl,jvl)
lp=lpl(ivl,jvl,i)
if (lp > lmaxq*lmaxq) call errore(' dqvan2b ',' lp out of bounds ',lp)
! extraction of angular momentum l from lp:
! l = int ( sqrt( DBLE(l-1) + epsilon) ) + 1
!
if (lp == 1) then
l=1
else if ((lp >= 2) .and. (lp <= 4)) then
l=2
else if ((lp >= 5) .and. (lp <= 9)) then
l=3
else if ((lp >= 10).and.(lp <= 16)) then
l=4
else if ((lp >= 17).and.(lp <= 25)) then
l=5
else if ((lp >= 26).and.(lp <= 36)) then
l=6
else if ((lp >= 37).and.(lp <= 49)) then
l=7
else
call errore(' qvan2b ',' not implemented ',lp)
endif
!
! sig= (-i)^l
!
sig = (0.0d0,-1.0d0)**(l-1)
!
sig = sig * ap( lp, ivl, jvl )
!
do ij=1,3
do ii=1,3
do ig=1,ngy
zfac = ylm(ig,lp) * dqrad(ig,ijvs,l,is,ii,ij)
zfac = zfac - dylm(ig,lp,ii,ij) * qradb(ig,ijvs,l,is)
dqg(ig,ii,ij) = dqg(ig,ii,ij) + sig * zfac
end do
end do
end do
end do
!
! WRITE(6,*) 'DEBUG dqvan2b: ', z1, z2
!
return
end subroutine dqvan2b
!-----------------------------------------------------------------------
subroutine dylmr2_( nylm, ngy, g, gg, ainv, dylm )
!-----------------------------------------------------------------------
!
! temporary CP interface for PW routine dylmr2
! dylmr2 calculates d Y_{lm} /d G_ipol
! dylmr2_ calculates G_ipol \sum_k h^(-1)(jpol,k) (dY_{lm} /dG_k)
!
USE kinds, ONLY: DP
implicit none
!
integer, intent(IN) :: nylm, ngy
real(DP), intent(IN) :: g (3, ngy), gg (ngy), ainv(3,3)
real(DP), intent(OUT) :: dylm (ngy, nylm, 3, 3)
!
integer :: ipol, jpol, lm, ig
real(DP), allocatable :: dylmaux (:,:,:)
!
allocate ( dylmaux(ngy,nylm,3) )
!
dylmaux(:,:,:) = 0.d0
!
do ipol =1,3
call dylmr2 (nylm, ngy, g, gg, dylmaux(1,1,ipol), ipol)
enddo
!
do ipol =1,3
do jpol =1,3
do lm=1,nylm
do ig = 1, ngy
dylm (ig,lm,ipol,jpol) = (dylmaux(ig,lm,1) * ainv(jpol,1) + &
dylmaux(ig,lm,2) * ainv(jpol,2) + &
dylmaux(ig,lm,3) * ainv(jpol,3) ) &
* g(ipol,ig)
end do
end do
end do
end do
!
deallocate ( dylmaux )
!
return
!
end subroutine dylmr2_
!-----------------------------------------------------------------------
SUBROUTINE denlcc_x( nnr, nspin, vxcr, sfac, drhocg, dcc )
!-----------------------------------------------------------------------
!
! derivative of non linear core correction exchange energy wrt cell
! parameters h
! Output in dcc
!
USE kinds, ONLY: DP
USE ions_base, ONLY: nsp
USE gvect, ONLY: gstart, g, gg
USE cell_base, ONLY: omega, ainv, tpiba2
USE mp, ONLY: mp_sum
USE mp_global, ONLY: intra_bgrp_comm
USE uspp_param, ONLY: upf
USE fft_interfaces, ONLY: fwfft
USE fft_base, ONLY: dfftp, dffts
USE fft_helper_subroutines, ONLY: fftx_threed2oned
IMPLICIT NONE
! input
INTEGER, INTENT(IN) :: nnr, nspin
REAL(DP), INTENT(IN) :: vxcr( :, : )
COMPLEX(DP), INTENT(IN) :: sfac( :, : )
REAL(DP), INTENT(IN) :: drhocg( :, : )
! output
REAL(DP), INTENT(OUT) :: dcc( :, : )
! local
INTEGER :: i, j, ig, is
COMPLEX(DP) :: srhoc
REAL(DP) :: vxcc
!
COMPLEX(DP), ALLOCATABLE :: vxc( : ), vxg(:)
!
dcc = 0.0d0
!
ALLOCATE( vxc( nnr ) )
ALLOCATE( vxg( dfftp%ngm ) )
!
vxc(:) = vxcr(:,1)
!
IF( nspin > 1 ) vxc(:) = vxc(:) + vxcr(:,2)
!
CALL fwfft( 'Rho', vxc, dfftp )
CALL fftx_threed2oned( dfftp, vxc, vxg )
!
DO i=1,3
DO j=1,3
DO ig = gstart, dffts%ngm
srhoc = 0.0d0
DO is = 1, nsp
IF( upf(is)%nlcc ) srhoc = srhoc + sfac( ig, is ) * drhocg( ig, is )
ENDDO
vxcc = DBLE( CONJG( vxg( ig ) ) * srhoc ) / SQRT( gg(ig) * tpiba2 )
dcc(i,j) = dcc(i,j) + vxcc * &
& 2.d0 * tpiba2 * g(i,ig) * &
& (g(1,ig)*ainv(j,1) + &
& g(2,ig)*ainv(j,2) + &
& g(3,ig)*ainv(j,3) )
ENDDO
ENDDO
ENDDO
DEALLOCATE( vxg )
DEALLOCATE( vxc )
dcc = dcc * omega
CALL mp_sum( dcc( 1:3, 1:3 ), intra_bgrp_comm )
RETURN
END SUBROUTINE denlcc_x
!-----------------------------------------------------------------------
SUBROUTINE dotcsc_x( betae, cp, ngw, n )
!-----------------------------------------------------------------------
!
USE kinds, ONLY: DP
USE ions_base, ONLY: na, nsp, nat, ityp
USE io_global, ONLY: stdout
USE gvect, ONLY: gstart
USE uspp, ONLY: nkb, qq_nt, ofsbeta
USE uspp_param, ONLY: nh, upf
USE mp, ONLY: mp_sum
USE mp_global, ONLY: intra_bgrp_comm, nbgrp, inter_bgrp_comm
USE cp_interfaces, ONLY: calbec
USE electrons_base, ONLY: ispin, ispin_bgrp, nbspx_bgrp, ibgrp_g2l, iupdwn, nupdwn, nbspx
!
IMPLICIT NONE
!
INTEGER, INTENT(IN) :: ngw, n
COMPLEX(DP), INTENT(IN) :: cp(:,:)
COMPLEX(DP), INTENT(INOUT) :: betae(:,:)
! local variables
REAL(DP) rsum, csc(n) ! automatic array
COMPLEX(DP) temp(ngw) ! automatic array
REAL(DP), ALLOCATABLE:: becp(:,:), cp_tmp(:), becp_tmp(:)
INTEGER i,kmax,nnn,k,ig,is,ia,iv,jv,inl,jnl
INTEGER :: ibgrp_i, ibgrp_k
!
ALLOCATE( becp( nkb, nbspx_bgrp ) )
ALLOCATE( cp_tmp( SIZE( cp, 1 ) ) )
ALLOCATE( becp_tmp( nkb ) )
!
! < beta | phi > is real. only the i lowest:
!
CALL calbec( nbspx_bgrp, betae, cp, becp, 2 )
nnn = MIN( 12, n )
DO i = nnn, 1, -1
csc = 0.0d0
ibgrp_i = ibgrp_g2l( i )
IF( ibgrp_i > 0 ) THEN
cp_tmp = cp( :, ibgrp_i )
ELSE
cp_tmp = 0.0d0
END IF
CALL mp_sum( cp_tmp, inter_bgrp_comm )
kmax = i
!
DO k=1,kmax
ibgrp_k = ibgrp_g2l( k )
IF( ibgrp_k > 0 ) THEN
DO ig=1,ngw
temp(ig)=CONJG(cp(ig,ibgrp_k))*cp_tmp(ig)
END DO
csc(k)=2.d0*DBLE(SUM(temp))
IF (gstart == 2) csc(k)=csc(k)-DBLE(temp(1))
END IF
END DO
CALL mp_sum( csc( 1:kmax ), intra_bgrp_comm )
IF( ibgrp_i > 0 ) THEN
becp_tmp = becp( :, ibgrp_i )
ELSE
becp_tmp = 0.0d0
END IF
CALL mp_sum( becp_tmp, inter_bgrp_comm )
DO k=1,kmax
rsum=0.d0
ibgrp_k = ibgrp_g2l( k )
IF( ibgrp_k > 0 ) THEN
DO is=1,nsp
IF( .NOT. upf(is)%tvanp ) CYCLE
DO ia=1,nat
IF( ityp(ia) /= is ) CYCLE
DO iv=1,nh(is)
DO jv=1,nh(is)
inl = ofsbeta(ia) + iv
jnl = ofsbeta(ia) + jv
rsum = rsum + qq_nt(iv,jv,is)*becp_tmp(inl)*becp(jnl,ibgrp_k)
END DO
END DO
END DO
END DO
END IF
csc(k)=csc(k)+rsum
END DO
!
CALL mp_sum( csc( 1:kmax ), inter_bgrp_comm )
WRITE( stdout,'("dotcsc =",12f18.15)') (csc(k),k=1,i)
!
END DO
WRITE( stdout,*)
!
DEALLOCATE(becp)
DEALLOCATE(cp_tmp)
DEALLOCATE(becp_tmp)
!
RETURN
END SUBROUTINE dotcsc_x
!
!-----------------------------------------------------------------------
FUNCTION enkin_x( c, f, n )
!-----------------------------------------------------------------------
!
! calculation of kinetic energy term
!
USE kinds, ONLY: DP
USE constants, ONLY: pi, fpi
USE gvecw, ONLY: ngw
USE gvect, ONLY: gstart
USE gvecw, ONLY: g2kin
USE mp, ONLY: mp_sum
USE mp_global, ONLY: intra_bgrp_comm
USE cell_base, ONLY: tpiba2
IMPLICIT NONE
REAL(DP) :: enkin_x
! input
INTEGER, INTENT(IN) :: n
COMPLEX(DP), INTENT(IN) :: c( :, : )
REAL(DP), INTENT(IN) :: f( : )
!
! local
INTEGER :: ig, i
REAL(DP) :: sk, rsum
!
sk = 0.0d0
!$omp parallel do reduction(+:sk) default(none) &
!$omp shared(c,g2kin,gstart,ngw,n,f) private(i,ig,rsum)
DO i=1,n
rsum = 0.0d0
DO ig=gstart,ngw
rsum = rsum + DBLE(CONJG(c(ig,i))*c(ig,i)) * g2kin(ig)
END DO
sk = sk + f(i) * rsum
END DO
!$omp end parallel do
CALL mp_sum( sk, intra_bgrp_comm )
! ... reciprocal-space vectors are in units of alat/(2 pi) so a
! ... multiplicative factor (2 pi/alat)**2 is required
enkin_x = tpiba2 * sk
!
RETURN
END FUNCTION enkin_x
#if defined (__CUDA)
!-----------------------------------------------------------------------
FUNCTION enkin_gpu_x( c, f, n )
!-----------------------------------------------------------------------
!
USE kinds, ONLY: DP
USE constants, ONLY: pi, fpi
USE gvecw, ONLY: ngw
USE gvect, ONLY: gstart
USE gvecw, ONLY: g2kin_d
USE mp, ONLY: mp_sum
USE mp_global, ONLY: intra_bgrp_comm
USE cell_base, ONLY: tpiba2
USE cudafor
IMPLICIT NONE
REAL(DP) :: enkin_gpu_x
INTEGER, INTENT(IN) :: n
COMPLEX(DP), DEVICE, INTENT(IN) :: c( :, : )
REAL(DP), DEVICE, INTENT(IN) :: f( : )
!
! local
INTEGER :: ig, i
REAL(DP) :: sk
!
sk=0.0d0
!$cuf kernel do(2) <<<*,*>>>
DO i=1,n
DO ig=gstart,ngw
sk = sk + f(i) * DBLE(CONJG(c(ig,i))*c(ig,i)) * g2kin_d(ig)
END DO
END DO
CALL mp_sum( sk, intra_bgrp_comm )
enkin_gpu_x = tpiba2 * sk
!
RETURN
END FUNCTION enkin_gpu_x
#endif
!-------------------------------------------------------------------------
SUBROUTINE nlfl_bgrp_x( bec_bgrp, becdr_bgrp, lambda, idesc, fion )
!-----------------------------------------------------------------------
! contribution to fion due to the orthonormality constraint
!
!
USE kinds, ONLY: DP
USE io_global, ONLY: stdout
USE ions_base, ONLY: na, nsp, nat, ityp
USE uspp, ONLY: nhsa=>nkb, qq_nt, ofsbeta
USE uspp_param, ONLY: nhm, nh, upf
USE electrons_base, ONLY: nspin, iupdwn, nupdwn, nbspx_bgrp, ibgrp_g2l, i2gupdwn_bgrp, nbspx, &
iupdwn_bgrp, nupdwn_bgrp
USE constants, ONLY: pi, fpi
USE mp, ONLY: mp_sum
USE mp_global, ONLY: intra_bgrp_comm, inter_bgrp_comm
!
IMPLICIT NONE
include 'laxlib.fh'
REAL(DP) :: bec_bgrp(:,:), becdr_bgrp(:,:,:)
REAL(DP), INTENT(IN) :: lambda(:,:,:)
INTEGER, INTENT(IN) :: idesc(:,:)
REAL(DP), INTENT(INOUT) :: fion(:,:)
!
INTEGER :: k, is, ia, iv, jv, i, j, inl, isa, iss, nss, istart, ir, ic, nr, nc, ibgrp_i
INTEGER :: n1, n2, m1, m2, nrcx
INTEGER :: nrr(nspin), irr, nrrx
REAL(DP), ALLOCATABLE :: temp(:,:), tmpbec(:,:),tmpdr(:,:), tmplam(:,:,:)
REAL(DP), ALLOCATABLE :: fion_tmp(:,:)
REAL(DP), ALLOCATABLE :: bec(:,:,:)
INTEGER, ALLOCATABLE :: ibgrp_l2g(:,:)
!
CALL start_clock( 'nlfl' )
!
ALLOCATE( fion_tmp( 3, nat ) )
!
fion_tmp = 0.0d0
!
nrcx = MAXVAL( idesc( LAX_DESC_NRCX, : ) )
!
! redistribute bec, becdr according to the ortho subgroup
! this is required because they are combined with "lambda" matrixes
CALL compute_nrr( nrr )
nrrx = MAXVAL(nrr)
IF( nrrx > 0 ) THEN
ALLOCATE( tmplam( nrrx, nrcx, nspin ) )
ALLOCATE( ibgrp_l2g( nrrx, nspin ) )
END IF
CALL get_local_bec()
CALL get_local_lambda()
!
!$omp parallel default(none), &
!$omp shared(nrrx,nhm,nrcx,nsp,na,nspin,nrr,nupdwn,iupdwn,idesc,nh,qq_nt,bec,becdr_bgrp,ibgrp_l2g,tmplam,fion_tmp), &
!$omp shared(upf, ityp,nat,ofsbeta), &
!$omp private(tmpdr,temp,tmpbec,is,k,ia,i,iss,nss,istart,ic,nc,jv,iv,inl,ir,nr)
IF( nrrx > 0 ) THEN
ALLOCATE( tmpdr( nrrx, nhm ) )
ALLOCATE( temp( nrrx, nrcx ) )
END IF
ALLOCATE( tmpbec( nhm, nrcx ) )
DO k=1,3
DO is=1,nsp
IF( .NOT. upf(is)%tvanp ) CYCLE
!$omp do
DO ia=1,nat
IF( ityp(ia) /= is ) CYCLE
!
DO iss = 1, nspin
!
IF( nrr(iss) == 0 ) CYCLE
!
nss = nupdwn( iss )
istart = iupdwn( iss )
!
tmpbec = 0.d0
!
IF( idesc( LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
! tmpbec distributed by columns
ic = idesc( LAX_DESC_IC, iss )
nc = idesc( LAX_DESC_NC, iss )
DO jv=1,nh(is)
inl = ofsbeta(ia) + jv
DO iv=1,nh(is)
IF(ABS(qq_nt(iv,jv,is)).GT.1.e-5) THEN
DO i=1,nc
tmpbec(iv,i)=tmpbec(iv,i) + qq_nt(iv,jv,is)*bec(inl,i,iss)
END DO
END IF
END DO
END DO
! tmpdr distributed by rows
ir = idesc( LAX_DESC_IR, iss )
nr = idesc( LAX_DESC_NR, iss )
DO iv=1,nh(is)
inl = ofsbeta(ia) + iv
DO i=1,nrr(iss)
tmpdr(i,iv) = becdr_bgrp( inl, ibgrp_l2g(i,iss), k )
END DO
END DO
END IF
!
IF( nh(is) > 0 )THEN
IF( idesc( LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
nc = idesc( LAX_DESC_NC, iss )
CALL dgemm( 'N', 'N', nrr(iss), nc, nh(is), 1.0d0, tmpdr, nrrx, tmpbec, nhm, 0.0d0, temp, nrrx )
DO j = 1, nc
DO i = 1, nrr(iss)
fion_tmp(k,ia) = fion_tmp(k,ia) + 2D0 * temp( i, j ) * tmplam( i, j, iss )
END DO
END DO
END IF
ENDIF
END DO
END DO
!$omp end do
END DO
END DO
!
DEALLOCATE( tmpbec )
!
IF(ALLOCATED(temp)) DEALLOCATE( temp )
IF(ALLOCATED(tmpdr)) DEALLOCATE( tmpdr )
!$omp end parallel
DEALLOCATE( bec )
IF(ALLOCATED(tmplam)) DEALLOCATE( tmplam )
IF(ALLOCATED(ibgrp_l2g)) DEALLOCATE( ibgrp_l2g )
!
CALL mp_sum( fion_tmp, inter_bgrp_comm )
CALL mp_sum( fion_tmp, intra_bgrp_comm )
!
fion = fion + fion_tmp
!
DEALLOCATE( fion_tmp )
!
CALL stop_clock( 'nlfl' )
!
RETURN
CONTAINS
SUBROUTINE compute_nrr( nrr )
INTEGER, INTENT(OUT) :: nrr(:)
nrr = 0
DO iss = 1, nspin
nss = nupdwn( iss )
istart = iupdwn( iss )
IF( idesc(LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
ir = idesc( LAX_DESC_IR, iss )
nr = idesc( LAX_DESC_NR, iss )
DO i=1,nr
ibgrp_i = ibgrp_g2l( i+istart-1+ir-1 )
IF( ibgrp_i > 0 ) THEN
nrr(iss) = nrr(iss) + 1
END IF
END DO
END IF
END DO
END SUBROUTINE compute_nrr
SUBROUTINE get_local_bec
ALLOCATE( bec( nhsa, nrcx, nspin ) )
DO iss = 1, nspin
nss = nupdwn( iss )
istart = iupdwn( iss )
IF( idesc(LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
ic = idesc( LAX_DESC_IC, iss )
nc = idesc( LAX_DESC_NC, iss )
DO i=1,nc
ibgrp_i = ibgrp_g2l( i+istart-1+ic-1 )
IF( ibgrp_i > 0 ) THEN
bec( :, i, iss ) = bec_bgrp( :, ibgrp_i )
ELSE
bec( :, i, iss ) = 0.0d0
END IF
END DO
ELSE
bec(:,:,iss) = 0.0d0
END IF
END DO
CALL mp_sum( bec, inter_bgrp_comm )
END SUBROUTINE get_local_bec
SUBROUTINE get_local_lambda
DO iss = 1, nspin
nss = nupdwn( iss )
istart = iupdwn( iss )
IF( idesc(LAX_DESC_ACTIVE_NODE, iss ) > 0 ) THEN
ir = idesc( LAX_DESC_IR, iss )
nr = idesc( LAX_DESC_NR, iss )
irr = 0
DO i=1,nr
ibgrp_i = ibgrp_g2l( i+istart-1+ir-1 )
IF( ibgrp_i > 0 ) THEN
irr = irr + 1
tmplam(irr,:,iss) = lambda(i,:,iss)
ibgrp_l2g(irr,iss) = ibgrp_i
END IF
END DO
tmplam( irr + 1 : nrrx , :, iss ) = 0.0d0
tmplam( 1 : nrrx , idesc( LAX_DESC_NC, iss ) + 1 : nrcx, iss ) = 0.0d0
END IF
END DO
END SUBROUTINE get_local_lambda
END SUBROUTINE nlfl_bgrp_x
!
!-----------------------------------------------------------------------
SUBROUTINE pbc(rin,a1,a2,a3,ainv,rout)
!-----------------------------------------------------------------------
!
! brings atoms inside the unit cell
!
USE kinds, ONLY: DP
IMPLICIT NONE
! input
REAL(DP) rin(3), a1(3),a2(3),a3(3), ainv(3,3)
! output
REAL(DP) rout(3)
! local
REAL(DP) x,y,z
!
! bring atomic positions to crystal axis
!
x = ainv(1,1)*rin(1)+ainv(1,2)*rin(2)+ainv(1,3)*rin(3)
y = ainv(2,1)*rin(1)+ainv(2,2)*rin(2)+ainv(2,3)*rin(3)
z = ainv(3,1)*rin(1)+ainv(3,2)*rin(2)+ainv(3,3)*rin(3)
!
! bring x,y,z in the range between -0.5 and 0.5
!
x = x - NINT(x)
y = y - NINT(y)
z = z - NINT(z)
!
! bring atomic positions back in cartesian axis
!
rout(1) = x*a1(1)+y*a2(1)+z*a3(1)
rout(2) = x*a1(2)+y*a2(2)+z*a3(2)
rout(3) = x*a1(3)+y*a2(3)+z*a3(3)
!
RETURN
END SUBROUTINE pbc
!
!-------------------------------------------------------------------------
SUBROUTINE prefor_x(eigr,betae)
!-----------------------------------------------------------------------
!
! input : eigr = e^-ig.r_i
! output: betae_i,i(g) = (-i)**l beta_i,i(g) e^-ig.r_i
!
USE kinds, ONLY : DP
USE ions_base, ONLY : nat, ityp
USE gvecw, ONLY : ngw
USE uspp, ONLY : beta, nhtol, ofsbeta
USE uspp_param, ONLY : nh, upf
USE gvect, ONLY : gstart
!
IMPLICIT NONE
COMPLEX(DP), INTENT(IN) :: eigr( :, : )
COMPLEX(DP), INTENT(OUT) :: betae( :, : )
!
INTEGER :: is, iv, ia, inl, ig, isa
COMPLEX(DP), PARAMETER, DIMENSION(4) :: cfact = & ! (l == 0), (l == 1), (l == 2), (l == 3)
[( 1.0_dp , 0.0_dp ), ( 0.0_dp , -1.0_dp ), ( -1.0_dp , 0.0_dp ), ( 0.0_dp , 1.0_dp )]
COMPLEX(DP) :: ci
!
CALL start_clock( 'prefor' )
!$omp parallel do default(shared) private(ia,is,iv,ci,inl,ig)
DO ia=1,nat
is=ityp(ia)
DO iv=1,nh(is)
ci=cfact( nhtol(iv,is) + 1 )
inl = ofsbeta(ia) + iv
DO ig=1,ngw
betae(ig,inl)=ci*beta(ig,iv,is)*eigr(ig,ia)
END DO
!beigr(1,inl)=betae(1,inl)
!DO ig=gstart,ngw
! beigr(ig,inl)=2.0d0 * betae(ig,inl)
!END DO
END DO
END DO
!$omp end parallel do
CALL stop_clock( 'prefor' )
!
RETURN
END SUBROUTINE prefor_x
!------------------------------------------------------------------------
SUBROUTINE collect_bec_x( bec_repl, bec_dist, idesc, nspin )
!------------------------------------------------------------------------
USE kinds, ONLY : DP
USE mp_global, ONLY : intra_bgrp_comm
USE mp, ONLY : mp_sum
USE io_global, ONLY : stdout
IMPLICIT NONE
include 'laxlib.fh'
REAL(DP), INTENT(OUT) :: bec_repl(:,:)
REAL(DP), INTENT(IN) :: bec_dist(:,:)
INTEGER, INTENT(IN) :: idesc(:,:)
INTEGER, INTENT(IN) :: nspin
INTEGER :: i, ir, n, nrcx, iss
!
bec_repl = 0.0d0
!
! bec is distributed across row processor, the first column is enough
!
IF( idesc( LAX_DESC_ACTIVE_NODE, 1 ) > 0 .AND. ( idesc( LAX_DESC_MYC, 1 ) == 0 ) ) THEN
ir = idesc( LAX_DESC_IR, 1 )
DO i = 1, idesc( LAX_DESC_NR, 1 )
bec_repl( :, i + ir - 1 ) = bec_dist( :, i )
END DO
IF( nspin == 2 ) THEN
n = idesc( LAX_DESC_N, 1 ) ! number of states with spin==1 ( nupdw(1) )
nrcx = idesc( LAX_DESC_NRCX, 1 ) ! array elements reserved for each spin ( bec(:,2*nrcx) )
ir = idesc( LAX_DESC_IR, 2 )
DO i = 1, idesc( LAX_DESC_NR, 2 )
bec_repl( :, i + ir - 1 + n ) = bec_dist( :, i + nrcx )
END DO
END IF
END IF
!
CALL mp_sum( bec_repl, intra_bgrp_comm )
!
RETURN
END SUBROUTINE collect_bec_x
!
!------------------------------------------------------------------------
SUBROUTINE distribute_bec_x( bec_repl, bec_dist, idesc, nspin )
!------------------------------------------------------------------------
USE kinds, ONLY : DP
IMPLICIT NONE
include 'laxlib.fh'
REAL(DP), INTENT(IN) :: bec_repl(:,:)
REAL(DP), INTENT(OUT) :: bec_dist(:,:)
INTEGER, INTENT(IN) :: idesc(:,:)
INTEGER, INTENT(IN) :: nspin
INTEGER :: i, ir, n, nrcx
!
IF( idesc( LAX_DESC_ACTIVE_NODE, 1 ) > 0 ) THEN
!
bec_dist = 0.0d0
!
ir = idesc( LAX_DESC_IR, 1 )
DO i = 1, idesc( LAX_DESC_NR, 1 )
bec_dist( :, i ) = bec_repl( :, i + ir - 1 )
END DO
!
IF( nspin == 2 ) THEN
n = idesc( LAX_DESC_N, 1 ) ! number of states with spin 1 ( nupdw(1) )
nrcx = idesc( LAX_DESC_NRCX, 1 ) ! array elements reserved for each spin ( bec(:,2*nrcx) )
ir = idesc( LAX_DESC_IR, 2 )
DO i = 1, idesc( LAX_DESC_NR, 2 )
bec_dist( :, i + nrcx ) = bec_repl( :, i + ir - 1 + n )
END DO
END IF
!
END IF
RETURN
END SUBROUTINE distribute_bec_x
|
QEF/q-e
|
CPV/src/cplib.f90
|
FORTRAN
|
gpl-2.0
| 65,262 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.optim.linear;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.exception.TooManyIterationsException;
import org.apache.commons.math3.optim.PointValuePair;
import org.apache.commons.math3.util.Precision;
/**
* Solves a linear problem using the "Two-Phase Simplex" method.
* <p>
* <b>Note:</b> Depending on the problem definition, the default convergence criteria
* may be too strict, resulting in {@link NoFeasibleSolutionException} or
* {@link TooManyIterationsException}. In such a case it is advised to adjust these
* criteria with more appropriate values, e.g. relaxing the epsilon value.
* <p>
* Default convergence criteria:
* <ul>
* <li>Algorithm convergence: 1e-6</li>
* <li>Floating-point comparisons: 10 ulp</li>
* <li>Cut-Off value: 1e-12</li>
* </ul>
* <p>
* The cut-off value has been introduced to zero out very small numbers in the Simplex tableau,
* as these may lead to numerical instabilities due to the nature of the Simplex algorithm
* (the pivot element is used as a denominator). If the problem definition is very tight, the
* default cut-off value may be too small, thus it is advised to increase it to a larger value,
* in accordance with the chosen epsilon.
* <p>
* It may also be counter-productive to provide a too large value for {@link
* org.apache.commons.math3.optim.MaxIter MaxIter} as parameter in the call of {@link
* #optimize(org.apache.commons.math3.optim.OptimizationData...) optimize(OptimizationData...)},
* as the {@link SimplexSolver} will use different strategies depending on the current iteration
* count. After half of the allowed max iterations has already been reached, the strategy to select
* pivot rows will change in order to break possible cycles due to degenerate problems.
*
* @version $Id$
* @since 2.0
*/
public class SimplexSolver extends LinearOptimizer {
/** Default amount of error to accept in floating point comparisons (as ulps). */
static final int DEFAULT_ULPS = 10;
/** Default cut-off value. */
static final double DEFAULT_CUT_OFF = 1e-12;
/** Default amount of error to accept for algorithm convergence. */
private static final double DEFAULT_EPSILON = 1.0e-6;
/** Amount of error to accept for algorithm convergence. */
private final double epsilon;
/** Amount of error to accept in floating point comparisons (as ulps). */
private final int maxUlps;
/**
* Cut-off value for entries in the tableau: values smaller than the cut-off
* are treated as zero to improve numerical stability.
*/
private final double cutOff;
/**
* Builds a simplex solver with default settings.
*/
public SimplexSolver() {
this(DEFAULT_EPSILON, DEFAULT_ULPS, DEFAULT_CUT_OFF);
}
/**
* Builds a simplex solver with a specified accepted amount of error.
*
* @param epsilon Amount of error to accept for algorithm convergence.
*/
public SimplexSolver(final double epsilon) {
this(epsilon, DEFAULT_ULPS, DEFAULT_CUT_OFF);
}
/**
* Builds a simplex solver with a specified accepted amount of error.
*
* @param epsilon Amount of error to accept for algorithm convergence.
* @param maxUlps Amount of error to accept in floating point comparisons.
*/
public SimplexSolver(final double epsilon, final int maxUlps) {
this(epsilon, maxUlps, DEFAULT_CUT_OFF);
}
/**
* Builds a simplex solver with a specified accepted amount of error.
*
* @param epsilon Amount of error to accept for algorithm convergence.
* @param maxUlps Amount of error to accept in floating point comparisons.
* @param cutOff Values smaller than the cutOff are treated as zero.
*/
public SimplexSolver(final double epsilon, final int maxUlps, final double cutOff) {
this.epsilon = epsilon;
this.maxUlps = maxUlps;
this.cutOff = cutOff;
}
/**
* Returns the column with the most negative coefficient in the objective function row.
*
* @param tableau Simple tableau for the problem.
* @return the column with the most negative coefficient.
*/
private Integer getPivotColumn(SimplexTableau tableau) {
double minValue = 0;
Integer minPos = null;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getWidth() - 1; i++) {
final double entry = tableau.getEntry(0, i);
// check if the entry is strictly smaller than the current minimum
// do not use a ulp/epsilon check
if (entry < minValue) {
minValue = entry;
minPos = i;
}
}
return minPos;
}
/**
* Returns the row with the minimum ratio as given by the minimum ratio test (MRT).
*
* @param tableau Simple tableau for the problem.
* @param col Column to test the ratio of (see {@link #getPivotColumn(SimplexTableau)}).
* @return the row with the minimum ratio.
*/
private Integer getPivotRow(SimplexTableau tableau, final int col) {
// create a list of all the rows that tie for the lowest score in the minimum ratio test
List<Integer> minRatioPositions = new ArrayList<Integer>();
double minRatio = Double.MAX_VALUE;
for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) {
final double rhs = tableau.getEntry(i, tableau.getWidth() - 1);
final double entry = tableau.getEntry(i, col);
if (Precision.compareTo(entry, 0d, maxUlps) > 0) {
final double ratio = rhs / entry;
// check if the entry is strictly equal to the current min ratio
// do not use a ulp/epsilon check
final int cmp = Double.compare(ratio, minRatio);
if (cmp == 0) {
minRatioPositions.add(i);
} else if (cmp < 0) {
minRatio = ratio;
minRatioPositions = new ArrayList<Integer>();
minRatioPositions.add(i);
}
}
}
if (minRatioPositions.size() == 0) {
return null;
} else if (minRatioPositions.size() > 1) {
// there's a degeneracy as indicated by a tie in the minimum ratio test
// 1. check if there's an artificial variable that can be forced out of the basis
if (tableau.getNumArtificialVariables() > 0) {
for (Integer row : minRatioPositions) {
for (int i = 0; i < tableau.getNumArtificialVariables(); i++) {
int column = i + tableau.getArtificialVariableOffset();
final double entry = tableau.getEntry(row, column);
if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) {
return row;
}
}
}
}
// 2. apply Bland's rule to prevent cycling:
// take the row for which the corresponding basic variable has the smallest index
//
// see http://www.stanford.edu/class/msande310/blandrule.pdf
// see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper)
//
// Additional heuristic: if we did not get a solution after half of maxIterations
// revert to the simple case of just returning the top-most row
// This heuristic is based on empirical data gathered while investigating MATH-828.
if (getEvaluations() < getMaxEvaluations() / 2) {
Integer minRow = null;
int minIndex = tableau.getWidth();
final int varStart = tableau.getNumObjectiveFunctions();
final int varEnd = tableau.getWidth() - 1;
for (Integer row : minRatioPositions) {
for (int i = varStart; i < varEnd && !row.equals(minRow); i++) {
final Integer basicRow = tableau.getBasicRow(i);
if (basicRow != null && basicRow.equals(row)) {
if (i < minIndex) {
minIndex = i;
minRow = row;
}
}
}
}
return minRow;
}
}
return minRatioPositions.get(0);
}
/**
* Runs one iteration of the Simplex method on the given model.
*
* @param tableau Simple tableau for the problem.
* @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
* @throws UnboundedSolutionException if the model is found not to have a bounded solution.
*/
protected void doIteration(final SimplexTableau tableau)
throws TooManyIterationsException,
UnboundedSolutionException {
incrementIterationCount();
Integer pivotCol = getPivotColumn(tableau);
Integer pivotRow = getPivotRow(tableau, pivotCol);
if (pivotRow == null) {
throw new UnboundedSolutionException();
}
// set the pivot element to 1
double pivotVal = tableau.getEntry(pivotRow, pivotCol);
tableau.divideRow(pivotRow, pivotVal);
// set the rest of the pivot column to 0
for (int i = 0; i < tableau.getHeight(); i++) {
if (i != pivotRow) {
final double multiplier = tableau.getEntry(i, pivotCol);
tableau.subtractRow(i, pivotRow, multiplier);
}
}
}
/**
* Solves Phase 1 of the Simplex method.
*
* @param tableau Simple tableau for the problem.
* @throws TooManyIterationsException if the allowed number of iterations has been exhausted.
* @throws UnboundedSolutionException if the model is found not to have a bounded solution.
* @throws NoFeasibleSolutionException if there is no feasible solution?
*/
protected void solvePhase1(final SimplexTableau tableau)
throws TooManyIterationsException,
UnboundedSolutionException,
NoFeasibleSolutionException {
// make sure we're in Phase 1
if (tableau.getNumArtificialVariables() == 0) {
return;
}
while (!tableau.isOptimal()) {
doIteration(tableau);
}
// if W is not zero then we have no feasible solution
if (!Precision.equals(tableau.getEntry(0, tableau.getRhsOffset()), 0d, epsilon)) {
throw new NoFeasibleSolutionException();
}
}
/** {@inheritDoc} */
@Override
public PointValuePair doOptimize()
throws TooManyIterationsException,
UnboundedSolutionException,
NoFeasibleSolutionException {
final SimplexTableau tableau =
new SimplexTableau(getFunction(),
getConstraints(),
getGoalType(),
isRestrictedToNonNegative(),
epsilon,
maxUlps,
cutOff);
solvePhase1(tableau);
tableau.dropPhase1Objective();
while (!tableau.isOptimal()) {
doIteration(tableau);
}
return tableau.getSolution();
}
}
|
martingwhite/astor
|
examples/math_5/src/main/java/org/apache/commons/math3/optim/linear/SimplexSolver.java
|
Java
|
gpl-2.0
| 12,421 |
import numpy as np
from numpy import random
import cv2
def make_gaussians(cluster_n, img_size):
points = []
ref_distrs = []
for i in xrange(cluster_n):
mean = (0.1 + 0.8*random.rand(2)) * img_size
a = (random.rand(2, 2)-0.5)*img_size*0.1
cov = np.dot(a.T, a) + img_size*0.05*np.eye(2)
n = 100 + random.randint(900)
pts = random.multivariate_normal(mean, cov, n)
points.append( pts )
ref_distrs.append( (mean, cov) )
points = np.float32( np.vstack(points) )
return points, ref_distrs
def draw_gaussain(img, mean, cov, color):
x, y = np.int32(mean)
w, u, vt = cv2.SVDecomp(cov)
ang = np.arctan2(u[1, 0], u[0, 0])*(180/np.pi)
s1, s2 = np.sqrt(w)*3.0
cv2.ellipse(img, (x, y), (s1, s2), ang, 0, 360, color, 1, cv2.CV_AA)
if __name__ == '__main__':
cluster_n = 5
img_size = 512
print 'press any key to update distributions, ESC - exit\n'
while True:
print 'sampling distributions...'
points, ref_distrs = make_gaussians(cluster_n, img_size)
print 'EM (opencv) ...'
em = cv2.EM(points, params = dict( nclusters = cluster_n, cov_mat_type = cv2.EM_COV_MAT_GENERIC) )
means = em.getMeans()
covs = np.zeros((cluster_n, 2, 2), np.float32)
covs = em.getCovs(covs) # FIXME
found_distrs = zip(means, covs)
print 'ready!\n'
img = np.zeros((img_size, img_size, 3), np.uint8)
for x, y in np.int32(points):
cv2.circle(img, (x, y), 1, (255, 255, 255), -1)
for m, cov in ref_distrs:
draw_gaussain(img, m, cov, (0, 255, 0))
for m, cov in found_distrs:
draw_gaussain(img, m, cov, (0, 0, 255))
cv2.imshow('gaussian mixture', img)
ch = cv2.waitKey(0)
if ch == 27:
break
|
petterreinholdtsen/cinelerra-hv
|
thirdparty/OpenCV-2.3.1/samples/python2/gaussian_mix.py
|
Python
|
gpl-2.0
| 1,907 |
<!-- custom-made header -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.10"/>
<title>SPECFEM3D_GLOBE: SPECFEM3D_GLOBE/src/meshfem3D/model_attenuation.f90 File Reference</title>
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<link href="../../navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../resize.js"></script>
<script type="text/javascript" src="../../navtreedata.js"></script>
<script type="text/javascript" src="../../navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="../../defaultstyle.css" rel="stylesheet" type="text/css" />
<link href="../../mystyle.css" rel="stylesheet" type="text/css"/>
<!-- Loading Lato Font -->
<link href='https://fonts.googleapis.com/css?family=Lato:300,400,700,300italic,400italic,700italic' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;"> <!-- <td style="padding-left: 0.5em;"> -->
<div id="projectname">SPECFEM3D_GLOBE
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.10 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li><a href="../../namespaces.html"><span>Modules</span></a></li>
<li><a href="../../annotated.html"><span>Data Types List</span></a></li>
<li class="current"><a href="../../files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="../../search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="../../search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="../../files.html"><span>File List</span></a></li>
<li><a href="../../globals.html"><span>File Members</span></a></li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('d2/d2c/model__attenuation_8f90.html','../../');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="summary">
<a href="#func-members">Functions/Subroutines</a> </div>
<div class="headertitle">
<div class="title">model_attenuation.f90 File Reference</div> </div>
</div><!--header-->
<div class="contents">
<p><a href="../../d2/d2c/model__attenuation_8f90_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions/Subroutines</h2></td></tr>
<tr class="memitem:a99c4aed02d34fbd73c178c76243d0fb8"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a99c4aed02d34fbd73c178c76243d0fb8">model_attenuation_broadcast</a> (AM_V, MIN_ATTENUATION_PERIOD, MAX_ATTENUATION_PERIOD)</td></tr>
<tr class="separator:a99c4aed02d34fbd73c178c76243d0fb8"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a84b2f788d16d8c34200a57b2d5a79d08"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a84b2f788d16d8c34200a57b2d5a79d08">read_attenuation_model</a> (min_att_period, max_att_period, AM_V)</td></tr>
<tr class="separator:a84b2f788d16d8c34200a57b2d5a79d08"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:adad501987bfa3f86074c504228dba3b2"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#adad501987bfa3f86074c504228dba3b2">model_attenuation_setup</a> (REFERENCE_1D_MODEL, RICB, RCMB, R670, R220, R80, AM_V, AM_S, AS_V, CRUSTAL)</td></tr>
<tr class="separator:adad501987bfa3f86074c504228dba3b2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a22533e26244b9fa6eeaae249eaec38c3"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a22533e26244b9fa6eeaae249eaec38c3">model_attenuation_getstored_tau</a> (Qmu_in, T_c_source, tau_s, tau_e, AM_V, AM_S, AS_V)</td></tr>
<tr class="separator:a22533e26244b9fa6eeaae249eaec38c3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a610dc0b96c48f66a9eb8955d365c8011"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a610dc0b96c48f66a9eb8955d365c8011">model_attenuation_storage</a> (Qmu, tau_e, rw, AM_S)</td></tr>
<tr class="separator:a610dc0b96c48f66a9eb8955d365c8011"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3b6e84767fc408cbdb44a2f13cd21045"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a3b6e84767fc408cbdb44a2f13cd21045">attenuation_source_frequency</a> (omega_not, min_period, max_period)</td></tr>
<tr class="separator:a3b6e84767fc408cbdb44a2f13cd21045"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ad22e7810bd9c29714ce728aa0e5d6361"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#ad22e7810bd9c29714ce728aa0e5d6361">attenuation_tau_sigma</a> (tau_s, n, min_period, max_period)</td></tr>
<tr class="separator:ad22e7810bd9c29714ce728aa0e5d6361"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a502c4f9c7fa1ca4e683dad98d13fa3cf"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a502c4f9c7fa1ca4e683dad98d13fa3cf">attenuation_invert_by_simplex</a> (t2, t1, n, Q_real, omega_not, tau_s, tau_e, AS_V)</td></tr>
<tr class="separator:a502c4f9c7fa1ca4e683dad98d13fa3cf"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:aee2e34f197bdfff0f25fcaa9d0dcb9b1"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#aee2e34f197bdfff0f25fcaa9d0dcb9b1">attenuation_simplex_finish</a> (AS_V)</td></tr>
<tr class="separator:aee2e34f197bdfff0f25fcaa9d0dcb9b1"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:af406929f0ccd52375e7c63dad02200d3"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#af406929f0ccd52375e7c63dad02200d3">attenuation_simplex_setup</a> (nf_in, nsls_in, f_in, Q_in, tau_s_in, AS_V)</td></tr>
<tr class="separator:af406929f0ccd52375e7c63dad02200d3"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a912bef52114c836f8ff3b1078d6356e2"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a912bef52114c836f8ff3b1078d6356e2">attenuation_maxwell</a> (nf, nsls, f, tau_s, tau_e, B, A)</td></tr>
<tr class="separator:a912bef52114c836f8ff3b1078d6356e2"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:ac5d3fdb001515e17dacfe001d355238d"><td class="memItemLeft" align="right" valign="top">double precision function </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#ac5d3fdb001515e17dacfe001d355238d">attenuation_eval</a> (Xin, AS_V)</td></tr>
<tr class="separator:ac5d3fdb001515e17dacfe001d355238d"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a1332ec42a63774c5e0fa7d8e0663b492"><td class="memItemLeft" align="right" valign="top">subroutine </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a1332ec42a63774c5e0fa7d8e0663b492">fminsearch</a> (funk, x, n, itercount, tolf, prnt, err, AS_V)</td></tr>
<tr class="separator:a1332ec42a63774c5e0fa7d8e0663b492"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a143b75a40f0cf8027066efee57dbe2c5"><td class="memItemLeft" align="right" valign="top">double precision function </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a143b75a40f0cf8027066efee57dbe2c5">max_value</a> (fv, n)</td></tr>
<tr class="separator:a143b75a40f0cf8027066efee57dbe2c5"><td class="memSeparator" colspan="2"> </td></tr>
<tr class="memitem:a3f3e7c079757fe5735f73b2867ea8268"><td class="memItemLeft" align="right" valign="top">double precision function </td><td class="memItemRight" valign="bottom"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html#a3f3e7c079757fe5735f73b2867ea8268">max_size_simplex</a> (v, n)</td></tr>
<tr class="separator:a3f3e7c079757fe5735f73b2867ea8268"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function/Subroutine Documentation</h2>
<a class="anchor" id="ac5d3fdb001515e17dacfe001d355238d"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double precision function attenuation_eval </td>
<td>(</td>
<td class="paramtype">double precision, dimension(as_v%nsls) </td>
<td class="paramname"><em>Xin</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00628">628</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_ac5d3fdb001515e17dacfe001d355238d_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_ac5d3fdb001515e17dacfe001d355238d_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_ac5d3fdb001515e17dacfe001d355238d_cgraph" id="d2/d2c/model__attenuation_8f90_ac5d3fdb001515e17dacfe001d355238d_cgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a912bef52114c836f8ff3b1078d6356e2" title="attenuation_maxwell" alt="" coords="173,5,317,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a502c4f9c7fa1ca4e683dad98d13fa3cf"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_invert_by_simplex </td>
<td>(</td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>t2</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>t1</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>n</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>Q_real</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>omega_not</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n) </td>
<td class="paramname"><em>tau_s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n) </td>
<td class="paramname"><em>tau_e</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00416">416</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_cgraph" id="d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_cgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#af406929f0ccd52375e7c63dad02200d3" title="attenuation_simplex\l_setup" alt="" coords="181,5,321,47"/>
<area shape="rect" id="node3" href="../../d2/d2c/model__attenuation_8f90.html#a1332ec42a63774c5e0fa7d8e0663b492" title="fminsearch" alt="" coords="208,71,295,98"/>
<area shape="rect" id="node4" href="../../d2/d2c/model__attenuation_8f90.html#aee2e34f197bdfff0f25fcaa9d0dcb9b1" title="attenuation_simplex\l_finish" alt="" coords="181,123,321,164"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_icgraph" id="d2/d2c/model__attenuation_8f90_a502c4f9c7fa1ca4e683dad98d13fa3cf_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a22533e26244b9fa6eeaae249eaec38c3" title="model_attenuation_getstored_tau" alt="" coords="181,13,401,39"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a912bef52114c836f8ff3b1078d6356e2"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_maxwell </td>
<td>(</td>
<td class="paramtype">integer </td>
<td class="paramname"><em>nf</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>nsls</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nf) </td>
<td class="paramname"><em>f</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nsls) </td>
<td class="paramname"><em>tau_s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nsls) </td>
<td class="paramname"><em>tau_e</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nf) </td>
<td class="paramname"><em>B</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nf) </td>
<td class="paramname"><em>A</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00575">575</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a912bef52114c836f8ff3b1078d6356e2_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a912bef52114c836f8ff3b1078d6356e2_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a912bef52114c836f8ff3b1078d6356e2_icgraph" id="d2/d2c/model__attenuation_8f90_a912bef52114c836f8ff3b1078d6356e2_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#ac5d3fdb001515e17dacfe001d355238d" title="attenuation_eval" alt="" coords="197,5,317,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="aee2e34f197bdfff0f25fcaa9d0dcb9b1"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_simplex_finish </td>
<td>(</td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em></td><td>)</td>
<td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00503">503</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_aee2e34f197bdfff0f25fcaa9d0dcb9b1_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_aee2e34f197bdfff0f25fcaa9d0dcb9b1_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_aee2e34f197bdfff0f25fcaa9d0dcb9b1_icgraph" id="d2/d2c/model__attenuation_8f90_aee2e34f197bdfff0f25fcaa9d0dcb9b1_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a502c4f9c7fa1ca4e683dad98d13fa3cf" title="attenuation_invert\l_by_simplex" alt="" coords="193,5,321,47"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="af406929f0ccd52375e7c63dad02200d3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_simplex_setup </td>
<td>(</td>
<td class="paramtype">integer </td>
<td class="paramname"><em>nf_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>nsls_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nf_in) </td>
<td class="paramname"><em>f_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>Q_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(nsls_in) </td>
<td class="paramname"><em>tau_s_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00518">518</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_af406929f0ccd52375e7c63dad02200d3_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_af406929f0ccd52375e7c63dad02200d3_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_af406929f0ccd52375e7c63dad02200d3_icgraph" id="d2/d2c/model__attenuation_8f90_af406929f0ccd52375e7c63dad02200d3_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a502c4f9c7fa1ca4e683dad98d13fa3cf" title="attenuation_invert\l_by_simplex" alt="" coords="193,5,321,47"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a3b6e84767fc408cbdb44a2f13cd21045"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_source_frequency </td>
<td>(</td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>omega_not</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>min_period</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>max_period</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00364">364</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a3b6e84767fc408cbdb44a2f13cd21045_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a3b6e84767fc408cbdb44a2f13cd21045_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a3b6e84767fc408cbdb44a2f13cd21045_icgraph" id="d2/d2c/model__attenuation_8f90_a3b6e84767fc408cbdb44a2f13cd21045_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a84b2f788d16d8c34200a57b2d5a79d08" title="read_attenuation_model" alt="" coords="189,13,355,39"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="ad22e7810bd9c29714ce728aa0e5d6361"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine attenuation_tau_sigma </td>
<td>(</td>
<td class="paramtype">double precision, dimension(n) </td>
<td class="paramname"><em>tau_s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>n</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>min_period</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>max_period</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00384">384</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_ad22e7810bd9c29714ce728aa0e5d6361_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_ad22e7810bd9c29714ce728aa0e5d6361_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_ad22e7810bd9c29714ce728aa0e5d6361_icgraph" id="d2/d2c/model__attenuation_8f90_ad22e7810bd9c29714ce728aa0e5d6361_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a84b2f788d16d8c34200a57b2d5a79d08" title="read_attenuation_model" alt="" coords="211,5,376,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a1332ec42a63774c5e0fa7d8e0663b492"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine fminsearch </td>
<td>(</td>
<td class="paramtype">double precision, external </td>
<td class="paramname"><em>funk</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n) </td>
<td class="paramname"><em>x</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>n</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>itercount</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>tolf</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>prnt</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>err</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00693">693</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_cgraph" id="d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_cgraph">
<area shape="rect" id="node2" href="../../da/dba/heap__sort_8f90.html#a94dbe3a5d32d862e89c2cc7dc0148f91" title="heap_sort_local" alt="" coords="140,5,256,32"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_icgraph" id="d2/d2c/model__attenuation_8f90_a1332ec42a63774c5e0fa7d8e0663b492_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a502c4f9c7fa1ca4e683dad98d13fa3cf" title="attenuation_invert\l_by_simplex" alt="" coords="140,5,268,47"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a3f3e7c079757fe5735f73b2867ea8268"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double precision function max_size_simplex </td>
<td>(</td>
<td class="paramtype">double precision, dimension(n,n+1) </td>
<td class="paramname"><em>v</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>n</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00969">969</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
</div>
</div>
<a class="anchor" id="a143b75a40f0cf8027066efee57dbe2c5"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">double precision function max_value </td>
<td>(</td>
<td class="paramtype">double precision, dimension(n) </td>
<td class="paramname"><em>fv</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>n</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00935">935</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
</div>
</div>
<a class="anchor" id="a99c4aed02d34fbd73c178c76243d0fb8"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine model_attenuation_broadcast </td>
<td>(</td>
<td class="paramtype">type (model_attenuation_variables) </td>
<td class="paramname"><em>AM_V</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>MIN_ATTENUATION_PERIOD</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>MAX_ATTENUATION_PERIOD</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00062">62</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_cgraph" id="d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_cgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a84b2f788d16d8c34200a57b2d5a79d08" title="read_attenuation_model" alt="" coords="251,5,416,32"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_icgraph" id="d2/d2c/model__attenuation_8f90_a99c4aed02d34fbd73c178c76243d0fb8_icgraph">
<area shape="rect" id="node2" href="../../d0/dad/meshfem3_d__models_8_f90.html#a6a7b79f82404dc9605de497f55fd078d" title="meshfem3d_models_broadcast" alt="" coords="251,5,459,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a22533e26244b9fa6eeaae249eaec38c3"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine model_attenuation_getstored_tau </td>
<td>(</td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>Qmu_in</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>T_c_source</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n_sls) </td>
<td class="paramname"><em>tau_s</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n_sls) </td>
<td class="paramname"><em>tau_e</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_variables) </td>
<td class="paramname"><em>AM_V</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_storage_var) </td>
<td class="paramname"><em>AM_S</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00247">247</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_cgraph" id="d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_cgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a610dc0b96c48f66a9eb8955d365c8011" title="model_attenuation_storage" alt="" coords="273,5,457,32"/>
<area shape="rect" id="node3" href="../../d2/d2c/model__attenuation_8f90.html#a502c4f9c7fa1ca4e683dad98d13fa3cf" title="attenuation_invert\l_by_simplex" alt="" coords="301,57,429,98"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_icgraph" id="d2/d2c/model__attenuation_8f90_a22533e26244b9fa6eeaae249eaec38c3_icgraph">
<area shape="rect" id="node2" href="../../d0/dad/meshfem3_d__models_8_f90.html#a5e6d2a37838965d05a5ced91adcedd56" title="meshfem3d_models_getatten_val" alt="" coords="273,5,496,32"/>
<area shape="rect" id="node3" href="../../d2/d2c/model__attenuation_8f90.html#adad501987bfa3f86074c504228dba3b2" title="model_attenuation_setup" alt="" coords="299,56,471,83"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="adad501987bfa3f86074c504228dba3b2"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine model_attenuation_setup </td>
<td>(</td>
<td class="paramtype">integer </td>
<td class="paramname"><em>REFERENCE_1D_MODEL</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>RICB</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>RCMB</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>R670</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>R220</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>R80</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_variables) </td>
<td class="paramname"><em>AM_V</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_storage_var) </td>
<td class="paramname"><em>AM_S</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (attenuation_simplex_variables) </td>
<td class="paramname"><em>AS_V</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">logical </td>
<td class="paramname"><em>CRUSTAL</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00125">125</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_cgraph" id="d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_cgraph">
<area shape="rect" id="node2" href="../../d3/d03/model__ak135_8f90.html#a3be789df8e7f965dc94b2d133d69bf8d" title="define_model_ak135" alt="" coords="263,5,408,32"/>
<area shape="rect" id="node3" href="../../db/d38/model__1066a_8f90.html#ad7909d96403969a6347474382006029e" title="define_model_1066a" alt="" coords="262,56,409,83"/>
<area shape="rect" id="node4" href="../../d4/d3d/model__1dref_8f90.html#af64d5affb8baf9e6b1dd313a9a9b5975" title="define_model_1dref" alt="" coords="265,107,405,133"/>
<area shape="rect" id="node5" href="../../df/d4e/model__sea1d_8f90.html#a72bf6a397aac2e239c85745addb3f37c" title="define_model_sea1d" alt="" coords="263,157,408,184"/>
<area shape="rect" id="node6" href="../../d2/d2c/model__attenuation_8f90.html#a22533e26244b9fa6eeaae249eaec38c3" title="model_attenuation_getstored_tau" alt="" coords="225,208,445,235"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_icgraph" id="d2/d2c/model__attenuation_8f90_adad501987bfa3f86074c504228dba3b2_icgraph">
<area shape="rect" id="node2" href="../../d0/dad/meshfem3_d__models_8_f90.html#a6a7b79f82404dc9605de497f55fd078d" title="meshfem3d_models_broadcast" alt="" coords="225,5,433,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a610dc0b96c48f66a9eb8955d365c8011"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine model_attenuation_storage </td>
<td>(</td>
<td class="paramtype">double precision </td>
<td class="paramname"><em>Qmu</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">double precision, dimension(n_sls) </td>
<td class="paramname"><em>tau_e</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>rw</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_storage_var) </td>
<td class="paramname"><em>AM_S</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00284">284</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a610dc0b96c48f66a9eb8955d365c8011_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a610dc0b96c48f66a9eb8955d365c8011_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a610dc0b96c48f66a9eb8955d365c8011_icgraph" id="d2/d2c/model__attenuation_8f90_a610dc0b96c48f66a9eb8955d365c8011_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a22533e26244b9fa6eeaae249eaec38c3" title="model_attenuation_getstored_tau" alt="" coords="237,5,457,32"/>
</map>
</div>
</p>
</div>
</div>
<a class="anchor" id="a84b2f788d16d8c34200a57b2d5a79d08"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">subroutine read_attenuation_model </td>
<td>(</td>
<td class="paramtype">integer </td>
<td class="paramname"><em>min_att_period</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">integer </td>
<td class="paramname"><em>max_att_period</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">type (model_attenuation_variables) </td>
<td class="paramname"><em>AM_V</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html#l00094">94</a> of file <a class="el" href="../../d2/d2c/model__attenuation_8f90_source.html">model_attenuation.f90</a>.</p>
<p><div class="dynheader">
Here is the call graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_cgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_cgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_cgraph" id="d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_cgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#ad22e7810bd9c29714ce728aa0e5d6361" title="attenuation_tau_sigma" alt="" coords="219,5,376,32"/>
<area shape="rect" id="node3" href="../../d2/d2c/model__attenuation_8f90.html#a3b6e84767fc408cbdb44a2f13cd21045" title="attenuation_source\l_frequency" alt="" coords="229,57,365,98"/>
</map>
</div>
</p>
<p><div class="dynheader">
Here is the caller graph for this function:</div>
<div class="dyncontent">
<div class="center"><img src="../../d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_icgraph.png" border="0" usemap="#d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_icgraph" alt=""/></div>
<map name="d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_icgraph" id="d2/d2c/model__attenuation_8f90_a84b2f788d16d8c34200a57b2d5a79d08_icgraph">
<area shape="rect" id="node2" href="../../d2/d2c/model__attenuation_8f90.html#a99c4aed02d34fbd73c178c76243d0fb8" title="model_attenuation_broadcast" alt="" coords="219,5,416,32"/>
</map>
</div>
</p>
</div>
</div>
</div><!-- contents -->
</div><!-- doc-content -->
<!-- custom-made footer -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="navelem"><a class="el" href="../../dir_76fc807e71a78804243adb7d05973764.html">SPECFEM3D_GLOBE</a></li><li class="navelem"><a class="el" href="../../dir_3e3821fc19411950b1ac0b3a66489b15.html">src</a></li><li class="navelem"><a class="el" href="../../dir_aee3096c0716f0bc718f2b2cf7df940f.html">meshfem3D</a></li><li class="navelem"><a class="el" href="../../d2/d2c/model__attenuation_8f90.html">model_attenuation.f90</a></li>
<li class="footer">
<!--
Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/></a> 1.8.10
-->
doxygen for <a href="https://github.com/geodynamics/specfem3d_globe">SPECFEM3D_GLOBE</a>
</li>
</ul>
</div>
</body>
</html>
|
komatits/specfem3d_globe
|
doc/call_trees_of_the_source_code/html/d2/d2c/model__attenuation_8f90.html
|
HTML
|
gpl-2.0
| 49,994 |
<?php
return [
'ctrl' => [
'label' => 'title',
'tstamp' => 'tstamp',
'default_sortby' => 'ORDER BY title',
'title' => 'LLL:EXT:lang/locallang_tca.xlf:sys_language',
'adminOnly' => 1,
'rootLevel' => 1,
'enablecolumns' => [
'disabled' => 'hidden'
],
'typeicon_column' => 'flag',
'typeicon_classes' => [
'default' => 'mimetypes-x-sys_language',
'mask' => 'flags-###TYPE###'
],
'versioningWS_alwaysAllowLiveEdit' => true
],
'interface' => [
'showRecordFieldList' => 'hidden,title'
],
'columns' => [
'title' => [
'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.language',
'config' => [
'type' => 'input',
'size' => '35',
'max' => '80',
'eval' => 'trim,required'
]
],
'hidden' => [
'label' => 'LLL:EXT:lang/locallang_general.xlf:LGL.disable',
'exclude' => 1,
'config' => [
'type' => 'check',
'default' => '0'
]
],
'language_isocode' => [
'exclude' => 1,
'label' => 'LLL:EXT:lang/locallang_tca.xlf:sys_language.language_isocode',
'config' => [
'type' => 'select',
'renderType' => 'selectSingle',
'size' => 1,
'minitems' => 0,
'maxitems' => 1,
'items' => [],
'itemsProcFunc' => \TYPO3\CMS\Core\Service\IsoCodeService::class . '->renderIsoCodeSelectDropdown',
]
],
'flag' => [
'label' => 'LLL:EXT:lang/locallang_tca.xlf:sys_language.flag',
'config' => [
'type' => 'select',
'renderType' => 'selectSingle',
'items' => [
['', 0, ''],
['multiple', 'multiple', 'flags-multiple'],
['ad', 'ad', 'flags-ad'],
['ae', 'ae', 'flags-ae'],
['af', 'af', 'flags-af'],
['ag', 'ag', 'flags-ag'],
['ai', 'ai', 'flags-ai'],
['al', 'al', 'flags-al'],
['am', 'am', 'flags-am'],
['an', 'an', 'flags-an'],
['ao', 'ao', 'flags-ao'],
['ar', 'ar', 'flags-ar'],
['as', 'as', 'flags-as'],
['at', 'at', 'flags-at'],
['au', 'au', 'flags-au'],
['aw', 'aw', 'flags-aw'],
['ax', 'ax', 'flags-ax'],
['az', 'az', 'flags-az'],
['ba', 'ba', 'flags-ba'],
['bb', 'bb', 'flags-bb'],
['bd', 'bd', 'flags-bd'],
['be', 'be', 'flags-be'],
['bf', 'bf', 'flags-bf'],
['bg', 'bg', 'flags-bg'],
['bh', 'bh', 'flags-bh'],
['bi', 'bi', 'flags-bi'],
['bj', 'bj', 'flags-bj'],
['bm', 'bm', 'flags-bm'],
['bn', 'bn', 'flags-bn'],
['bo', 'bo', 'flags-bo'],
['br', 'br', 'flags-br'],
['bs', 'bs', 'flags-bs'],
['bt', 'bt', 'flags-bt'],
['bv', 'bv', 'flags-bv'],
['bw', 'bw', 'flags-bw'],
['by', 'by', 'flags-by'],
['bz', 'bz', 'flags-bz'],
['ca', 'ca', 'flags-ca'],
['catalonia', 'catalonia', 'flags-catalonia'],
['cc', 'cc', 'flags-cc'],
['cd', 'cd', 'flags-cd'],
['cf', 'cf', 'flags-cf'],
['cg', 'cg', 'flags-cg'],
['ch', 'ch', 'flags-ch'],
['ci', 'ci', 'flags-ci'],
['ck', 'ck', 'flags-ck'],
['cl', 'cl', 'flags-cl'],
['cm', 'cm', 'flags-cm'],
['cn', 'cn', 'flags-cn'],
['co', 'co', 'flags-co'],
['cr', 'cr', 'flags-cr'],
['cs', 'cs', 'flags-cs'],
['cu', 'cu', 'flags-cu'],
['cv', 'cv', 'flags-cv'],
['cx', 'cx', 'flags-cx'],
['cy', 'cy', 'flags-cy'],
['cz', 'cz', 'flags-cz'],
['de', 'de', 'flags-de'],
['dj', 'dj', 'flags-dj'],
['dk', 'dk', 'flags-dk'],
['dm', 'dm', 'flags-dm'],
['do', 'do', 'flags-do'],
['dz', 'dz', 'flags-dz'],
['ec', 'ec', 'flags-ec'],
['ee', 'ee', 'flags-ee'],
['eg', 'eg', 'flags-eg'],
['eh', 'eh', 'flags-eh'],
['en-us-gb', 'en-us-gb', 'flags-en-us-gb'],
['england', 'england', 'flags-gb-eng'],
['er', 'er', 'flags-er'],
['es', 'es', 'flags-es'],
['et', 'et', 'flags-et'],
['eu', 'eu', 'flags-eu'],
['fam', 'fam', 'flags-fam'],
['fi', 'fi', 'flags-fi'],
['fj', 'fj', 'flags-fj'],
['fk', 'fk', 'flags-fk'],
['fm', 'fm', 'flags-fm'],
['fo', 'fo', 'flags-fo'],
['fr', 'fr', 'flags-fr'],
['ga', 'ga', 'flags-ga'],
['gb', 'gb', 'flags-gb'],
['gd', 'gd', 'flags-gd'],
['ge', 'ge', 'flags-ge'],
['gf', 'gf', 'flags-gf'],
['gh', 'gh', 'flags-gh'],
['gi', 'gi', 'flags-gi'],
['gl', 'gl', 'flags-gl'],
['gm', 'gm', 'flags-gm'],
['gn', 'gn', 'flags-gn'],
['gp', 'gp', 'flags-gp'],
['gq', 'gq', 'flags-gq'],
['gr', 'gr', 'flags-gr'],
['gs', 'gs', 'flags-gs'],
['gt', 'gt', 'flags-gt'],
['gu', 'gu', 'flags-gu'],
['gw', 'gw', 'flags-gw'],
['gy', 'gy', 'flags-gy'],
['hk', 'hk', 'flags-hk'],
['hm', 'hm', 'flags-hm'],
['hn', 'hn', 'flags-hn'],
['hr', 'hr', 'flags-hr'],
['ht', 'ht', 'flags-ht'],
['hu', 'hu', 'flags-hu'],
['id', 'id', 'flags-id'],
['ie', 'ie', 'flags-ie'],
['il', 'il', 'flags-il'],
['in', 'in', 'flags-in'],
['io', 'io', 'flags-io'],
['iq', 'iq', 'flags-iq'],
['ir', 'ir', 'flags-ir'],
['is', 'is', 'flags-is'],
['it', 'it', 'flags-it'],
['jm', 'jm', 'flags-jm'],
['jo', 'jo', 'flags-jo'],
['jp', 'jp', 'flags-jp'],
['ke', 'ke', 'flags-ke'],
['kg', 'kg', 'flags-kg'],
['kh', 'kh', 'flags-kh'],
['ki', 'ki', 'flags-ki'],
['km', 'km', 'flags-km'],
['kn', 'kn', 'flags-kn'],
['kp', 'kp', 'flags-kp'],
['kr', 'kr', 'flags-kr'],
['kw', 'kw', 'flags-kw'],
['ky', 'ky', 'flags-ky'],
['kz', 'kz', 'flags-kz'],
['la', 'la', 'flags-la'],
['lb', 'lb', 'flags-lb'],
['lc', 'lc', 'flags-lc'],
['li', 'li', 'flags-li'],
['lk', 'lk', 'flags-lk'],
['lr', 'lr', 'flags-lr'],
['ls', 'ls', 'flags-ls'],
['lt', 'lt', 'flags-lt'],
['lu', 'lu', 'flags-lu'],
['lv', 'lv', 'flags-lv'],
['ly', 'ly', 'flags-ly'],
['ma', 'ma', 'flags-ma'],
['mc', 'mc', 'flags-mc'],
['md', 'md', 'flags-md'],
['me', 'me', 'flags-me'],
['mg', 'mg', 'flags-mg'],
['mh', 'mh', 'flags-mh'],
['mk', 'mk', 'flags-mk'],
['ml', 'ml', 'flags-ml'],
['mm', 'mm', 'flags-mm'],
['mn', 'mn', 'flags-mn'],
['mo', 'mo', 'flags-mo'],
['mp', 'mp', 'flags-mp'],
['mq', 'mq', 'flags-mq'],
['mr', 'mr', 'flags-mr'],
['ms', 'ms', 'flags-ms'],
['mt', 'mt', 'flags-mt'],
['mu', 'mu', 'flags-mu'],
['mv', 'mv', 'flags-mv'],
['mw', 'mw', 'flags-mw'],
['mx', 'mx', 'flags-mx'],
['my', 'my', 'flags-my'],
['mz', 'mz', 'flags-mz'],
['na', 'na', 'flags-na'],
['nc', 'nc', 'flags-nc'],
['ne', 'ne', 'flags-ne'],
['nf', 'nf', 'flags-nf'],
['ng', 'ng', 'flags-ng'],
['ni', 'ni', 'flags-ni'],
['nl', 'nl', 'flags-nl'],
['no', 'no', 'flags-no'],
['np', 'np', 'flags-np'],
['nr', 'nr', 'flags-nr'],
['nu', 'nu', 'flags-nu'],
['nz', 'nz', 'flags-nz'],
['om', 'om', 'flags-om'],
['pa', 'pa', 'flags-pa'],
['pe', 'pe', 'flags-pe'],
['pf', 'pf', 'flags-pf'],
['pg', 'pg', 'flags-pg'],
['ph', 'ph', 'flags-ph'],
['pk', 'pk', 'flags-pk'],
['pl', 'pl', 'flags-pl'],
['pm', 'pm', 'flags-pm'],
['pn', 'pn', 'flags-pn'],
['pr', 'pr', 'flags-pr'],
['ps', 'ps', 'flags-ps'],
['pt', 'pt', 'flags-pt'],
['pw', 'pw', 'flags-pw'],
['py', 'py', 'flags-py'],
['qa', 'qa', 'flags-qa'],
['qc', 'qc', 'flags-qc'],
['re', 're', 'flags-re'],
['ro', 'ro', 'flags-ro'],
['rs', 'rs', 'flags-rs'],
['ru', 'ru', 'flags-ru'],
['rw', 'rw', 'flags-rw'],
['sa', 'sa', 'flags-sa'],
['sb', 'sb', 'flags-sb'],
['sc', 'sc', 'flags-sc'],
['scotland', 'scotland', 'flags-scotland'],
['sd', 'sd', 'flags-sd'],
['se', 'se', 'flags-se'],
['sg', 'sg', 'flags-sg'],
['sh', 'sh', 'flags-sh'],
['si', 'si', 'flags-si'],
['sj', 'sj', 'flags-sj'],
['sk', 'sk', 'flags-sk'],
['sl', 'sl', 'flags-sl'],
['sm', 'sm', 'flags-sm'],
['sn', 'sn', 'flags-sn'],
['so', 'so', 'flags-so'],
['sr', 'sr', 'flags-sr'],
['st', 'st', 'flags-st'],
['sv', 'sv', 'flags-sv'],
['sy', 'sy', 'flags-sy'],
['sz', 'sz', 'flags-sz'],
['tc', 'tc', 'flags-tc'],
['td', 'td', 'flags-td'],
['tf', 'tf', 'flags-tf'],
['tg', 'tg', 'flags-tg'],
['th', 'th', 'flags-th'],
['tj', 'tj', 'flags-tj'],
['tk', 'tk', 'flags-tk'],
['tl', 'tl', 'flags-tl'],
['tm', 'tm', 'flags-tm'],
['tn', 'tn', 'flags-tn'],
['to', 'to', 'flags-to'],
['tr', 'tr', 'flags-tr'],
['tt', 'tt', 'flags-tt'],
['tv', 'tv', 'flags-tv'],
['tw', 'tw', 'flags-tw'],
['tz', 'tz', 'flags-tz'],
['ua', 'ua', 'flags-ua'],
['ug', 'ug', 'flags-ug'],
['um', 'um', 'flags-um'],
['us', 'us', 'flags-us'],
['uy', 'uy', 'flags-uy'],
['uz', 'uz', 'flags-uz'],
['va', 'va', 'flags-va'],
['vc', 'vc', 'flags-vc'],
['ve', 've', 'flags-ve'],
['vg', 'vg', 'flags-vg'],
['vi', 'vi', 'flags-vi'],
['vn', 'vn', 'flags-vn'],
['vu', 'vu', 'flags-vu'],
['wales', 'wales', 'flags-wales'],
['wf', 'wf', 'flags-wf'],
['ws', 'ws', 'flags-ws'],
['ye', 'ye', 'flags-ye'],
['yt', 'yt', 'flags-yt'],
['za', 'za', 'flags-za'],
['zm', 'zm', 'flags-zm'],
['zw', 'zw', 'flags-zw']
],
'selicon_cols' => 16,
'size' => 1,
'minitems' => 0,
'maxitems' => 1,
'showIconTable' => true,
]
]
],
'types' => [
'1' => ['showitem' => '--palette--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:palette.general;general,
title,language_isocode,flag,
--div--;LLL:EXT:frontend/Resources/Private/Language/locallang_ttc.xlf:tabs.access,
hidden']
]
];
|
ahmedRguei/job
|
typo3/sysext/core/Configuration/TCA/sys_language.php
|
PHP
|
gpl-2.0
| 14,104 |
#ifndef H_RESUME
#define H_RESUME
Resume *Resume_create(int vec_num) ;
void Resume_destroy(Resume *resume) ;
void Resume_set_write_flag(Resume *resume) ;
void Resume_set_read_flag(Resume *resume) ;
void Resume_set_IO_grid_flag(Resume *resume) ;
void Resume_reset_write_flag(Resume *resume) ;
void Resume_reset_read_flag(Resume *resume) ;
void Resume_reset_IO_grid_flag(Resume *resume) ;
void Resume_write_data(Resume *resume) ;
void Resume_read_data() ;
void Resume_set_IO_filename(Resume *resume, int vec_id, char *filename) ;
void Resume_set_IO_type(Resume *resume, int IO_type) ;
void Resume_set_vec_max(Resume *resume, int max_vec) ;
void Resume_set_vec_data(Resume *resume, int vec_id, Vec *data) ;
void Resume_set_data(Resume *resume, GVG_bag *data_bag) ;
void Resume_write_primary_data(Resume *resume, GVG_bag *data_bag) ;
void Resume_read_primary_data(Resume *resume, GVG_bag *data_bag) ;
void Resume_write_2D_data(Resume *resume, double **data, char *filename, int NX, int NZ) ;
void Resume_read_2D_data(Resume *resume, double **data, char *filename, int NX, int NZ) ;
#endif
|
csdms-contrib/turbins
|
src/Include/Resume.h
|
C
|
gpl-2.0
| 1,090 |
/*
* s3fs - FUSE-based file system backed by Amazon S3
*
* Copyright(C) 2007 Randy Rizun <[email protected]>
*
* 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 <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#ifndef HAVE_CLOCK_GETTIME
#include <sys/time.h>
#endif
#include <unistd.h>
#include <stdint.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#include <syslog.h>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <list>
#include "cache.h"
#include "s3fs.h"
#include "s3fs_util.h"
#include "string_util.h"
using namespace std;
//-------------------------------------------------------------------
// Utility
//-------------------------------------------------------------------
#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 0
#endif
#ifndef CLOCK_MONOTONIC
#define CLOCK_MONOTONIC CLOCK_REALTIME
#endif
#ifndef CLOCK_MONOTONIC_COARSE
#define CLOCK_MONOTONIC_COARSE CLOCK_MONOTONIC
#endif
#ifdef HAVE_CLOCK_GETTIME
static int s3fs_clock_gettime(int clk_id, struct timespec* ts)
{
return clock_gettime(clk_id, ts);
}
#else
static int s3fs_clock_gettime(int clk_id, struct timespec* ts)
{
struct timeval now;
if(0 != gettimeofday(&now, NULL)){
return -1;
}
ts->tv_sec = now.tv_sec;
ts->tv_nsec = now.tv_usec * 1000;
return 0;
}
#endif
inline void SetStatCacheTime(struct timespec& ts)
{
if(-1 == s3fs_clock_gettime(CLOCK_MONOTONIC_COARSE, &ts)){
ts.tv_sec = time(NULL);
ts.tv_nsec = 0;
}
}
inline void InitStatCacheTime(struct timespec& ts)
{
ts.tv_sec = 0;
ts.tv_nsec = 0;
}
inline int CompareStatCacheTime(struct timespec& ts1, struct timespec& ts2)
{
// return -1: ts1 < ts2
// 0: ts1 == ts2
// 1: ts1 > ts2
if(ts1.tv_sec < ts2.tv_sec){
return -1;
}else if(ts1.tv_sec > ts2.tv_sec){
return 1;
}else{
if(ts1.tv_nsec < ts2.tv_nsec){
return -1;
}else if(ts1.tv_nsec > ts2.tv_nsec){
return 1;
}
}
return 0;
}
inline bool IsExpireStatCacheTime(const struct timespec& ts, const time_t& expire)
{
struct timespec nowts;
SetStatCacheTime(nowts);
return ((ts.tv_sec + expire) < nowts.tv_sec);
}
//
// For cache out
//
typedef std::vector<stat_cache_t::iterator> statiterlist_t;
struct sort_statiterlist{
// ascending order
bool operator()(const stat_cache_t::iterator& src1, const stat_cache_t::iterator& src2) const
{
int result = CompareStatCacheTime(src1->second->cache_date, src2->second->cache_date);
if(0 == result){
if(src1->second->hit_count < src2->second->hit_count){
result = -1;
}
}
return (result < 0);
}
};
//-------------------------------------------------------------------
// Static
//-------------------------------------------------------------------
StatCache StatCache::singleton;
pthread_mutex_t StatCache::stat_cache_lock;
//-------------------------------------------------------------------
// Constructor/Destructor
//-------------------------------------------------------------------
StatCache::StatCache() : IsExpireTime(false), IsExpireIntervalType(false), ExpireTime(0), CacheSize(1000), IsCacheNoObject(false)
{
if(this == StatCache::getStatCacheData()){
stat_cache.clear();
pthread_mutex_init(&(StatCache::stat_cache_lock), NULL);
}else{
assert(false);
}
}
StatCache::~StatCache()
{
if(this == StatCache::getStatCacheData()){
Clear();
pthread_mutex_destroy(&(StatCache::stat_cache_lock));
}else{
assert(false);
}
}
//-------------------------------------------------------------------
// Methods
//-------------------------------------------------------------------
unsigned long StatCache::GetCacheSize(void) const
{
return CacheSize;
}
unsigned long StatCache::SetCacheSize(unsigned long size)
{
unsigned long old = CacheSize;
CacheSize = size;
return old;
}
time_t StatCache::GetExpireTime(void) const
{
return (IsExpireTime ? ExpireTime : (-1));
}
time_t StatCache::SetExpireTime(time_t expire, bool is_interval)
{
time_t old = ExpireTime;
ExpireTime = expire;
IsExpireTime = true;
IsExpireIntervalType = is_interval;
return old;
}
time_t StatCache::UnsetExpireTime(void)
{
time_t old = IsExpireTime ? ExpireTime : (-1);
ExpireTime = 0;
IsExpireTime = false;
IsExpireIntervalType = false;
return old;
}
bool StatCache::SetCacheNoObject(bool flag)
{
bool old = IsCacheNoObject;
IsCacheNoObject = flag;
return old;
}
void StatCache::Clear(void)
{
pthread_mutex_lock(&StatCache::stat_cache_lock);
for(stat_cache_t::iterator iter = stat_cache.begin(); iter != stat_cache.end(); stat_cache.erase(iter++)){
if((*iter).second){
delete (*iter).second;
}
}
S3FS_MALLOCTRIM(0);
pthread_mutex_unlock(&StatCache::stat_cache_lock);
}
bool StatCache::GetStat(string& key, struct stat* pst, headers_t* meta, bool overcheck, const char* petag, bool* pisforce)
{
bool is_delete_cache = false;
string strpath = key;
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter = stat_cache.end();
if(overcheck && '/' != strpath[strpath.length() - 1]){
strpath += "/";
iter = stat_cache.find(strpath.c_str());
}
if(iter == stat_cache.end()){
strpath = key;
iter = stat_cache.find(strpath.c_str());
}
if(iter != stat_cache.end() && (*iter).second){
stat_cache_entry* ent = (*iter).second;
if(!IsExpireTime || !IsExpireStatCacheTime(ent->cache_date, ExpireTime)){
if(ent->noobjcache){
pthread_mutex_unlock(&StatCache::stat_cache_lock);
if(!IsCacheNoObject){
// need to delete this cache.
DelStat(strpath);
}else{
// noobjcache = true means no object.
}
return false;
}
// hit without checking etag
string stretag;
if(petag){
// find & check ETag
for(headers_t::iterator iter = ent->meta.begin(); iter != ent->meta.end(); ++iter){
string tag = lower(iter->first);
if(tag == "etag"){
stretag = iter->second;
if('\0' != petag[0] && 0 != strcmp(petag, stretag.c_str())){
is_delete_cache = true;
}
break;
}
}
}
if(is_delete_cache){
// not hit by different ETag
S3FS_PRN_DBG("stat cache not hit by ETag[path=%s][time=%jd.%09ld][hit count=%lu][ETag(%s)!=(%s)]",
strpath.c_str(), (intmax_t)(ent->cache_date.tv_sec), ent->cache_date.tv_nsec, ent->hit_count, petag ? petag : "null", stretag.c_str());
}else{
// hit
S3FS_PRN_DBG("stat cache hit [path=%s][time=%jd.%09ld][hit count=%lu]",
strpath.c_str(), (intmax_t)(ent->cache_date.tv_sec), ent->cache_date.tv_nsec, ent->hit_count);
if(pst!= NULL){
*pst= ent->stbuf;
}
if(meta != NULL){
*meta = ent->meta;
}
if(pisforce != NULL){
(*pisforce) = ent->isforce;
}
ent->hit_count++;
if(IsExpireIntervalType){
SetStatCacheTime(ent->cache_date);
}
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
}else{
// timeout
is_delete_cache = true;
}
}
pthread_mutex_unlock(&StatCache::stat_cache_lock);
if(is_delete_cache){
DelStat(strpath);
}
return false;
}
bool StatCache::IsNoObjectCache(string& key, bool overcheck)
{
bool is_delete_cache = false;
string strpath = key;
if(!IsCacheNoObject){
return false;
}
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter = stat_cache.end();
if(overcheck && '/' != strpath[strpath.length() - 1]){
strpath += "/";
iter = stat_cache.find(strpath.c_str());
}
if(iter == stat_cache.end()){
strpath = key;
iter = stat_cache.find(strpath.c_str());
}
if(iter != stat_cache.end() && (*iter).second) {
if(!IsExpireTime || !IsExpireStatCacheTime((*iter).second->cache_date, ExpireTime)){
if((*iter).second->noobjcache){
// noobjcache = true means no object.
SetStatCacheTime((*iter).second->cache_date);
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
}else{
// timeout
is_delete_cache = true;
}
}
pthread_mutex_unlock(&StatCache::stat_cache_lock);
if(is_delete_cache){
DelStat(strpath);
}
return false;
}
bool StatCache::AddStat(std::string& key, headers_t& meta, bool forcedir, bool no_truncate)
{
if(!no_truncate && CacheSize< 1){
return true;
}
S3FS_PRN_INFO3("add stat cache entry[path=%s]", key.c_str());
pthread_mutex_lock(&StatCache::stat_cache_lock);
bool found = stat_cache.end() != stat_cache.find(key);
bool do_truncate = stat_cache.size() > CacheSize;
pthread_mutex_unlock(&StatCache::stat_cache_lock);
if(found){
DelStat(key.c_str());
}else{
if(do_truncate){
if(!TruncateCache()){
return false;
}
}
}
// make new
stat_cache_entry* ent = new stat_cache_entry();
if(!convert_header_to_stat(key.c_str(), meta, &(ent->stbuf), forcedir)){
delete ent;
return false;
}
ent->hit_count = 0;
ent->isforce = forcedir;
ent->noobjcache = false;
ent->notruncate = (no_truncate ? 1L : 0L);
ent->meta.clear();
SetStatCacheTime(ent->cache_date); // Set time.
//copy only some keys
for(headers_t::iterator iter = meta.begin(); iter != meta.end(); ++iter){
string tag = lower(iter->first);
string value = iter->second;
if(tag == "content-type"){
ent->meta[iter->first] = value;
}else if(tag == "content-length"){
ent->meta[iter->first] = value;
}else if(tag == "etag"){
ent->meta[iter->first] = value;
}else if(tag == "last-modified"){
ent->meta[iter->first] = value;
}else if(tag.substr(0, 5) == "x-amz"){
ent->meta[tag] = value; // key is lower case for "x-amz"
}
}
// add
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter = stat_cache.find(key); // recheck for same key exists
if(stat_cache.end() != iter){
if(iter->second){
delete iter->second;
}
stat_cache.erase(iter);
}
stat_cache[key] = ent;
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
bool StatCache::AddNoObjectCache(string& key)
{
if(!IsCacheNoObject){
return true; // pretend successful
}
if(CacheSize < 1){
return true;
}
S3FS_PRN_INFO3("add no object cache entry[path=%s]", key.c_str());
pthread_mutex_lock(&StatCache::stat_cache_lock);
bool found = stat_cache.end() != stat_cache.find(key);
bool do_truncate = stat_cache.size() > CacheSize;
pthread_mutex_unlock(&StatCache::stat_cache_lock);
if(found){
DelStat(key.c_str());
}else{
if(do_truncate){
if(!TruncateCache()){
return false;
}
}
}
// make new
stat_cache_entry* ent = new stat_cache_entry();
memset(&(ent->stbuf), 0, sizeof(struct stat));
ent->hit_count = 0;
ent->isforce = false;
ent->noobjcache = true;
ent->notruncate = 0L;
ent->meta.clear();
SetStatCacheTime(ent->cache_date); // Set time.
// add
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter = stat_cache.find(key); // recheck for same key exists
if(stat_cache.end() != iter){
if(iter->second){
delete iter->second;
}
stat_cache.erase(iter);
}
stat_cache[key] = ent;
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
void StatCache::ChangeNoTruncateFlag(std::string key, bool no_truncate)
{
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter = stat_cache.find(key);
if(stat_cache.end() != iter){
stat_cache_entry* ent = iter->second;
if(ent){
if(no_truncate){
++(ent->notruncate);
}else{
if(0L < ent->notruncate){
--(ent->notruncate);
}
}
}
}
pthread_mutex_unlock(&StatCache::stat_cache_lock);
}
bool StatCache::TruncateCache(void)
{
if(stat_cache.empty()){
return true;
}
pthread_mutex_lock(&StatCache::stat_cache_lock);
// 1) erase over expire time
if(IsExpireTime){
for(stat_cache_t::iterator iter = stat_cache.begin(); iter != stat_cache.end(); ){
stat_cache_entry* entry = iter->second;
if(!entry || (0L == entry->notruncate && IsExpireStatCacheTime(entry->cache_date, ExpireTime))){
if(entry){
delete entry;
}
stat_cache.erase(iter++);
}else{
++iter;
}
}
}
// 2) check stat cache count
if(stat_cache.size() < CacheSize){
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
// 3) erase from the old cache in order
size_t erase_count= stat_cache.size() - CacheSize + 1;
statiterlist_t erase_iters;
for(stat_cache_t::iterator iter = stat_cache.begin(); iter != stat_cache.end(); ++iter){
// check no truncate
stat_cache_entry* ent = iter->second;
if(ent && 0L < ent->notruncate){
// skip for no truncate entry
if(0 < erase_count){
--erase_count; // decrement
}
}
// iter is not have notruncate flag
erase_iters.push_back(iter);
sort(erase_iters.begin(), erase_iters.end(), sort_statiterlist());
if(erase_count < erase_iters.size()){
erase_iters.pop_back();
}
}
for(statiterlist_t::iterator iiter = erase_iters.begin(); iiter != erase_iters.end(); ++iiter){
stat_cache_t::iterator siter = *iiter;
S3FS_PRN_DBG("truncate stat cache[path=%s]", siter->first.c_str());
if(siter->second){
delete siter->second;
}
stat_cache.erase(siter);
}
S3FS_MALLOCTRIM(0);
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
bool StatCache::DelStat(const char* key)
{
if(!key){
return false;
}
S3FS_PRN_INFO3("delete stat cache entry[path=%s]", key);
pthread_mutex_lock(&StatCache::stat_cache_lock);
stat_cache_t::iterator iter;
if(stat_cache.end() != (iter = stat_cache.find(string(key)))){
if((*iter).second){
delete (*iter).second;
}
stat_cache.erase(iter);
}
if(0 < strlen(key) && 0 != strcmp(key, "/")){
string strpath = key;
if('/' == strpath[strpath.length() - 1]){
// If there is "path" cache, delete it.
strpath = strpath.substr(0, strpath.length() - 1);
}else{
// If there is "path/" cache, delete it.
strpath += "/";
}
if(stat_cache.end() != (iter = stat_cache.find(strpath.c_str()))){
if((*iter).second){
delete (*iter).second;
}
stat_cache.erase(iter);
}
}
S3FS_MALLOCTRIM(0);
pthread_mutex_unlock(&StatCache::stat_cache_lock);
return true;
}
//-------------------------------------------------------------------
// Functions
//-------------------------------------------------------------------
bool convert_header_to_stat(const char* path, headers_t& meta, struct stat* pst, bool forcedir)
{
if(!path || !pst){
return false;
}
memset(pst, 0, sizeof(struct stat));
pst->st_nlink = 1; // see fuse FAQ
// mode
pst->st_mode = get_mode(meta, path, true, forcedir);
// blocks
if(S_ISREG(pst->st_mode)){
pst->st_blocks = get_blocks(pst->st_size);
}
pst->st_blksize = 4096;
// mtime
pst->st_mtime = get_mtime(meta);
// size
pst->st_size = get_size(meta);
// uid/gid
pst->st_uid = get_uid(meta);
pst->st_gid = get_gid(meta);
return true;
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
mauricios/s3fs-fuse
|
src/cache.cpp
|
C++
|
gpl-2.0
| 16,408 |
/*
* Linux Security plug
*
* Copyright (C) 2001 WireX Communications, Inc <[email protected]>
* Copyright (C) 2001 Greg Kroah-Hartman <[email protected]>
* Copyright (C) 2001 Networks Associates Technology, Inc <[email protected]>
* Copyright (C) 2001 James Morris <[email protected]>
* Copyright (C) 2001 Silicon Graphics, Inc. (Trust Technology Group)
*
* 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.
*
* Due to this file being licensed under the GPL there is controversy over
* whether this permits you to write a module that #includes this file
* without placing your module under the GPL. Please consult a lawyer for
* advice before doing this.
*
*/
#ifndef __LINUX_SECURITY_H
#define __LINUX_SECURITY_H
#include <linux/key.h>
#include <linux/capability.h>
#include <linux/slab.h>
#include <linux/err.h>
#include <linux/string.h>
#include <linux/bio.h>
struct linux_binprm;
struct cred;
struct rlimit;
struct siginfo;
struct sem_array;
struct sembuf;
struct kern_ipc_perm;
struct audit_context;
struct super_block;
struct inode;
struct dentry;
struct file;
struct vfsmount;
struct path;
struct qstr;
struct nameidata;
struct iattr;
struct fown_struct;
struct file_operations;
struct shmid_kernel;
struct msg_msg;
struct msg_queue;
struct xattr;
struct xfrm_sec_ctx;
struct mm_struct;
#ifdef CONFIG_TIMA_RKP_RO_CRED
/* For understand size of struct cred*/
#include <linux/cred.h>
#endif /*CONFIG_TIMA_RKP_RO_CRED*/
/* Maximum number of letters for an LSM name string */
#define SECURITY_NAME_MAX 10
/* If capable should audit the security request */
#define SECURITY_CAP_NOAUDIT 0
#define SECURITY_CAP_AUDIT 1
/* LSM Agnostic defines for sb_set_mnt_opts */
#define SECURITY_LSM_NATIVE_LABELS 1
struct ctl_table;
struct audit_krule;
struct user_namespace;
struct timezone;
#ifdef CONFIG_TIMA_RKP_RO_CRED
#define cred_usage_length ((1 << (RO_PAGES_ORDER + PAGE_SHIFT)) / (sizeof(struct cred) + 4) ) + 1
#define cred_usage_offset(addr) ((unsigned long) addr - (unsigned long) __rkp_ro_start) / (cred_align_size)
#define rocred_uc_read(x) atomic_read(&cred_usage[cred_usage_offset(x)])
#define rocred_uc_inc(x) atomic_inc(&cred_usage[cred_usage_offset(x)])
#define rocred_uc_dec_and_test(x) atomic_dec_and_test(&cred_usage[cred_usage_offset(x)])
#define rocred_uc_inc_not_zero(x) atomic_inc_not_zero(&cred_usage[cred_usage_offset(x)])
#define rocred_uc_set(x,v) atomic_set(&cred_usage[cred_usage_offset(x)],v)
#define CRED_RO_AREA __attribute__((section (".tima.rkp.initcred")))
#define RO_PAGES_ORDER 9
#define cred_align_size (*((unsigned long *)((unsigned long)__rkp_ro_start+sizeof(struct cred))))
extern char __rkp_ro_start[], __rkp_ro_end[];
/*Check whether the address belong to Cred Area*/
static inline int tima_ro_page(unsigned long addr)
{
return (addr >= ((unsigned long) __rkp_ro_start)
&& addr < ((unsigned long) __rkp_ro_end)
&& (addr+cred_align_size <= ((unsigned long)__rkp_ro_end)));
}
extern int security_integrity_current(void);
#else
#define CRED_RO_AREA
#define security_integrity_current() 0
#endif /*CONFIG_TIMA_RKP_RO_CRED*/
/*
* These functions are in security/capability.c and are used
* as the default capabilities functions
*/
extern int cap_capable(const struct cred *cred, struct user_namespace *ns,
int cap, int audit);
extern int cap_settime(const struct timespec *ts, const struct timezone *tz);
extern int cap_ptrace_access_check(struct task_struct *child, unsigned int mode);
extern int cap_ptrace_traceme(struct task_struct *parent);
extern int cap_capget(struct task_struct *target, kernel_cap_t *effective, kernel_cap_t *inheritable, kernel_cap_t *permitted);
extern int cap_capset(struct cred *new, const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted);
extern int cap_bprm_set_creds(struct linux_binprm *bprm);
extern int cap_bprm_secureexec(struct linux_binprm *bprm);
extern int cap_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags);
extern int cap_inode_removexattr(struct dentry *dentry, const char *name);
extern int cap_inode_need_killpriv(struct dentry *dentry);
extern int cap_inode_killpriv(struct dentry *dentry);
extern int cap_mmap_addr(unsigned long addr);
extern int cap_mmap_file(struct file *file, unsigned long reqprot,
unsigned long prot, unsigned long flags);
extern int cap_task_fix_setuid(struct cred *new, const struct cred *old, int flags);
extern int cap_task_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
extern int cap_task_setscheduler(struct task_struct *p);
extern int cap_task_setioprio(struct task_struct *p, int ioprio);
extern int cap_task_setnice(struct task_struct *p, int nice);
extern int cap_vm_enough_memory(struct mm_struct *mm, long pages);
struct msghdr;
struct sk_buff;
struct sock;
struct sockaddr;
struct socket;
struct flowi;
struct dst_entry;
struct xfrm_selector;
struct xfrm_policy;
struct xfrm_state;
struct xfrm_user_sec_ctx;
struct seq_file;
extern int cap_netlink_send(struct sock *sk, struct sk_buff *skb);
void reset_security_ops(void);
#ifdef CONFIG_MMU
extern unsigned long mmap_min_addr;
extern unsigned long dac_mmap_min_addr;
#else
#define mmap_min_addr 0UL
#define dac_mmap_min_addr 0UL
#endif
/*
* Values used in the task_security_ops calls
*/
/* setuid or setgid, id0 == uid or gid */
#define LSM_SETID_ID 1
/* setreuid or setregid, id0 == real, id1 == eff */
#define LSM_SETID_RE 2
/* setresuid or setresgid, id0 == real, id1 == eff, uid2 == saved */
#define LSM_SETID_RES 4
/* setfsuid or setfsgid, id0 == fsuid or fsgid */
#define LSM_SETID_FS 8
/* forward declares to avoid warnings */
struct sched_param;
struct request_sock;
/* bprm->unsafe reasons */
#define LSM_UNSAFE_SHARE 1
#define LSM_UNSAFE_PTRACE 2
#define LSM_UNSAFE_PTRACE_CAP 4
#define LSM_UNSAFE_NO_NEW_PRIVS 8
#ifdef CONFIG_MMU
extern int mmap_min_addr_handler(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos);
#endif
/* security_inode_init_security callback function to write xattrs */
typedef int (*initxattrs) (struct inode *inode,
const struct xattr *xattr_array, void *fs_data);
#ifdef CONFIG_SECURITY
struct security_mnt_opts {
char **mnt_opts;
int *mnt_opts_flags;
int num_mnt_opts;
};
static inline void security_init_mnt_opts(struct security_mnt_opts *opts)
{
opts->mnt_opts = NULL;
opts->mnt_opts_flags = NULL;
opts->num_mnt_opts = 0;
}
static inline void security_free_mnt_opts(struct security_mnt_opts *opts)
{
int i;
if (opts->mnt_opts)
for (i = 0; i < opts->num_mnt_opts; i++)
kfree(opts->mnt_opts[i]);
kfree(opts->mnt_opts);
opts->mnt_opts = NULL;
kfree(opts->mnt_opts_flags);
opts->mnt_opts_flags = NULL;
opts->num_mnt_opts = 0;
}
/**
* struct security_operations - main security structure
*
* Security module identifier.
*
* @name:
* A string that acts as a unique identifier for the LSM with max number
* of characters = SECURITY_NAME_MAX.
*
* Security hooks for program execution operations.
*
* @bprm_set_creds:
* Save security information in the bprm->security field, typically based
* on information about the bprm->file, for later use by the apply_creds
* hook. This hook may also optionally check permissions (e.g. for
* transitions between security domains).
* This hook may be called multiple times during a single execve, e.g. for
* interpreters. The hook can tell whether it has already been called by
* checking to see if @bprm->security is non-NULL. If so, then the hook
* may decide either to retain the security information saved earlier or
* to replace it.
* @bprm contains the linux_binprm structure.
* Return 0 if the hook is successful and permission is granted.
* @bprm_check_security:
* This hook mediates the point when a search for a binary handler will
* begin. It allows a check the @bprm->security value which is set in the
* preceding set_creds call. The primary difference from set_creds is
* that the argv list and envp list are reliably available in @bprm. This
* hook may be called multiple times during a single execve; and in each
* pass set_creds is called first.
* @bprm contains the linux_binprm structure.
* Return 0 if the hook is successful and permission is granted.
* @bprm_committing_creds:
* Prepare to install the new security attributes of a process being
* transformed by an execve operation, based on the old credentials
* pointed to by @current->cred and the information set in @bprm->cred by
* the bprm_set_creds hook. @bprm points to the linux_binprm structure.
* This hook is a good place to perform state changes on the process such
* as closing open file descriptors to which access will no longer be
* granted when the attributes are changed. This is called immediately
* before commit_creds().
* @bprm_committed_creds:
* Tidy up after the installation of the new security attributes of a
* process being transformed by an execve operation. The new credentials
* have, by this point, been set to @current->cred. @bprm points to the
* linux_binprm structure. This hook is a good place to perform state
* changes on the process such as clearing out non-inheritable signal
* state. This is called immediately after commit_creds().
* @bprm_secureexec:
* Return a boolean value (0 or 1) indicating whether a "secure exec"
* is required. The flag is passed in the auxiliary table
* on the initial stack to the ELF interpreter to indicate whether libc
* should enable secure mode.
* @bprm contains the linux_binprm structure.
*
* Security hooks for filesystem operations.
*
* @sb_alloc_security:
* Allocate and attach a security structure to the sb->s_security field.
* The s_security field is initialized to NULL when the structure is
* allocated.
* @sb contains the super_block structure to be modified.
* Return 0 if operation was successful.
* @sb_free_security:
* Deallocate and clear the sb->s_security field.
* @sb contains the super_block structure to be modified.
* @sb_statfs:
* Check permission before obtaining filesystem statistics for the @mnt
* mountpoint.
* @dentry is a handle on the superblock for the filesystem.
* Return 0 if permission is granted.
* @sb_mount:
* Check permission before an object specified by @dev_name is mounted on
* the mount point named by @nd. For an ordinary mount, @dev_name
* identifies a device if the file system type requires a device. For a
* remount (@flags & MS_REMOUNT), @dev_name is irrelevant. For a
* loopback/bind mount (@flags & MS_BIND), @dev_name identifies the
* pathname of the object being mounted.
* @dev_name contains the name for object being mounted.
* @path contains the path for mount point object.
* @type contains the filesystem type.
* @flags contains the mount flags.
* @data contains the filesystem-specific data.
* Return 0 if permission is granted.
* @sb_copy_data:
* Allow mount option data to be copied prior to parsing by the filesystem,
* so that the security module can extract security-specific mount
* options cleanly (a filesystem may modify the data e.g. with strsep()).
* This also allows the original mount data to be stripped of security-
* specific options to avoid having to make filesystems aware of them.
* @type the type of filesystem being mounted.
* @orig the original mount data copied from userspace.
* @copy copied data which will be passed to the security module.
* Returns 0 if the copy was successful.
* @sb_remount:
* Extracts security system specific mount options and verifies no changes
* are being made to those options.
* @sb superblock being remounted
* @data contains the filesystem-specific data.
* Return 0 if permission is granted.
* @sb_umount:
* Check permission before the @mnt file system is unmounted.
* @mnt contains the mounted file system.
* @flags contains the unmount flags, e.g. MNT_FORCE.
* Return 0 if permission is granted.
* @sb_pivotroot:
* Check permission before pivoting the root filesystem.
* @old_path contains the path for the new location of the current root (put_old).
* @new_path contains the path for the new root (new_root).
* Return 0 if permission is granted.
* @sb_set_mnt_opts:
* Set the security relevant mount options used for a superblock
* @sb the superblock to set security mount options for
* @opts binary data structure containing all lsm mount data
* @sb_clone_mnt_opts:
* Copy all security options from a given superblock to another
* @oldsb old superblock which contain information to clone
* @newsb new superblock which needs filled in
* @sb_parse_opts_str:
* Parse a string of security data filling in the opts structure
* @options string containing all mount options known by the LSM
* @opts binary data structure usable by the LSM
* @dentry_init_security:
* Compute a context for a dentry as the inode is not yet available
* since NFSv4 has no label backed by an EA anyway.
* @dentry dentry to use in calculating the context.
* @mode mode used to determine resource type.
* @name name of the last path component used to create file
* @ctx pointer to place the pointer to the resulting context in.
* @ctxlen point to place the length of the resulting context.
*
*
* Security hooks for inode operations.
*
* @inode_alloc_security:
* Allocate and attach a security structure to @inode->i_security. The
* i_security field is initialized to NULL when the inode structure is
* allocated.
* @inode contains the inode structure.
* Return 0 if operation was successful.
* @inode_free_security:
* @inode contains the inode structure.
* Deallocate the inode security structure and set @inode->i_security to
* NULL.
* @inode_init_security:
* Obtain the security attribute name suffix and value to set on a newly
* created inode and set up the incore security field for the new inode.
* This hook is called by the fs code as part of the inode creation
* transaction and provides for atomic labeling of the inode, unlike
* the post_create/mkdir/... hooks called by the VFS. The hook function
* is expected to allocate the name and value via kmalloc, with the caller
* being responsible for calling kfree after using them.
* If the security module does not use security attributes or does
* not wish to put a security attribute on this particular inode,
* then it should return -EOPNOTSUPP to skip this processing.
* @inode contains the inode structure of the newly created inode.
* @dir contains the inode structure of the parent directory.
* @qstr contains the last path component of the new object
* @name will be set to the allocated name suffix (e.g. selinux).
* @value will be set to the allocated attribute value.
* @len will be set to the length of the value.
* Returns 0 if @name and @value have been successfully set,
* -EOPNOTSUPP if no security attribute is needed, or
* -ENOMEM on memory allocation failure.
* @inode_create:
* Check permission to create a regular file.
* @dir contains inode structure of the parent of the new file.
* @dentry contains the dentry structure for the file to be created.
* @mode contains the file mode of the file to be created.
* Return 0 if permission is granted.
* @inode_link:
* Check permission before creating a new hard link to a file.
* @old_dentry contains the dentry structure for an existing link to the file.
* @dir contains the inode structure of the parent directory of the new link.
* @new_dentry contains the dentry structure for the new link.
* Return 0 if permission is granted.
* @path_link:
* Check permission before creating a new hard link to a file.
* @old_dentry contains the dentry structure for an existing link
* to the file.
* @new_dir contains the path structure of the parent directory of
* the new link.
* @new_dentry contains the dentry structure for the new link.
* Return 0 if permission is granted.
* @inode_unlink:
* Check the permission to remove a hard link to a file.
* @dir contains the inode structure of parent directory of the file.
* @dentry contains the dentry structure for file to be unlinked.
* Return 0 if permission is granted.
* @path_unlink:
* Check the permission to remove a hard link to a file.
* @dir contains the path structure of parent directory of the file.
* @dentry contains the dentry structure for file to be unlinked.
* Return 0 if permission is granted.
* @inode_symlink:
* Check the permission to create a symbolic link to a file.
* @dir contains the inode structure of parent directory of the symbolic link.
* @dentry contains the dentry structure of the symbolic link.
* @old_name contains the pathname of file.
* Return 0 if permission is granted.
* @path_symlink:
* Check the permission to create a symbolic link to a file.
* @dir contains the path structure of parent directory of
* the symbolic link.
* @dentry contains the dentry structure of the symbolic link.
* @old_name contains the pathname of file.
* Return 0 if permission is granted.
* @inode_mkdir:
* Check permissions to create a new directory in the existing directory
* associated with inode structure @dir.
* @dir contains the inode structure of parent of the directory to be created.
* @dentry contains the dentry structure of new directory.
* @mode contains the mode of new directory.
* Return 0 if permission is granted.
* @path_mkdir:
* Check permissions to create a new directory in the existing directory
* associated with path structure @path.
* @dir contains the path structure of parent of the directory
* to be created.
* @dentry contains the dentry structure of new directory.
* @mode contains the mode of new directory.
* Return 0 if permission is granted.
* @inode_rmdir:
* Check the permission to remove a directory.
* @dir contains the inode structure of parent of the directory to be removed.
* @dentry contains the dentry structure of directory to be removed.
* Return 0 if permission is granted.
* @path_rmdir:
* Check the permission to remove a directory.
* @dir contains the path structure of parent of the directory to be
* removed.
* @dentry contains the dentry structure of directory to be removed.
* Return 0 if permission is granted.
* @inode_mknod:
* Check permissions when creating a special file (or a socket or a fifo
* file created via the mknod system call). Note that if mknod operation
* is being done for a regular file, then the create hook will be called
* and not this hook.
* @dir contains the inode structure of parent of the new file.
* @dentry contains the dentry structure of the new file.
* @mode contains the mode of the new file.
* @dev contains the device number.
* Return 0 if permission is granted.
* @path_mknod:
* Check permissions when creating a file. Note that this hook is called
* even if mknod operation is being done for a regular file.
* @dir contains the path structure of parent of the new file.
* @dentry contains the dentry structure of the new file.
* @mode contains the mode of the new file.
* @dev contains the undecoded device number. Use new_decode_dev() to get
* the decoded device number.
* Return 0 if permission is granted.
* @inode_rename:
* Check for permission to rename a file or directory.
* @old_dir contains the inode structure for parent of the old link.
* @old_dentry contains the dentry structure of the old link.
* @new_dir contains the inode structure for parent of the new link.
* @new_dentry contains the dentry structure of the new link.
* Return 0 if permission is granted.
* @path_rename:
* Check for permission to rename a file or directory.
* @old_dir contains the path structure for parent of the old link.
* @old_dentry contains the dentry structure of the old link.
* @new_dir contains the path structure for parent of the new link.
* @new_dentry contains the dentry structure of the new link.
* Return 0 if permission is granted.
* @path_chmod:
* Check for permission to change DAC's permission of a file or directory.
* @dentry contains the dentry structure.
* @mnt contains the vfsmnt structure.
* @mode contains DAC's mode.
* Return 0 if permission is granted.
* @path_chown:
* Check for permission to change owner/group of a file or directory.
* @path contains the path structure.
* @uid contains new owner's ID.
* @gid contains new group's ID.
* Return 0 if permission is granted.
* @path_chroot:
* Check for permission to change root directory.
* @path contains the path structure.
* Return 0 if permission is granted.
* @inode_readlink:
* Check the permission to read the symbolic link.
* @dentry contains the dentry structure for the file link.
* Return 0 if permission is granted.
* @inode_follow_link:
* Check permission to follow a symbolic link when looking up a pathname.
* @dentry contains the dentry structure for the link.
* @nd contains the nameidata structure for the parent directory.
* Return 0 if permission is granted.
* @inode_permission:
* Check permission before accessing an inode. This hook is called by the
* existing Linux permission function, so a security module can use it to
* provide additional checking for existing Linux permission checks.
* Notice that this hook is called when a file is opened (as well as many
* other operations), whereas the file_security_ops permission hook is
* called when the actual read/write operations are performed.
* @inode contains the inode structure to check.
* @mask contains the permission mask.
* Return 0 if permission is granted.
* @inode_setattr:
* Check permission before setting file attributes. Note that the kernel
* call to notify_change is performed from several locations, whenever
* file attributes change (such as when a file is truncated, chown/chmod
* operations, transferring disk quotas, etc).
* @dentry contains the dentry structure for the file.
* @attr is the iattr structure containing the new file attributes.
* Return 0 if permission is granted.
* @path_truncate:
* Check permission before truncating a file.
* @path contains the path structure for the file.
* Return 0 if permission is granted.
* @inode_getattr:
* Check permission before obtaining file attributes.
* @mnt is the vfsmount where the dentry was looked up
* @dentry contains the dentry structure for the file.
* Return 0 if permission is granted.
* @inode_setxattr:
* Check permission before setting the extended attributes
* @value identified by @name for @dentry.
* Return 0 if permission is granted.
* @inode_post_setxattr:
* Update inode security field after successful setxattr operation.
* @value identified by @name for @dentry.
* @inode_getxattr:
* Check permission before obtaining the extended attributes
* identified by @name for @dentry.
* Return 0 if permission is granted.
* @inode_listxattr:
* Check permission before obtaining the list of extended attribute
* names for @dentry.
* Return 0 if permission is granted.
* @inode_removexattr:
* Check permission before removing the extended attribute
* identified by @name for @dentry.
* Return 0 if permission is granted.
* @inode_getsecurity:
* Retrieve a copy of the extended attribute representation of the
* security label associated with @name for @inode via @buffer. Note that
* @name is the remainder of the attribute name after the security prefix
* has been removed. @alloc is used to specify of the call should return a
* value via the buffer or just the value length Return size of buffer on
* success.
* @inode_setsecurity:
* Set the security label associated with @name for @inode from the
* extended attribute value @value. @size indicates the size of the
* @value in bytes. @flags may be XATTR_CREATE, XATTR_REPLACE, or 0.
* Note that @name is the remainder of the attribute name after the
* security. prefix has been removed.
* Return 0 on success.
* @inode_listsecurity:
* Copy the extended attribute names for the security labels
* associated with @inode into @buffer. The maximum size of @buffer
* is specified by @buffer_size. @buffer may be NULL to request
* the size of the buffer required.
* Returns number of bytes used/required on success.
* @inode_need_killpriv:
* Called when an inode has been changed.
* @dentry is the dentry being changed.
* Return <0 on error to abort the inode change operation.
* Return 0 if inode_killpriv does not need to be called.
* Return >0 if inode_killpriv does need to be called.
* @inode_killpriv:
* The setuid bit is being removed. Remove similar security labels.
* Called with the dentry->d_inode->i_mutex held.
* @dentry is the dentry being changed.
* Return 0 on success. If error is returned, then the operation
* causing setuid bit removal is failed.
* @inode_getsecid:
* Get the secid associated with the node.
* @inode contains a pointer to the inode.
* @secid contains a pointer to the location where result will be saved.
* In case of failure, @secid will be set to zero.
*
* Security hooks for file operations
*
* @file_permission:
* Check file permissions before accessing an open file. This hook is
* called by various operations that read or write files. A security
* module can use this hook to perform additional checking on these
* operations, e.g. to revalidate permissions on use to support privilege
* bracketing or policy changes. Notice that this hook is used when the
* actual read/write operations are performed, whereas the
* inode_security_ops hook is called when a file is opened (as well as
* many other operations).
* Caveat: Although this hook can be used to revalidate permissions for
* various system call operations that read or write files, it does not
* address the revalidation of permissions for memory-mapped files.
* Security modules must handle this separately if they need such
* revalidation.
* @file contains the file structure being accessed.
* @mask contains the requested permissions.
* Return 0 if permission is granted.
* @file_alloc_security:
* Allocate and attach a security structure to the file->f_security field.
* The security field is initialized to NULL when the structure is first
* created.
* @file contains the file structure to secure.
* Return 0 if the hook is successful and permission is granted.
* @file_free_security:
* Deallocate and free any security structures stored in file->f_security.
* @file contains the file structure being modified.
* @file_ioctl:
* @file contains the file structure.
* @cmd contains the operation to perform.
* @arg contains the operational arguments.
* Check permission for an ioctl operation on @file. Note that @arg
* sometimes represents a user space pointer; in other cases, it may be a
* simple integer value. When @arg represents a user space pointer, it
* should never be used by the security module.
* Return 0 if permission is granted.
* @mmap_addr :
* Check permissions for a mmap operation at @addr.
* @addr contains virtual address that will be used for the operation.
* Return 0 if permission is granted.
* @mmap_file :
* Check permissions for a mmap operation. The @file may be NULL, e.g.
* if mapping anonymous memory.
* @file contains the file structure for file to map (may be NULL).
* @reqprot contains the protection requested by the application.
* @prot contains the protection that will be applied by the kernel.
* @flags contains the operational flags.
* Return 0 if permission is granted.
* @file_mprotect:
* Check permissions before changing memory access permissions.
* @vma contains the memory region to modify.
* @reqprot contains the protection requested by the application.
* @prot contains the protection that will be applied by the kernel.
* Return 0 if permission is granted.
* @file_lock:
* Check permission before performing file locking operations.
* Note: this hook mediates both flock and fcntl style locks.
* @file contains the file structure.
* @cmd contains the posix-translated lock operation to perform
* (e.g. F_RDLCK, F_WRLCK).
* Return 0 if permission is granted.
* @file_fcntl:
* Check permission before allowing the file operation specified by @cmd
* from being performed on the file @file. Note that @arg sometimes
* represents a user space pointer; in other cases, it may be a simple
* integer value. When @arg represents a user space pointer, it should
* never be used by the security module.
* @file contains the file structure.
* @cmd contains the operation to be performed.
* @arg contains the operational arguments.
* Return 0 if permission is granted.
* @file_set_fowner:
* Save owner security information (typically from current->security) in
* file->f_security for later use by the send_sigiotask hook.
* @file contains the file structure to update.
* Return 0 on success.
* @file_send_sigiotask:
* Check permission for the file owner @fown to send SIGIO or SIGURG to the
* process @tsk. Note that this hook is sometimes called from interrupt.
* Note that the fown_struct, @fown, is never outside the context of a
* struct file, so the file structure (and associated security information)
* can always be obtained:
* container_of(fown, struct file, f_owner)
* @tsk contains the structure of task receiving signal.
* @fown contains the file owner information.
* @sig is the signal that will be sent. When 0, kernel sends SIGIO.
* Return 0 if permission is granted.
* @file_receive:
* This hook allows security modules to control the ability of a process
* to receive an open file descriptor via socket IPC.
* @file contains the file structure being received.
* Return 0 if permission is granted.
* @file_open
* Save open-time permission checking state for later use upon
* file_permission, and recheck access if anything has changed
* since inode_permission.
*
* Security hooks for task operations.
*
* @task_create:
* Check permission before creating a child process. See the clone(2)
* manual page for definitions of the @clone_flags.
* @clone_flags contains the flags indicating what should be shared.
* Return 0 if permission is granted.
* @task_free:
* @task task being freed
* Handle release of task-related resources. (Note that this can be called
* from interrupt context.)
* @cred_alloc_blank:
* @cred points to the credentials.
* @gfp indicates the atomicity of any memory allocations.
* Only allocate sufficient memory and attach to @cred such that
* cred_transfer() will not get ENOMEM.
* @cred_free:
* @cred points to the credentials.
* Deallocate and clear the cred->security field in a set of credentials.
* @cred_prepare:
* @new points to the new credentials.
* @old points to the original credentials.
* @gfp indicates the atomicity of any memory allocations.
* Prepare a new set of credentials by copying the data from the old set.
* @cred_transfer:
* @new points to the new credentials.
* @old points to the original credentials.
* Transfer data from original creds to new creds
* @kernel_act_as:
* Set the credentials for a kernel service to act as (subjective context).
* @new points to the credentials to be modified.
* @secid specifies the security ID to be set
* The current task must be the one that nominated @secid.
* Return 0 if successful.
* @kernel_create_files_as:
* Set the file creation context in a set of credentials to be the same as
* the objective context of the specified inode.
* @new points to the credentials to be modified.
* @inode points to the inode to use as a reference.
* The current task must be the one that nominated @inode.
* Return 0 if successful.
* @kernel_module_request:
* Ability to trigger the kernel to automatically upcall to userspace for
* userspace to load a kernel module with the given name.
* @kmod_name name of the module requested by the kernel
* Return 0 if successful.
* @kernel_module_from_file:
* Load a kernel module from userspace.
* @file contains the file structure pointing to the file containing
* the kernel module to load. If the module is being loaded from a blob,
* this argument will be NULL.
* Return 0 if permission is granted.
* @task_fix_setuid:
* Update the module's state after setting one or more of the user
* identity attributes of the current process. The @flags parameter
* indicates which of the set*uid system calls invoked this hook. If
* @new is the set of credentials that will be installed. Modifications
* should be made to this rather than to @current->cred.
* @old is the set of credentials that are being replaces
* @flags contains one of the LSM_SETID_* values.
* Return 0 on success.
* @task_setpgid:
* Check permission before setting the process group identifier of the
* process @p to @pgid.
* @p contains the task_struct for process being modified.
* @pgid contains the new pgid.
* Return 0 if permission is granted.
* @task_getpgid:
* Check permission before getting the process group identifier of the
* process @p.
* @p contains the task_struct for the process.
* Return 0 if permission is granted.
* @task_getsid:
* Check permission before getting the session identifier of the process
* @p.
* @p contains the task_struct for the process.
* Return 0 if permission is granted.
* @task_getsecid:
* Retrieve the security identifier of the process @p.
* @p contains the task_struct for the process and place is into @secid.
* In case of failure, @secid will be set to zero.
*
* @task_setnice:
* Check permission before setting the nice value of @p to @nice.
* @p contains the task_struct of process.
* @nice contains the new nice value.
* Return 0 if permission is granted.
* @task_setioprio
* Check permission before setting the ioprio value of @p to @ioprio.
* @p contains the task_struct of process.
* @ioprio contains the new ioprio value
* Return 0 if permission is granted.
* @task_getioprio
* Check permission before getting the ioprio value of @p.
* @p contains the task_struct of process.
* Return 0 if permission is granted.
* @task_setrlimit:
* Check permission before setting the resource limits of the current
* process for @resource to @new_rlim. The old resource limit values can
* be examined by dereferencing (current->signal->rlim + resource).
* @resource contains the resource whose limit is being set.
* @new_rlim contains the new limits for @resource.
* Return 0 if permission is granted.
* @task_setscheduler:
* Check permission before setting scheduling policy and/or parameters of
* process @p based on @policy and @lp.
* @p contains the task_struct for process.
* @policy contains the scheduling policy.
* @lp contains the scheduling parameters.
* Return 0 if permission is granted.
* @task_getscheduler:
* Check permission before obtaining scheduling information for process
* @p.
* @p contains the task_struct for process.
* Return 0 if permission is granted.
* @task_movememory
* Check permission before moving memory owned by process @p.
* @p contains the task_struct for process.
* Return 0 if permission is granted.
* @task_kill:
* Check permission before sending signal @sig to @p. @info can be NULL,
* the constant 1, or a pointer to a siginfo structure. If @info is 1 or
* SI_FROMKERNEL(info) is true, then the signal should be viewed as coming
* from the kernel and should typically be permitted.
* SIGIO signals are handled separately by the send_sigiotask hook in
* file_security_ops.
* @p contains the task_struct for process.
* @info contains the signal information.
* @sig contains the signal value.
* @secid contains the sid of the process where the signal originated
* Return 0 if permission is granted.
* @task_wait:
* Check permission before allowing a process to reap a child process @p
* and collect its status information.
* @p contains the task_struct for process.
* Return 0 if permission is granted.
* @task_prctl:
* Check permission before performing a process control operation on the
* current process.
* @option contains the operation.
* @arg2 contains a argument.
* @arg3 contains a argument.
* @arg4 contains a argument.
* @arg5 contains a argument.
* Return -ENOSYS if no-one wanted to handle this op, any other value to
* cause prctl() to return immediately with that value.
* @task_to_inode:
* Set the security attributes for an inode based on an associated task's
* security attributes, e.g. for /proc/pid inodes.
* @p contains the task_struct for the task.
* @inode contains the inode structure for the inode.
*
* Security hooks for Netlink messaging.
*
* @netlink_send:
* Save security information for a netlink message so that permission
* checking can be performed when the message is processed. The security
* information can be saved using the eff_cap field of the
* netlink_skb_parms structure. Also may be used to provide fine
* grained control over message transmission.
* @sk associated sock of task sending the message.
* @skb contains the sk_buff structure for the netlink message.
* Return 0 if the information was successfully saved and message
* is allowed to be transmitted.
*
* Security hooks for Unix domain networking.
*
* @unix_stream_connect:
* Check permissions before establishing a Unix domain stream connection
* between @sock and @other.
* @sock contains the sock structure.
* @other contains the peer sock structure.
* @newsk contains the new sock structure.
* Return 0 if permission is granted.
* @unix_may_send:
* Check permissions before connecting or sending datagrams from @sock to
* @other.
* @sock contains the socket structure.
* @other contains the peer socket structure.
* Return 0 if permission is granted.
*
* The @unix_stream_connect and @unix_may_send hooks were necessary because
* Linux provides an alternative to the conventional file name space for Unix
* domain sockets. Whereas binding and connecting to sockets in the file name
* space is mediated by the typical file permissions (and caught by the mknod
* and permission hooks in inode_security_ops), binding and connecting to
* sockets in the abstract name space is completely unmediated. Sufficient
* control of Unix domain sockets in the abstract name space isn't possible
* using only the socket layer hooks, since we need to know the actual target
* socket, which is not looked up until we are inside the af_unix code.
*
* Security hooks for socket operations.
*
* @socket_create:
* Check permissions prior to creating a new socket.
* @family contains the requested protocol family.
* @type contains the requested communications type.
* @protocol contains the requested protocol.
* @kern set to 1 if a kernel socket.
* Return 0 if permission is granted.
* @socket_post_create:
* This hook allows a module to update or allocate a per-socket security
* structure. Note that the security field was not added directly to the
* socket structure, but rather, the socket security information is stored
* in the associated inode. Typically, the inode alloc_security hook will
* allocate and and attach security information to
* sock->inode->i_security. This hook may be used to update the
* sock->inode->i_security field with additional information that wasn't
* available when the inode was allocated.
* @sock contains the newly created socket structure.
* @family contains the requested protocol family.
* @type contains the requested communications type.
* @protocol contains the requested protocol.
* @kern set to 1 if a kernel socket.
* @socket_bind:
* Check permission before socket protocol layer bind operation is
* performed and the socket @sock is bound to the address specified in the
* @address parameter.
* @sock contains the socket structure.
* @address contains the address to bind to.
* @addrlen contains the length of address.
* Return 0 if permission is granted.
* @socket_connect:
* Check permission before socket protocol layer connect operation
* attempts to connect socket @sock to a remote address, @address.
* @sock contains the socket structure.
* @address contains the address of remote endpoint.
* @addrlen contains the length of address.
* Return 0 if permission is granted.
* @socket_listen:
* Check permission before socket protocol layer listen operation.
* @sock contains the socket structure.
* @backlog contains the maximum length for the pending connection queue.
* Return 0 if permission is granted.
* @socket_accept:
* Check permission before accepting a new connection. Note that the new
* socket, @newsock, has been created and some information copied to it,
* but the accept operation has not actually been performed.
* @sock contains the listening socket structure.
* @newsock contains the newly created server socket for connection.
* Return 0 if permission is granted.
* @socket_sendmsg:
* Check permission before transmitting a message to another socket.
* @sock contains the socket structure.
* @msg contains the message to be transmitted.
* @size contains the size of message.
* Return 0 if permission is granted.
* @socket_recvmsg:
* Check permission before receiving a message from a socket.
* @sock contains the socket structure.
* @msg contains the message structure.
* @size contains the size of message structure.
* @flags contains the operational flags.
* Return 0 if permission is granted.
* @socket_getsockname:
* Check permission before the local address (name) of the socket object
* @sock is retrieved.
* @sock contains the socket structure.
* Return 0 if permission is granted.
* @socket_getpeername:
* Check permission before the remote address (name) of a socket object
* @sock is retrieved.
* @sock contains the socket structure.
* Return 0 if permission is granted.
* @socket_getsockopt:
* Check permissions before retrieving the options associated with socket
* @sock.
* @sock contains the socket structure.
* @level contains the protocol level to retrieve option from.
* @optname contains the name of option to retrieve.
* Return 0 if permission is granted.
* @socket_setsockopt:
* Check permissions before setting the options associated with socket
* @sock.
* @sock contains the socket structure.
* @level contains the protocol level to set options for.
* @optname contains the name of the option to set.
* Return 0 if permission is granted.
* @socket_shutdown:
* Checks permission before all or part of a connection on the socket
* @sock is shut down.
* @sock contains the socket structure.
* @how contains the flag indicating how future sends and receives are handled.
* Return 0 if permission is granted.
* @socket_sock_rcv_skb:
* Check permissions on incoming network packets. This hook is distinct
* from Netfilter's IP input hooks since it is the first time that the
* incoming sk_buff @skb has been associated with a particular socket, @sk.
* Must not sleep inside this hook because some callers hold spinlocks.
* @sk contains the sock (not socket) associated with the incoming sk_buff.
* @skb contains the incoming network data.
* @socket_getpeersec_stream:
* This hook allows the security module to provide peer socket security
* state for unix or connected tcp sockets to userspace via getsockopt
* SO_GETPEERSEC. For tcp sockets this can be meaningful if the
* socket is associated with an ipsec SA.
* @sock is the local socket.
* @optval userspace memory where the security state is to be copied.
* @optlen userspace int where the module should copy the actual length
* of the security state.
* @len as input is the maximum length to copy to userspace provided
* by the caller.
* Return 0 if all is well, otherwise, typical getsockopt return
* values.
* @socket_getpeersec_dgram:
* This hook allows the security module to provide peer socket security
* state for udp sockets on a per-packet basis to userspace via
* getsockopt SO_GETPEERSEC. The application must first have indicated
* the IP_PASSSEC option via getsockopt. It can then retrieve the
* security state returned by this hook for a packet via the SCM_SECURITY
* ancillary message type.
* @skb is the skbuff for the packet being queried
* @secdata is a pointer to a buffer in which to copy the security data
* @seclen is the maximum length for @secdata
* Return 0 on success, error on failure.
* @sk_alloc_security:
* Allocate and attach a security structure to the sk->sk_security field,
* which is used to copy security attributes between local stream sockets.
* @sk_free_security:
* Deallocate security structure.
* @sk_clone_security:
* Clone/copy security structure.
* @sk_getsecid:
* Retrieve the LSM-specific secid for the sock to enable caching of network
* authorizations.
* @sock_graft:
* Sets the socket's isec sid to the sock's sid.
* @inet_conn_request:
* Sets the openreq's sid to socket's sid with MLS portion taken from peer sid.
* @inet_csk_clone:
* Sets the new child socket's sid to the openreq sid.
* @inet_conn_established:
* Sets the connection's peersid to the secmark on skb.
* @secmark_relabel_packet:
* check if the process should be allowed to relabel packets to the given secid
* @security_secmark_refcount_inc
* tells the LSM to increment the number of secmark labeling rules loaded
* @security_secmark_refcount_dec
* tells the LSM to decrement the number of secmark labeling rules loaded
* @req_classify_flow:
* Sets the flow's sid to the openreq sid.
* @tun_dev_alloc_security:
* This hook allows a module to allocate a security structure for a TUN
* device.
* @security pointer to a security structure pointer.
* Returns a zero on success, negative values on failure.
* @tun_dev_free_security:
* This hook allows a module to free the security structure for a TUN
* device.
* @security pointer to the TUN device's security structure
* @tun_dev_create:
* Check permissions prior to creating a new TUN device.
* @tun_dev_attach_queue:
* Check permissions prior to attaching to a TUN device queue.
* @security pointer to the TUN device's security structure.
* @tun_dev_attach:
* This hook can be used by the module to update any security state
* associated with the TUN device's sock structure.
* @sk contains the existing sock structure.
* @security pointer to the TUN device's security structure.
* @tun_dev_open:
* This hook can be used by the module to update any security state
* associated with the TUN device's security structure.
* @security pointer to the TUN devices's security structure.
* @skb_owned_by:
* This hook sets the packet's owning sock.
* @skb is the packet.
* @sk the sock which owns the packet.
*
* Security hooks for XFRM operations.
*
* @xfrm_policy_alloc_security:
* @ctxp is a pointer to the xfrm_sec_ctx being added to Security Policy
* Database used by the XFRM system.
* @sec_ctx contains the security context information being provided by
* the user-level policy update program (e.g., setkey).
* Allocate a security structure to the xp->security field; the security
* field is initialized to NULL when the xfrm_policy is allocated.
* Return 0 if operation was successful (memory to allocate, legal context)
* @xfrm_policy_clone_security:
* @old_ctx contains an existing xfrm_sec_ctx.
* @new_ctxp contains a new xfrm_sec_ctx being cloned from old.
* Allocate a security structure in new_ctxp that contains the
* information from the old_ctx structure.
* Return 0 if operation was successful (memory to allocate).
* @xfrm_policy_free_security:
* @ctx contains the xfrm_sec_ctx
* Deallocate xp->security.
* @xfrm_policy_delete_security:
* @ctx contains the xfrm_sec_ctx.
* Authorize deletion of xp->security.
* @xfrm_state_alloc_security:
* @x contains the xfrm_state being added to the Security Association
* Database by the XFRM system.
* @sec_ctx contains the security context information being provided by
* the user-level SA generation program (e.g., setkey or racoon).
* @secid contains the secid from which to take the mls portion of the context.
* Allocate a security structure to the x->security field; the security
* field is initialized to NULL when the xfrm_state is allocated. Set the
* context to correspond to either sec_ctx or polsec, with the mls portion
* taken from secid in the latter case.
* Return 0 if operation was successful (memory to allocate, legal context).
* @xfrm_state_free_security:
* @x contains the xfrm_state.
* Deallocate x->security.
* @xfrm_state_delete_security:
* @x contains the xfrm_state.
* Authorize deletion of x->security.
* @xfrm_policy_lookup:
* @ctx contains the xfrm_sec_ctx for which the access control is being
* checked.
* @fl_secid contains the flow security label that is used to authorize
* access to the policy xp.
* @dir contains the direction of the flow (input or output).
* Check permission when a flow selects a xfrm_policy for processing
* XFRMs on a packet. The hook is called when selecting either a
* per-socket policy or a generic xfrm policy.
* Return 0 if permission is granted, -ESRCH otherwise, or -errno
* on other errors.
* @xfrm_state_pol_flow_match:
* @x contains the state to match.
* @xp contains the policy to check for a match.
* @fl contains the flow to check for a match.
* Return 1 if there is a match.
* @xfrm_decode_session:
* @skb points to skb to decode.
* @secid points to the flow key secid to set.
* @ckall says if all xfrms used should be checked for same secid.
* Return 0 if ckall is zero or all xfrms used have the same secid.
*
* Security hooks affecting all Key Management operations
*
* @key_alloc:
* Permit allocation of a key and assign security data. Note that key does
* not have a serial number assigned at this point.
* @key points to the key.
* @flags is the allocation flags
* Return 0 if permission is granted, -ve error otherwise.
* @key_free:
* Notification of destruction; free security data.
* @key points to the key.
* No return value.
* @key_permission:
* See whether a specific operational right is granted to a process on a
* key.
* @key_ref refers to the key (key pointer + possession attribute bit).
* @cred points to the credentials to provide the context against which to
* evaluate the security data on the key.
* @perm describes the combination of permissions required of this key.
* Return 0 if permission is granted, -ve error otherwise.
* @key_getsecurity:
* Get a textual representation of the security context attached to a key
* for the purposes of honouring KEYCTL_GETSECURITY. This function
* allocates the storage for the NUL-terminated string and the caller
* should free it.
* @key points to the key to be queried.
* @_buffer points to a pointer that should be set to point to the
* resulting string (if no label or an error occurs).
* Return the length of the string (including terminating NUL) or -ve if
* an error.
* May also return 0 (and a NULL buffer pointer) if there is no label.
*
* Security hooks affecting all System V IPC operations.
*
* @ipc_permission:
* Check permissions for access to IPC
* @ipcp contains the kernel IPC permission structure
* @flag contains the desired (requested) permission set
* Return 0 if permission is granted.
* @ipc_getsecid:
* Get the secid associated with the ipc object.
* @ipcp contains the kernel IPC permission structure.
* @secid contains a pointer to the location where result will be saved.
* In case of failure, @secid will be set to zero.
*
* Security hooks for individual messages held in System V IPC message queues
* @msg_msg_alloc_security:
* Allocate and attach a security structure to the msg->security field.
* The security field is initialized to NULL when the structure is first
* created.
* @msg contains the message structure to be modified.
* Return 0 if operation was successful and permission is granted.
* @msg_msg_free_security:
* Deallocate the security structure for this message.
* @msg contains the message structure to be modified.
*
* Security hooks for System V IPC Message Queues
*
* @msg_queue_alloc_security:
* Allocate and attach a security structure to the
* msq->q_perm.security field. The security field is initialized to
* NULL when the structure is first created.
* @msq contains the message queue structure to be modified.
* Return 0 if operation was successful and permission is granted.
* @msg_queue_free_security:
* Deallocate security structure for this message queue.
* @msq contains the message queue structure to be modified.
* @msg_queue_associate:
* Check permission when a message queue is requested through the
* msgget system call. This hook is only called when returning the
* message queue identifier for an existing message queue, not when a
* new message queue is created.
* @msq contains the message queue to act upon.
* @msqflg contains the operation control flags.
* Return 0 if permission is granted.
* @msg_queue_msgctl:
* Check permission when a message control operation specified by @cmd
* is to be performed on the message queue @msq.
* The @msq may be NULL, e.g. for IPC_INFO or MSG_INFO.
* @msq contains the message queue to act upon. May be NULL.
* @cmd contains the operation to be performed.
* Return 0 if permission is granted.
* @msg_queue_msgsnd:
* Check permission before a message, @msg, is enqueued on the message
* queue, @msq.
* @msq contains the message queue to send message to.
* @msg contains the message to be enqueued.
* @msqflg contains operational flags.
* Return 0 if permission is granted.
* @msg_queue_msgrcv:
* Check permission before a message, @msg, is removed from the message
* queue, @msq. The @target task structure contains a pointer to the
* process that will be receiving the message (not equal to the current
* process when inline receives are being performed).
* @msq contains the message queue to retrieve message from.
* @msg contains the message destination.
* @target contains the task structure for recipient process.
* @type contains the type of message requested.
* @mode contains the operational flags.
* Return 0 if permission is granted.
*
* Security hooks for System V Shared Memory Segments
*
* @shm_alloc_security:
* Allocate and attach a security structure to the shp->shm_perm.security
* field. The security field is initialized to NULL when the structure is
* first created.
* @shp contains the shared memory structure to be modified.
* Return 0 if operation was successful and permission is granted.
* @shm_free_security:
* Deallocate the security struct for this memory segment.
* @shp contains the shared memory structure to be modified.
* @shm_associate:
* Check permission when a shared memory region is requested through the
* shmget system call. This hook is only called when returning the shared
* memory region identifier for an existing region, not when a new shared
* memory region is created.
* @shp contains the shared memory structure to be modified.
* @shmflg contains the operation control flags.
* Return 0 if permission is granted.
* @shm_shmctl:
* Check permission when a shared memory control operation specified by
* @cmd is to be performed on the shared memory region @shp.
* The @shp may be NULL, e.g. for IPC_INFO or SHM_INFO.
* @shp contains shared memory structure to be modified.
* @cmd contains the operation to be performed.
* Return 0 if permission is granted.
* @shm_shmat:
* Check permissions prior to allowing the shmat system call to attach the
* shared memory segment @shp to the data segment of the calling process.
* The attaching address is specified by @shmaddr.
* @shp contains the shared memory structure to be modified.
* @shmaddr contains the address to attach memory region to.
* @shmflg contains the operational flags.
* Return 0 if permission is granted.
*
* Security hooks for System V Semaphores
*
* @sem_alloc_security:
* Allocate and attach a security structure to the sma->sem_perm.security
* field. The security field is initialized to NULL when the structure is
* first created.
* @sma contains the semaphore structure
* Return 0 if operation was successful and permission is granted.
* @sem_free_security:
* deallocate security struct for this semaphore
* @sma contains the semaphore structure.
* @sem_associate:
* Check permission when a semaphore is requested through the semget
* system call. This hook is only called when returning the semaphore
* identifier for an existing semaphore, not when a new one must be
* created.
* @sma contains the semaphore structure.
* @semflg contains the operation control flags.
* Return 0 if permission is granted.
* @sem_semctl:
* Check permission when a semaphore operation specified by @cmd is to be
* performed on the semaphore @sma. The @sma may be NULL, e.g. for
* IPC_INFO or SEM_INFO.
* @sma contains the semaphore structure. May be NULL.
* @cmd contains the operation to be performed.
* Return 0 if permission is granted.
* @sem_semop
* Check permissions before performing operations on members of the
* semaphore set @sma. If the @alter flag is nonzero, the semaphore set
* may be modified.
* @sma contains the semaphore structure.
* @sops contains the operations to perform.
* @nsops contains the number of operations to perform.
* @alter contains the flag indicating whether changes are to be made.
* Return 0 if permission is granted.
*
* @ptrace_access_check:
* Check permission before allowing the current process to trace the
* @child process.
* Security modules may also want to perform a process tracing check
* during an execve in the set_security or apply_creds hooks of
* tracing check during an execve in the bprm_set_creds hook of
* binprm_security_ops if the process is being traced and its security
* attributes would be changed by the execve.
* @child contains the task_struct structure for the target process.
* @mode contains the PTRACE_MODE flags indicating the form of access.
* Return 0 if permission is granted.
* @ptrace_traceme:
* Check that the @parent process has sufficient permission to trace the
* current process before allowing the current process to present itself
* to the @parent process for tracing.
* @parent contains the task_struct structure for debugger process.
* Return 0 if permission is granted.
* @capget:
* Get the @effective, @inheritable, and @permitted capability sets for
* the @target process. The hook may also perform permission checking to
* determine if the current process is allowed to see the capability sets
* of the @target process.
* @target contains the task_struct structure for target process.
* @effective contains the effective capability set.
* @inheritable contains the inheritable capability set.
* @permitted contains the permitted capability set.
* Return 0 if the capability sets were successfully obtained.
* @capset:
* Set the @effective, @inheritable, and @permitted capability sets for
* the current process.
* @new contains the new credentials structure for target process.
* @old contains the current credentials structure for target process.
* @effective contains the effective capability set.
* @inheritable contains the inheritable capability set.
* @permitted contains the permitted capability set.
* Return 0 and update @new if permission is granted.
* @capable:
* Check whether the @tsk process has the @cap capability in the indicated
* credentials.
* @cred contains the credentials to use.
* @ns contains the user namespace we want the capability in
* @cap contains the capability <include/linux/capability.h>.
* @audit: Whether to write an audit message or not
* Return 0 if the capability is granted for @tsk.
* @syslog:
* Check permission before accessing the kernel message ring or changing
* logging to the console.
* See the syslog(2) manual page for an explanation of the @type values.
* @type contains the type of action.
* @from_file indicates the context of action (if it came from /proc).
* Return 0 if permission is granted.
* @settime:
* Check permission to change the system time.
* struct timespec and timezone are defined in include/linux/time.h
* @ts contains new time
* @tz contains new timezone
* Return 0 if permission is granted.
* @vm_enough_memory:
* Check permissions for allocating a new virtual mapping.
* @mm contains the mm struct it is being added to.
* @pages contains the number of pages.
* Return 0 if permission is granted.
*
* @ismaclabel:
* Check if the extended attribute specified by @name
* represents a MAC label. Returns 1 if name is a MAC
* attribute otherwise returns 0.
* @name full extended attribute name to check against
* LSM as a MAC label.
*
* @secid_to_secctx:
* Convert secid to security context. If secdata is NULL the length of
* the result will be returned in seclen, but no secdata will be returned.
* This does mean that the length could change between calls to check the
* length and the next call which actually allocates and returns the secdata.
* @secid contains the security ID.
* @secdata contains the pointer that stores the converted security context.
* @seclen pointer which contains the length of the data
* @secctx_to_secid:
* Convert security context to secid.
* @secid contains the pointer to the generated security ID.
* @secdata contains the security context.
*
* @release_secctx:
* Release the security context.
* @secdata contains the security context.
* @seclen contains the length of the security context.
*
* Security hooks for Audit
*
* @audit_rule_init:
* Allocate and initialize an LSM audit rule structure.
* @field contains the required Audit action. Fields flags are defined in include/linux/audit.h
* @op contains the operator the rule uses.
* @rulestr contains the context where the rule will be applied to.
* @lsmrule contains a pointer to receive the result.
* Return 0 if @lsmrule has been successfully set,
* -EINVAL in case of an invalid rule.
*
* @audit_rule_known:
* Specifies whether given @rule contains any fields related to current LSM.
* @rule contains the audit rule of interest.
* Return 1 in case of relation found, 0 otherwise.
*
* @audit_rule_match:
* Determine if given @secid matches a rule previously approved
* by @audit_rule_known.
* @secid contains the security id in question.
* @field contains the field which relates to current LSM.
* @op contains the operator that will be used for matching.
* @rule points to the audit rule that will be checked against.
* @actx points to the audit context associated with the check.
* Return 1 if secid matches the rule, 0 if it does not, -ERRNO on failure.
*
* @audit_rule_free:
* Deallocate the LSM audit rule structure previously allocated by
* audit_rule_init.
* @rule contains the allocated rule
*
* @inode_notifysecctx:
* Notify the security module of what the security context of an inode
* should be. Initializes the incore security context managed by the
* security module for this inode. Example usage: NFS client invokes
* this hook to initialize the security context in its incore inode to the
* value provided by the server for the file when the server returned the
* file's attributes to the client.
*
* Must be called with inode->i_mutex locked.
*
* @inode we wish to set the security context of.
* @ctx contains the string which we wish to set in the inode.
* @ctxlen contains the length of @ctx.
*
* @inode_setsecctx:
* Change the security context of an inode. Updates the
* incore security context managed by the security module and invokes the
* fs code as needed (via __vfs_setxattr_noperm) to update any backing
* xattrs that represent the context. Example usage: NFS server invokes
* this hook to change the security context in its incore inode and on the
* backing filesystem to a value provided by the client on a SETATTR
* operation.
*
* Must be called with inode->i_mutex locked.
*
* @dentry contains the inode we wish to set the security context of.
* @ctx contains the string which we wish to set in the inode.
* @ctxlen contains the length of @ctx.
*
* @inode_getsecctx:
* Returns a string containing all relevant security context information
*
* @inode we wish to get the security context of.
* @ctx is a pointer in which to place the allocated security context.
* @ctxlen points to the place to put the length of @ctx.
* This is the main security structure.
*/
struct security_operations {
char name[SECURITY_NAME_MAX + 1];
int (*binder_set_context_mgr) (struct task_struct *mgr);
int (*binder_transaction) (struct task_struct *from, struct task_struct *to);
int (*binder_transfer_binder) (struct task_struct *from, struct task_struct *to);
int (*binder_transfer_file) (struct task_struct *from, struct task_struct *to, struct file *file);
int (*ptrace_access_check) (struct task_struct *child, unsigned int mode);
int (*ptrace_traceme) (struct task_struct *parent);
int (*capget) (struct task_struct *target,
kernel_cap_t *effective,
kernel_cap_t *inheritable, kernel_cap_t *permitted);
int (*capset) (struct cred *new,
const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted);
int (*capable) (const struct cred *cred, struct user_namespace *ns,
int cap, int audit);
int (*quotactl) (int cmds, int type, int id, struct super_block *sb);
int (*quota_on) (struct dentry *dentry);
int (*syslog) (int type);
int (*settime) (const struct timespec *ts, const struct timezone *tz);
int (*vm_enough_memory) (struct mm_struct *mm, long pages);
int (*bprm_set_creds) (struct linux_binprm *bprm);
int (*bprm_check_security) (struct linux_binprm *bprm);
int (*bprm_secureexec) (struct linux_binprm *bprm);
void (*bprm_committing_creds) (struct linux_binprm *bprm);
void (*bprm_committed_creds) (struct linux_binprm *bprm);
int (*sb_alloc_security) (struct super_block *sb);
void (*sb_free_security) (struct super_block *sb);
int (*sb_copy_data) (char *orig, char *copy);
int (*sb_remount) (struct super_block *sb, void *data);
int (*sb_kern_mount) (struct super_block *sb, int flags, void *data);
int (*sb_show_options) (struct seq_file *m, struct super_block *sb);
int (*sb_statfs) (struct dentry *dentry);
int (*sb_mount) (const char *dev_name, struct path *path,
const char *type, unsigned long flags, void *data);
int (*sb_umount) (struct vfsmount *mnt, int flags);
int (*sb_pivotroot) (struct path *old_path,
struct path *new_path);
int (*sb_set_mnt_opts) (struct super_block *sb,
struct security_mnt_opts *opts,
unsigned long kern_flags,
unsigned long *set_kern_flags);
int (*sb_clone_mnt_opts) (const struct super_block *oldsb,
struct super_block *newsb);
int (*sb_parse_opts_str) (char *options, struct security_mnt_opts *opts);
int (*dentry_init_security) (struct dentry *dentry, int mode,
struct qstr *name, void **ctx,
u32 *ctxlen);
#ifdef CONFIG_SECURITY_PATH
int (*path_unlink) (struct path *dir, struct dentry *dentry);
int (*path_mkdir) (struct path *dir, struct dentry *dentry, umode_t mode);
int (*path_rmdir) (struct path *dir, struct dentry *dentry);
int (*path_mknod) (struct path *dir, struct dentry *dentry, umode_t mode,
unsigned int dev);
int (*path_truncate) (struct path *path);
int (*path_symlink) (struct path *dir, struct dentry *dentry,
const char *old_name);
int (*path_link) (struct dentry *old_dentry, struct path *new_dir,
struct dentry *new_dentry);
int (*path_rename) (struct path *old_dir, struct dentry *old_dentry,
struct path *new_dir, struct dentry *new_dentry);
int (*path_chmod) (struct path *path, umode_t mode);
int (*path_chown) (struct path *path, kuid_t uid, kgid_t gid);
int (*path_chroot) (struct path *path);
#endif
int (*inode_alloc_security) (struct inode *inode);
void (*inode_free_security) (struct inode *inode);
int (*inode_init_security) (struct inode *inode, struct inode *dir,
const struct qstr *qstr, char **name,
void **value, size_t *len);
int (*inode_create) (struct inode *dir,
struct dentry *dentry, umode_t mode);
int (*inode_post_create) (struct inode *dir,
struct dentry *dentry, umode_t mode);
int (*inode_link) (struct dentry *old_dentry,
struct inode *dir, struct dentry *new_dentry);
int (*inode_unlink) (struct inode *dir, struct dentry *dentry);
int (*inode_symlink) (struct inode *dir,
struct dentry *dentry, const char *old_name);
int (*inode_mkdir) (struct inode *dir, struct dentry *dentry, umode_t mode);
int (*inode_rmdir) (struct inode *dir, struct dentry *dentry);
int (*inode_mknod) (struct inode *dir, struct dentry *dentry,
umode_t mode, dev_t dev);
int (*inode_rename) (struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry);
int (*inode_readlink) (struct dentry *dentry);
int (*inode_follow_link) (struct dentry *dentry, struct nameidata *nd);
int (*inode_permission) (struct inode *inode, int mask);
int (*inode_setattr) (struct dentry *dentry, struct iattr *attr);
int (*inode_getattr) (struct vfsmount *mnt, struct dentry *dentry);
int (*inode_setxattr) (struct dentry *dentry, const char *name,
const void *value, size_t size, int flags);
void (*inode_post_setxattr) (struct dentry *dentry, const char *name,
const void *value, size_t size, int flags);
int (*inode_getxattr) (struct dentry *dentry, const char *name);
int (*inode_listxattr) (struct dentry *dentry);
int (*inode_removexattr) (struct dentry *dentry, const char *name);
int (*inode_need_killpriv) (struct dentry *dentry);
int (*inode_killpriv) (struct dentry *dentry);
int (*inode_getsecurity) (const struct inode *inode, const char *name, void **buffer, bool alloc);
int (*inode_setsecurity) (struct inode *inode, const char *name, const void *value, size_t size, int flags);
int (*inode_listsecurity) (struct inode *inode, char *buffer, size_t buffer_size);
void (*inode_getsecid) (const struct inode *inode, u32 *secid);
int (*file_permission) (struct file *file, int mask);
int (*file_alloc_security) (struct file *file);
void (*file_free_security) (struct file *file);
int (*file_ioctl) (struct file *file, unsigned int cmd,
unsigned long arg);
int (*mmap_addr) (unsigned long addr);
int (*mmap_file) (struct file *file,
unsigned long reqprot, unsigned long prot,
unsigned long flags);
int (*file_mprotect) (struct vm_area_struct *vma,
unsigned long reqprot,
unsigned long prot);
int (*file_lock) (struct file *file, unsigned int cmd);
int (*file_fcntl) (struct file *file, unsigned int cmd,
unsigned long arg);
int (*file_set_fowner) (struct file *file);
int (*file_send_sigiotask) (struct task_struct *tsk,
struct fown_struct *fown, int sig);
int (*file_receive) (struct file *file);
int (*file_open) (struct file *file, const struct cred *cred);
int (*file_close) (struct file *file);
bool (*allow_merge_bio)(struct bio *bio1, struct bio *bio2);
int (*task_create) (unsigned long clone_flags);
void (*task_free) (struct task_struct *task);
int (*cred_alloc_blank) (struct cred *cred, gfp_t gfp);
void (*cred_free) (struct cred *cred);
int (*cred_prepare)(struct cred *new, const struct cred *old,
gfp_t gfp);
void (*cred_transfer)(struct cred *new, const struct cred *old);
int (*kernel_act_as)(struct cred *new, u32 secid);
int (*kernel_create_files_as)(struct cred *new, struct inode *inode);
int (*kernel_module_request)(char *kmod_name);
int (*kernel_module_from_file)(struct file *file);
int (*task_fix_setuid) (struct cred *new, const struct cred *old,
int flags);
int (*task_setpgid) (struct task_struct *p, pid_t pgid);
int (*task_getpgid) (struct task_struct *p);
int (*task_getsid) (struct task_struct *p);
void (*task_getsecid) (struct task_struct *p, u32 *secid);
int (*task_setnice) (struct task_struct *p, int nice);
int (*task_setioprio) (struct task_struct *p, int ioprio);
int (*task_getioprio) (struct task_struct *p);
int (*task_setrlimit) (struct task_struct *p, unsigned int resource,
struct rlimit *new_rlim);
int (*task_setscheduler) (struct task_struct *p);
int (*task_getscheduler) (struct task_struct *p);
int (*task_movememory) (struct task_struct *p);
int (*task_kill) (struct task_struct *p,
struct siginfo *info, int sig, u32 secid);
int (*task_wait) (struct task_struct *p);
int (*task_prctl) (int option, unsigned long arg2,
unsigned long arg3, unsigned long arg4,
unsigned long arg5);
void (*task_to_inode) (struct task_struct *p, struct inode *inode);
int (*ipc_permission) (struct kern_ipc_perm *ipcp, short flag);
void (*ipc_getsecid) (struct kern_ipc_perm *ipcp, u32 *secid);
int (*msg_msg_alloc_security) (struct msg_msg *msg);
void (*msg_msg_free_security) (struct msg_msg *msg);
int (*msg_queue_alloc_security) (struct msg_queue *msq);
void (*msg_queue_free_security) (struct msg_queue *msq);
int (*msg_queue_associate) (struct msg_queue *msq, int msqflg);
int (*msg_queue_msgctl) (struct msg_queue *msq, int cmd);
int (*msg_queue_msgsnd) (struct msg_queue *msq,
struct msg_msg *msg, int msqflg);
int (*msg_queue_msgrcv) (struct msg_queue *msq,
struct msg_msg *msg,
struct task_struct *target,
long type, int mode);
int (*shm_alloc_security) (struct shmid_kernel *shp);
void (*shm_free_security) (struct shmid_kernel *shp);
int (*shm_associate) (struct shmid_kernel *shp, int shmflg);
int (*shm_shmctl) (struct shmid_kernel *shp, int cmd);
int (*shm_shmat) (struct shmid_kernel *shp,
char __user *shmaddr, int shmflg);
int (*sem_alloc_security) (struct sem_array *sma);
void (*sem_free_security) (struct sem_array *sma);
int (*sem_associate) (struct sem_array *sma, int semflg);
int (*sem_semctl) (struct sem_array *sma, int cmd);
int (*sem_semop) (struct sem_array *sma,
struct sembuf *sops, unsigned nsops, int alter);
int (*netlink_send) (struct sock *sk, struct sk_buff *skb);
void (*d_instantiate) (struct dentry *dentry, struct inode *inode);
int (*getprocattr) (struct task_struct *p, char *name, char **value);
int (*setprocattr) (struct task_struct *p, char *name, void *value, size_t size);
int (*ismaclabel) (const char *name);
int (*secid_to_secctx) (u32 secid, char **secdata, u32 *seclen);
int (*secctx_to_secid) (const char *secdata, u32 seclen, u32 *secid);
void (*release_secctx) (char *secdata, u32 seclen);
int (*inode_notifysecctx)(struct inode *inode, void *ctx, u32 ctxlen);
int (*inode_setsecctx)(struct dentry *dentry, void *ctx, u32 ctxlen);
int (*inode_getsecctx)(struct inode *inode, void **ctx, u32 *ctxlen);
#ifdef CONFIG_SECURITY_NETWORK
int (*unix_stream_connect) (struct sock *sock, struct sock *other, struct sock *newsk);
int (*unix_may_send) (struct socket *sock, struct socket *other);
int (*socket_create) (int family, int type, int protocol, int kern);
int (*socket_post_create) (struct socket *sock, int family,
int type, int protocol, int kern);
int (*socket_bind) (struct socket *sock,
struct sockaddr *address, int addrlen);
int (*socket_connect) (struct socket *sock,
struct sockaddr *address, int addrlen);
int (*socket_listen) (struct socket *sock, int backlog);
int (*socket_accept) (struct socket *sock, struct socket *newsock);
int (*socket_sendmsg) (struct socket *sock,
struct msghdr *msg, int size);
int (*socket_recvmsg) (struct socket *sock,
struct msghdr *msg, int size, int flags);
int (*socket_getsockname) (struct socket *sock);
int (*socket_getpeername) (struct socket *sock);
int (*socket_getsockopt) (struct socket *sock, int level, int optname);
int (*socket_setsockopt) (struct socket *sock, int level, int optname);
int (*socket_shutdown) (struct socket *sock, int how);
int (*socket_sock_rcv_skb) (struct sock *sk, struct sk_buff *skb);
int (*socket_getpeersec_stream) (struct socket *sock, char __user *optval, int __user *optlen, unsigned len);
int (*socket_getpeersec_dgram) (struct socket *sock, struct sk_buff *skb, u32 *secid);
int (*sk_alloc_security) (struct sock *sk, int family, gfp_t priority);
void (*sk_free_security) (struct sock *sk);
void (*sk_clone_security) (const struct sock *sk, struct sock *newsk);
void (*sk_getsecid) (struct sock *sk, u32 *secid);
void (*sock_graft) (struct sock *sk, struct socket *parent);
int (*inet_conn_request) (struct sock *sk, struct sk_buff *skb,
struct request_sock *req);
void (*inet_csk_clone) (struct sock *newsk, const struct request_sock *req);
void (*inet_conn_established) (struct sock *sk, struct sk_buff *skb);
int (*secmark_relabel_packet) (u32 secid);
void (*secmark_refcount_inc) (void);
void (*secmark_refcount_dec) (void);
void (*req_classify_flow) (const struct request_sock *req, struct flowi *fl);
int (*tun_dev_alloc_security) (void **security);
void (*tun_dev_free_security) (void *security);
int (*tun_dev_create) (void);
int (*tun_dev_attach_queue) (void *security);
int (*tun_dev_attach) (struct sock *sk, void *security);
int (*tun_dev_open) (void *security);
void (*skb_owned_by) (struct sk_buff *skb, struct sock *sk);
#endif /* CONFIG_SECURITY_NETWORK */
#ifdef CONFIG_SECURITY_NETWORK_XFRM
int (*xfrm_policy_alloc_security) (struct xfrm_sec_ctx **ctxp,
struct xfrm_user_sec_ctx *sec_ctx);
int (*xfrm_policy_clone_security) (struct xfrm_sec_ctx *old_ctx, struct xfrm_sec_ctx **new_ctx);
void (*xfrm_policy_free_security) (struct xfrm_sec_ctx *ctx);
int (*xfrm_policy_delete_security) (struct xfrm_sec_ctx *ctx);
int (*xfrm_state_alloc_security) (struct xfrm_state *x,
struct xfrm_user_sec_ctx *sec_ctx,
u32 secid);
void (*xfrm_state_free_security) (struct xfrm_state *x);
int (*xfrm_state_delete_security) (struct xfrm_state *x);
int (*xfrm_policy_lookup) (struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir);
int (*xfrm_state_pol_flow_match) (struct xfrm_state *x,
struct xfrm_policy *xp,
const struct flowi *fl);
int (*xfrm_decode_session) (struct sk_buff *skb, u32 *secid, int ckall);
#endif /* CONFIG_SECURITY_NETWORK_XFRM */
/* key management security hooks */
#ifdef CONFIG_KEYS
int (*key_alloc) (struct key *key, const struct cred *cred, unsigned long flags);
void (*key_free) (struct key *key);
int (*key_permission) (key_ref_t key_ref,
const struct cred *cred,
key_perm_t perm);
int (*key_getsecurity)(struct key *key, char **_buffer);
#endif /* CONFIG_KEYS */
#ifdef CONFIG_AUDIT
int (*audit_rule_init) (u32 field, u32 op, char *rulestr, void **lsmrule);
int (*audit_rule_known) (struct audit_krule *krule);
int (*audit_rule_match) (u32 secid, u32 field, u32 op, void *lsmrule,
struct audit_context *actx);
void (*audit_rule_free) (void *lsmrule);
#endif /* CONFIG_AUDIT */
};
/* prototypes */
extern int security_init(void);
extern int security_module_enable(struct security_operations *ops);
extern int register_security(struct security_operations *ops);
extern void __init security_fixup_ops(struct security_operations *ops);
/* Security operations */
int security_binder_set_context_mgr(struct task_struct *mgr);
int security_binder_transaction(struct task_struct *from, struct task_struct *to);
int security_binder_transfer_binder(struct task_struct *from, struct task_struct *to);
int security_binder_transfer_file(struct task_struct *from, struct task_struct *to, struct file *file);
int security_ptrace_access_check(struct task_struct *child, unsigned int mode);
int security_ptrace_traceme(struct task_struct *parent);
int security_capget(struct task_struct *target,
kernel_cap_t *effective,
kernel_cap_t *inheritable,
kernel_cap_t *permitted);
int security_capset(struct cred *new, const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted);
int security_capable(const struct cred *cred, struct user_namespace *ns,
int cap);
int security_capable_noaudit(const struct cred *cred, struct user_namespace *ns,
int cap);
int security_quotactl(int cmds, int type, int id, struct super_block *sb);
int security_quota_on(struct dentry *dentry);
int security_syslog(int type);
int security_settime(const struct timespec *ts, const struct timezone *tz);
int security_vm_enough_memory_mm(struct mm_struct *mm, long pages);
int security_bprm_set_creds(struct linux_binprm *bprm);
int security_bprm_check(struct linux_binprm *bprm);
void security_bprm_committing_creds(struct linux_binprm *bprm);
void security_bprm_committed_creds(struct linux_binprm *bprm);
int security_bprm_secureexec(struct linux_binprm *bprm);
int security_sb_alloc(struct super_block *sb);
void security_sb_free(struct super_block *sb);
int security_sb_copy_data(char *orig, char *copy);
int security_sb_remount(struct super_block *sb, void *data);
int security_sb_kern_mount(struct super_block *sb, int flags, void *data);
int security_sb_show_options(struct seq_file *m, struct super_block *sb);
int security_sb_statfs(struct dentry *dentry);
int security_sb_mount(const char *dev_name, struct path *path,
const char *type, unsigned long flags, void *data);
int security_sb_umount(struct vfsmount *mnt, int flags);
int security_sb_pivotroot(struct path *old_path, struct path *new_path);
int security_sb_set_mnt_opts(struct super_block *sb,
struct security_mnt_opts *opts,
unsigned long kern_flags,
unsigned long *set_kern_flags);
int security_sb_clone_mnt_opts(const struct super_block *oldsb,
struct super_block *newsb);
int security_sb_parse_opts_str(char *options, struct security_mnt_opts *opts);
int security_dentry_init_security(struct dentry *dentry, int mode,
struct qstr *name, void **ctx,
u32 *ctxlen);
int security_inode_alloc(struct inode *inode);
void security_inode_free(struct inode *inode);
int security_inode_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr,
initxattrs initxattrs, void *fs_data);
int security_old_inode_init_security(struct inode *inode, struct inode *dir,
const struct qstr *qstr, char **name,
void **value, size_t *len);
int security_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode);
int security_inode_post_create(struct inode *dir, struct dentry *dentry,
umode_t mode);
int security_inode_link(struct dentry *old_dentry, struct inode *dir,
struct dentry *new_dentry);
int security_inode_unlink(struct inode *dir, struct dentry *dentry);
int security_inode_symlink(struct inode *dir, struct dentry *dentry,
const char *old_name);
int security_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
int security_inode_rmdir(struct inode *dir, struct dentry *dentry);
int security_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev);
int security_inode_rename(struct inode *old_dir, struct dentry *old_dentry,
struct inode *new_dir, struct dentry *new_dentry);
int security_inode_readlink(struct dentry *dentry);
int security_inode_follow_link(struct dentry *dentry, struct nameidata *nd);
int security_inode_permission(struct inode *inode, int mask);
int security_inode_setattr(struct dentry *dentry, struct iattr *attr);
int security_inode_getattr(struct vfsmount *mnt, struct dentry *dentry);
int security_inode_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags);
void security_inode_post_setxattr(struct dentry *dentry, const char *name,
const void *value, size_t size, int flags);
int security_inode_getxattr(struct dentry *dentry, const char *name);
int security_inode_listxattr(struct dentry *dentry);
int security_inode_removexattr(struct dentry *dentry, const char *name);
int security_inode_need_killpriv(struct dentry *dentry);
int security_inode_killpriv(struct dentry *dentry);
int security_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc);
int security_inode_setsecurity(struct inode *inode, const char *name, const void *value, size_t size, int flags);
int security_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size);
void security_inode_getsecid(const struct inode *inode, u32 *secid);
int security_file_permission(struct file *file, int mask);
int security_file_alloc(struct file *file);
void security_file_free(struct file *file);
int security_file_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
int security_mmap_file(struct file *file, unsigned long prot,
unsigned long flags);
int security_mmap_addr(unsigned long addr);
int security_file_mprotect(struct vm_area_struct *vma, unsigned long reqprot,
unsigned long prot);
int security_file_lock(struct file *file, unsigned int cmd);
int security_file_fcntl(struct file *file, unsigned int cmd, unsigned long arg);
int security_file_set_fowner(struct file *file);
int security_file_send_sigiotask(struct task_struct *tsk,
struct fown_struct *fown, int sig);
int security_file_receive(struct file *file);
int security_file_open(struct file *file, const struct cred *cred);
int security_file_close(struct file *file);
bool security_allow_merge_bio(struct bio *bio1, struct bio *bio2);
int security_task_create(unsigned long clone_flags);
void security_task_free(struct task_struct *task);
int security_cred_alloc_blank(struct cred *cred, gfp_t gfp);
void security_cred_free(struct cred *cred);
int security_prepare_creds(struct cred *new, const struct cred *old, gfp_t gfp);
void security_transfer_creds(struct cred *new, const struct cred *old);
int security_kernel_act_as(struct cred *new, u32 secid);
int security_kernel_create_files_as(struct cred *new, struct inode *inode);
int security_kernel_module_request(char *kmod_name);
int security_kernel_module_from_file(struct file *file);
int security_task_fix_setuid(struct cred *new, const struct cred *old,
int flags);
int security_task_setpgid(struct task_struct *p, pid_t pgid);
int security_task_getpgid(struct task_struct *p);
int security_task_getsid(struct task_struct *p);
void security_task_getsecid(struct task_struct *p, u32 *secid);
int security_task_setnice(struct task_struct *p, int nice);
int security_task_setioprio(struct task_struct *p, int ioprio);
int security_task_getioprio(struct task_struct *p);
int security_task_setrlimit(struct task_struct *p, unsigned int resource,
struct rlimit *new_rlim);
int security_task_setscheduler(struct task_struct *p);
int security_task_getscheduler(struct task_struct *p);
int security_task_movememory(struct task_struct *p);
int security_task_kill(struct task_struct *p, struct siginfo *info,
int sig, u32 secid);
int security_task_wait(struct task_struct *p);
int security_task_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
void security_task_to_inode(struct task_struct *p, struct inode *inode);
int security_ipc_permission(struct kern_ipc_perm *ipcp, short flag);
void security_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid);
int security_msg_msg_alloc(struct msg_msg *msg);
void security_msg_msg_free(struct msg_msg *msg);
int security_msg_queue_alloc(struct msg_queue *msq);
void security_msg_queue_free(struct msg_queue *msq);
int security_msg_queue_associate(struct msg_queue *msq, int msqflg);
int security_msg_queue_msgctl(struct msg_queue *msq, int cmd);
int security_msg_queue_msgsnd(struct msg_queue *msq,
struct msg_msg *msg, int msqflg);
int security_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
struct task_struct *target, long type, int mode);
int security_shm_alloc(struct shmid_kernel *shp);
void security_shm_free(struct shmid_kernel *shp);
int security_shm_associate(struct shmid_kernel *shp, int shmflg);
int security_shm_shmctl(struct shmid_kernel *shp, int cmd);
int security_shm_shmat(struct shmid_kernel *shp, char __user *shmaddr, int shmflg);
int security_sem_alloc(struct sem_array *sma);
void security_sem_free(struct sem_array *sma);
int security_sem_associate(struct sem_array *sma, int semflg);
int security_sem_semctl(struct sem_array *sma, int cmd);
int security_sem_semop(struct sem_array *sma, struct sembuf *sops,
unsigned nsops, int alter);
void security_d_instantiate(struct dentry *dentry, struct inode *inode);
int security_getprocattr(struct task_struct *p, char *name, char **value);
int security_setprocattr(struct task_struct *p, char *name, void *value, size_t size);
int security_netlink_send(struct sock *sk, struct sk_buff *skb);
int security_ismaclabel(const char *name);
int security_secid_to_secctx(u32 secid, char **secdata, u32 *seclen);
int security_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid);
void security_release_secctx(char *secdata, u32 seclen);
int security_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen);
int security_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen);
int security_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen);
#else /* CONFIG_SECURITY */
struct security_mnt_opts {
};
static inline void security_init_mnt_opts(struct security_mnt_opts *opts)
{
}
static inline void security_free_mnt_opts(struct security_mnt_opts *opts)
{
}
/*
* This is the default capabilities functionality. Most of these functions
* are just stubbed out, but a few must call the proper capable code.
*/
static inline int security_init(void)
{
return 0;
}
static inline int security_binder_set_context_mgr(struct task_struct *mgr)
{
return 0;
}
static inline int security_binder_transaction(struct task_struct *from, struct task_struct *to)
{
return 0;
}
static inline int security_binder_transfer_binder(struct task_struct *from, struct task_struct *to)
{
return 0;
}
static inline int security_binder_transfer_file(struct task_struct *from, struct task_struct *to, struct file *file)
{
return 0;
}
static inline int security_ptrace_access_check(struct task_struct *child,
unsigned int mode)
{
return cap_ptrace_access_check(child, mode);
}
static inline int security_ptrace_traceme(struct task_struct *parent)
{
return cap_ptrace_traceme(parent);
}
static inline int security_capget(struct task_struct *target,
kernel_cap_t *effective,
kernel_cap_t *inheritable,
kernel_cap_t *permitted)
{
return cap_capget(target, effective, inheritable, permitted);
}
static inline int security_capset(struct cred *new,
const struct cred *old,
const kernel_cap_t *effective,
const kernel_cap_t *inheritable,
const kernel_cap_t *permitted)
{
return cap_capset(new, old, effective, inheritable, permitted);
}
static inline int security_capable(const struct cred *cred,
struct user_namespace *ns, int cap)
{
return cap_capable(cred, ns, cap, SECURITY_CAP_AUDIT);
}
static inline int security_capable_noaudit(const struct cred *cred,
struct user_namespace *ns, int cap) {
return cap_capable(cred, ns, cap, SECURITY_CAP_NOAUDIT);
}
static inline int security_quotactl(int cmds, int type, int id,
struct super_block *sb)
{
return 0;
}
static inline int security_quota_on(struct dentry *dentry)
{
return 0;
}
static inline int security_syslog(int type)
{
return 0;
}
static inline int security_settime(const struct timespec *ts,
const struct timezone *tz)
{
return cap_settime(ts, tz);
}
static inline int security_vm_enough_memory_mm(struct mm_struct *mm, long pages)
{
return cap_vm_enough_memory(mm, pages);
}
static inline int security_bprm_set_creds(struct linux_binprm *bprm)
{
return cap_bprm_set_creds(bprm);
}
static inline int security_bprm_check(struct linux_binprm *bprm)
{
return 0;
}
static inline void security_bprm_committing_creds(struct linux_binprm *bprm)
{
}
static inline void security_bprm_committed_creds(struct linux_binprm *bprm)
{
}
static inline int security_bprm_secureexec(struct linux_binprm *bprm)
{
return cap_bprm_secureexec(bprm);
}
static inline int security_sb_alloc(struct super_block *sb)
{
return 0;
}
static inline void security_sb_free(struct super_block *sb)
{ }
static inline int security_sb_copy_data(char *orig, char *copy)
{
return 0;
}
static inline int security_sb_remount(struct super_block *sb, void *data)
{
return 0;
}
static inline int security_sb_kern_mount(struct super_block *sb, int flags, void *data)
{
return 0;
}
static inline int security_sb_show_options(struct seq_file *m,
struct super_block *sb)
{
return 0;
}
static inline int security_sb_statfs(struct dentry *dentry)
{
return 0;
}
static inline int security_sb_mount(const char *dev_name, struct path *path,
const char *type, unsigned long flags,
void *data)
{
return 0;
}
static inline int security_sb_umount(struct vfsmount *mnt, int flags)
{
return 0;
}
static inline int security_sb_pivotroot(struct path *old_path,
struct path *new_path)
{
return 0;
}
static inline int security_sb_set_mnt_opts(struct super_block *sb,
struct security_mnt_opts *opts,
unsigned long kern_flags,
unsigned long *set_kern_flags)
{
return 0;
}
static inline int security_sb_clone_mnt_opts(const struct super_block *oldsb,
struct super_block *newsb)
{
return 0;
}
static inline int security_sb_parse_opts_str(char *options, struct security_mnt_opts *opts)
{
return 0;
}
static inline int security_inode_alloc(struct inode *inode)
{
return 0;
}
static inline void security_inode_free(struct inode *inode)
{ }
static inline int security_dentry_init_security(struct dentry *dentry,
int mode,
struct qstr *name,
void **ctx,
u32 *ctxlen)
{
return -EOPNOTSUPP;
}
static inline int security_inode_init_security(struct inode *inode,
struct inode *dir,
const struct qstr *qstr,
const initxattrs initxattrs,
void *fs_data)
{
return 0;
}
static inline int security_old_inode_init_security(struct inode *inode,
struct inode *dir,
const struct qstr *qstr,
char **name, void **value,
size_t *len)
{
return -EOPNOTSUPP;
}
static inline int security_inode_create(struct inode *dir,
struct dentry *dentry,
umode_t mode)
{
return 0;
}
static inline int security_inode_post_create(struct inode *dir,
struct dentry *dentry,
umode_t mode)
{
return 0;
}
static inline int security_inode_link(struct dentry *old_dentry,
struct inode *dir,
struct dentry *new_dentry)
{
return 0;
}
static inline int security_inode_unlink(struct inode *dir,
struct dentry *dentry)
{
return 0;
}
static inline int security_inode_symlink(struct inode *dir,
struct dentry *dentry,
const char *old_name)
{
return 0;
}
static inline int security_inode_mkdir(struct inode *dir,
struct dentry *dentry,
int mode)
{
return 0;
}
static inline int security_inode_rmdir(struct inode *dir,
struct dentry *dentry)
{
return 0;
}
static inline int security_inode_mknod(struct inode *dir,
struct dentry *dentry,
int mode, dev_t dev)
{
return 0;
}
static inline int security_inode_rename(struct inode *old_dir,
struct dentry *old_dentry,
struct inode *new_dir,
struct dentry *new_dentry)
{
return 0;
}
static inline int security_inode_readlink(struct dentry *dentry)
{
return 0;
}
static inline int security_inode_follow_link(struct dentry *dentry,
struct nameidata *nd)
{
return 0;
}
static inline int security_inode_permission(struct inode *inode, int mask)
{
return 0;
}
static inline int security_inode_setattr(struct dentry *dentry,
struct iattr *attr)
{
return 0;
}
static inline int security_inode_getattr(struct vfsmount *mnt,
struct dentry *dentry)
{
return 0;
}
static inline int security_inode_setxattr(struct dentry *dentry,
const char *name, const void *value, size_t size, int flags)
{
return cap_inode_setxattr(dentry, name, value, size, flags);
}
static inline void security_inode_post_setxattr(struct dentry *dentry,
const char *name, const void *value, size_t size, int flags)
{ }
static inline int security_inode_getxattr(struct dentry *dentry,
const char *name)
{
return 0;
}
static inline int security_inode_listxattr(struct dentry *dentry)
{
return 0;
}
static inline int security_inode_removexattr(struct dentry *dentry,
const char *name)
{
return cap_inode_removexattr(dentry, name);
}
static inline int security_inode_need_killpriv(struct dentry *dentry)
{
return cap_inode_need_killpriv(dentry);
}
static inline int security_inode_killpriv(struct dentry *dentry)
{
return cap_inode_killpriv(dentry);
}
static inline int security_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc)
{
return -EOPNOTSUPP;
}
static inline int security_inode_setsecurity(struct inode *inode, const char *name, const void *value, size_t size, int flags)
{
return -EOPNOTSUPP;
}
static inline int security_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
{
return 0;
}
static inline void security_inode_getsecid(const struct inode *inode, u32 *secid)
{
*secid = 0;
}
static inline int security_file_permission(struct file *file, int mask)
{
return 0;
}
static inline int security_file_alloc(struct file *file)
{
return 0;
}
static inline void security_file_free(struct file *file)
{ }
static inline int security_file_ioctl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return 0;
}
static inline int security_mmap_file(struct file *file, unsigned long prot,
unsigned long flags)
{
return 0;
}
static inline int security_mmap_addr(unsigned long addr)
{
return cap_mmap_addr(addr);
}
static inline int security_file_mprotect(struct vm_area_struct *vma,
unsigned long reqprot,
unsigned long prot)
{
return 0;
}
static inline int security_file_lock(struct file *file, unsigned int cmd)
{
return 0;
}
static inline int security_file_fcntl(struct file *file, unsigned int cmd,
unsigned long arg)
{
return 0;
}
static inline int security_file_set_fowner(struct file *file)
{
return 0;
}
static inline int security_file_send_sigiotask(struct task_struct *tsk,
struct fown_struct *fown,
int sig)
{
return 0;
}
static inline int security_file_receive(struct file *file)
{
return 0;
}
static inline int security_file_open(struct file *file,
const struct cred *cred)
{
return 0;
}
static inline int security_file_close(struct file *file)
{
return 0;
}
static inline bool security_allow_merge_bio(struct bio *bio1, struct bio *bio2)
{
return true;
}
static inline int security_task_create(unsigned long clone_flags)
{
return 0;
}
static inline void security_task_free(struct task_struct *task)
{ }
static inline int security_cred_alloc_blank(struct cred *cred, gfp_t gfp)
{
return 0;
}
static inline void security_cred_free(struct cred *cred)
{ }
static inline int security_prepare_creds(struct cred *new,
const struct cred *old,
gfp_t gfp)
{
return 0;
}
static inline void security_transfer_creds(struct cred *new,
const struct cred *old)
{
}
static inline int security_kernel_act_as(struct cred *cred, u32 secid)
{
return 0;
}
static inline int security_kernel_create_files_as(struct cred *cred,
struct inode *inode)
{
return 0;
}
static inline int security_kernel_module_request(char *kmod_name)
{
return 0;
}
static inline int security_kernel_module_from_file(struct file *file)
{
return 0;
}
static inline int security_task_fix_setuid(struct cred *new,
const struct cred *old,
int flags)
{
return cap_task_fix_setuid(new, old, flags);
}
static inline int security_task_setpgid(struct task_struct *p, pid_t pgid)
{
return 0;
}
static inline int security_task_getpgid(struct task_struct *p)
{
return 0;
}
static inline int security_task_getsid(struct task_struct *p)
{
return 0;
}
static inline void security_task_getsecid(struct task_struct *p, u32 *secid)
{
*secid = 0;
}
static inline int security_task_setnice(struct task_struct *p, int nice)
{
return cap_task_setnice(p, nice);
}
static inline int security_task_setioprio(struct task_struct *p, int ioprio)
{
return cap_task_setioprio(p, ioprio);
}
static inline int security_task_getioprio(struct task_struct *p)
{
return 0;
}
static inline int security_task_setrlimit(struct task_struct *p,
unsigned int resource,
struct rlimit *new_rlim)
{
return 0;
}
static inline int security_task_setscheduler(struct task_struct *p)
{
return cap_task_setscheduler(p);
}
static inline int security_task_getscheduler(struct task_struct *p)
{
return 0;
}
static inline int security_task_movememory(struct task_struct *p)
{
return 0;
}
static inline int security_task_kill(struct task_struct *p,
struct siginfo *info, int sig,
u32 secid)
{
return 0;
}
static inline int security_task_wait(struct task_struct *p)
{
return 0;
}
static inline int security_task_prctl(int option, unsigned long arg2,
unsigned long arg3,
unsigned long arg4,
unsigned long arg5)
{
return cap_task_prctl(option, arg2, arg3, arg4, arg5);
}
static inline void security_task_to_inode(struct task_struct *p, struct inode *inode)
{ }
static inline int security_ipc_permission(struct kern_ipc_perm *ipcp,
short flag)
{
return 0;
}
static inline void security_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
{
*secid = 0;
}
static inline int security_msg_msg_alloc(struct msg_msg *msg)
{
return 0;
}
static inline void security_msg_msg_free(struct msg_msg *msg)
{ }
static inline int security_msg_queue_alloc(struct msg_queue *msq)
{
return 0;
}
static inline void security_msg_queue_free(struct msg_queue *msq)
{ }
static inline int security_msg_queue_associate(struct msg_queue *msq,
int msqflg)
{
return 0;
}
static inline int security_msg_queue_msgctl(struct msg_queue *msq, int cmd)
{
return 0;
}
static inline int security_msg_queue_msgsnd(struct msg_queue *msq,
struct msg_msg *msg, int msqflg)
{
return 0;
}
static inline int security_msg_queue_msgrcv(struct msg_queue *msq,
struct msg_msg *msg,
struct task_struct *target,
long type, int mode)
{
return 0;
}
static inline int security_shm_alloc(struct shmid_kernel *shp)
{
return 0;
}
static inline void security_shm_free(struct shmid_kernel *shp)
{ }
static inline int security_shm_associate(struct shmid_kernel *shp,
int shmflg)
{
return 0;
}
static inline int security_shm_shmctl(struct shmid_kernel *shp, int cmd)
{
return 0;
}
static inline int security_shm_shmat(struct shmid_kernel *shp,
char __user *shmaddr, int shmflg)
{
return 0;
}
static inline int security_sem_alloc(struct sem_array *sma)
{
return 0;
}
static inline void security_sem_free(struct sem_array *sma)
{ }
static inline int security_sem_associate(struct sem_array *sma, int semflg)
{
return 0;
}
static inline int security_sem_semctl(struct sem_array *sma, int cmd)
{
return 0;
}
static inline int security_sem_semop(struct sem_array *sma,
struct sembuf *sops, unsigned nsops,
int alter)
{
return 0;
}
static inline void security_d_instantiate(struct dentry *dentry, struct inode *inode)
{ }
static inline int security_getprocattr(struct task_struct *p, char *name, char **value)
{
return -EINVAL;
}
static inline int security_setprocattr(struct task_struct *p, char *name, void *value, size_t size)
{
return -EINVAL;
}
static inline int security_netlink_send(struct sock *sk, struct sk_buff *skb)
{
return cap_netlink_send(sk, skb);
}
static inline int security_ismaclabel(const char *name)
{
return 0;
}
static inline int security_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
{
return -EOPNOTSUPP;
}
static inline int security_secctx_to_secid(const char *secdata,
u32 seclen,
u32 *secid)
{
return -EOPNOTSUPP;
}
static inline void security_release_secctx(char *secdata, u32 seclen)
{
}
static inline int security_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
{
return -EOPNOTSUPP;
}
static inline int security_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
{
return -EOPNOTSUPP;
}
static inline int security_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
{
return -EOPNOTSUPP;
}
#endif /* CONFIG_SECURITY */
#ifdef CONFIG_SECURITY_NETWORK
int security_unix_stream_connect(struct sock *sock, struct sock *other, struct sock *newsk);
int security_unix_may_send(struct socket *sock, struct socket *other);
int security_socket_create(int family, int type, int protocol, int kern);
int security_socket_post_create(struct socket *sock, int family,
int type, int protocol, int kern);
int security_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen);
int security_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen);
int security_socket_listen(struct socket *sock, int backlog);
int security_socket_accept(struct socket *sock, struct socket *newsock);
int security_socket_sendmsg(struct socket *sock, struct msghdr *msg, int size);
int security_socket_recvmsg(struct socket *sock, struct msghdr *msg,
int size, int flags);
int security_socket_getsockname(struct socket *sock);
int security_socket_getpeername(struct socket *sock);
int security_socket_getsockopt(struct socket *sock, int level, int optname);
int security_socket_setsockopt(struct socket *sock, int level, int optname);
int security_socket_shutdown(struct socket *sock, int how);
int security_sock_rcv_skb(struct sock *sk, struct sk_buff *skb);
int security_socket_getpeersec_stream(struct socket *sock, char __user *optval,
int __user *optlen, unsigned len);
int security_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid);
int security_sk_alloc(struct sock *sk, int family, gfp_t priority);
void security_sk_free(struct sock *sk);
void security_sk_clone(const struct sock *sk, struct sock *newsk);
void security_sk_classify_flow(struct sock *sk, struct flowi *fl);
void security_req_classify_flow(const struct request_sock *req, struct flowi *fl);
void security_sock_graft(struct sock*sk, struct socket *parent);
int security_inet_conn_request(struct sock *sk,
struct sk_buff *skb, struct request_sock *req);
void security_inet_csk_clone(struct sock *newsk,
const struct request_sock *req);
void security_inet_conn_established(struct sock *sk,
struct sk_buff *skb);
int security_secmark_relabel_packet(u32 secid);
void security_secmark_refcount_inc(void);
void security_secmark_refcount_dec(void);
int security_tun_dev_alloc_security(void **security);
void security_tun_dev_free_security(void *security);
int security_tun_dev_create(void);
int security_tun_dev_attach_queue(void *security);
int security_tun_dev_attach(struct sock *sk, void *security);
int security_tun_dev_open(void *security);
void security_skb_owned_by(struct sk_buff *skb, struct sock *sk);
#else /* CONFIG_SECURITY_NETWORK */
static inline int security_unix_stream_connect(struct sock *sock,
struct sock *other,
struct sock *newsk)
{
return 0;
}
static inline int security_unix_may_send(struct socket *sock,
struct socket *other)
{
return 0;
}
static inline int security_socket_create(int family, int type,
int protocol, int kern)
{
return 0;
}
static inline int security_socket_post_create(struct socket *sock,
int family,
int type,
int protocol, int kern)
{
return 0;
}
static inline int security_socket_bind(struct socket *sock,
struct sockaddr *address,
int addrlen)
{
return 0;
}
static inline int security_socket_connect(struct socket *sock,
struct sockaddr *address,
int addrlen)
{
return 0;
}
static inline int security_socket_listen(struct socket *sock, int backlog)
{
return 0;
}
static inline int security_socket_accept(struct socket *sock,
struct socket *newsock)
{
return 0;
}
static inline int security_socket_sendmsg(struct socket *sock,
struct msghdr *msg, int size)
{
return 0;
}
static inline int security_socket_recvmsg(struct socket *sock,
struct msghdr *msg, int size,
int flags)
{
return 0;
}
static inline int security_socket_getsockname(struct socket *sock)
{
return 0;
}
static inline int security_socket_getpeername(struct socket *sock)
{
return 0;
}
static inline int security_socket_getsockopt(struct socket *sock,
int level, int optname)
{
return 0;
}
static inline int security_socket_setsockopt(struct socket *sock,
int level, int optname)
{
return 0;
}
static inline int security_socket_shutdown(struct socket *sock, int how)
{
return 0;
}
static inline int security_sock_rcv_skb(struct sock *sk,
struct sk_buff *skb)
{
return 0;
}
static inline int security_socket_getpeersec_stream(struct socket *sock, char __user *optval,
int __user *optlen, unsigned len)
{
return -ENOPROTOOPT;
}
static inline int security_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
{
return -ENOPROTOOPT;
}
static inline int security_sk_alloc(struct sock *sk, int family, gfp_t priority)
{
return 0;
}
static inline void security_sk_free(struct sock *sk)
{
}
static inline void security_sk_clone(const struct sock *sk, struct sock *newsk)
{
}
static inline void security_sk_classify_flow(struct sock *sk, struct flowi *fl)
{
}
static inline void security_req_classify_flow(const struct request_sock *req, struct flowi *fl)
{
}
static inline void security_sock_graft(struct sock *sk, struct socket *parent)
{
}
static inline int security_inet_conn_request(struct sock *sk,
struct sk_buff *skb, struct request_sock *req)
{
return 0;
}
static inline void security_inet_csk_clone(struct sock *newsk,
const struct request_sock *req)
{
}
static inline void security_inet_conn_established(struct sock *sk,
struct sk_buff *skb)
{
}
static inline int security_secmark_relabel_packet(u32 secid)
{
return 0;
}
static inline void security_secmark_refcount_inc(void)
{
}
static inline void security_secmark_refcount_dec(void)
{
}
static inline int security_tun_dev_alloc_security(void **security)
{
return 0;
}
static inline void security_tun_dev_free_security(void *security)
{
}
static inline int security_tun_dev_create(void)
{
return 0;
}
static inline int security_tun_dev_attach_queue(void *security)
{
return 0;
}
static inline int security_tun_dev_attach(struct sock *sk, void *security)
{
return 0;
}
static inline int security_tun_dev_open(void *security)
{
return 0;
}
static inline void security_skb_owned_by(struct sk_buff *skb, struct sock *sk)
{
}
#endif /* CONFIG_SECURITY_NETWORK */
#ifdef CONFIG_SECURITY_NETWORK_XFRM
int security_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp, struct xfrm_user_sec_ctx *sec_ctx);
int security_xfrm_policy_clone(struct xfrm_sec_ctx *old_ctx, struct xfrm_sec_ctx **new_ctxp);
void security_xfrm_policy_free(struct xfrm_sec_ctx *ctx);
int security_xfrm_policy_delete(struct xfrm_sec_ctx *ctx);
int security_xfrm_state_alloc(struct xfrm_state *x, struct xfrm_user_sec_ctx *sec_ctx);
int security_xfrm_state_alloc_acquire(struct xfrm_state *x,
struct xfrm_sec_ctx *polsec, u32 secid);
int security_xfrm_state_delete(struct xfrm_state *x);
void security_xfrm_state_free(struct xfrm_state *x);
int security_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir);
int security_xfrm_state_pol_flow_match(struct xfrm_state *x,
struct xfrm_policy *xp,
const struct flowi *fl);
int security_xfrm_decode_session(struct sk_buff *skb, u32 *secid);
void security_skb_classify_flow(struct sk_buff *skb, struct flowi *fl);
#else /* CONFIG_SECURITY_NETWORK_XFRM */
static inline int security_xfrm_policy_alloc(struct xfrm_sec_ctx **ctxp, struct xfrm_user_sec_ctx *sec_ctx)
{
return 0;
}
static inline int security_xfrm_policy_clone(struct xfrm_sec_ctx *old, struct xfrm_sec_ctx **new_ctxp)
{
return 0;
}
static inline void security_xfrm_policy_free(struct xfrm_sec_ctx *ctx)
{
}
static inline int security_xfrm_policy_delete(struct xfrm_sec_ctx *ctx)
{
return 0;
}
static inline int security_xfrm_state_alloc(struct xfrm_state *x,
struct xfrm_user_sec_ctx *sec_ctx)
{
return 0;
}
static inline int security_xfrm_state_alloc_acquire(struct xfrm_state *x,
struct xfrm_sec_ctx *polsec, u32 secid)
{
return 0;
}
static inline void security_xfrm_state_free(struct xfrm_state *x)
{
}
static inline int security_xfrm_state_delete(struct xfrm_state *x)
{
return 0;
}
static inline int security_xfrm_policy_lookup(struct xfrm_sec_ctx *ctx, u32 fl_secid, u8 dir)
{
return 0;
}
static inline int security_xfrm_state_pol_flow_match(struct xfrm_state *x,
struct xfrm_policy *xp, const struct flowi *fl)
{
return 1;
}
static inline int security_xfrm_decode_session(struct sk_buff *skb, u32 *secid)
{
return 0;
}
static inline void security_skb_classify_flow(struct sk_buff *skb, struct flowi *fl)
{
}
#endif /* CONFIG_SECURITY_NETWORK_XFRM */
#ifdef CONFIG_SECURITY_PATH
int security_path_unlink(struct path *dir, struct dentry *dentry);
int security_path_mkdir(struct path *dir, struct dentry *dentry, umode_t mode);
int security_path_rmdir(struct path *dir, struct dentry *dentry);
int security_path_mknod(struct path *dir, struct dentry *dentry, umode_t mode,
unsigned int dev);
int security_path_truncate(struct path *path);
int security_path_symlink(struct path *dir, struct dentry *dentry,
const char *old_name);
int security_path_link(struct dentry *old_dentry, struct path *new_dir,
struct dentry *new_dentry);
int security_path_rename(struct path *old_dir, struct dentry *old_dentry,
struct path *new_dir, struct dentry *new_dentry);
int security_path_chmod(struct path *path, umode_t mode);
int security_path_chown(struct path *path, kuid_t uid, kgid_t gid);
int security_path_chroot(struct path *path);
#else /* CONFIG_SECURITY_PATH */
static inline int security_path_unlink(struct path *dir, struct dentry *dentry)
{
return 0;
}
static inline int security_path_mkdir(struct path *dir, struct dentry *dentry,
umode_t mode)
{
return 0;
}
static inline int security_path_rmdir(struct path *dir, struct dentry *dentry)
{
return 0;
}
static inline int security_path_mknod(struct path *dir, struct dentry *dentry,
umode_t mode, unsigned int dev)
{
return 0;
}
static inline int security_path_truncate(struct path *path)
{
return 0;
}
static inline int security_path_symlink(struct path *dir, struct dentry *dentry,
const char *old_name)
{
return 0;
}
static inline int security_path_link(struct dentry *old_dentry,
struct path *new_dir,
struct dentry *new_dentry)
{
return 0;
}
static inline int security_path_rename(struct path *old_dir,
struct dentry *old_dentry,
struct path *new_dir,
struct dentry *new_dentry)
{
return 0;
}
static inline int security_path_chmod(struct path *path, umode_t mode)
{
return 0;
}
static inline int security_path_chown(struct path *path, kuid_t uid, kgid_t gid)
{
return 0;
}
static inline int security_path_chroot(struct path *path)
{
return 0;
}
#endif /* CONFIG_SECURITY_PATH */
#ifdef CONFIG_KEYS
#ifdef CONFIG_SECURITY
int security_key_alloc(struct key *key, const struct cred *cred, unsigned long flags);
void security_key_free(struct key *key);
int security_key_permission(key_ref_t key_ref,
const struct cred *cred, key_perm_t perm);
int security_key_getsecurity(struct key *key, char **_buffer);
#else
static inline int security_key_alloc(struct key *key,
const struct cred *cred,
unsigned long flags)
{
return 0;
}
static inline void security_key_free(struct key *key)
{
}
static inline int security_key_permission(key_ref_t key_ref,
const struct cred *cred,
key_perm_t perm)
{
return 0;
}
static inline int security_key_getsecurity(struct key *key, char **_buffer)
{
*_buffer = NULL;
return 0;
}
#endif
#endif /* CONFIG_KEYS */
#ifdef CONFIG_AUDIT
#ifdef CONFIG_SECURITY
int security_audit_rule_init(u32 field, u32 op, char *rulestr, void **lsmrule);
int security_audit_rule_known(struct audit_krule *krule);
int security_audit_rule_match(u32 secid, u32 field, u32 op, void *lsmrule,
struct audit_context *actx);
void security_audit_rule_free(void *lsmrule);
#else
static inline int security_audit_rule_init(u32 field, u32 op, char *rulestr,
void **lsmrule)
{
return 0;
}
static inline int security_audit_rule_known(struct audit_krule *krule)
{
return 0;
}
static inline int security_audit_rule_match(u32 secid, u32 field, u32 op,
void *lsmrule, struct audit_context *actx)
{
return 0;
}
static inline void security_audit_rule_free(void *lsmrule)
{ }
#endif /* CONFIG_SECURITY */
#endif /* CONFIG_AUDIT */
#ifdef CONFIG_SECURITYFS
extern struct dentry *securityfs_create_file(const char *name, umode_t mode,
struct dentry *parent, void *data,
const struct file_operations *fops);
extern struct dentry *securityfs_create_dir(const char *name, struct dentry *parent);
extern void securityfs_remove(struct dentry *dentry);
#else /* CONFIG_SECURITYFS */
static inline struct dentry *securityfs_create_dir(const char *name,
struct dentry *parent)
{
return ERR_PTR(-ENODEV);
}
static inline struct dentry *securityfs_create_file(const char *name,
umode_t mode,
struct dentry *parent,
void *data,
const struct file_operations *fops)
{
return ERR_PTR(-ENODEV);
}
static inline void securityfs_remove(struct dentry *dentry)
{}
#endif
#ifdef CONFIG_SECURITY
static inline char *alloc_secdata(void)
{
return (char *)get_zeroed_page(GFP_KERNEL);
}
static inline void free_secdata(void *secdata)
{
free_page((unsigned long)secdata);
}
#else
static inline char *alloc_secdata(void)
{
return (char *)1;
}
static inline void free_secdata(void *secdata)
{ }
#endif /* CONFIG_SECURITY */
#ifdef CONFIG_SECURITY_YAMA
extern int yama_ptrace_access_check(struct task_struct *child,
unsigned int mode);
extern int yama_ptrace_traceme(struct task_struct *parent);
extern void yama_task_free(struct task_struct *task);
extern int yama_task_prctl(int option, unsigned long arg2, unsigned long arg3,
unsigned long arg4, unsigned long arg5);
#else
static inline int yama_ptrace_access_check(struct task_struct *child,
unsigned int mode)
{
return 0;
}
static inline int yama_ptrace_traceme(struct task_struct *parent)
{
return 0;
}
static inline void yama_task_free(struct task_struct *task)
{
}
static inline int yama_task_prctl(int option, unsigned long arg2,
unsigned long arg3, unsigned long arg4,
unsigned long arg5)
{
return -ENOSYS;
}
#endif /* CONFIG_SECURITY_YAMA */
#endif /* ! __LINUX_SECURITY_H */
|
javilonas/Lonas_KL-SM-G901F
|
include/linux/security.h
|
C
|
gpl-2.0
| 119,430 |
// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <[email protected]>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#ifndef IGL_HARWELL_BOEING_H
#define IGL_HARWELL_BOEING_H
#include "igl_inline.h"
#define EIGEN_YES_I_KNOW_SPARSE_MODULE_IS_NOT_STABLE_YET
#include <Eigen/Sparse>
#include <vector>
namespace igl
{
// Convert the matrix to Compressed sparse column (CSC or CCS) format,
// also known as Harwell Boeing format. As described:
// http://netlib.org/linalg/html_templates/node92.html
// or
// http://en.wikipedia.org/wiki/Sparse_matrix
// #Compressed_sparse_column_.28CSC_or_CCS.29
// Templates:
// Scalar type of sparse matrix like double
// Inputs:
// A sparse m by n matrix
// Outputs:
// num_rows number of rows
// V non-zero values, row indices running fastest, size(V) = nnz
// R row indices corresponding to vals, size(R) = nnz
// C index in vals of first entry in each column, size(C) = num_cols+1
//
// All indices and pointers are 0-based
template <typename Scalar, typename Index>
IGL_INLINE void harwell_boeing(
const Eigen::SparseMatrix<Scalar> & A,
int & num_rows,
std::vector<Scalar> & V,
std::vector<Index> & R,
std::vector<Index> & C);
}
#ifndef IGL_STATIC_LIBRARY
# include "harwell_boeing.cpp"
#endif
#endif
|
tlgimenes/SparseModelingOfIntrinsicCorrespondences
|
external/igl/harwell_boeing.h
|
C
|
gpl-2.0
| 1,551 |
if not modules then modules = { } end modules ['l-number'] = {
version = 1.001,
comment = "companion to luat-lib.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- this module will be replaced when we have the bit library .. the number based sets
-- might go away
local tostring, tonumber = tostring, tonumber
local format, floor, match, rep = string.format, math.floor, string.match, string.rep
local concat, insert = table.concat, table.insert
local lpegmatch = lpeg.match
local floor = math.floor
number = number or { }
local number = number
-- begin obsolete code --
-- if bit32 then
--
-- local btest, bor = bit32.btest, bit32.bor
--
-- function number.bit(p)
-- return 2 ^ (p - 1) -- 1-based indexing
-- end
--
-- number.hasbit = btest
-- number.setbit = bor
--
-- function number.setbit(x,p) -- why not bor?
-- return btest(x,p) and x or x + p
-- end
--
-- function number.clearbit(x,p)
-- return btest(x,p) and x - p or x
-- end
--
-- else
--
-- -- http://ricilake.blogspot.com/2007/10/iterating-bits-in-lua.html
--
-- function number.bit(p)
-- return 2 ^ (p - 1) -- 1-based indexing
-- end
--
-- function number.hasbit(x, p) -- typical call: if hasbit(x, bit(3)) then ...
-- return x % (p + p) >= p
-- end
--
-- function number.setbit(x, p)
-- return (x % (p + p) >= p) and x or x + p
-- end
--
-- function number.clearbit(x, p)
-- return (x % (p + p) >= p) and x - p or x
-- end
--
-- end
-- end obsolete code --
-- print(number.tobitstring(8))
-- print(number.tobitstring(14))
-- print(number.tobitstring(66))
-- print(number.tobitstring(0x00))
-- print(number.tobitstring(0xFF))
-- print(number.tobitstring(46260767936,4))
if bit32 then
local bextract = bit32.extract
local t = {
"0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0",
"0", "0", "0", "0", "0", "0", "0", "0",
}
function number.tobitstring(b,m,w)
if not w then
w = 32
end
local n = w
for i=0,w-1 do
local v = bextract(b,i)
local k = w - i
if v == 1 then
n = k
t[k] = "1"
else
t[k] = "0"
end
end
if w then
return concat(t,"",1,w)
elseif m then
m = 33 - m * 8
if m < 1 then
m = 1
end
return concat(t,"",1,m)
elseif n < 8 then
return concat(t)
elseif n < 16 then
return concat(t,"",9)
elseif n < 24 then
return concat(t,"",17)
else
return concat(t,"",25)
end
end
else
function number.tobitstring(n,m)
if n > 0 then
local t = { }
while n > 0 do
insert(t,1,n % 2 > 0 and 1 or 0)
n = floor(n/2)
end
local nn = 8 - #t % 8
if nn > 0 and nn < 8 then
for i=1,nn do
insert(t,1,0)
end
end
if m then
m = m * 8 - #t
if m > 0 then
insert(t,1,rep("0",m))
end
end
return concat(t)
elseif m then
rep("00000000",m)
else
return "00000000"
end
end
end
function number.valid(str,default)
return tonumber(str) or default or nil
end
function number.toevenhex(n)
local s = format("%X",n)
if #s % 2 == 0 then
return s
else
return "0" .. s
end
end
-- -- a,b,c,d,e,f = number.toset(100101)
-- --
-- -- function number.toset(n)
-- -- return match(tostring(n),"(.?)(.?)(.?)(.?)(.?)(.?)(.?)(.?)")
-- -- end
-- --
-- -- -- the lpeg way is slower on 8 digits, but faster on 4 digits, some 7.5%
-- -- -- on
-- --
-- -- for i=1,1000000 do
-- -- local a,b,c,d,e,f,g,h = number.toset(12345678)
-- -- local a,b,c,d = number.toset(1234)
-- -- local a,b,c = number.toset(123)
-- -- local a,b,c = number.toset("123")
-- -- end
--
-- local one = lpeg.C(1-lpeg.S('')/tonumber)^1
--
-- function number.toset(n)
-- return lpegmatch(one,tostring(n))
-- end
--
-- -- function number.bits(n,zero)
-- -- local t, i = { }, (zero and 0) or 1
-- -- while n > 0 do
-- -- local m = n % 2
-- -- if m > 0 then
-- -- insert(t,1,i)
-- -- end
-- -- n = floor(n/2)
-- -- i = i + 1
-- -- end
-- -- return t
-- -- end
-- --
-- -- -- a bit faster
--
-- local function bits(n,i,...)
-- if n > 0 then
-- local m = n % 2
-- local n = floor(n/2)
-- if m > 0 then
-- return bits(n, i+1, i, ...)
-- else
-- return bits(n, i+1, ...)
-- end
-- else
-- return ...
-- end
-- end
--
-- function number.bits(n)
-- return { bits(n,1) }
-- end
function number.bytetodecimal(b)
local d = floor(b * 100 / 255 + 0.5)
if d > 100 then
return 100
elseif d < -100 then
return -100
else
return d
end
end
function number.decimaltobyte(d)
local b = floor(d * 255 / 100 + 0.5)
if b > 255 then
return 255
elseif b < -255 then
return -255
else
return b
end
end
function number.idiv(i,d)
return floor(i/d) -- i//d in 5.3
end
|
fzimmermann89/texlive.js
|
texlive/texmf-dist/tex/luatex/lualibs/lualibs-number.lua
|
Lua
|
gpl-2.0
| 5,720 |
/*
* Copyright c Realtek Semiconductor Corporation, 2002
* All rights reserved.
*
* Program : Header File of Model Code for 865xC
* Abstract :
* Author : Louis Yung-Chieh Lo ([email protected])
* $Id: icTest.h,v 1.1 2012/08/07 02:58:33 krammer Exp $
*/
#ifndef _MODEL_TEST_
#define _MODEL_TEST_
#include "rtl_glue.h"
#include "hsModel.h"
#include "virtualMac.h"
#define IS_NOT_EQUAL_INT_DETAIL(str, v1, v2, _f_, _l_,i) \
do{if ((v1) == (v2)) { \
rtlglue_printf("\t%s(%u): %s\n\t%s: %d(0x%08x), %d(0x%08x)\n", _f_, _l_,i==IC_TYPE_REAL?"IC MODE":"MODEL MODE", str, v1, v1, v2, v2); \
return FAILED; \
}}while(0)
#define IS_EQUAL_INT_DETAIL(str, v1, v2, _f_, _l_,i) \
do{if ((v1) != (v2)) { \
rtlglue_printf("\t%s(%u): %s\n\t%s: %d(0x%08x), %d(0x%08x)", _f_, _l_, i==IC_TYPE_REAL?"IC MODE":"MODEL MODE",str, v1, v1,v2,v2); \
return FAILED; \
}}while(0)
#define IS_EQUAL_MAC_DETAIL(str, v1, v2, _f_, _l_,i) \
do { \
if (memcmp((int8 *)&(v1), (int8 *)&(v2), 6)) { \
rtlglue_printf("\t%s(%u):%s\n\t %s: %02x:%02x:%02x:%02x:%02x:%02x, %02x:%02x:%02x:%02x:%02x:%02x\n", _f_, _l_,i==IC_TYPE_REAL?"IC MODE":"MODEL MODE", str, \
*( (uint8*)&v1+0),*( (uint8*)&v1+1),*( (uint8*)&v1+2),*( (uint8*)&v1+3),*( (uint8*)&v1+4),*( (uint8*)&v1+5),\
*( (uint8*)&v2+0),*( (uint8*)&v2+1),*( (uint8*)&v2+2),*( (uint8*)&v2+3),*( (uint8*)&v2+4),*( (uint8*)&v2+5));\
return FAILED; \
} \
} while(0)
int32 runModelTest(uint32 userId, int32 argc,int8 **saved);
/* Bitmask for test code and model export */
#define AUTO_CASE_NO 0 /* auto-increased Case No */
#define GRP_NONE 0x80000000
#define GRP_ALL 0x00000001
#define GRP_PKT_PARSER 0x00000002
#define GRP_PKT_TRANSLATOR 0x00000004
#define GRP_PRE_CORE 0x00000008
#define GRP_L2 0x00000010
#define GRP_L34 0x00000020
#define GRP_POST_CORE 0x00000040
#define GRP_GDMA 0x00000080
#define GRP_NIC 0x00000100
#define GRP_NAPT 0x00000200
#define GRP_FT2 0x00000400
#define GROUP_TBLDRV 0x00000800
#ifdef CONFIG_RTL865X_MODEL_TEST_FT2
int32 runMpFt2(uint32 userId, int32 argc,int8 **saved);
#endif
int32 runModelTest(uint32 userId, int32 argc,int8 **saved);
int32 compHsa( hsa_param_t* hsa1, hsa_param_t* hsa2 );
int32 compHsb( hsb_param_t* hsb1, hsb_param_t* hsb2 );
int32 _rtl8651_setTarget(uint32 userId, int32 argc,int8 **saved);
extern void mbufList_init(void);
#endif
|
ysleu/RTL8685
|
uClinux-dist/u-boot/u-boot-2011.12/arch/mips/cpu/rlx5281/rtl8686/rtk_soc/test/gdma/remove/icTest.h
|
C
|
gpl-2.0
| 2,442 |
ctopcodes_gpu\Release\ctopcodes_gpu.exe -i 1.bmp
|
mgleonard425/Dino_Project
|
c++/run_fixed_input.cmd
|
Batchfile
|
gpl-2.0
| 50 |
#define COMPONENT optics
#include "\x\cba\addons\main\script_mod.hpp"
// #define DEBUG_MODE_FULL
// #define DISABLE_COMPILE_CACHE
// #define DEBUG_ENABLED_OPTICS
#ifdef DEBUG_ENABLED_OPTICS
#define DEBUG_MODE_FULL
#endif
#ifdef DEBUG_SETTINGS_OPTICS
#define DEBUG_SETTINGS DEBUG_SETTINGS_OPTICS
#endif
#define DEBUG_SYNCHRONOUS
#include "\x\cba\addons\main\script_macros.hpp"
#include "\a3\ui_f\hpp\defineDIKCodes.inc"
#define PARSE(value) (call compile format ["%1", value])
#define AMBIENT_BRIGHTNESS (sunOrMoon * sunOrMoon * (1 - overcast * 0.25) + moonIntensity / 5 * (1 - overcast) min 1) // idea by Falke
#define WEAPON_MAGAZINES(unit,weapon) (weaponsItems (unit) select {_x select 0 == (weapon)} param [0, []] select {_x isEqualType []})
#define SOUND_RETICLE_SWITCH ["A3\Sounds_F\arsenal\weapons\UGL\Firemode_ugl",0.31622776,1,5]
#define THIRD_SCREEN_WIDTH ((safezoneX - safezoneXAbs) * ((getResolution select 4)/(16/3)))
// control ids
#define IDC_RETICLE 4000
#define IDC_BODY 4001
#define IDC_BODY_NIGHT 4002
#define IDC_RETICLE_SAFEZONE 4010
#define IDC_BLACK_SCOPE 4020
#define IDC_BLACK_LEFT 4021
#define IDC_BLACK_RIGHT 4022
#define IDC_RED_DOT 4030
#define IDC_MAGNIFICATION 4040
#define IDC_ACTIVE_DISPLAY 8888
#define IDC_ENABLE_ZOOM 9999
// control positions
#define POS_W(size) ((size) / (getResolution select 5))
#define POS_H(size) (POS_W(size) * 4/3)
#define POS_X(size) (0.5 - 0.5 * POS_W(size))
#define POS_Y(size) (0.5 - 0.5 * POS_H(size))
#define RETICLE_SAFEZONE_DEFAULT_SIZE 0.84
#define RETICLE_SAFEZONE_DEFAULT_WIDTH POS_W(RETICLE_SAFEZONE_DEFAULT_SIZE)
#define RETICLE_SAFEZONE_DEFAULT_HEIGHT POS_H(RETICLE_SAFEZONE_DEFAULT_SIZE)
#define RETICLE_SAFEZONE_DEFAULT_LEFT POS_X(RETICLE_SAFEZONE_DEFAULT_SIZE)
#define RETICLE_SAFEZONE_DEFAULT_TOP POS_Y(RETICLE_SAFEZONE_DEFAULT_SIZE)
// scope animation config
#define SCOPE_RECOIL_COEF 1
#define SCOPE_RECOIL_COEF_RESTED 0.4
#define SCOPE_RECOIL_COEF_DEPLOYED 0.1
#define SCOPE_RECOIL_MIN 0.03
#define SCOPE_RECOIL_MAX 0.032
#define SCOPE_SHIFT_X_MIN 0.04
#define SCOPE_SHIFT_X_MAX 0.05
#define SCOPE_SHIFT_Y_MIN -0.02
#define SCOPE_SHIFT_Y_MAX -0.03
#define RETICLE_SHIFT_X_MIN 0.006
#define RETICLE_SHIFT_X_MAX 0.011
#define RETICLE_SHIFT_Y_MIN -0.009
#define RETICLE_SHIFT_Y_MAX -0.014
#define RECENTER_TIME 0.09
|
CBATeam/CBA_A3
|
addons/optics/script_component.hpp
|
C++
|
gpl-2.0
| 2,316 |
/*
mtr -- a network diagnostic tool
Copyright (C) 1997,1998 Matt Kimball
Copyright (C) 2005 [email protected]
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Typedefs */
/* Find the proper type for 8 bits */
#if SIZEOF_UNSIGNED_CHAR == 1
typedef unsigned char uint8;
#else
#error No 8 bit type
#endif
/* Find the proper type for 16 bits */
#if SIZEOF_UNSIGNED_SHORT == 2
typedef unsigned short uint16;
#elif SIZEOF_UNSIGNED_INT == 2
typedef unsigned int uint16;
#elif SIZEOF_UNSIGNED_LONG == 2
typedef unsigned long uint16;
#else
#error No 16 bit type
#endif
/* Find the proper type for 32 bits */
#if SIZEOF_UNSIGNED_SHORT == 4
typedef unsigned short uint32;
#elif SIZEOF_UNSIGNED_INT == 4
typedef unsigned int uint32;
#elif SIZEOF_UNSIGNED_LONG == 4
typedef unsigned long uint32;
#else
#error No 32 bit type
#endif
typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;
#ifdef ENABLE_IPV6
typedef struct in6_addr ip_t;
#else
typedef struct in_addr ip_t;
#endif
#ifdef ENABLE_BILIIP
#define BILIIP_BASE_PTR 5
struct bb_biliip
{
FILE *fp;
char *mmap;
size_t ptr;
size_t size;
size_t nCount;
unsigned int *index_start;
unsigned int *index_end;
unsigned int *index_ptr;
int rsrc_id;
};
extern int ip_resolve;
extern struct bb_biliip *biliip;
#endif
extern int enablempls;
extern int dns;
extern int show_ips;
extern int use_dns;
#ifdef __GNUC__
#define UNUSED __attribute__((__unused__))
#else
#define UNUSED
#endif
#ifndef HAVE_SOCKLEN_T
typedef int socklen_t;
#endif
char *
trim(char * s);
|
Bilibili/mtr
|
mtr.h
|
C
|
gpl-2.0
| 2,195 |
<?php
require_once("include/bittorrent.php");
dbconn();
require_once(get_langfile_path());
require_once(get_langfile_path("",true));
loggedinorreturn();
function bark($msg) {
global $lang_fastdelete;
stdhead();
stdmsg($lang_fastdelete['std_delete_failed'], $msg);
stdfoot();
exit;
}
echo "<script type='text/javascript'> alert('由于不能填写删种原因,暂时关闭此功能。完善之后再开放');history.go(-1) </script>";die;
if (!mkglobal("id"))
bark($lang_fastdelete['std_missing_form_data']);
$id = 0 + $id;
int_check($id);
$sure = $_GET["sure"];
$res = sql_query("SELECT name,owner,seeders,anonymous FROM torrents WHERE id = $id");
$row = mysql_fetch_array($res);
if (!$row)
die();
if (get_user_class() < $torrentmanage_class)
bark($lang_fastdelete['text_no_permission']);
if (!$sure)
{
stderr($lang_fastdelete['std_delete_torrent'], $lang_fastdelete['std_delete_torrent_note']."<a class=altlink href=fastdelete.php?id=$id&sure=1>".$lang_fastdelete['std_here_if_sure'],false);
}
deletetorrent($id);
KPS("-",$uploadtorrent_bonus,$row["owner"]);
if ($row['anonymous'] == 'yes' && $CURUSER["id"] == $row["owner"]) {
write_log("Torrent $id ($row[name]) was deleted by its anonymous uploader",'normal');
} else {
write_log("Torrent $id ($row[name]) was deleted by $CURUSER[username]",'normal');
}
//Send pm to torrent uploader
if ($CURUSER["id"] != $row["owner"]){
$dt = sqlesc(date("Y-m-d H:i:s"));
$subject = sqlesc($lang_fastdelete_target[get_user_lang($row["owner"])]['msg_torrent_deleted']);
$msg = sqlesc($lang_fastdelete_target[get_user_lang($row["owner"])]['msg_the_torrent_you_uploaded'].$row['name'].$lang_fastdelete_target[get_user_lang($row["owner"])]['msg_was_deleted_by']."[url=userdetails.php?id=".$CURUSER['id']."]".$CURUSER['username']."[/url]".$lang_fastdelete_target[get_user_lang($row["owner"])]['msg_blank']);
sql_query("INSERT INTO messages (sender, receiver, subject, added, msg) VALUES(0, $row[owner], $subject, $dt, $msg)") or sqlerr(__FILE__, __LINE__);
}
header("Refresh: 0; url=torrents.php");
?>
|
samuraime/mtpt
|
mtpt/fastdelete.php
|
PHP
|
gpl-2.0
| 2,075 |
#!d:/usr/djgpp/bin/python/python.exe
# Written by Bram Cohen
# see LICENSE.txt for license information
from BitTorrent.download import download
from threading import Event
from os.path import abspath
from sys import argv, stdout
from cStringIO import StringIO
from time import time
def hours(n):
if n == -1:
return '<unknown>'
if n == 0:
return 'complete!'
n = long(n)
h, r = divmod(n, 60 * 60)
m, sec = divmod(r, 60)
if h > 1000000:
return '<unknown>'
if h > 0:
return '%d hour %02d min %02d sec' % (h, m, sec)
else:
return '%d min %02d sec' % (m, sec)
class HeadlessDisplayer:
def __init__(self):
self.done = False
self.file = ''
self.percentDone = ''
self.timeEst = ''
self.downloadTo = ''
self.downRate = ''
self.upRate = ''
self.downTotal = ''
self.upTotal = ''
self.errors = []
self.last_update_time = 0
def finished(self):
self.done = True
self.percentDone = '100'
self.timeEst = 'Download Succeeded!'
self.downRate = ''
self.display({})
def failed(self):
self.done = True
self.percentDone = '0'
self.timeEst = 'Download Failed!'
self.downRate = ''
self.display({})
def error(self, errormsg):
self.errors.append(errormsg)
self.display({})
def display(self, dict):
if self.last_update_time + 0.1 > time() and dict.get('fractionDone') not in (0.0, 1.0) and not dict.has_key('activity'):
return
self.last_update_time = time()
if dict.has_key('spew'):
print_spew(dict['spew'])
if dict.has_key('fractionDone'):
self.percentDone = str(float(int(dict['fractionDone'] * 1000)) / 10)
if dict.has_key('timeEst'):
self.timeEst = hours(dict['timeEst'])
if dict.has_key('activity') and not self.done:
self.timeEst = dict['activity']
if dict.has_key('downRate'):
self.downRate = '%.2f kB/s' % (float(dict['downRate']) / (1 << 10))
if dict.has_key('upRate'):
self.upRate = '%.2f kB/s' % (float(dict['upRate']) / (1 << 10))
if dict.has_key('upTotal'):
self.upTotal = '%.1f MiB' % (dict['upTotal'])
if dict.has_key('downTotal'):
self.downTotal = '%.1f MiB' % (dict['downTotal'])
print '\n\n'
for err in self.errors:
print 'ERROR:\n' + err + '\n'
print 'saving: ', self.file
print 'percent done: ', self.percentDone
print 'time left: ', self.timeEst
print 'download to: ', self.downloadTo
if self.downRate != '':
print 'download rate: ', self.downRate
if self.upRate != '':
print 'upload rate: ', self.upRate
if self.downTotal != '':
print 'download total:', self.downTotal
if self.upTotal != '':
print 'upload total: ', self.upTotal
stdout.flush()
def chooseFile(self, default, size, saveas, dir):
self.file = '%s (%.1f MB)' % (default, float(size) / (1 << 20))
if saveas != '':
default = saveas
self.downloadTo = abspath(default)
return default
def newpath(self, path):
self.downloadTo = path
def print_spew(spew):
s = StringIO()
s.write('\n\n\n')
for c in spew:
s.write('%20s ' % c['ip'])
if c['initiation'] == 'local':
s.write('l')
else:
s.write('r')
rate, interested, choked = c['upload']
s.write(' %10s ' % str(int(rate)))
if c['is_optimistic_unchoke']:
s.write('*')
else:
s.write(' ')
if interested:
s.write('i')
else:
s.write(' ')
if choked:
s.write('c')
else:
s.write(' ')
rate, interested, choked, snubbed = c['download']
s.write(' %10s ' % str(int(rate)))
if interested:
s.write('i')
else:
s.write(' ')
if choked:
s.write('c')
else:
s.write(' ')
if snubbed:
s.write('s')
else:
s.write(' ')
s.write('\n')
print s.getvalue()
def run(params):
try:
import curses
curses.initscr()
cols = curses.COLS
curses.endwin()
except:
cols = 80
h = HeadlessDisplayer()
download(params, h.chooseFile, h.display, h.finished, h.error, Event(), cols, h.newpath)
if not h.done:
h.failed()
if __name__ == '__main__':
run(argv[1:])
|
fxia22/ASM_xf
|
PythonD/bin/python/btdownloadheadless.py
|
Python
|
gpl-2.0
| 4,894 |
<?php
/**
* @package RedSHOP.Frontend
* @subpackage Template
*
* @copyright Copyright (C) 2005 - 2013 redCOMPONENT.com. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('_JEXEC') or die;
JHTML::_('behavior.tooltip');
JHTML::_('behavior.modal');
require_once JPATH_ADMINISTRATOR . '/components/com_redshop/helpers/category.php';
require_once JPATH_ROOT . '/components/com_redshop/helpers/product.php';
require_once JPATH_ROOT . '/components/com_redshop/helpers/helper.php';
$config = new Redconfiguration;
$producthelper = new producthelper;
$redhelper = new redhelper;
$url = JURI::base();
$Itemid = JRequest::getInt('Itemid');
$wishlists = $this->wishlists;
$product_id = JRequest::getInt('product_id');
$user = JFactory::getUser();
$pagetitle = JText::_('COM_REDSHOP_MY_WISHLIST');
$redTemplate = new Redtemplate;
$extraField = new extraField;
$template = $redTemplate->getTemplate("wishlist_template");
$wishlist_data1 = $template[0]->template_desc;
$returnArr = $producthelper->getProductUserfieldFromTemplate($wishlist_data1);
$template_userfield = $returnArr[0];
$userfieldArr = $returnArr[1];
if ($this->params->get('show_page_heading', 1))
{
?>
<h1 class="componentheading<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>"><?php echo $pagetitle; ?></h1>
<div> </div>
<?php
}
if (!$user->id)
{
$rows = $this->wish_session;
echo "<div class='mod_redshop_wishlist'>";
if (count($rows) > 0)
{
// Send mail link
$mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component";
display_products($rows);
$reglink = JRoute::_("index.php?wishlist=1&option=com_redshop&view=login&Itemid=" . $Itemid);
for ($p = 0; $p < count($rows); $p++)
{
for ($ui = 0; $ui < count($userfieldArr); $ui++)
{
$product_userfileds = $extraField->list_all_user_fields($userfieldArr[$ui], 12, '', 0, 0, $rows[$p]->product_id);
$ufield .= $product_userfileds[1];
//
if ($product_userfileds[1] != "")
{
$count_no_user_field++;
}
}
$myproductid .= $rows[$p]->product_id . ",";
}
?>
<script language="javascript">
function clickMe() {
window.location = "<?php echo $reglink ?>";
}
</script>
<?php
//echo "<br /><div><a href=\"".$reglink."\"><input type='button' onClick="clickMe();" value='".JText::_('COM_REDSHOP_SAVE_WISHLIST')."' onclick="" ></a></div>";
if ($count_no_user_field > 0)
{
echo "<br /><div id='saveid' style='clear:both;' style='display:block'><form method='post' ><input type='hidden' name='product_id' value='" . $myproductid . "' ><input type='button' onClick='return productalladdprice(1)' value='" . JText::_('SAVE_WISHLIST') . "' ></form></div>";
}
else
{
echo "<br /><div id='saveid' style='clear:both;'><input type='button' onClick='clickMe()' value='" . JText::_('COM_REDSHOP_SAVE_WISHLIST') . "' ></div>";
}
}
else
{
echo "<div>" . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "</div>";
}
echo "</div>";
}
else
{
// If user logged in than display this code.
echo "<div class='mod_redshop_wishlist'>";
if (count($this->wish_session) > 0)
{
$mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component";
display_products($this->wish_session);
for ($p = 0; $p < count($mysesspro); $p++)
{
for ($ui = 0; $ui < count($userfieldArr); $ui++)
{
$product_userfileds = $extraField->list_all_user_fields($userfieldArr[$ui], 12, '', 0, 0, $rows[$p]->product_id);
$ufield .= $product_userfileds[1];
if ($product_userfileds[1] != "")
{
$count_no_user_field++;
}
}
$myproductid .= $mysesspro[$p]->product_id . ",";
}
echo "<br />";
$mywishlist_link = "index.php?tmpl=component&option=com_redshop&view=wishlist&task=addtowishlist&tmpl=component";
if ($count_no_user_field > 0)
{
echo "<br /><div style='clear:both;' ><a class=\"redcolorproductimg\" href=\"" . $mywishlist_link . "\" ><form method='post' ><input type='hidden' name='product_id' value='" . $myproductid . "' ><input type='button' onClick='return productalladdprice(2)' value='" . JText::_('COM_REDSHOP_SAVE_WISHLIST') . "' ></form></a></div>";
}
else
{
echo "<div style=\"clear:both;\" ><a class=\"redcolorproductimg\" href=\"" . $mywishlist_link . "\" ><input type='button' value='" . JText::_('SAVE_WISHLIST') . "'></a></div><br /><br />";
}
}
if (count($wishlists) > 0)
{
$wish_products = $this->wish_products;
// Send mail link
echo "<table>";
for ($j = 0; $j < count($wishlists); $j++)
{
$wishlist_link = JRoute::_("index.php?view=account&layout=mywishlist&wishlist_id=" . $wishlists[$j]->wishlist_id . "&option=com_redshop&Itemid=" . $Itemid);
$del_wishlist = JRoute::_("index.php?view=wishlist&task=delwishlist&wishlist_id=" . $wishlists[$j]->wishlist_id . "&option=com_redshop&Itemid=" . $Itemid);
echo "<tr><td><a href=\"" . $wishlist_link . "\">" . $wishlists[$j]->wishlist_name . "</a></td>"
. "<td><a href=\"" . $del_wishlist . "\">" . JText::_('COM_REDSHOP_DELETE') . "</a></td></tr>";
}
echo "</table>";
}
elseif (count($this->wish_session) <= 0 && count($wishlists) <= 0)
{
echo "<div>" . JText::_('COM_REDSHOP_NO_PRODUCTS_IN_WISHLIST') . "</div>";
}
echo "</div>";
}
function display_products($rows)
{
$url = JURI::base();
$extraField = new extraField;
$session = JFactory::getSession();
$producthelper = new producthelper;
$redhelper = new redhelper;
$config = new Redconfiguration;
$redTemplate = new Redtemplate;
$template = $redTemplate->getTemplate("wishlist_template");
if (count($template) <= 0)
{
for ($i = 0; $i < count($rows); $i++)
{
$row = $rows[$i];
$Itemid = $redhelper->getItemid($row->product_id);
$link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $row->product_id . '&Itemid=' . $Itemid);
$product_price = $producthelper->getProductPrice($row->product_id);
$product_price_discount = $producthelper->getProductNetPrice($row->product_id);
echo "<div id='wishlist_box'>";
if ($row->product_full_image)
{
echo $thum_image = "<div class='wishlist_left'><div class='mod_wishlist_product_image wishlist_image'>" .
$thum_image = $producthelper->getProductImage($row->product_id, $link, "85", "63") . "</div></div>";
}
else
{
$maindefaultpath = REDSHOP_FRONT_IMAGES_ABSPATH . "product/" . PRODUCT_DEFAULT_IMAGE;
echo $thum_image = "<div class='wishlist_left'><div class='mod_wishlist_product_image wishlist_image'><a href='" . $link . "'><img src='" . $maindefaultpath . "' height='85' width='63' /></a></div></div>";
}
echo "<div class='wishlist_center'><div class='wishlist_title'><a href='" . $link . "'>" . $row->product_name . "</a></div><br>";
if (!$row->not_for_sale)
{
if ($row->product_on_sale && $product_price_discount > 0)
{
if ($product_price > $product_price_discount)
{
$s_price = $product_price - $product_price_discount;
if ($this->show_discountpricelayout)
{
echo "<div id='mod_redoldprice' class='mod_redoldprice'><span style='text-decoration:line-through;'>" . $producthelper->getProductFormattedPrice($product_price) . "</span></div>";
$product_price = $product_price_discount;
echo "<div id='mod_redmainprice' class='mod_redmainprice wishlist_price'>" . $producthelper->getProductFormattedPrice($product_price_discount) . "</div>";
echo "<div id='mod_redsavedprice' class='mod_redsavedprice'>" . JText::_('COM_REDSHOP_PRODCUT_PRICE_YOU_SAVED') . ' ' . $producthelper->getProductFormattedPrice($s_price) . "</div>";
}
else
{
$product_price = $product_price_discount;
echo "<div class='mod_redproducts_price wishlist_price'>" . $producthelper->getProductFormattedPrice($product_price) . "</div>";
}
}
else
{
echo "<div class='mod_redproducts_price wishlist_price'>" . $producthelper->getProductFormattedPrice($product_price) . "</div>";
}
}
else
{
echo "<div class='mod_redproducts_price wishlist_price'>" . $producthelper->getProductFormattedPrice($product_price) . "</div>";
}
}
echo "<br><div class='wishlist_readmore'><a href='" . $link . "'>" . JText::_('COM_REDSHOP_READ_MORE') . "</a></div> </div> ";
$addtocartdata = $producthelper->replaceCartTemplate($row->product_id, 0, 0, $row->product_id);
echo "<div class='wishlist_right'>" . $addtocartdata . "</div><br class='clear' /></div><br class='clear' />";
}
}
else
{
$ph_thumb = CATEGORY_PRODUCT_THUMB_HEIGHT;
$pw_thumb = CATEGORY_PRODUCT_THUMB_WIDTH;
$wishlist_data1 = $template[0]->template_desc;
$mlink = JURI::root() . "index.php?option=com_redshop&view=account&layout=mywishlist&mail=1&tmpl=component&wishlist_id=" . $wishlist_id;
$mail_link = '<a class="redcolorproductimg" href="' . $mlink . '" ><img src="' . REDSHOP_ADMIN_IMAGES_ABSPATH . 'mailcenter16.png" ></a>';
$wishlist_data1 = str_replace('{mail_link}', $mail_link, $wishlist_data1);
$template_d1 = explode("{product_loop_start}", $wishlist_data1);
$template_d2 = explode("{product_loop_end}", $template_d1[1]);
$temp_template = '';
$extraFieldName = $extraField->getSectionFieldNameArray(1, 1, 1);
for ($i = 0; $i < count($rows); $i++)
{
$row = $rows[$i];
$wishlist_data = $template_d2[0];
$Itemid = $redhelper->getItemid($rows[$i]->product_id);
$link = JRoute::_('index.php?option=com_redshop&view=product&pid=' . $rows[$i]->product_id . '&Itemid=' . $Itemid);
$product_price = $producthelper->getProductPrice($row->product_id);
$product_price_discount = $producthelper->getProductNetPrice($row->product_id);
if ($row->product_full_image)
{
$thum_image = $producthelper->getProductImage($row->product_id, $link, $pw_thumb, $ph_thumb);
$wishlist_data = str_replace('{product_thumb_image}', $thum_image, $wishlist_data);
}
else
{
$maindefaultpath = RedShopHelperImages::getImagePath(
PRODUCT_DEFAULT_IMAGE,
'',
'thumb',
'product',
$pw_thumb,
$ph_thumb,
USE_IMAGE_SIZE_SWAPPING
);
$thum_image = "<a href='" . $link . "'><img src='" . $maindefaultpath . "' /></a>";
$wishlist_data = str_replace('{product_thumb_image}', $thum_image, $wishlist_data);
}
$pname = "<a href='" . $link . "'>" . $row->product_name . "</a>";
$pnumber = $row->product_number;
$pdesc = $row->product_s_desc;
// Checking for child products start
if (strstr($wishlist_data, "{child_products}"))
{
$parentproductid = $row->product_id;
if ($this->data->product_parent_id != 0)
{
$parentproductid = $producthelper->getMainParentProduct($row->product_id);
}
$frmChild = "";
if ($parentproductid != 0)
{
$productInfo = $producthelper->getProductById($parentproductid);
// Get child products
$childproducts = $model->getAllChildProductArrayList(0, $parentproductid);
if (count($childproducts) > 0)
{
$childproducts = array_merge(array($productInfo), $childproducts);
$cld_name = array();
if (count($childproducts) > 0)
{
$parentid = 0;
for ($c = 0; $c < count($childproducts); $c++)
{
if ($childproducts[$c]->product_parent_id == 0)
{
$level = "";
}
else
{
if ($parentid != $childproducts[$c]->product_parent_id)
{
$level = $level;
}
}
$parentid = $childproducts[$c]->product_parent_id;
$childproducts[$c]->product_name = $level . $childproducts[$c]->product_name;
}
$cld_name = @array_merge($cld_name, $childproducts);
}
$selected = array($row->product_id);
$lists['product_child_id'] = JHTML::_('select.genericlist', $cld_name, 'pid', 'class="inputbox" size="1" onchange="document.frmChild.submit();"', 'product_id', 'product_name', $selected);
$frmChild .= "<form name='frmChild' method='get'>";
$frmChild .= JText::_('COM_REDSHOP_CHILD_PRODUCTS') . $lists ['product_child_id'];
$frmChild .= "<input type='hidden' name='Itemid' value='" . $Itemid . "'>";
$frmChild .= "<input type='hidden' name='cid' value='" . $row->category_id . "'>";
$frmChild .= "<input type='hidden' name='view' value='product'>";
$frmChild .= "<input type='hidden' name='option' value='com_redshop'>";
$frmChild .= "</form>";
}
}
$wishlist_data = str_replace("{child_products}", $frmChild, $wishlist_data);
}
$childproduct = $producthelper->getChildProduct($row->product_id);
if (count($childproduct) > 0)
{
if (PURCHASE_PARENT_WITH_CHILD == 1)
{
$isChilds = false;
$attributes_set = array();
if ($row->attribute_set_id > 0)
{
$attributes_set = $producthelper->getProductAttribute(0, $row->attribute_set_id, 0, 1);
}
$attributes = $producthelper->getProductAttribute($row->product_id);
$attributes = array_merge($attributes, $wishlist_data);
}
else
{
$isChilds = true;
$attributes = array();
}
}
else
{
$isChilds = false;
$attributes_set = array();
if ($row->attribute_set_id > 0)
{
$attributes_set = $producthelper->getProductAttribute(0, $row->attribute_set_id, 0, 1);
}
$attributes = $producthelper->getProductAttribute($row->product_id);
$attributes = array_merge($attributes, $attributes_set);
}
$attribute_template = $producthelper->getAttributeTemplate($wishlist_data);
// Check product for not for sale
$wishlist_data = $producthelper->getProductNotForSaleComment($row, $wishlist_data, $attributes);
$wishlist_data = $producthelper->replaceProductInStock($row->product_id, $wishlist_data, $attributes, $attribute_template);
/////////////////////////////////// Product attribute Start /////////////////////////////////
$totalatt = count($attributes);
$wishlist_data = $producthelper->replaceAttributeData($row->product_id, 0, 0, $attributes, $wishlist_data, $attribute_template, $isChilds);
/////////////////////////////////// Product attribute End // Checking for child products end/////////////////////////////////
if (!$row->not_for_sale)
{
if ($row->product_on_sale && $product_price_discount > 0)
{
if ($product_price > $product_price_discount)
{
$s_price = $product_price - $product_price_discount;
if ($this->show_discountpricelayout)
{
$mainproduct_price = $producthelper->getProductFormattedPrice($product_price);
$product_price = $product_price_discount;
$mainproduct_price = $producthelper->getProductFormattedPrice($product_price_discount);
}
else
{
$product_price = $product_price_discount;
$mainproduct_price = $producthelper->getProductFormattedPrice($product_price);
}
}
else
{
$mainproduct_price = $producthelper->getProductFormattedPrice($product_price);
}
}
else
{
$mainproduct_price = $producthelper->getProductFormattedPrice($product_price);
}
$wishlist_data = str_replace('{product_price}', $mainproduct_price, $wishlist_data);
}
// Product User Field Start
$count_no_user_field = 0;
$returnArr = $producthelper->getProductUserfieldFromTemplate($wishlist_data);
$template_userfield = $returnArr[0];
$userfieldArr = $returnArr[1];
if (strstr($wishlist_data, "{if product_userfield}") && strstr($wishlist_data, "{product_userfield end if}") && $template_userfield != "")
{
$ufield = "";
$cart = $session->get('cart');
if (isset($cart['idx']))
{
$idx = (int) ($cart['idx']);
}
$idx = 0;
$cart_id = '';
for ($j = 0; $j < $idx; $j++)
{
if ($cart[$j]['product_id'] == $row->product_id)
{
$cart_id = $j;
}
}
for ($ui = 0; $ui < count($userfieldArr); $ui++)
{
if (!$idx)
{
$cart_id = "";
}
$mysesspro = "productuserfield_" . $ui;
for ($check_i = 1; $check_i <= $_SESSION ["no_of_prod"]; $check_i++)
{
if ($_SESSION ['wish_' . $check_i]->product_id == $row->product_id)
{
$product_userfileds_final = $_SESSION['wish_' . $check_i]->$mysesspro;
}
}
if ($product_userfileds_final != '')
{
$product_userfileds = $extraField->list_all_user_fields($userfieldArr[$ui], 12, '', '', 0, $row->product_id, $product_userfileds_final, 1);
}
else
{
$product_userfileds = $extraField->list_all_user_fields($userfieldArr[$ui], 12, '', $cart_id, 0, $row->product_id);
}
$ufield .= $product_userfileds[1];
//
if ($product_userfileds[1] != "")
{
$count_no_user_field++;
}
if ($product_userfileds_final != '')
{
$wishlist_data = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $product_userfileds[0], $wishlist_data);
$wishlist_data = str_replace('{' . $userfieldArr[$ui] . '}', $product_userfileds[1], $wishlist_data);
}
else
{
$wishlist_data = str_replace('{' . $userfieldArr[$ui] . '_lbl}', $product_userfileds[0], $wishlist_data);
$wishlist_data = str_replace('{' . $userfieldArr[$ui] . '}', $product_userfileds[1], $wishlist_data);
}
}
$product_userfileds_form = "<form method='post' action='' id='user_fields_form' name='user_fields_form'>";
if ($ufield != "")
{
$wishlist_data = str_replace("{if product_userfield}", $product_userfileds_form, $wishlist_data);
$wishlist_data = str_replace("{product_userfield end if}", "</form>", $wishlist_data);
}
else
{
$wishlist_data = str_replace("{if product_userfield}", "", $wishlist_data);
$wishlist_data = str_replace("{product_userfield end if}", "", $wishlist_data);
}
}
// Product User Field End
/////////////////////////////////// Product accessory Start /////////////////////////////////
$accessory = $producthelper->getProductAccessory(0, $row->product_id);
$totalAccessory = count($accessory);
$wishlist_data = $producthelper->replaceAccessoryData($row->product_id, 0, $accessory, $wishlist_data, $isChilds);
/////////////////////////////////// Product accessory End /////////////////////////////////
$wishlist_data = str_replace('{product_name}', $pname, $wishlist_data);
$wishlist_data = str_replace('{product_number}', $pnumber, $wishlist_data);
$wishlist_data = str_replace('{product_s_desc}', $pdesc, $wishlist_data);
$wishlist_data = $producthelper->getExtraSectionTag($extraFieldName, $row->product_id, "1", $wishlist_data, 1);
$wishlist_data = $producthelper->replaceCartTemplate($row->product_id, $row->category_id, 0, 0, $wishlist_data, $isChilds, $userfieldArr, $totalatt, $totalAccessory, $count_no_user_field);
$rmore = "<a href='" . $link . "' title='" . $row->product_name . "'>" . JText::_('COM_REDSHOP_READ_MORE') . "</a>";
$wishlist_data = str_replace("{read_more}", $rmore, $wishlist_data);
$wishlist_data = str_replace("{read_more_link}", $link, $wishlist_data);
$wishlist_data = str_replace("{product_loop_start}", '', $wishlist_data);
$wishlist_data = str_replace("{product_loop_end}", '', $wishlist_data);
$wishlist_data = str_replace("{back_link}", '', $wishlist_data);
$wishlist_data = str_replace("{back_link}", '', $wishlist_data);
$wishlist_data = str_replace("{mail_link}", '', $wishlist_data);
$wishlist_data = str_replace("{if product_on_sale}", '', $wishlist_data);
$wishlist_data = str_replace("{product_on_sale end if}", '', $wishlist_data);
$wishlist_data = str_replace("<table></table>", '', $wishlist_data);
$wishlist_data = str_replace("{all_cart}", '', $wishlist_data);
$wishlist_data = str_replace("{if product_on_sale}", "", $wishlist_data);
$wishlist_data = str_replace("{product_on_sale end if}", "", $wishlist_data);
$regdellink = JRoute::_("index.php?mydel=1&view=wishlist&wishlist_id=" . $row->product_id . "&task=mysessdelwishlist");
$mainregdellink = "<div><a href=\"" . $regdellink . "\">" . JText::_('COM_REDSHOP_REMOVE_PRODUCT_FROM_WISHLIST') . "</a></div>";
$wishlist_data = str_replace('{remove_product_link}', $mainregdellink, $wishlist_data);
$mainid .= $row->product_id . ",";
$totattid .= $totalatt . ",";
$totcount_no_user_field .= $count_no_user_field . ",";
$temp_template .= $wishlist_data;
}
$my = "<form name='frm' method='POST' action=''>";
$my .= "<input type='hidden' name='product_id' id='product_id' value='" . $mainid . "' >
<input type='hidden' name='totacc_id' id='totacc_id' value='" . $totattid . "' >
<input type='hidden' name='totcount_no_user_field' id='totcount_no_user_field' value='" . $totcount_no_user_field . "' >
<input type='button' name='submit' onclick='return productalladdprice();' value='" . JText::_('COM_REDSHOP_ADD_TO_CART') . "'>
</form>";
$data = $template_d1[0] . $temp_template . $template_d2[1];
$data = str_replace('{back_link}', '', $data);
$data = str_replace('{all_cart}', $my, $data);
$data = $redTemplate->parseredSHOPplugin($data);
echo eval("?>" . $data . "<?php ");
}
}
|
jaanusnurmoja/redjoomla
|
components/com_redshop/views/wishlist/tmpl/viewwishlist.php
|
PHP
|
gpl-2.0
| 21,532 |
<?php
include ('../../config/config.php');
if (!checkAdminLogin()) {
$link = baseUrl('admin/index.php?err=' . base64_encode('Please login to access admin panel'));
redirect($link);
}
$admin_full_name = '';
$admin_email = '';
$admin_type = '';
if (isset($_POST['admin_create']) AND $_POST['admin_create'] == 'Submit') {
extract($_POST);
if ($admin_full_name == '') {
$err = 'Name field is required!!';
} elseif(!ctype_alpha($_POST['admin_full_name'])){
$err = 'Name field only accepts alphabet!!';
} elseif ($admin_email == '') {
$err = 'Email field is required!!';
} elseif (!isValidEmail($admin_email)) {
$err = 'Valid email is required!!';
} elseif ($admin_password == '') {
$err = 'Admin password field is required!!';
} elseif ((strlen($admin_password) > $config['ADMIN_PASSWORD_LENGTH_MAX'] OR strlen($admin_password) < $config['ADMIN_PASSWORD_LENGTH_MIN'])) {
$err = 'Password length should be with in maximum: ' . $config['ADMIN_PASSWORD_LENGTH_MAX'] . ' AND Minimum: ' . $config['ADMIN_PASSWORD_LENGTH_MIN'] . '!! Given password length is :' . strlen($admin_password);
} elseif ($admin_conf_password == '') {
$err = 'Confirm password field is required!!';
} elseif ($admin_conf_password != $admin_password) {
$err = 'Confirm Password should match with Admin password !!';
} elseif ($admin_type == '') {
$err = 'Type filed is required!!';
} else {
/* Start :Checking the user already exist or not */
$adminCheckSql = "SELECT admin_email FROM admins WHERE admin_email='" . mysqli_real_escape_string($con, $admin_email) . "'";
$adminCheckSqlResult = mysqli_query($con, $adminCheckSql);
if ($adminCheckSqlResult) {
$adminCheckSqlResultRowObj = mysqli_fetch_object($adminCheckSqlResult);
if (isset($adminCheckSqlResultRowObj->admin_email) AND $adminCheckSqlResultRowObj->admin_email = $admin_email) {
$err = '(<b>' . $admin_email . '</b>) already exist in our databse ';
}
mysqli_free_result($adminCheckSqlResult);
} else {
if (DEBUG) {
echo 'adminCheckSqlResult Error: ' . mysqli_error($con);
}
$err = "Query failed.";
}
/* End :Checking the user already exist or not */
}
if ($err == '') {
$secured_admin_password = securedPass($admin_password);
$admin_hash = rand(10000, 999999) . $config['PASSWORD_KEY'] . rand(100000, 999999);
$adminFiled = '';
$adminFiled .=' admin_full_name = "' . mysqli_real_escape_string($con, $admin_full_name) . '"';
$adminFiled .=', admin_email ="' . mysqli_real_escape_string($con, $admin_email) . '"';
$adminFiled .=', admin_password ="' . mysqli_real_escape_string($con, $secured_admin_password) . '"';
$adminFiled .=', admin_hash ="' . $admin_hash . '"';
$adminFiled .=', admin_type="' . $admin_type . '"';
$adminFiled .=', admin_status="inactive"';
$adminFiled .=', admin_update ="' . date("Y-m-d H:i:s") . '"';
$adminFiled .=', admin_updated_by=0'; /* it will be loged in user ussesion id */
$adminInsSql = "INSERT INTO admins SET $adminFiled";
$adminInsSqlResult = mysqli_query($con, $adminInsSql);
if ($adminInsSqlResult) {
$msg = "Admin created successfully";
} else {
if (DEBUG) {
echo 'adminInsSqlResult Error: ' . mysqli_error($con);
}
$err = "Insert Query failed.";
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="<?php echo baseUrl('admin/images/favicon.ico')?>" />
<title>Admin panel: Admin create </title>
<link href="<?php echo baseUrl('admin/css/main.css'); ?>" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Cuprum' rel='stylesheet' type='text/css' />
<script src="<?php echo baseUrl('admin/js/jquery-1.4.4.js'); ?>" type="text/javascript"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, File upload, editor -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/spinner/ui.spinner.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jquery-ui.min.js'); ?>"></script>
<script type="text/javascript" src="<?php echo baseUrl('admin/js/fileManager/elfinder.min.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/wysiwyg/jquery.wysiwyg.js'); ?>"></script>
<!--Effect on wysiwyg editor -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/wysiwyg/wysiwyg.image.js'); ?>"></script>
<!--Effect on wysiwyg editor -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/wysiwyg/wysiwyg.link.js'); ?>"></script>
<!--Effect on wysiwyg editor -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/wysiwyg/wysiwyg.table.js'); ?>"></script>
<!--Effect on wysiwyg editor -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/dataTables/jquery.dataTables.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/dataTables/colResizable.min.js'); ?>"></script>
<!--Effect on left error menu, top message menu -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/forms/forms.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/forms/autogrowtextarea.js'); ?>"></script>
<!--Effect on left error menu, top message menu, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/forms/autotab.js'); ?>"></script>
<!--Effect on left error menu, top message menu -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/forms/jquery.validationEngine.js'); ?>"></script>
<!--Effect on left error menu, top message menu-->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/colorPicker/colorpicker.js'); ?>"></script>
<!--Effect on left error menu, top message menu -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/uploader/plupload.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/uploader/plupload.html5.js'); ?>"></script>
<!--Effect on file upload-->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/uploader/plupload.html4.js'); ?>"></script>
<!--No effect-->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/uploader/jquery.plupload.queue.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/ui/jquery.tipsy.js'); ?>"></script>
<!--Effect on left error menu, top message menu, -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jBreadCrumb.1.1.js'); ?>"></script>
<!--Effect on left error menu, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/cal.min.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jquery.collapsible.min.js'); ?>"></script>
<!--Effect on left error menu, File upload -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jquery.ToTop.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio, -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jquery.listnav.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/jquery.sourcerer.js'); ?>"></script>
<!--Effect on left error menu, top message menu,Drowpdowns and selects, Checkbox and radio -->
<script type="text/javascript" src="<?php echo baseUrl('admin/js/custom.js'); ?>"></script>
<!--Effect on left error menu, top message menu, body-->
</head>
<body>
<?php include basePath('admin/top_navigation.php'); ?>
<?php include basePath('admin/module_link.php'); ?>
<!-- Content wrapper -->
<div class="wrapper">
<!-- Left navigation -->
<?php include ('admin_left_navigation.php'); ?>
<!-- Content Start -->
<div class="content">
<div class="title"><h5>Admin Module</h5></div>
<!-- Notification messages -->
<?php include basePath('admin/message.php'); ?>
<!-- Charts -->
<div class="widget first">
<div class="head">
<h5 class="iGraph">Create Admin </h5></div>
<div class="body">
<div class="charts" style="width: 700px; height: auto;">
<form action="<?php echo baseUrl('admin/admin/admin_create.php'); ?>" method="post" class="mainForm">
<!-- Input text fields -->
<fieldset>
<div class="widget first">
<div class="head"><h5 class="iList">Admin Information</h5></div>
<div class="rowElem noborder"><label> Name:</label><div class="formRight"><input type="text" name="admin_full_name" value="<?php echo $admin_full_name; ?>" /></div><div class="fix"></div></div>
<div class="rowElem noborder"><label>Admin Email:</label><div class="formRight"><input type="text" name="admin_email" value="<?php echo $admin_email; ?>"/></div><div class="fix"></div></div>
<div class="rowElem"><label>Admin password:</label><div class="formRight"><input type="password" name="admin_password" /></div><div class="fix"></div></div>
<div class="rowElem"><label>Confirm Password:</label><div class="formRight"><input type="password" name="admin_conf_password"/></div><div class="fix"></div></div>
<div class="rowElem noborder">
<label>Admin Type :</label>
<div class="formRight">
<select name="admin_type">
<option value="normal" <?php
if ($admin_type == 'normal') {
echo 'selected="selected"';
}
?>>Normal</option>
<option value="super" <?php
if ($admin_type == 'super') {
echo 'selected="selected"';
}
?> >Super Admin</option>
</select>
</div>
<div class="fix"></div>
</div>
<input type="submit" name="admin_create" value="Submit" class="greyishBtn submitForm" />
<div class="fix"></div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
<!-- Content End -->
<div class="fix"></div>
</div>
<?php include basePath('admin/footer.php'); ?>
|
tariqulislam/sing_in_with_twitter_auth
|
tuizo/admin/admin_create_copy.php
|
PHP
|
gpl-2.0
| 13,203 |
/***************************************************************************
main.cpp - description
-------------------
begin : Fri Jun 21 10:48:28 AKDT 2002
copyright : (C) 2002 by Gary E.Sherman
email : sherman at mrcc.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. *
* *
***************************************************************************/
//qt includes
#include <QBitmap>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QFont>
#include <QFontDatabase>
#include <QPixmap>
#include <QLocale>
#include <QSplashScreen>
#include <QString>
#include <QStringList>
#include <QStyle>
#include <QStyleFactory>
#include <QDesktopWidget>
#include <QImageReader>
#include <QMessageBox>
#include <QStandardPaths>
#include <cstdio>
#include <cstdlib>
#include <cstdarg>
#if !defined(Q_OS_WIN)
#include "sigwatch.h"
#endif
#ifdef WIN32
// Open files in binary mode
#include <fcntl.h> /* _O_BINARY */
#include <windows.h>
#include <dbghelp.h>
#include <time.h>
#ifdef MSVC
#undef _fmode
int _fmode = _O_BINARY;
#else
// Only do this if we are not building on windows with msvc.
// Recommended method for doing this with msvc is with a call to _set_fmode
// which is the first thing we do in main().
// Similarly, with MinGW set _fmode in main().
#endif //_MSC_VER
#else
#include <getopt.h>
#endif
#ifdef Q_OS_MACX
#include <ApplicationServices/ApplicationServices.h>
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1050
typedef SInt32 SRefCon;
#endif
#endif
#ifdef Q_OS_UNIX
// For getrlimit() / setrlimit()
#include <sys/resource.h>
#include <sys/time.h>
#endif
#if defined(__GLIBC__) || defined(__FreeBSD__)
#define QGIS_CRASH
#include <unistd.h>
#include <execinfo.h>
#include <csignal>
#include <sys/wait.h>
#include <cerrno>
#endif
#include "qgscustomization.h"
#include "qgssettings.h"
#include "qgsfontutils.h"
#include "qgspluginregistry.h"
#include "qgsmessagelog.h"
#include "qgspythonrunner.h"
#include "qgslocalec.h"
#include "qgisapp.h"
#include "qgsmapcanvas.h"
#include "qgsapplication.h"
#include "qgsconfig.h"
#include "qgsversion.h"
#include "qgsexception.h"
#include "qgsproject.h"
#include "qgsrectangle.h"
#include "qgslogger.h"
#include "qgsdxfexport.h"
#include "qgsmapthemes.h"
#include "qgsvectorlayer.h"
#include "qgis_app.h"
#include "qgscrashhandler.h"
#include "qgsziputils.h"
#include "qgsversionmigration.h"
#include "qgsfirstrundialog.h"
#include "qgsproxystyle.h"
#include "qgsmessagebar.h"
#include "qgsuserprofilemanager.h"
#include "qgsuserprofile.h"
#include "qgsdatetimefieldformatter.h"
#ifdef HAVE_OPENCL
#include "qgsopenclutils.h"
#endif
/**
* Print QGIS version
*/
void version( )
{
const QString msg = QStringLiteral( "QGIS %1 '%2' (%3)\n" ).arg( VERSION ).arg( RELEASE_NAME ).arg( QGSVERSION );
std::cout << msg.toStdString();
}
/**
* Print usage text
*/
void usage( const QString &appName )
{
QStringList msg;
msg
<< QStringLiteral( "QGIS is a user friendly Open Source Geographic Information System.\n" )
<< QStringLiteral( "Usage: " ) << appName << QStringLiteral( " [OPTION] [FILE]\n" )
<< QStringLiteral( " OPTION:\n" )
<< QStringLiteral( "\t[--version]\tdisplay version information and exit\n" )
<< QStringLiteral( "\t[--snapshot filename]\temit snapshot of loaded datasets to given file\n" )
<< QStringLiteral( "\t[--width width]\twidth of snapshot to emit\n" )
<< QStringLiteral( "\t[--height height]\theight of snapshot to emit\n" )
<< QStringLiteral( "\t[--lang language]\tuse language for interface text (changes existing override)\n" )
<< QStringLiteral( "\t[--project projectfile]\tload the given QGIS project\n" )
<< QStringLiteral( "\t[--extent xmin,ymin,xmax,ymax]\tset initial map extent\n" )
<< QStringLiteral( "\t[--nologo]\thide splash screen\n" )
<< QStringLiteral( "\t[--noversioncheck]\tdon't check for new version of QGIS at startup\n" )
<< QStringLiteral( "\t[--noplugins]\tdon't restore plugins on startup\n" )
<< QStringLiteral( "\t[--nocustomization]\tdon't apply GUI customization\n" )
<< QStringLiteral( "\t[--customizationfile path]\tuse the given ini file as GUI customization\n" )
<< QStringLiteral( "\t[--globalsettingsfile path]\tuse the given ini file as Global Settings (defaults)\n" )
<< QStringLiteral( "\t[--authdbdirectory path] use the given directory for authentication database\n" )
<< QStringLiteral( "\t[--code path]\trun the given python file on load\n" )
<< QStringLiteral( "\t[--defaultui]\tstart by resetting user ui settings to default\n" )
<< QStringLiteral( "\t[--hide-browser]\thide the browser widget\n" )
<< QStringLiteral( "\t[--dxf-export filename.dxf]\temit dxf output of loaded datasets to given file\n" )
<< QStringLiteral( "\t[--dxf-extent xmin,ymin,xmax,ymax]\tset extent to export to dxf\n" )
<< QStringLiteral( "\t[--dxf-symbology-mode none|symbollayer|feature]\tsymbology mode for dxf output\n" )
<< QStringLiteral( "\t[--dxf-scale-denom scale]\tscale for dxf output\n" )
<< QStringLiteral( "\t[--dxf-encoding encoding]\tencoding to use for dxf output\n" )
<< QStringLiteral( "\t[--dxf-map-theme maptheme]\tmap theme to use for dxf output\n" )
<< QStringLiteral( "\t[--take-screenshots output_path]\ttake screen shots for the user documentation\n" )
<< QStringLiteral( "\t[--screenshots-categories categories]\tspecify the categories of screenshot to be used (see QgsAppScreenShots::Categories).\n" )
<< QStringLiteral( "\t[--profile name]\tload a named profile from the users profiles folder.\n" )
<< QStringLiteral( "\t[--profiles-path path]\tpath to store user profile folders. Will create profiles inside a {path}\\profiles folder \n" )
<< QStringLiteral( "\t[--version-migration]\tforce the settings migration from older version if found\n" )
#ifdef HAVE_OPENCL
<< QStringLiteral( "\t[--openclprogramfolder]\t\tpath to the folder containing the sources for OpenCL programs.\n" )
#endif
<< QStringLiteral( "\t[--help]\t\tthis text\n" )
<< QStringLiteral( "\t[--]\t\ttreat all following arguments as FILEs\n\n" )
<< QStringLiteral( " FILE:\n" )
<< QStringLiteral( " Files specified on the command line can include rasters, vectors,\n" )
<< QStringLiteral( " QGIS layer definition files (.qlr) and QGIS project files (.qgs and .qgz): \n" )
<< QStringLiteral( " 1. Rasters - supported formats include GeoTiff, DEM \n" )
<< QStringLiteral( " and others supported by GDAL\n" )
<< QStringLiteral( " 2. Vectors - supported formats include ESRI Shapefiles\n" )
<< QStringLiteral( " and others supported by OGR and PostgreSQL layers using\n" )
<< QStringLiteral( " the PostGIS extension\n" ) ; // OK
#ifdef Q_OS_WIN
MessageBox( nullptr,
msg.join( QString() ).toLocal8Bit().constData(),
"QGIS command line options",
MB_OK );
#else
std::cout << msg.join( QString() ).toLocal8Bit().constData();
#endif
} // usage()
/////////////////////////////////////////////////////////////////
// Command line options 'behavior' flag setup
////////////////////////////////////////////////////////////////
// These two are global so that they can be set by the OpenDocuments
// AppleEvent handler as well as by the main routine argv processing
// This behavior will cause QGIS to autoload a project
static QString sProjectFileName;
// This is the 'leftover' arguments collection
static QStringList sFileList;
/* Test to determine if this program was started on Mac OS X by double-clicking
* the application bundle rather then from a command line. If clicked, argv[1]
* contains a process serial number in the form -psn_0_1234567. Don't process
* the command line arguments in this case because argv[1] confuses the processing.
*/
bool bundleclicked( int argc, char *argv[] )
{
return ( argc > 1 && memcmp( argv[1], "-psn_", 5 ) == 0 );
}
void myPrint( const char *fmt, ... )
{
va_list ap;
va_start( ap, fmt );
#if defined(Q_OS_WIN)
char buffer[1024];
vsnprintf( buffer, sizeof buffer, fmt, ap );
OutputDebugString( buffer );
#else
vfprintf( stderr, fmt, ap );
#endif
va_end( ap );
}
static void dumpBacktrace( unsigned int depth )
{
if ( depth == 0 )
depth = 20;
#ifdef QGIS_CRASH
// Below there is a bunch of operations that are not safe in multi-threaded
// environment (dup()+close() combo, wait(), juggling with file descriptors).
// Maybe some problems could be resolved with dup2() and waitpid(), but it seems
// that if the operations on descriptors are not serialized, things will get nasty.
// That's why there's this lovely mutex here...
static QMutex sMutex;
QMutexLocker locker( &sMutex );
int stderr_fd = -1;
if ( access( "/usr/bin/c++filt", X_OK ) < 0 )
{
myPrint( "Stacktrace (c++filt NOT FOUND):\n" );
}
else
{
int fd[2];
if ( pipe( fd ) == 0 && fork() == 0 )
{
close( STDIN_FILENO ); // close stdin
// stdin from pipe
if ( dup( fd[0] ) != STDIN_FILENO )
{
QgsDebugMsg( QStringLiteral( "dup to stdin failed" ) );
}
close( fd[1] ); // close writing end
execl( "/usr/bin/c++filt", "c++filt", static_cast< char * >( nullptr ) );
perror( "could not start c++filt" );
exit( 1 );
}
myPrint( "Stacktrace (piped through c++filt):\n" );
stderr_fd = dup( STDERR_FILENO );
close( fd[0] ); // close reading end
close( STDERR_FILENO ); // close stderr
// stderr to pipe
int stderr_new = dup( fd[1] );
if ( stderr_new != STDERR_FILENO )
{
if ( stderr_new >= 0 )
close( stderr_new );
QgsDebugMsg( QStringLiteral( "dup to stderr failed" ) );
}
close( fd[1] ); // close duped pipe
}
void **buffer = new void *[ depth ];
int nptrs = backtrace( buffer, depth );
backtrace_symbols_fd( buffer, nptrs, STDERR_FILENO );
delete [] buffer;
if ( stderr_fd >= 0 )
{
int status;
close( STDERR_FILENO );
int dup_stderr = dup( stderr_fd );
if ( dup_stderr != STDERR_FILENO )
{
close( dup_stderr );
QgsDebugMsg( QStringLiteral( "dup to stderr failed" ) );
}
close( stderr_fd );
wait( &status );
}
#elif defined(Q_OS_WIN)
// TODO Replace with incoming QgsStackTrace
#else
Q_UNUSED( depth )
#endif
}
#ifdef QGIS_CRASH
void qgisCrash( int signal )
{
fprintf( stderr, "QGIS died on signal %d", signal );
if ( access( "/usr/bin/gdb", X_OK ) == 0 )
{
// take full stacktrace using gdb
// http://stackoverflow.com/questions/3151779/how-its-better-to-invoke-gdb-from-program-to-print-its-stacktrace
// unfortunately, this is not so simple. the proper method is way more OS-specific
// than this code would suggest, see http://stackoverflow.com/a/1024937
char exename[512];
#if defined(__FreeBSD__)
int len = readlink( "/proc/curproc/file", exename, sizeof( exename ) - 1 );
#else
int len = readlink( "/proc/self/exe", exename, sizeof( exename ) - 1 );
#endif
if ( len < 0 )
{
myPrint( "Could not read link (%d: %s)\n", errno, strerror( errno ) );
}
else
{
exename[ len ] = 0;
char pidstr[32];
snprintf( pidstr, sizeof pidstr, "--pid=%d", getpid() );
int gdbpid = fork();
if ( gdbpid == 0 )
{
// attach, backtrace and continue
execl( "/usr/bin/gdb", "gdb", "-q", "-batch", "-n", pidstr, "-ex", "thread", "-ex", "bt full", exename, NULL );
perror( "cannot exec gdb" );
exit( 1 );
}
else if ( gdbpid >= 0 )
{
int status;
waitpid( gdbpid, &status, 0 );
myPrint( "gdb returned %d\n", status );
}
else
{
myPrint( "Cannot fork (%d: %s)\n", errno, strerror( errno ) );
dumpBacktrace( 256 );
}
}
}
abort();
}
#endif
/*
* Hook into the qWarning/qFatal mechanism so that we can channel messages
* from libpng to the user.
*
* Some JPL WMS images tend to overload the libpng 1.2.2 implementation
* somehow (especially when zoomed in)
* and it would be useful for the user to know why their picture turned up blank
*
* Based on qInstallMsgHandler example code in the Qt documentation.
*
*/
void myMessageOutput( QtMsgType type, const QMessageLogContext &, const QString &msg )
{
switch ( type )
{
case QtDebugMsg:
myPrint( "%s\n", msg.toLocal8Bit().constData() );
if ( msg.startsWith( QLatin1String( "Backtrace" ) ) )
{
const QString trace = msg.mid( 9 );
dumpBacktrace( atoi( trace.toLocal8Bit().constData() ) );
}
break;
case QtCriticalMsg:
myPrint( "Critical: %s\n", msg.toLocal8Bit().constData() );
#ifdef QGISDEBUG
dumpBacktrace( 20 );
#endif
break;
case QtWarningMsg:
{
/* Ignore:
* - libpng iCPP known incorrect SRGB profile errors (which are thrown by 3rd party components
* we have no control over and have low value anyway);
* - QtSVG warnings with regards to lack of implementation beyond Tiny SVG 1.2
*/
if ( msg.startsWith( QLatin1String( "libpng warning: iCCP: known incorrect sRGB profile" ), Qt::CaseInsensitive ) ||
msg.contains( QLatin1String( "Could not add child element to parent element because the types are incorrect" ), Qt::CaseInsensitive ) ||
msg.contains( QLatin1String( "OpenType support missing for" ), Qt::CaseInsensitive ) )
break;
myPrint( "Warning: %s\n", msg.toLocal8Bit().constData() );
#ifdef QGISDEBUG
// Print all warnings except setNamedColor.
// Only seems to happen on windows
if ( !msg.startsWith( QLatin1String( "QColor::setNamedColor: Unknown color name 'param" ), Qt::CaseInsensitive )
&& !msg.startsWith( QLatin1String( "Trying to create a QVariant instance of QMetaType::Void type, an invalid QVariant will be constructed instead" ), Qt::CaseInsensitive )
&& !msg.startsWith( QLatin1String( "Logged warning" ), Qt::CaseInsensitive ) )
{
// TODO: Verify this code in action.
dumpBacktrace( 20 );
// also be super obnoxious -- we DON'T want to allow these errors to be ignored!!
if ( QgisApp::instance() && QgisApp::instance()->messageBar() && QgisApp::instance()->thread() == QThread::currentThread() )
{
QgisApp::instance()->messageBar()->pushCritical( QStringLiteral( "Qt" ), msg );
}
else
{
QgsMessageLog::logMessage( msg, QStringLiteral( "Qt" ) );
}
}
#endif
// TODO: Verify this code in action.
if ( msg.startsWith( QLatin1String( "libpng error:" ), Qt::CaseInsensitive ) )
{
// Let the user know
QgsMessageLog::logMessage( msg, QStringLiteral( "libpng" ) );
}
break;
}
case QtFatalMsg:
{
myPrint( "Fatal: %s\n", msg.toLocal8Bit().constData() );
#ifdef QGIS_CRASH
qgisCrash( -1 );
#else
dumpBacktrace( 256 );
abort(); // deliberately dump core
#endif
break; // silence warnings
}
case QtInfoMsg:
myPrint( "Info: %s\n", msg.toLocal8Bit().constData() );
break;
}
}
#ifdef _MSC_VER
#undef APP_EXPORT
#define APP_EXPORT __declspec(dllexport)
#endif
#if defined(ANDROID) || defined(Q_OS_WIN)
// On Android, there there is a libqgis.so instead of a qgis executable.
// The main method symbol of this library needs to be exported so it can be called by java
// On Windows this main is included in qgis_app and called from mainwin.cpp
APP_EXPORT
#endif
int main( int argc, char *argv[] )
{
//log messages written before creating QgsApplication
QStringList preApplicationLogMessages;
#ifdef Q_OS_UNIX
// Increase file resource limits (i.e., number of allowed open files)
// (from code provided by Larry Biehl, Purdue University, USA, from 'MultiSpec' project)
// This is generally 256 for the soft limit on Mac
// NOTE: setrlimit() must come *before* initialization of stdio strings,
// e.g. before any debug messages, or setrlimit() gets ignored
// see: http://stackoverflow.com/a/17726104/2865523
struct rlimit rescLimit;
if ( getrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
{
const rlim_t oldSoft( rescLimit.rlim_cur );
#ifdef OPEN_MAX
rlim_t newSoft( OPEN_MAX );
#else
rlim_t newSoft( 4096 );
#endif
const char *qgisMaxFileCount = getenv( "QGIS_MAX_FILE_COUNT" );
if ( qgisMaxFileCount )
newSoft = static_cast<rlim_t>( atoi( qgisMaxFileCount ) );
if ( rescLimit.rlim_cur < newSoft || qgisMaxFileCount )
{
rescLimit.rlim_cur = std::min( newSoft, rescLimit.rlim_max );
if ( setrlimit( RLIMIT_NOFILE, &rescLimit ) == 0 )
{
QgsDebugMsg( QStringLiteral( "RLIMIT_NOFILE Soft NEW: %1 / %2" )
.arg( rescLimit.rlim_cur ).arg( rescLimit.rlim_max ) );
}
}
Q_UNUSED( oldSoft ) //avoid warnings
QgsDebugMsg( QStringLiteral( "RLIMIT_NOFILE Soft/Hard ORIG: %1 / %2" )
.arg( oldSoft ).arg( rescLimit.rlim_max ) );
}
#endif
QgsDebugMsg( QStringLiteral( "Starting qgis main" ) );
#ifdef WIN32 // Windows
#ifdef _MSC_VER
_set_fmode( _O_BINARY );
#else //MinGW
_fmode = _O_BINARY;
#endif // _MSC_VER
#endif // WIN32
// Set up the custom qWarning/qDebug custom handler
#ifndef ANDROID
qInstallMessageHandler( myMessageOutput );
#endif
#ifdef QGIS_CRASH
signal( SIGQUIT, qgisCrash );
signal( SIGILL, qgisCrash );
signal( SIGFPE, qgisCrash );
signal( SIGSEGV, qgisCrash );
signal( SIGBUS, qgisCrash );
signal( SIGSYS, qgisCrash );
signal( SIGTRAP, qgisCrash );
signal( SIGXCPU, qgisCrash );
signal( SIGXFSZ, qgisCrash );
#endif
#ifdef _MSC_VER
SetUnhandledExceptionFilter( QgsCrashHandler::handle );
#endif
// initialize random number seed
qsrand( time( nullptr ) );
/////////////////////////////////////////////////////////////////
// Command line options 'behavior' flag setup
////////////////////////////////////////////////////////////////
//
// Parse the command line arguments, looking to see if the user has asked for any
// special behaviors. Any remaining non command arguments will be kept aside to
// be passed as a list of layers and / or a project that should be loaded.
//
// This behavior is used to load the app, snapshot the map,
// save the image to disk and then exit
QString mySnapshotFileName;
QString configLocalStorageLocation;
QString profileName;
int mySnapshotWidth = 800;
int mySnapshotHeight = 600;
bool myHideSplash = false;
bool settingsMigrationForce = false;
bool mySkipVersionCheck = false;
bool hideBrowser = false;
#if defined(ANDROID)
QgsDebugMsg( QStringLiteral( "Android: Splash hidden" ) );
myHideSplash = true;
#endif
bool myRestoreDefaultWindowState = false;
bool myRestorePlugins = true;
bool myCustomization = true;
QString dxfOutputFile;
QgsDxfExport::SymbologyExport dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
double dxfScale = 50000.0;
QString dxfEncoding = QStringLiteral( "CP1252" );
QString dxfMapTheme;
QgsRectangle dxfExtent;
bool takeScreenShots = false;
QString screenShotsPath;
int screenShotsCategories = 0;
// This behavior will set initial extent of map canvas, but only if
// there are no command line arguments. This gives a usable map
// extent when qgis starts with no layers loaded. When layers are
// loaded, we let the layers define the initial extent.
QString myInitialExtent;
if ( argc == 1 )
myInitialExtent = QStringLiteral( "-1,-1,1,1" );
// This behavior will allow you to force the use of a translation file
// which is useful for testing
QString translationCode;
// The user can specify a path which will override the default path of custom
// user settings (~/.qgis) and it will be used for QgsSettings INI file
QString authdbdirectory;
QString pythonfile;
QString customizationfile;
QString globalsettingsfile;
#ifdef HAVE_OPENCL
QString openClProgramFolder;
#endif
// TODO Fix android
#if defined(ANDROID)
QgsDebugMsg( QStringLiteral( "Android: All params stripped" ) );// Param %1" ).arg( argv[0] ) );
//put all QGIS settings in the same place
QString configpath = QgsApplication::qgisSettingsDirPath();
QgsDebugMsg( QStringLiteral( "Android: configpath set to %1" ).arg( configpath ) );
#endif
QStringList args;
{
QCoreApplication coreApp( argc, argv );
( void ) QgsApplication::resolvePkgPath(); // trigger storing of application path in QgsApplication
if ( !bundleclicked( argc, argv ) )
{
// Build a local QCoreApplication from arguments. This way, arguments are correctly parsed from their native locale
// It will use QString::fromLocal8Bit( argv ) under Unix and GetCommandLine() under Windows.
args = QCoreApplication::arguments();
for ( int i = 1; i < args.size(); ++i )
{
const QString &arg = args[i];
if ( arg == QLatin1String( "--help" ) || arg == QLatin1String( "-?" ) )
{
usage( args[0] );
return EXIT_SUCCESS;
}
else if ( arg == QLatin1String( "--version" ) || arg == QLatin1String( "-v" ) )
{
version();
return EXIT_SUCCESS;
}
else if ( arg == QLatin1String( "--nologo" ) || arg == QLatin1String( "-n" ) )
{
myHideSplash = true;
}
else if ( arg == QLatin1String( "--version-migration" ) )
{
settingsMigrationForce = true;
}
else if ( arg == QLatin1String( "--noversioncheck" ) || arg == QLatin1String( "-V" ) )
{
mySkipVersionCheck = true;
}
else if ( arg == QLatin1String( "--noplugins" ) || arg == QLatin1String( "-P" ) )
{
myRestorePlugins = false;
}
else if ( arg == QLatin1String( "--nocustomization" ) || arg == QLatin1String( "-C" ) )
{
myCustomization = false;
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--profile" ) ) )
{
profileName = args[++i];
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--profiles-path" ) || arg == QLatin1String( "-s" ) ) )
{
configLocalStorageLocation = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--snapshot" ) || arg == QLatin1String( "-s" ) ) )
{
mySnapshotFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--width" ) || arg == QLatin1String( "-w" ) ) )
{
mySnapshotWidth = QString( args[++i] ).toInt();
}
else if ( arg == QLatin1String( "--hide-browser" ) )
{
hideBrowser = true;
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--height" ) || arg == QLatin1String( "-h" ) ) )
{
mySnapshotHeight = QString( args[++i] ).toInt();
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--lang" ) || arg == QLatin1String( "-l" ) ) )
{
translationCode = args[++i];
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--project" ) || arg == QLatin1String( "-p" ) ) )
{
sProjectFileName = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--extent" ) || arg == QLatin1String( "-e" ) ) )
{
myInitialExtent = args[++i];
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--authdbdirectory" ) || arg == QLatin1String( "-a" ) ) )
{
authdbdirectory = QDir::toNativeSeparators( QDir( args[++i] ).absolutePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--code" ) || arg == QLatin1String( "-f" ) ) )
{
pythonfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--customizationfile" ) || arg == QLatin1String( "-z" ) ) )
{
customizationfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( i + 1 < argc && ( arg == QLatin1String( "--globalsettingsfile" ) || arg == QLatin1String( "-g" ) ) )
{
globalsettingsfile = QDir::toNativeSeparators( QFileInfo( args[++i] ).absoluteFilePath() );
}
else if ( arg == QLatin1String( "--defaultui" ) || arg == QLatin1String( "-d" ) )
{
myRestoreDefaultWindowState = true;
}
else if ( arg == QLatin1String( "--dxf-export" ) )
{
dxfOutputFile = args[++i];
}
else if ( arg == QLatin1String( "--dxf-extent" ) )
{
QgsLocaleNumC l;
QString ext( args[++i] );
QStringList coords( ext.split( ',' ) );
if ( coords.size() != 4 )
{
std::cerr << "invalid dxf extent " << ext.toStdString() << std::endl;
return 2;
}
for ( int i = 0; i < 4; i++ )
{
bool ok;
double d;
d = coords[i].toDouble( &ok );
if ( !ok )
{
std::cerr << "invalid dxf coordinate " << coords[i].toStdString() << " in extent " << ext.toStdString() << std::endl;
return 2;
}
switch ( i )
{
case 0:
dxfExtent.setXMinimum( d );
break;
case 1:
dxfExtent.setYMinimum( d );
break;
case 2:
dxfExtent.setXMaximum( d );
break;
case 3:
dxfExtent.setYMaximum( d );
break;
}
}
}
else if ( arg == QLatin1String( "--dxf-symbology-mode" ) )
{
QString mode( args[++i] );
if ( mode == QLatin1String( "none" ) )
{
dxfSymbologyMode = QgsDxfExport::NoSymbology;
}
else if ( mode == QLatin1String( "symbollayer" ) )
{
dxfSymbologyMode = QgsDxfExport::SymbolLayerSymbology;
}
else if ( mode == QLatin1String( "feature" ) )
{
dxfSymbologyMode = QgsDxfExport::FeatureSymbology;
}
else
{
std::cerr << "invalid dxf symbology mode " << mode.toStdString() << std::endl;
return 2;
}
}
else if ( arg == QLatin1String( "--dxf-scale-denom" ) )
{
bool ok;
QString scale( args[++i] );
dxfScale = scale.toDouble( &ok );
if ( !ok )
{
std::cerr << "invalid dxf scale " << scale.toStdString() << std::endl;
return 2;
}
}
else if ( arg == QLatin1String( "--dxf-encoding" ) )
{
dxfEncoding = args[++i];
}
else if ( arg == QLatin1String( "--dxf-map-theme" ) )
{
dxfMapTheme = args[++i];
}
else if ( arg == QLatin1String( "--take-screenshots" ) )
{
takeScreenShots = true;
screenShotsPath = args[++i];
}
else if ( arg == QLatin1String( "--screenshots-categories" ) )
{
screenShotsCategories = args[++i].toInt();
}
#ifdef HAVE_OPENCL
else if ( arg == QLatin1String( "--openclprogramfolder" ) )
{
openClProgramFolder = args[++i];
}
#endif
else if ( arg == QLatin1String( "--" ) )
{
for ( i++; i < args.size(); ++i )
sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
}
else
{
sFileList.append( QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() ) );
}
}
}
}
/////////////////////////////////////////////////////////////////////
// If no --project was specified, parse the args to look for a //
// .qgs file and set myProjectFileName to it. This allows loading //
// of a project file by clicking on it in various desktop managers //
// where an appropriate mime-type has been set up. //
/////////////////////////////////////////////////////////////////////
if ( sProjectFileName.isEmpty() )
{
// check for a .qgs/z
for ( int i = 0; i < args.size(); i++ )
{
QString arg = QDir::toNativeSeparators( QFileInfo( args[i] ).absoluteFilePath() );
if ( arg.endsWith( QLatin1String( ".qgs" ), Qt::CaseInsensitive ) ||
arg.endsWith( QLatin1String( ".qgz" ), Qt::CaseInsensitive ) )
{
sProjectFileName = arg;
break;
}
}
}
/////////////////////////////////////////////////////////////////////
// Now we have the handlers for the different behaviors...
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// Initialize the application and the translation stuff
/////////////////////////////////////////////////////////////////////
#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC) && !defined(ANDROID)
bool myUseGuiFlag = nullptr != getenv( "DISPLAY" );
#else
bool myUseGuiFlag = true;
#endif
if ( !myUseGuiFlag )
{
std::cerr << QObject::tr(
"QGIS starting in non-interactive mode not supported.\n"
"You are seeing this message most likely because you "
"have no DISPLAY environment variable set.\n"
).toUtf8().constData();
exit( 1 ); //exit for now until a version of qgis is capable of running non interactive
}
// GUI customization is enabled according to settings (loaded when instance is created)
// we force disabled here if --nocustomization argument is used
if ( !myCustomization )
{
QgsCustomization::instance()->setEnabled( false );
}
QCoreApplication::setOrganizationName( QgsApplication::QGIS_ORGANIZATION_NAME );
QCoreApplication::setOrganizationDomain( QgsApplication::QGIS_ORGANIZATION_DOMAIN );
QCoreApplication::setApplicationName( QgsApplication::QGIS_APPLICATION_NAME );
QCoreApplication::setAttribute( Qt::AA_DontShowIconsInMenus, false );
QCoreApplication::setAttribute( Qt::AA_DisableWindowContextHelpButton, true );
// Set up an OpenGL Context to be shared between threads beforehand
// for plugins that depend on Qt WebEngine module.
// As suggested by Qt documentation at:
// - https://doc.qt.io/qt-5/qtwebengine.html
// - https://code.qt.io/cgit/qt/qtwebengine.git/plain/src/webenginewidgets/api/qtwebenginewidgetsglobal.cpp
#if defined(QT_OS_WIN) && !defined(QT_NO_OPENGL)
QCoreApplication::setAttribute( Qt::AA_ShareOpenGLContexts, true );
#endif
// Set up the QgsSettings Global Settings:
// - use the path specified with --globalsettingsfile path,
// - use the environment if not found
// - use the AppDataLocation ($HOME/.local/share/QGIS/QGIS3 on Linux, roaming path on Windows)
// - use a default location as a fallback
if ( globalsettingsfile.isEmpty() )
{
globalsettingsfile = getenv( "QGIS_GLOBAL_SETTINGS_FILE" );
}
if ( globalsettingsfile.isEmpty() )
{
QStringList startupPaths = QStandardPaths::locateAll( QStandardPaths::AppDataLocation, QStringLiteral( "qgis_global_settings.ini" ) );
if ( !startupPaths.isEmpty() )
{
globalsettingsfile = startupPaths.at( 0 );
}
}
if ( globalsettingsfile.isEmpty() )
{
QString default_globalsettingsfile = QgsApplication::resolvePkgPath() + "/resources/qgis_global_settings.ini";
if ( QFile::exists( default_globalsettingsfile ) )
{
globalsettingsfile = default_globalsettingsfile;
}
}
if ( !globalsettingsfile.isEmpty() )
{
if ( !QgsSettings::setGlobalSettingsPath( globalsettingsfile ) )
{
preApplicationLogMessages << QObject::tr( "Invalid globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" );
}
else
{
preApplicationLogMessages << QObject::tr( "Successfully loaded globalsettingsfile path: %1" ).arg( globalsettingsfile ), QStringLiteral( "QGIS" );
}
}
if ( configLocalStorageLocation.isEmpty() )
{
QSettings globalSettings( globalsettingsfile, QSettings::IniFormat );
if ( getenv( "QGIS_CUSTOM_CONFIG_PATH" ) )
{
configLocalStorageLocation = getenv( "QGIS_CUSTOM_CONFIG_PATH" );
}
else if ( globalSettings.contains( QStringLiteral( "core/profilesPath" ) ) )
{
configLocalStorageLocation = globalSettings.value( QStringLiteral( "core/profilesPath" ), "" ).toString();
QgsDebugMsg( QStringLiteral( "Loading profiles path from global config at %1" ).arg( configLocalStorageLocation ) );
}
// If it is still empty at this point we get it from the standard location.
if ( configLocalStorageLocation.isEmpty() )
{
configLocalStorageLocation = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation ).value( 0 );
}
}
QString rootProfileFolder = QgsUserProfileManager::resolveProfilesFolder( configLocalStorageLocation );
QgsUserProfileManager manager( rootProfileFolder );
QgsUserProfile *profile = manager.getProfile( profileName, true );
QString profileFolder = profile->folder();
profileName = profile->name();
delete profile;
{
/* Translation file for QGIS.
*/
QString myUserTranslation = QgsApplication::settingsLocaleUserLocale.value();
QString myGlobalLocale = QgsApplication::settingsLocaleGlobalLocale.value();
bool myShowGroupSeparatorFlag = false; // Default to false
bool myLocaleOverrideFlag = QgsApplication::settingsLocaleOverrideFlag.value();
// Override Show Group Separator if the global override flag is set
if ( myLocaleOverrideFlag )
{
// Default to false again
myShowGroupSeparatorFlag = QgsApplication::settingsLocaleShowGroupSeparator.value();
}
//
// Priority of translation is:
// - command line
// - user specified in options dialog (with group checked on)
// - system locale
//
// When specifying from the command line it will change the user
// specified user locale
//
if ( !translationCode.isNull() && !translationCode.isEmpty() )
{
QgsApplication::settingsLocaleUserLocale.setValue( translationCode );
}
else
{
if ( !myLocaleOverrideFlag || myUserTranslation.isEmpty() )
{
translationCode = QLocale().name();
//setting the locale/userLocale when the --lang= option is not set will allow third party
//plugins to always use the same locale as the QGIS, otherwise they can be out of sync
QgsApplication::settingsLocaleUserLocale.setValue( translationCode );
}
else
{
translationCode = myUserTranslation;
}
}
// Global locale settings
if ( myLocaleOverrideFlag && ! myGlobalLocale.isEmpty( ) )
{
QLocale currentLocale( myGlobalLocale );
QLocale::setDefault( currentLocale );
}
// Number settings
QLocale currentLocale;
if ( myShowGroupSeparatorFlag )
{
currentLocale.setNumberOptions( currentLocale.numberOptions() &= ~QLocale::NumberOption::OmitGroupSeparator );
}
else
{
currentLocale.setNumberOptions( currentLocale.numberOptions() |= QLocale::NumberOption::OmitGroupSeparator );
}
QLocale::setDefault( currentLocale );
// Date time settings
QgsDateTimeFieldFormatter::applyLocaleChange();
QgsApplication::setTranslation( translationCode );
}
QgsApplication myApp( argc, argv, myUseGuiFlag );
//write the log messages written before creating QgsApplication
for ( const QString &preApplicationLogMessage : std::as_const( preApplicationLogMessages ) )
QgsMessageLog::logMessage( preApplicationLogMessage );
// Settings migration is only supported on the default profile for now.
if ( profileName == QLatin1String( "default" ) )
{
// Note: this flag is ka version number so that we can reset it once we change the version.
// Note2: Is this a good idea can we do it better.
// Note3: Updated to only show if we have a migration from QGIS 2 - see https://github.com/qgis/QGIS/pull/38616
QString path = QSettings( "QGIS", "QGIS2" ).fileName() ;
if ( QFile::exists( path ) )
{
QgsSettings migSettings;
int firstRunVersion = migSettings.value( QStringLiteral( "migration/firstRunVersionFlag" ), 0 ).toInt();
bool showWelcome = ( firstRunVersion == 0 || Qgis::versionInt() > firstRunVersion );
std::unique_ptr< QgsVersionMigration > migration( QgsVersionMigration::canMigrate( 20000, Qgis::versionInt() ) );
if ( migration && ( settingsMigrationForce || migration->requiresMigration() ) )
{
bool runMigration = true;
if ( !settingsMigrationForce && showWelcome )
{
QgsFirstRunDialog dlg;
dlg.exec();
runMigration = dlg.migrateSettings();
migSettings.setValue( QStringLiteral( "migration/firstRunVersionFlag" ), Qgis::versionInt() );
}
if ( runMigration )
{
QgsDebugMsg( QStringLiteral( "RUNNING MIGRATION" ) );
migration->runMigration();
}
}
}
}
// We can't use QgsSettings until this point because the format and
// folder isn't set until profile is fetch.
// Should be cleaned up in future to make this cleaner.
QgsSettings settings;
QgsDebugMsgLevel( QStringLiteral( "User profile details:" ), 2 );
QgsDebugMsgLevel( QStringLiteral( "\t - %1" ).arg( profileName ), 2 );
QgsDebugMsgLevel( QStringLiteral( "\t - %1" ).arg( profileFolder ), 2 );
QgsDebugMsgLevel( QStringLiteral( "\t - %1" ).arg( rootProfileFolder ), 2 );
myApp.init( profileFolder );
// Redefine QgsApplication::libraryPaths as necessary.
// IMPORTANT: Do *after* QgsApplication myApp(...), but *before* Qt uses any plugins,
// e.g. loading splash screen, setting window icon, etc.
// Always honor QT_PLUGIN_PATH env var or qt.conf, which will
// be part of libraryPaths just after QgsApplication creation.
#ifdef Q_OS_WIN
// For non static builds on win (static builds are not supported)
// we need to be sure we can find the qt image plugins.
QCoreApplication::addLibraryPath( QApplication::applicationDirPath()
+ QDir::separator() + "qtplugins" );
#endif
#if defined(Q_OS_UNIX)
// Resulting libraryPaths has critical QGIS plugin paths first, then any Qt plugin paths, then
// any dev-defined paths (in app's qt.conf) and/or user-defined paths (QT_PLUGIN_PATH env var).
//
// NOTE: Minimizes, though does not fully protect against, crashes due to dev/user-defined libs
// built against a different Qt/QGIS, while still allowing custom C++ plugins to load.
QStringList libPaths( QCoreApplication::libraryPaths() );
QgsDebugMsgLevel( QStringLiteral( "Initial macOS/UNIX QCoreApplication::libraryPaths: %1" )
.arg( libPaths.join( " " ) ), 4 );
// Strip all critical paths that should always be prepended
if ( libPaths.removeAll( QDir::cleanPath( QgsApplication::pluginPath() ) ) )
{
QgsDebugMsgLevel( QStringLiteral( "QgsApplication::pluginPath removed from initial libraryPaths" ), 4 );
}
if ( libPaths.removeAll( QCoreApplication::applicationDirPath() ) )
{
QgsDebugMsgLevel( QStringLiteral( "QCoreApplication::applicationDirPath removed from initial libraryPaths" ), 4 );
}
// Prepend path, so a standard Qt bundle directory is parsed
QgsDebugMsgLevel( QStringLiteral( "Prepending QCoreApplication::applicationDirPath to libraryPaths" ), 4 );
libPaths.prepend( QCoreApplication::applicationDirPath() );
// Check if we are running in a 'release' app bundle, i.e. contains copied-in
// standard Qt-specific plugin subdirectories (ones never created by QGIS, e.g. 'sqldrivers' is).
// Note: bundleclicked(...) is inadequate to determine which *type* of bundle was opened, e.g. release or build dir.
// An app bundled with QGIS_MACAPP_BUNDLE > 0 is considered a release bundle.
QString relLibPath( QDir::cleanPath( QCoreApplication::applicationDirPath().append( "/../PlugIns" ) ) );
// Note: relLibPath becomes the defacto QT_PLUGINS_DIR of a release app bundle
if ( QFile::exists( relLibPath + QStringLiteral( "/imageformats" ) ) )
{
// We are in a release app bundle.
// Strip QT_PLUGINS_DIR because it will crash a launched release app bundle, since
// the appropriate Qt frameworks and plugins have been copied into the bundle.
if ( libPaths.removeAll( QT_PLUGINS_DIR ) )
{
QgsDebugMsgLevel( QStringLiteral( "QT_PLUGINS_DIR removed from initial libraryPaths" ), 4 );
}
// Prepend the Plugins path, so copied-in Qt plugin bundle directories are parsed.
QgsDebugMsgLevel( QStringLiteral( "Prepending <bundle>/Plugins to libraryPaths" ), 4 );
libPaths.prepend( relLibPath );
// TODO: see if this or another method can be used to avoid QCA's install prefix plugins
// from being parsed and loaded (causes multi-Qt-loaded errors when bundled Qt should
// be the only one loaded). QCA core (> v2.1.3) needs an update first.
//setenv( "QCA_PLUGIN_PATH", relLibPath.toUtf8().constData(), 1 );
}
else
{
// We are either running from build dir bundle, or launching Mach-O binary directly. //#spellok
// Add system Qt plugins, since they are not bundled, and not always referenced by default.
// An app bundled with QGIS_MACAPP_BUNDLE = 0 will still have Plugins/qgis in it.
// Note: Don't always prepend.
// User may have already defined it in QT_PLUGIN_PATH in a specific order.
if ( !libPaths.contains( QT_PLUGINS_DIR ) )
{
QgsDebugMsgLevel( QStringLiteral( "Prepending QT_PLUGINS_DIR to libraryPaths" ), 4 );
libPaths.prepend( QT_PLUGINS_DIR );
}
}
QgsDebugMsgLevel( QStringLiteral( "Prepending QgsApplication::pluginPath to libraryPaths" ), 4 );
libPaths.prepend( QDir::cleanPath( QgsApplication::pluginPath() ) );
// Redefine library search paths.
QCoreApplication::setLibraryPaths( libPaths );
QgsDebugMsgLevel( QStringLiteral( "Rewritten macOS QCoreApplication::libraryPaths: %1" )
.arg( QCoreApplication::libraryPaths().join( " " ) ), 4 );
#endif
#ifdef Q_OS_MAC
// Set hidpi icons; use SVG icons, as PNGs will be relatively too small
QCoreApplication::setAttribute( Qt::AA_UseHighDpiPixmaps );
// Set 1024x1024 icon for dock, app switcher, etc., rendering
myApp.setWindowIcon( QIcon( QgsApplication::iconsPath() + QStringLiteral( "qgis-icon-macos.png" ) ) );
#else
myApp.setWindowIcon( QIcon( QgsApplication::appIconPath() ) );
#endif
// TODO: use QgsSettings
QSettings *customizationsettings = nullptr;
if ( !customizationfile.isEmpty() )
{
// Using the customizationfile option always overrides the option and config path options.
QgsCustomization::instance()->setEnabled( true );
}
else
{
// Use the default file location
customizationfile = profileFolder + QDir::separator() + QStringLiteral( "QGIS" ) + QDir::separator() + QStringLiteral( "QGISCUSTOMIZATION3.ini" ) ;
}
customizationsettings = new QSettings( customizationfile, QSettings::IniFormat );
// Load and set possible default customization, must be done after QgsApplication init and QgsSettings ( QCoreApplication ) init
QgsCustomization::instance()->setSettings( customizationsettings );
QgsCustomization::instance()->loadDefault();
#ifdef Q_OS_MACX
if ( !getenv( "GDAL_DRIVER_PATH" ) )
{
// If the GDAL plugins are bundled with the application and GDAL_DRIVER_PATH
// is not already defined, use the GDAL plugins in the application bundle.
QString gdalPlugins( QCoreApplication::applicationDirPath().append( "/lib/gdalplugins" ) );
if ( QFile::exists( gdalPlugins ) )
{
setenv( "GDAL_DRIVER_PATH", gdalPlugins.toUtf8(), 1 );
}
}
// Point GDAL_DATA at any GDAL share directory embedded in the app bundle
if ( !getenv( "GDAL_DATA" ) )
{
QStringList gdalShares;
gdalShares << QCoreApplication::applicationDirPath().append( "/share/gdal" )
<< QDir::cleanPath( QgsApplication::pkgDataPath() ).append( "/share/gdal" )
<< QDir::cleanPath( QgsApplication::pkgDataPath() ).append( "/gdal" );
const auto constGdalShares = gdalShares;
for ( const QString &gdalShare : constGdalShares )
{
if ( QFile::exists( gdalShare ) )
{
setenv( "GDAL_DATA", gdalShare.toUtf8().constData(), 1 );
break;
}
}
}
// Point PYTHONHOME to embedded interpreter if present in the bundle
if ( !getenv( "PYTHONHOME" ) )
{
if ( QFile::exists( QCoreApplication::applicationDirPath().append( "/bin/python3" ) ) )
{
setenv( "PYTHONHOME", QCoreApplication::applicationDirPath().toUtf8().constData(), 1 );
}
}
#endif
// custom environment variables
QMap<QString, QString> systemEnvVars = QgsApplication::systemEnvVars();
bool useCustomVars = settings.value( QStringLiteral( "qgis/customEnvVarsUse" ), QVariant( false ) ).toBool();
if ( useCustomVars )
{
QStringList customVarsList = settings.value( QStringLiteral( "qgis/customEnvVars" ), "" ).toStringList();
if ( !customVarsList.isEmpty() )
{
const auto constCustomVarsList = customVarsList;
for ( const QString &varStr : constCustomVarsList )
{
int pos = varStr.indexOf( QLatin1Char( '|' ) );
if ( pos == -1 )
continue;
QString envVarApply = varStr.left( pos );
QString varStrNameValue = varStr.mid( pos + 1 );
pos = varStrNameValue.indexOf( QLatin1Char( '=' ) );
if ( pos == -1 )
continue;
QString envVarName = varStrNameValue.left( pos );
QString envVarValue = varStrNameValue.mid( pos + 1 );
if ( systemEnvVars.contains( envVarName ) )
{
if ( envVarApply == QLatin1String( "prepend" ) )
{
envVarValue += systemEnvVars.value( envVarName );
}
else if ( envVarApply == QLatin1String( "append" ) )
{
envVarValue = systemEnvVars.value( envVarName ) + envVarValue;
}
}
if ( systemEnvVars.contains( envVarName ) && envVarApply == QLatin1String( "unset" ) )
{
#ifdef Q_OS_WIN
putenv( envVarName.toUtf8().constData() );
#else
unsetenv( envVarName.toUtf8().constData() );
#endif
}
else
{
#ifdef Q_OS_WIN
if ( envVarApply != "undefined" || !getenv( envVarName.toUtf8().constData() ) )
putenv( QString( "%1=%2" ).arg( envVarName ).arg( envVarValue ).toUtf8().constData() );
#else
setenv( envVarName.toUtf8().constData(), envVarValue.toUtf8().constData(), envVarApply == QLatin1String( "undefined" ) ? 0 : 1 );
#endif
}
}
}
}
#ifdef QGISDEBUG
QgsFontUtils::loadStandardTestFonts( QStringList() << QStringLiteral( "Roman" ) << QStringLiteral( "Bold" ) );
#endif
// Set the application style. If it's not set QT will use the platform style except on Windows
// as it looks really ugly so we use QPlastiqueStyle.
QString desiredStyle = settings.value( QStringLiteral( "qgis/style" ) ).toString();
const QString theme = settings.value( QStringLiteral( "UI/UITheme" ) ).toString();
if ( theme != QLatin1String( "default" ) )
{
if ( QStyleFactory::keys().contains( QStringLiteral( "fusion" ), Qt::CaseInsensitive ) )
{
desiredStyle = QStringLiteral( "fusion" );
}
}
const QString activeStyleName = QApplication::style()->metaObject()->className();
if ( desiredStyle.contains( QLatin1String( "adwaita" ), Qt::CaseInsensitive )
|| ( desiredStyle.isEmpty() && activeStyleName.contains( QLatin1String( "adwaita" ), Qt::CaseInsensitive ) ) )
{
//never allow Adwaita themes - the Qt variants of these are VERY broken
//for apps like QGIS. E.g. oversized controls like spinbox widgets prevent actually showing
//any content in these widgets, leaving a very bad impression of QGIS
//note... we only do this if there's a known good style available (fusion), as SOME
//style choices can cause Qt apps to crash...
if ( QStyleFactory::keys().contains( QStringLiteral( "fusion" ), Qt::CaseInsensitive ) )
{
desiredStyle = QStringLiteral( "fusion" );
}
}
if ( !desiredStyle.isEmpty() )
{
QApplication::setStyle( new QgsAppStyle( desiredStyle ) );
if ( activeStyleName != desiredStyle )
settings.setValue( QStringLiteral( "qgis/style" ), desiredStyle );
}
else
{
// even if user has not set a style, we need to override the application style with the QgsAppStyle proxy
// based on the default style (or we miss custom style tweaks)
QApplication::setStyle( new QgsAppStyle( activeStyleName ) );
}
// set authentication database directory
if ( !authdbdirectory.isEmpty() )
{
QgsApplication::setAuthDatabaseDirPath( authdbdirectory );
}
//set up splash screen
QString mySplashPath( QgsCustomization::instance()->splashPath() );
QPixmap myPixmap( mySplashPath + QStringLiteral( "splash.png" ) );
int w = 600 * qApp->desktop()->logicalDpiX() / 96;
int h = 300 * qApp->desktop()->logicalDpiY() / 96;
QSplashScreen *mypSplash = new QSplashScreen( myPixmap.scaled( w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation ) );
if ( !takeScreenShots && !myHideSplash && !settings.value( QStringLiteral( "qgis/hideSplash" ) ).toBool() )
{
//for win and linux we can just automask and png transparency areas will be used
mypSplash->setMask( myPixmap.mask() );
mypSplash->show();
}
// optionally restore default window state
// use restoreDefaultWindowState setting only if NOT using command line (then it is set already)
if ( myRestoreDefaultWindowState || settings.value( QStringLiteral( "qgis/restoreDefaultWindowState" ), false ).toBool() )
{
QgsDebugMsg( QStringLiteral( "Resetting /UI/state settings!" ) );
settings.remove( QStringLiteral( "/UI/state" ) );
settings.remove( QStringLiteral( "/qgis/restoreDefaultWindowState" ) );
}
if ( hideBrowser )
{
if ( settings.value( QStringLiteral( "/Windows/Data Source Manager/tab" ) ).toInt() == 0 )
settings.setValue( QStringLiteral( "/Windows/Data Source Manager/tab" ), 1 );
settings.setValue( QStringLiteral( "/UI/hidebrowser" ), true );
}
// set max. thread count
// this should be done in QgsApplication::init() but it doesn't know the settings dir.
QgsApplication::setMaxThreads( settings.value( QStringLiteral( "qgis/max_threads" ), -1 ).toInt() );
QgisApp *qgis = new QgisApp( mypSplash, myRestorePlugins, mySkipVersionCheck, rootProfileFolder, profileName ); // "QgisApp" used to find canonical instance
qgis->setObjectName( QStringLiteral( "QgisApp" ) );
myApp.connect(
&myApp, SIGNAL( preNotify( QObject *, QEvent *, bool * ) ),
//qgis, SLOT( preNotify( QObject *, QEvent *))
QgsCustomization::instance(), SLOT( preNotify( QObject *, QEvent *, bool * ) )
);
/////////////////////////////////////////////////////////////////////
// Load a project file if one was specified
/////////////////////////////////////////////////////////////////////
if ( ! sProjectFileName.isEmpty() )
{
// in case the project contains broken layers, interactive
// "Handle Bad Layers" is displayed that could be blocked by splash screen
mypSplash->hide();
qgis->openProject( sProjectFileName );
}
/////////////////////////////////////////////////////////////////////
// autoload any file names that were passed in on the command line
/////////////////////////////////////////////////////////////////////
for ( const QString &layerName : std::as_const( sFileList ) )
{
QgsDebugMsg( QStringLiteral( "Trying to load file : %1" ).arg( layerName ) );
// don't load anything with a .qgs extension - these are project files
if ( layerName.endsWith( QLatin1String( ".qgs" ), Qt::CaseInsensitive ) ||
layerName.endsWith( QLatin1String( ".qgz" ), Qt::CaseInsensitive ) ||
QgsZipUtils::isZipFile( layerName ) )
{
continue;
}
else if ( layerName.endsWith( QLatin1String( ".qlr" ), Qt::CaseInsensitive ) )
{
qgis->openLayerDefinition( layerName );
}
else
{
qgis->openLayer( layerName );
}
}
/////////////////////////////////////////////////////////////////////
// Set initial extent if requested
/////////////////////////////////////////////////////////////////////
if ( ! myInitialExtent.isEmpty() )
{
QgsLocaleNumC l;
double coords[4];
int pos, posOld = 0;
bool ok = true;
// parse values from string
// extent is defined by string "xmin,ymin,xmax,ymax"
for ( int i = 0; i < 3; i++ )
{
// find comma and get coordinate
pos = myInitialExtent.indexOf( ',', posOld );
if ( pos == -1 )
{
ok = false;
break;
}
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 2)
coords[i] = myInitialExtent.midRef( posOld, pos - posOld ).toDouble( &ok );
#else
coords[i] = QStringView {myInitialExtent}.mid( posOld, pos - posOld ).toDouble( &ok );
#endif
if ( !ok )
break;
posOld = pos + 1;
}
// parse last coordinate
if ( ok )
{
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 2)
coords[3] = myInitialExtent.midRef( posOld ).toDouble( &ok );
#else
coords[3] = QStringView {myInitialExtent}.mid( posOld ).toDouble( &ok );
#endif
}
if ( !ok )
{
QgsDebugMsg( QStringLiteral( "Error while parsing initial extent!" ) );
}
else
{
// set extent from parsed values
QgsRectangle rect( coords[0], coords[1], coords[2], coords[3] );
qgis->setExtent( rect );
}
}
if ( !pythonfile.isEmpty() )
{
#ifdef Q_OS_WIN
//replace backslashes with forward slashes
pythonfile.replace( '\\', '/' );
#endif
QgsPythonRunner::run( QStringLiteral( "with open('%1','r') as f: exec(f.read())" ).arg( pythonfile ) );
}
/////////////////////////////////`////////////////////////////////////
// Take a snapshot of the map view then exit if snapshot mode requested
/////////////////////////////////////////////////////////////////////
if ( !mySnapshotFileName.isEmpty() )
{
/*You must have at least one paintEvent() delivered for the window to be
rendered properly.
It looks like you don't run the event loop in non-interactive mode, so the
event is never occurring.
To achieve this without running the event loop: show the window, then call
qApp->processEvents(), grab the pixmap, save it, hide the window and exit.
*/
//qgis->show();
myApp.processEvents();
QPixmap *myQPixmap = new QPixmap( mySnapshotWidth, mySnapshotHeight );
myQPixmap->fill();
qgis->saveMapAsImage( mySnapshotFileName, myQPixmap );
myApp.processEvents();
qgis->hide();
return 1;
}
if ( !dxfOutputFile.isEmpty() )
{
qgis->hide();
QgsDxfExport dxfExport;
dxfExport.setSymbologyScale( dxfScale );
dxfExport.setSymbologyExport( dxfSymbologyMode );
dxfExport.setExtent( dxfExtent );
QStringList layerIds;
QList< QgsDxfExport::DxfLayer > layers;
if ( !dxfMapTheme.isEmpty() )
{
const auto constMapThemeVisibleLayers = QgsProject::instance()->mapThemeCollection()->mapThemeVisibleLayers( dxfMapTheme );
for ( QgsMapLayer *layer : constMapThemeVisibleLayers )
{
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( layer );
if ( !vl )
continue;
layers << QgsDxfExport::DxfLayer( vl );
layerIds << vl->id();
}
}
else
{
const auto constMapLayers = QgsProject::instance()->mapLayers();
for ( QgsMapLayer *ml : constMapLayers )
{
QgsVectorLayer *vl = qobject_cast<QgsVectorLayer *>( ml );
if ( !vl )
continue;
layers << QgsDxfExport::DxfLayer( vl );
layerIds << vl->id();
}
}
if ( !layers.isEmpty() )
{
dxfExport.addLayers( layers );
}
QFile dxfFile;
if ( dxfOutputFile == QLatin1String( "-" ) )
{
if ( !dxfFile.open( stdout, QIODevice::WriteOnly | QIODevice::Truncate ) )
{
std::cerr << "could not open stdout" << std::endl;
return 2;
}
}
else
{
if ( !dxfOutputFile.endsWith( QLatin1String( ".dxf" ), Qt::CaseInsensitive ) )
dxfOutputFile += QLatin1String( ".dxf" );
dxfFile.setFileName( dxfOutputFile );
}
QgsDxfExport::ExportResult res = dxfExport.writeToFile( &dxfFile, dxfEncoding );
switch ( res )
{
case QgsDxfExport::ExportResult::Success:
break;
case QgsDxfExport::ExportResult::DeviceNotWritableError:
std::cerr << "dxf output failed, the device is not wriable" << std::endl;
break;
case QgsDxfExport::ExportResult::InvalidDeviceError:
std::cerr << "dxf output failed, the device is invalid" << std::endl;
break;
case QgsDxfExport::ExportResult::EmptyExtentError:
std::cerr << "dxf output failed, the extent could not be determined" << std::endl;
break;
}
delete qgis;
return static_cast<int>( res );
}
// make sure we don't have a dirty blank project after launch
QgsProject::instance()->setDirty( false );
#ifdef HAVE_OPENCL
// Overrides the OpenCL path to the folder containing the programs
// - use the path specified with --openclprogramfolder,
// - use the environment QGIS_OPENCL_PROGRAM_FOLDER if not found
// - use a default location as a fallback (this is set in QgsApplication initialization)
if ( openClProgramFolder.isEmpty() )
{
openClProgramFolder = getenv( "QGIS_OPENCL_PROGRAM_FOLDER" );
}
if ( ! openClProgramFolder.isEmpty() )
{
QgsOpenClUtils::setSourcePath( openClProgramFolder );
}
#endif
if ( takeScreenShots )
{
qgis->takeAppScreenShots( screenShotsPath, screenShotsCategories );
}
/////////////////////////////////////////////////////////////////////
// Continue on to interactive gui...
/////////////////////////////////////////////////////////////////////
qgis->show();
myApp.connect( &myApp, SIGNAL( lastWindowClosed() ), &myApp, SLOT( quit() ) );
mypSplash->finish( qgis );
delete mypSplash;
qgis->completeInitialization();
#if defined(ANDROID)
// fix for Qt Ministro hiding app's menubar in favor of native Android menus
qgis->menuBar()->setNativeMenuBar( false );
qgis->menuBar()->setVisible( true );
#endif
#if !defined(Q_OS_WIN)
UnixSignalWatcher sigwatch;
sigwatch.watchForSignal( SIGINT );
QObject::connect( &sigwatch, &UnixSignalWatcher::unixSignal, &myApp, [&myApp ]( int signal )
{
switch ( signal )
{
case SIGINT:
myApp.exit( 1 );
break;
default:
break;
}
} );
#endif
int retval = myApp.exec();
delete qgis;
return retval;
}
|
jgrocha/QGIS
|
src/app/main.cpp
|
C++
|
gpl-2.0
| 60,258 |
/***************************************************************************
modifyconstraintbreaktimesform.cpp - description
-------------------
begin : Feb 10, 2005
copyright : (C) 2005 by Lalescu Liviu
email : Please see http://lalescu.ro/liviu/ for details about contacting Liviu Lalescu (in particular, you can find here the e-mail address)
***************************************************************************/
/***************************************************************************
* *
* 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 <QMessageBox>
#include "tablewidgetupdatebug.h"
#include "modifyconstraintbreaktimesform.h"
#include "timeconstraint.h"
#include <QHeaderView>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QBrush>
#include <QColor>
#define YES (QString("X"))
#define NO (QString(" "))
ModifyConstraintBreakTimesForm::ModifyConstraintBreakTimesForm(QWidget* parent, ConstraintBreakTimes* ctr): QDialog(parent)
{
setupUi(this);
okPushButton->setDefault(true);
connect(okPushButton, SIGNAL(clicked()), this, SLOT(ok()));
connect(cancelPushButton, SIGNAL(clicked()), this, SLOT(cancel()));
connect(notAllowedTimesTable, SIGNAL(itemClicked(QTableWidgetItem*)), this, SLOT(itemClicked(QTableWidgetItem*)));
connect(setAllAllowedPushButton, SIGNAL(clicked()), this, SLOT(setAllAllowed()));
connect(setAllBreakPushButton, SIGNAL(clicked()), this, SLOT(setAllBreak()));
centerWidgetOnScreen(this);
restoreFETDialogGeometry(this);
this->_ctr=ctr;
weightLineEdit->setText(CustomFETString::number(ctr->weightPercentage));
notAllowedTimesTable->setRowCount(gt.rules.nHoursPerDay);
notAllowedTimesTable->setColumnCount(gt.rules.nDaysPerWeek);
for(int j=0; j<gt.rules.nDaysPerWeek; j++){
QTableWidgetItem* item=new QTableWidgetItem(gt.rules.daysOfTheWeek[j]);
notAllowedTimesTable->setHorizontalHeaderItem(j, item);
}
for(int i=0; i<gt.rules.nHoursPerDay; i++){
QTableWidgetItem* item=new QTableWidgetItem(gt.rules.hoursOfTheDay[i]);
notAllowedTimesTable->setVerticalHeaderItem(i, item);
}
//bool currentMatrix[MAX_HOURS_PER_DAY][MAX_DAYS_PER_WEEK];
Matrix2D<bool> currentMatrix;
currentMatrix.resize(gt.rules.nHoursPerDay, gt.rules.nDaysPerWeek);
for(int i=0; i<gt.rules.nHoursPerDay; i++)
for(int j=0; j<gt.rules.nDaysPerWeek; j++)
currentMatrix[i][j]=false;
assert(ctr->days.count()==ctr->hours.count());
for(int k=0; k<ctr->days.count(); k++){
if(ctr->hours.at(k)==-1 || ctr->days.at(k)==-1)
assert(0);
int i=ctr->hours.at(k);
int j=ctr->days.at(k);
if(i>=0 && i<gt.rules.nHoursPerDay && j>=0 && j<gt.rules.nDaysPerWeek)
currentMatrix[i][j]=true;
}
for(int i=0; i<gt.rules.nHoursPerDay; i++)
for(int j=0; j<gt.rules.nDaysPerWeek; j++){
QTableWidgetItem* item= new QTableWidgetItem();
item->setTextAlignment(Qt::AlignCenter);
item->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled);
notAllowedTimesTable->setItem(i, j, item);
if(!currentMatrix[i][j])
item->setText(NO);
else
item->setText(YES);
colorItem(item);
}
notAllowedTimesTable->resizeRowsToContents();
connect(notAllowedTimesTable->horizontalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(horizontalHeaderClicked(int)));
connect(notAllowedTimesTable->verticalHeader(), SIGNAL(sectionClicked(int)), this, SLOT(verticalHeaderClicked(int)));
notAllowedTimesTable->setSelectionMode(QAbstractItemView::NoSelection);
tableWidgetUpdateBug(notAllowedTimesTable);
setStretchAvailabilityTableNicely(notAllowedTimesTable);
}
ModifyConstraintBreakTimesForm::~ModifyConstraintBreakTimesForm()
{
saveFETDialogGeometry(this);
}
void ModifyConstraintBreakTimesForm::colorItem(QTableWidgetItem* item)
{
if(USE_GUI_COLORS){
if(item->text()==NO)
item->setBackground(QBrush(Qt::darkGreen));
else
item->setBackground(QBrush(Qt::darkRed));
item->setForeground(QBrush(Qt::lightGray));
}
}
void ModifyConstraintBreakTimesForm::horizontalHeaderClicked(int col)
{
if(col>=0 && col<gt.rules.nDaysPerWeek){
QString s=notAllowedTimesTable->item(0, col)->text();
if(s==YES)
s=NO;
else{
assert(s==NO);
s=YES;
}
for(int row=0; row<gt.rules.nHoursPerDay; row++){
notAllowedTimesTable->item(row, col)->setText(s);
colorItem(notAllowedTimesTable->item(row,col));
}
tableWidgetUpdateBug(notAllowedTimesTable);
}
}
void ModifyConstraintBreakTimesForm::verticalHeaderClicked(int row)
{
if(row>=0 && row<gt.rules.nHoursPerDay){
QString s=notAllowedTimesTable->item(row, 0)->text();
if(s==YES)
s=NO;
else{
assert(s==NO);
s=YES;
}
for(int col=0; col<gt.rules.nDaysPerWeek; col++){
notAllowedTimesTable->item(row, col)->setText(s);
colorItem(notAllowedTimesTable->item(row,col));
}
tableWidgetUpdateBug(notAllowedTimesTable);
}
}
void ModifyConstraintBreakTimesForm::setAllAllowed()
{
for(int i=0; i<gt.rules.nHoursPerDay; i++)
for(int j=0; j<gt.rules.nDaysPerWeek; j++){
notAllowedTimesTable->item(i, j)->setText(NO);
colorItem(notAllowedTimesTable->item(i,j));
}
tableWidgetUpdateBug(notAllowedTimesTable);
}
void ModifyConstraintBreakTimesForm::setAllBreak()
{
for(int i=0; i<gt.rules.nHoursPerDay; i++)
for(int j=0; j<gt.rules.nDaysPerWeek; j++){
notAllowedTimesTable->item(i, j)->setText(YES);
colorItem(notAllowedTimesTable->item(i,j));
}
tableWidgetUpdateBug(notAllowedTimesTable);
}
void ModifyConstraintBreakTimesForm::itemClicked(QTableWidgetItem* item)
{
QString s=item->text();
if(s==YES)
s=NO;
else{
assert(s==NO);
s=YES;
}
item->setText(s);
colorItem(item);
tableWidgetUpdateBug(notAllowedTimesTable);
}
void ModifyConstraintBreakTimesForm::ok()
{
double weight;
QString tmp=weightLineEdit->text();
weight_sscanf(tmp, "%lf", &weight);
if(weight<100.0 || weight>100.0){
QMessageBox::warning(this, tr("FET information"),
tr("Invalid weight (percentage). It has to be 100"));
return;
}
this->_ctr->weightPercentage=weight;
QList<int> days;
QList<int> hours;
for(int j=0; j<gt.rules.nDaysPerWeek; j++)
for(int i=0; i<gt.rules.nHoursPerDay; i++)
if(notAllowedTimesTable->item(i, j)->text()==YES){
days.append(j);
hours.append(i);
}
this->_ctr->days=days;
this->_ctr->hours=hours;
gt.rules.internalStructureComputed=false;
setRulesModifiedAndOtherThings(>.rules);
this->close();
}
void ModifyConstraintBreakTimesForm::cancel()
{
this->close();
}
|
vanyog/FET
|
src/interface/modifyconstraintbreaktimesform.cpp
|
C++
|
gpl-2.0
| 7,025 |
var ItemView = require('lib/config/item-view');
var hbs = require('handlebars');
var _ = require('lodash');
var tmpl = require('./buttons.hbs');
var polyglot = require('lib/utilities/polyglot');
var ButtonsBehavior = require('./behavior');
module.exports = ItemView.extend({
viewOptions: ['buttons'],
buttons: [{
action: 'save',
className: 'btn-primary'
}],
template: hbs.compile(tmpl),
initialize: function(options){
this.mergeOptions(options, this.viewOptions);
},
templateHelpers: function(){
_.each(this.buttons, function(button){
var type = button.type || 'button';
button[type] = true;
button.label = button.label || polyglot.t('buttons.' + button.action);
});
return {
buttons: this.buttons
};
},
behaviors: {
Buttons: {
behaviorClass: ButtonsBehavior
}
}
});
|
tablesmit/WooCommerce-POS
|
assets/js/src/lib/components/buttons/view.js
|
JavaScript
|
gpl-2.0
| 860 |
/**
* Functionality specific to Trope.
*
* Provides helper functions to enhance the theme experience.
*/
( function( $ ) {
var body = $( 'body' ),
_window = $( window );
/**
* Adds a top margin to the footer if the sidebar widget area is higher
* than the rest of the page, to help the footer always visually clear
* the sidebar.
*/
$( function() {
if ( body.is( '.sidebar' ) ) {
var sidebar = $( '#secondary .widget-area' ),
secondary = ( 0 === sidebar.length ) ? -40 : sidebar.height(),
margin = $( '#tertiary .widget-area' ).height() - $( '#content' ).height() - secondary;
if ( margin > 0 && _window.innerWidth() > 999 ) {
$( '#colophon' ).css( 'margin-top', margin + 'px' );
}
}
} );
/**
* Enables menu toggle for small screens.
*/
( function() {
var nav = $( '#site-navigation' ), button, menu;
if ( ! nav ) {
return;
}
button = nav.find( '.menu-toggle' );
if ( ! button ) {
return;
}
// Hide button if menu is missing or empty.
menu = nav.find( '.nav-menu' );
if ( ! menu || ! menu.children().length ) {
button.hide();
return;
}
button.on( 'click.proxi', function() {
nav.toggleClass( 'toggled-on' );
} );
// Better focus for hidden submenu items for accessibility.
menu.find( 'a' ).on( 'focus.proxi blur.proxi', function() {
$( this ).parents( '.menu-item, .page_item' ).toggleClass( 'focus' );
} );
} )();
/**
* Makes "skip to content" link work correctly in IE9 and Chrome for better
* accessibility.
*
* @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
*/
_window.on( 'hashchange.proxi', function() {
var element = document.getElementById( location.hash.substring( 1 ) );
if ( element ) {
if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.tagName ) ) {
element.tabIndex = -1;
}
element.focus();
}
} );
/**
* Arranges footer widgets vertically.
*/
if ( $.isFunction( $.fn.masonry ) ) {
var columnWidth = body.is( '.sidebar' ) ? 228 : 245;
$( '#secondary .widget-area' ).masonry( {
itemSelector: '.widget',
columnWidth: columnWidth,
gutterWidth: 20,
isRTL: body.is( '.rtl' )
} );
}
} )( jQuery );
|
prakyath/samudra
|
wp-content/themes/trope/js/functions.js
|
JavaScript
|
gpl-2.0
| 2,318 |
/*
* (C) Copyright 2001
* Wolfgang Denk, DENX Software Engineering, [email protected].
*
* See file CREDITS for list of people who contributed to this
* project.
*
* 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
*/
/*
* Date & Time support for Philips PCF8563 RTC
*/
#include <common.h>
#include <command.h>
#include <rtc.h>
#if defined(CONFIG_CMD_DATE) || defined(CONFIG_TIMESTAMP)
#define FEBRUARY 2
#define STARTOFTIME 1970
#define SECDAY 86400L
#define SECYR (SECDAY * 365)
#define leapyear(year) ((year) % 4 == 0)
#define days_in_year(a) (leapyear(a) ? 366 : 365)
#define days_in_month(a) (month_days[(a) - 1])
static int month_days[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
/*
* This only works for the Gregorian calendar - i.e. after 1752 (in the UK)
*/
void GregorianDay(struct rtc_time * tm) {
int leapsToDate;
int lastYear;
int day;
int MonthOffset[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
lastYear = tm->tm_year - 1;
/*
* Number of leap corrections to apply up to end of last year
*/
leapsToDate = lastYear / 4 - lastYear / 100 + lastYear / 400;
/*
* This year is a leap year if it is divisible by 4 except when it is
* divisible by 100 unless it is divisible by 400
*
* e.g. 1904 was a leap year, 1900 was not, 1996 is, and 2000 will be
*/
if ((tm->tm_year % 4 == 0) && ((tm->tm_year % 100 != 0) || (tm->tm_year % 400 == 0)) && (tm->tm_mon > 2)) {
/*
* We are past Feb. 29 in a leap year
*/
day = 1;
} else {
day = 0;
}
day += lastYear * 365 + leapsToDate + MonthOffset[tm->tm_mon - 1] + tm->tm_mday;
tm->tm_wday = day % 7;
}
void to_tm(int tim, struct rtc_time * tm) {
register int i;
register long hms, day;
day = tim / SECDAY;
hms = tim % SECDAY;
/* Hours, minutes, seconds are easy */
tm->tm_hour = hms / 3600;
tm->tm_min = (hms % 3600) / 60;
tm->tm_sec = (hms % 3600) % 60;
/* Number of years in days */
for (i = STARTOFTIME; day >= days_in_year(i); i++) {
day -= days_in_year(i);
}
tm->tm_year = i;
/* Number of months in days left */
if (leapyear(tm->tm_year)) {
days_in_month(FEBRUARY) = 29;
}
for (i = 1; day >= days_in_month(i); i++) {
day -= days_in_month(i);
}
days_in_month(FEBRUARY) = 28;
tm->tm_mon = i;
/* Days are what is left over (+1) from all that. */
tm->tm_mday = day + 1;
/*
* Determine the day of week
*/
GregorianDay(tm);
}
/* Converts Gregorian date to seconds since 1970-01-01 00:00:00.
* Assumes input in normal date format, i.e. 1980-12-31 23:59:59
* => year=1980, mon=12, day=31, hour=23, min=59, sec=59.
*
* [For the Julian calendar (which was used in Russia before 1917,
* Britain & colonies before 1752, anywhere else before 1582,
* and is still in use by some communities) leave out the
* -year/100+year/400 terms, and add 10.]
*
* This algorithm was first published by Gauss (I think).
*
* WARNING: this function will overflow on 2106-02-07 06:28:16 on
* machines were long is 32-bit! (However, as time_t is signed, we
* will already get problems at other places on 2038-01-19 03:14:08)
*/
unsigned long mktime(unsigned int year, unsigned int mon, unsigned int day, unsigned int hour, unsigned int min, unsigned int sec) {
if (0 >= (int) (mon -= 2)) { /* 1..12 -> 11,12,1..10 */
mon += 12; /* Puts Feb last since it has leap day */
year -= 1;
}
return ((((unsigned long) (year / 4 - year / 100 + year / 400 + 367 * mon / 12 + day) + year * 365 - 719499) * 24 + hour /* now have hours */
) * 60 + min /* now have minutes */
) * 60 + sec; /* finally seconds */
}
#endif /* CONFIG_CMD_DATE */
|
pepe2k/u-boot_mod
|
u-boot/rtc/date.c
|
C
|
gpl-2.0
| 4,273 |
cmd_net/llc/llc_output.o := /opt/buildroot-gcc342/bin/mipsel-linux-uclibc-gcc -Wp,-MD,net/llc/.llc_output.o.d -nostdinc -isystem /root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include -D__KERNEL__ -Iinclude -include include/linux/autoconf.h -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -O2 -mabi=32 -G 0 -mno-abicalls -fno-pic -pipe -msoft-float -ffreestanding -march=mips32r2 -Wa,-mips32r2 -Wa,--trap -Iinclude/asm-mips/rt2880 -Iinclude/asm-mips/mach-generic -fomit-frame-pointer -gdwarf-2 -fno-stack-protector -membedded-data -muninit-const-in-rodata -funit-at-a-time -Wdeclaration-after-statement -Wno-pointer-sign -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(llc_output)" -D"KBUILD_MODNAME=KBUILD_STR(llc)" -c -o net/llc/llc_output.o net/llc/llc_output.c
deps_net/llc/llc_output.o := \
net/llc/llc_output.c \
$(wildcard include/config/tr.h) \
include/linux/if_arp.h \
include/linux/netdevice.h \
$(wildcard include/config/ax25.h) \
$(wildcard include/config/net/ipip.h) \
$(wildcard include/config/net/ipgre.h) \
$(wildcard include/config/ipv6/sit.h) \
$(wildcard include/config/ipv6/tunnel.h) \
$(wildcard include/config/wireless/ext.h) \
$(wildcard include/config/netpoll.h) \
$(wildcard include/config/net/poll/controller.h) \
$(wildcard include/config/netpoll/trap.h) \
$(wildcard include/config/net/dma.h) \
$(wildcard include/config/bug.h) \
$(wildcard include/config/proc/fs.h) \
include/linux/if.h \
include/linux/types.h \
$(wildcard include/config/uid16.h) \
$(wildcard include/config/lbd.h) \
$(wildcard include/config/lsf.h) \
$(wildcard include/config/resources/64bit.h) \
include/linux/posix_types.h \
include/linux/stddef.h \
include/linux/compiler.h \
$(wildcard include/config/enable/must/check.h) \
include/linux/compiler-gcc4.h \
$(wildcard include/config/forced/inlining.h) \
include/linux/compiler-gcc.h \
include/asm/posix_types.h \
include/asm/sgidefs.h \
include/asm/types.h \
$(wildcard include/config/highmem.h) \
$(wildcard include/config/64bit/phys/addr.h) \
$(wildcard include/config/64bit.h) \
include/linux/socket.h \
$(wildcard include/config/compat.h) \
include/asm/socket.h \
include/asm/sockios.h \
include/asm/ioctl.h \
include/linux/sockios.h \
include/linux/uio.h \
include/linux/hdlc/ioctl.h \
include/linux/if_ether.h \
$(wildcard include/config/sysctl.h) \
include/linux/skbuff.h \
$(wildcard include/config/nf/conntrack.h) \
$(wildcard include/config/bridge/netfilter.h) \
$(wildcard include/config/vlan/8021q.h) \
$(wildcard include/config/raeth/skb/recycle/2k.h) \
$(wildcard include/config/net/sched.h) \
$(wildcard include/config/net/cls/act.h) \
$(wildcard include/config/network/secmark.h) \
$(wildcard include/config/imq.h) \
include/linux/kernel.h \
$(wildcard include/config/preempt/voluntary.h) \
$(wildcard include/config/debug/spinlock/sleep.h) \
$(wildcard include/config/printk.h) \
$(wildcard include/config/numa.h) \
/root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include/stdarg.h \
include/linux/linkage.h \
include/asm/linkage.h \
include/linux/bitops.h \
include/asm/bitops.h \
$(wildcard include/config/cpu/mipsr2.h) \
$(wildcard include/config/cpu/mips32.h) \
$(wildcard include/config/cpu/mips64.h) \
include/linux/irqflags.h \
$(wildcard include/config/trace/irqflags.h) \
$(wildcard include/config/trace/irqflags/support.h) \
$(wildcard include/config/x86.h) \
include/asm/irqflags.h \
$(wildcard include/config/mips/mt/smtc.h) \
$(wildcard include/config/irq/cpu.h) \
$(wildcard include/config/mips/mt/smtc/instant/replay.h) \
include/asm/hazards.h \
$(wildcard include/config/cpu/r10000.h) \
$(wildcard include/config/cpu/rm9000.h) \
$(wildcard include/config/cpu/sb1.h) \
include/asm/barrier.h \
$(wildcard include/config/cpu/has/sync.h) \
$(wildcard include/config/cpu/has/wb.h) \
$(wildcard include/config/weak/ordering.h) \
$(wildcard include/config/smp.h) \
include/asm/bug.h \
include/asm/break.h \
include/asm-generic/bug.h \
$(wildcard include/config/generic/bug.h) \
$(wildcard include/config/debug/bugverbose.h) \
include/asm/byteorder.h \
$(wildcard include/config/cpu/mips64/r2.h) \
include/linux/byteorder/little_endian.h \
include/linux/byteorder/swab.h \
include/linux/byteorder/generic.h \
include/asm/cpu-features.h \
$(wildcard include/config/32bit.h) \
$(wildcard include/config/cpu/mipsr2/irq/vi.h) \
$(wildcard include/config/cpu/mipsr2/irq/ei.h) \
include/asm/cpu.h \
include/asm/cpu-info.h \
$(wildcard include/config/sgi/ip27.h) \
$(wildcard include/config/mips/mt.h) \
include/asm/cache.h \
$(wildcard include/config/mips/l1/cache/shift.h) \
include/asm-mips/mach-generic/kmalloc.h \
$(wildcard include/config/dma/coherent.h) \
include/asm-mips/mach-generic/cpu-feature-overrides.h \
include/asm/war.h \
$(wildcard include/config/sgi/ip22.h) \
$(wildcard include/config/sni/rm.h) \
$(wildcard include/config/cpu/r5432.h) \
$(wildcard include/config/sb1/pass/1/workarounds.h) \
$(wildcard include/config/sb1/pass/2/workarounds.h) \
$(wildcard include/config/mips/malta.h) \
$(wildcard include/config/mips/atlas.h) \
$(wildcard include/config/mips/sead.h) \
$(wildcard include/config/cpu/tx49xx.h) \
$(wildcard include/config/momenco/jaguar/atx.h) \
$(wildcard include/config/pmc/yosemite.h) \
$(wildcard include/config/basler/excite.h) \
$(wildcard include/config/momenco/ocelot/3.h) \
include/asm-generic/bitops/non-atomic.h \
include/asm-generic/bitops/fls64.h \
include/asm-generic/bitops/ffz.h \
include/asm-generic/bitops/find.h \
include/asm-generic/bitops/sched.h \
include/asm-generic/bitops/hweight.h \
include/asm-generic/bitops/ext2-non-atomic.h \
include/asm-generic/bitops/le.h \
include/asm-generic/bitops/ext2-atomic.h \
include/asm-generic/bitops/minix.h \
include/linux/log2.h \
$(wildcard include/config/arch/has/ilog2/u32.h) \
$(wildcard include/config/arch/has/ilog2/u64.h) \
include/linux/time.h \
include/linux/seqlock.h \
include/linux/spinlock.h \
$(wildcard include/config/debug/spinlock.h) \
$(wildcard include/config/preempt.h) \
$(wildcard include/config/debug/lock/alloc.h) \
include/linux/preempt.h \
$(wildcard include/config/debug/preempt.h) \
include/linux/thread_info.h \
include/asm/thread_info.h \
$(wildcard include/config/page/size/4kb.h) \
$(wildcard include/config/page/size/8kb.h) \
$(wildcard include/config/page/size/16kb.h) \
$(wildcard include/config/page/size/64kb.h) \
$(wildcard include/config/debug/stack/usage.h) \
include/asm/processor.h \
$(wildcard include/config/mips/mt/fpaff.h) \
$(wildcard include/config/cpu/has/prefetch.h) \
include/linux/cpumask.h \
$(wildcard include/config/hotplug/cpu.h) \
include/linux/threads.h \
$(wildcard include/config/nr/cpus.h) \
$(wildcard include/config/base/small.h) \
include/linux/bitmap.h \
include/linux/string.h \
include/asm/string.h \
$(wildcard include/config/cpu/r3000.h) \
include/asm/cachectl.h \
include/asm/mipsregs.h \
$(wildcard include/config/cpu/vr41xx.h) \
include/asm/prefetch.h \
include/asm/system.h \
include/asm/addrspace.h \
$(wildcard include/config/cpu/r4300.h) \
$(wildcard include/config/cpu/r4x00.h) \
$(wildcard include/config/cpu/r5000.h) \
$(wildcard include/config/cpu/rm7000.h) \
$(wildcard include/config/cpu/nevada.h) \
$(wildcard include/config/cpu/r8000.h) \
$(wildcard include/config/cpu/sb1a.h) \
include/asm-mips/mach-generic/spaces.h \
$(wildcard include/config/dma/noncoherent.h) \
include/asm/dsp.h \
include/linux/stringify.h \
include/linux/bottom_half.h \
include/linux/spinlock_types.h \
include/linux/lockdep.h \
$(wildcard include/config/lockdep.h) \
$(wildcard include/config/generic/hardirqs.h) \
$(wildcard include/config/prove/locking.h) \
include/linux/spinlock_types_up.h \
include/linux/spinlock_up.h \
include/linux/spinlock_api_up.h \
include/asm/atomic.h \
include/asm-generic/atomic.h \
include/linux/cache.h \
$(wildcard include/config/arch/has/cache/line/size.h) \
include/linux/net.h \
include/linux/wait.h \
include/linux/list.h \
$(wildcard include/config/debug/list.h) \
include/linux/poison.h \
include/linux/prefetch.h \
include/asm/current.h \
include/linux/random.h \
include/linux/ioctl.h \
include/linux/sysctl.h \
$(wildcard include/config/bcm/nat.h) \
include/linux/textsearch.h \
include/linux/module.h \
$(wildcard include/config/modules.h) \
$(wildcard include/config/modversions.h) \
$(wildcard include/config/unused/symbols.h) \
$(wildcard include/config/module/unload.h) \
$(wildcard include/config/kallsyms.h) \
$(wildcard include/config/sysfs.h) \
include/linux/stat.h \
include/asm/stat.h \
include/linux/kmod.h \
$(wildcard include/config/kmod.h) \
include/linux/errno.h \
include/asm/errno.h \
include/asm-generic/errno-base.h \
include/linux/elf.h \
include/linux/auxvec.h \
include/asm/auxvec.h \
include/linux/elf-em.h \
include/asm/elf.h \
$(wildcard include/config/mips32/n32.h) \
$(wildcard include/config/mips32/o32.h) \
$(wildcard include/config/mips32/compat.h) \
include/linux/kobject.h \
$(wildcard include/config/hotplug.h) \
include/linux/sysfs.h \
include/linux/kref.h \
include/linux/moduleparam.h \
include/linux/init.h \
$(wildcard include/config/memory/hotplug.h) \
$(wildcard include/config/acpi/hotplug/memory.h) \
include/asm/local.h \
include/linux/percpu.h \
include/linux/slab.h \
$(wildcard include/config/slab/debug.h) \
$(wildcard include/config/slub.h) \
$(wildcard include/config/slob.h) \
$(wildcard include/config/debug/slab.h) \
include/linux/gfp.h \
$(wildcard include/config/zone/dma.h) \
$(wildcard include/config/zone/dma32.h) \
include/linux/mmzone.h \
$(wildcard include/config/force/max/zoneorder.h) \
$(wildcard include/config/arch/populates/node/map.h) \
$(wildcard include/config/discontigmem.h) \
$(wildcard include/config/flat/node/mem/map.h) \
$(wildcard include/config/have/memory/present.h) \
$(wildcard include/config/need/node/memmap/size.h) \
$(wildcard include/config/need/multiple/nodes.h) \
$(wildcard include/config/sparsemem.h) \
$(wildcard include/config/have/arch/early/pfn/to/nid.h) \
$(wildcard include/config/flatmem.h) \
$(wildcard include/config/sparsemem/extreme.h) \
$(wildcard include/config/nodes/span/other/nodes.h) \
$(wildcard include/config/holes/in/zone.h) \
include/linux/numa.h \
$(wildcard include/config/nodes/shift.h) \
include/linux/nodemask.h \
include/asm/page.h \
$(wildcard include/config/build/elf64.h) \
$(wildcard include/config/limited/dma.h) \
include/linux/pfn.h \
include/asm/io.h \
include/asm-generic/iomap.h \
include/asm/pgtable-bits.h \
$(wildcard include/config/cpu/mips32/r1.h) \
$(wildcard include/config/cpu/tx39xx.h) \
$(wildcard include/config/mips/uncached.h) \
include/asm-mips/mach-generic/ioremap.h \
include/asm-mips/mach-generic/mangle-port.h \
$(wildcard include/config/swap/io/space.h) \
include/asm-generic/memory_model.h \
$(wildcard include/config/out/of/line/pfn/to/page.h) \
include/asm-generic/page.h \
include/linux/memory_hotplug.h \
$(wildcard include/config/have/arch/nodedata/extension.h) \
include/linux/notifier.h \
include/linux/mutex.h \
$(wildcard include/config/debug/mutexes.h) \
include/linux/rwsem.h \
$(wildcard include/config/rwsem/generic/spinlock.h) \
include/linux/rwsem-spinlock.h \
include/linux/srcu.h \
include/linux/topology.h \
$(wildcard include/config/sched/smt.h) \
$(wildcard include/config/sched/mc.h) \
include/linux/smp.h \
include/asm/topology.h \
include/asm-mips/mach-generic/topology.h \
include/asm-generic/topology.h \
include/linux/slub_def.h \
include/linux/workqueue.h \
include/linux/timer.h \
$(wildcard include/config/timer/stats.h) \
include/linux/ktime.h \
$(wildcard include/config/ktime/scalar.h) \
include/linux/jiffies.h \
include/linux/calc64.h \
include/asm/div64.h \
include/asm-generic/div64.h \
include/linux/timex.h \
$(wildcard include/config/time/interpolation.h) \
$(wildcard include/config/no/hz.h) \
include/asm/param.h \
$(wildcard include/config/hz.h) \
include/asm/timex.h \
include/asm-mips/mach-generic/timex.h \
include/asm/percpu.h \
include/asm-generic/percpu.h \
include/asm/module.h \
$(wildcard include/config/cpu/mips32/r2.h) \
$(wildcard include/config/cpu/mips64/r1.h) \
$(wildcard include/config/cpu/r6000.h) \
include/asm/uaccess.h \
include/asm-generic/uaccess.h \
include/linux/err.h \
include/net/checksum.h \
include/asm/checksum.h \
include/linux/in6.h \
include/linux/rcupdate.h \
include/linux/dmaengine.h \
$(wildcard include/config/dma/engine.h) \
include/linux/device.h \
$(wildcard include/config/debug/devres.h) \
include/linux/ioport.h \
include/linux/klist.h \
include/linux/completion.h \
include/linux/pm.h \
$(wildcard include/config/pm.h) \
include/asm/semaphore.h \
include/asm/device.h \
include/asm-generic/device.h \
include/linux/hrtimer.h \
$(wildcard include/config/high/res/timers.h) \
include/linux/rbtree.h \
include/linux/if_packet.h \
include/linux/interrupt.h \
$(wildcard include/config/generic/irq/probe.h) \
include/linux/irqreturn.h \
include/linux/hardirq.h \
$(wildcard include/config/preempt/bkl.h) \
$(wildcard include/config/virt/cpu/accounting.h) \
include/linux/smp_lock.h \
$(wildcard include/config/lock/kernel.h) \
include/asm/hardirq.h \
include/linux/irq.h \
$(wildcard include/config/s390.h) \
$(wildcard include/config/irq/per/cpu.h) \
$(wildcard include/config/irq/release/method.h) \
$(wildcard include/config/generic/pending/irq.h) \
$(wildcard include/config/irqbalance.h) \
$(wildcard include/config/auto/irq/affinity.h) \
$(wildcard include/config/generic/hardirqs/no//do/irq.h) \
include/asm/irq.h \
$(wildcard include/config/i8259.h) \
include/asm/mipsmtregs.h \
include/asm-mips/mach-generic/irq.h \
$(wildcard include/config/irq/cpu/rm7k.h) \
$(wildcard include/config/irq/cpu/rm9k.h) \
include/asm/ptrace.h \
$(wildcard include/config/cpu/has/smartmips.h) \
include/asm/isadep.h \
include/asm/irq_regs.h \
include/asm/hw_irq.h \
include/linux/profile.h \
$(wildcard include/config/profiling.h) \
include/linux/irq_cpustat.h \
include/linux/sched.h \
$(wildcard include/config/detect/softlockup.h) \
$(wildcard include/config/split/ptlock/cpus.h) \
$(wildcard include/config/keys.h) \
$(wildcard include/config/bsd/process/acct.h) \
$(wildcard include/config/taskstats.h) \
$(wildcard include/config/inotify/user.h) \
$(wildcard include/config/schedstats.h) \
$(wildcard include/config/task/delay/acct.h) \
$(wildcard include/config/blk/dev/io/trace.h) \
$(wildcard include/config/cc/stackprotector.h) \
$(wildcard include/config/sysvipc.h) \
$(wildcard include/config/rt/mutexes.h) \
$(wildcard include/config/task/xacct.h) \
$(wildcard include/config/cpusets.h) \
$(wildcard include/config/fault/injection.h) \
include/linux/capability.h \
include/asm/mmu.h \
include/asm/cputime.h \
include/asm-generic/cputime.h \
include/linux/sem.h \
include/linux/ipc.h \
$(wildcard include/config/ipc/ns.h) \
include/asm/ipcbuf.h \
include/asm/sembuf.h \
include/linux/signal.h \
include/asm/signal.h \
$(wildcard include/config/trad/signals.h) \
$(wildcard include/config/binfmt/irix.h) \
include/asm-generic/signal.h \
include/asm/sigcontext.h \
include/asm/siginfo.h \
include/asm-generic/siginfo.h \
include/linux/securebits.h \
include/linux/fs_struct.h \
include/linux/pid.h \
include/linux/seccomp.h \
$(wildcard include/config/seccomp.h) \
include/linux/futex.h \
$(wildcard include/config/futex.h) \
include/linux/rtmutex.h \
$(wildcard include/config/debug/rt/mutexes.h) \
include/linux/plist.h \
$(wildcard include/config/debug/pi/list.h) \
include/linux/param.h \
include/linux/resource.h \
include/asm/resource.h \
include/asm-generic/resource.h \
include/linux/task_io_accounting.h \
$(wildcard include/config/task/io/accounting.h) \
include/linux/aio.h \
include/linux/aio_abi.h \
include/linux/if_tr.h \
include/linux/trdevice.h \
include/net/llc.h \
include/net/llc_pdu.h \
net/llc/llc_output.o: $(deps_net/llc/llc_output.o)
$(deps_net/llc/llc_output.o):
|
smx-smx/dsl-n55u-bender
|
release/src-ra/linux/linux-2.6.21.x/net/llc/.llc_output.o.cmd
|
Batchfile
|
gpl-2.0
| 17,215 |
<a href="https://github.com/alchemy-fr/PHP-FFmpeg">
<img style="z-index:1200;position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub">
</a>
|
wp-plugins/audio-video-bonus-pack
|
vendor/php-ffmpeg/php-ffmpeg/docs/source/_themes/Alchemy/ribbon.html
|
HTML
|
gpl-2.0
| 239 |
/*
* This material is distributed under the GNU General Public License
* Version 2. You may review the terms of this license at
* http://www.gnu.org/licenses/gpl-2.0.html
*
* Copyright (c) 2014, Purdue University
* Copyright (c) 2014, 2016, Oracle and/or its affiliates
*
* All rights reserved.
*/
package com.oracle.truffle.r.test.builtins;
import org.junit.Test;
import com.oracle.truffle.r.test.TestBase;
// Checkstyle: stop line length check
public class TestBuiltin_filecreate extends TestBase {
@Test
public void testfilecreate1() {
assertEval("argv <- list('codetools-manual.log', TRUE); .Internal(file.create(argv[[1]], argv[[2]]))");
}
@Test
public void testfilecreate2() {
assertEval("argv <- list(character(0), TRUE); .Internal(file.create(argv[[1]], argv[[2]]))");
}
@Test
public void testfilecreate4() {
assertEval("argv <- structure(list('foo1'), .Names = '');do.call('file.create', argv)");
}
}
|
akunft/fastr
|
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/builtins/TestBuiltin_filecreate.java
|
Java
|
gpl-2.0
| 985 |
<?php
/*
+------------------------------------------------
| BitsB PHP based BitTorrent Tracker
| =============================================
| by d6bmg
| Copyright (C) 2010-2011 BitsB v1.0
| =============================================
| svn: http:// coming soon.. :)
| Licence Info: GPL
+------------------------------------------------
*/
/*************************************************************************************
* dcs.php
* ---------------------------------
* Author: Stelio Passaris ([email protected])
* Copyright: (c) 2009 Stelio Passaris (http://stelio.net/stiki/GeSHi)
* Release Version: 1.0.8.3
* Date Started: 2009/01/20
*
* DCS language file for GeSHi.
*
* DCS (Data Conversion System) is part of Sungard iWorks' Prophet suite and is used
* to convert external data files into a format that Prophet and Glean can read.
* See http://www.prophet-web.com/Products/DCS for product information.
* This language file is current for DCS version 7.3.2.
*
* Note that the DCS IDE does not handle escape characters correctly. The IDE thinks
* that a backslash '\' is an escape character, but in practice the backslash does
* not escape the string delimiter character '"' when the program runs. A '\\' is
* escaped to '\' when the program runs, but '\"' is treated as '\' at the end of a
* string. Therefore in this language file, we do not recognise the backslash as an
* escape character. For the purposes of GeSHi, there is no character escaping.
*
* CHANGES
* -------
* 2009/02/21 (1.0.8.3)
* - First Release
*
* TODO (updated 2009/02/21)
* -------------------------
* * Add handling for embedded C code. Note that the DCS IDE does not highlight C code
* correctly, but that doesn't mean that we can't! This will be included for a
* stable release of GeSHi of version 1.1.x (or later) that allows for highlighting
* embedded code using that code's appropriate language file.
*
*************************************************************************************
*
* This file is part of GeSHi.
*
* GeSHi 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.
*
* GeSHi 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 GeSHi; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*************************************************************************************/
$language_data = array (
'LANG_NAME' => 'DCS',
'COMMENT_SINGLE' => array(
1 => ';'
),
'COMMENT_MULTI' => array(
),
'HARDQUOTE' => array(
),
'HARDESCAPE' => '',
'COMMENT_REGEXP' => array(
// Highlight embedded C code in a separate color:
2 => '/\bINSERT_C_CODE\b.*?\bEND_C_CODE\b/ims'
),
'CASE_KEYWORDS' => GESHI_CAPS_UPPER,
'QUOTEMARKS' => array(
'"'
),
'ESCAPE_CHAR' => '',
'ESCAPE_REGEXP' => '',
'NUMBERS' =>
GESHI_NUMBER_INT_BASIC | GESHI_NUMBER_FLT_SCI_ZERO,
'KEYWORDS' => array(
1 => array(
'abs', 'ascii_value', 'bit_value', 'blank_date', 'calc_unit_values', 'cm',
'complete_months', 'complete_years', 'correct', 'create_input_file', 'cy',
'date_convert', 'day', 'del_output_separator',
'delete_existing_output_files', 'div', 'ex', 'exact_years', 'exp',
'extract_date', 'failed_validation', 'file_number', 'first_record',
'fract', 'fund_fac_a', 'fund_fac_b', 'fund_fac_c', 'fund_fac_d',
'fund_fac_e', 'fund_fac_f', 'fund_fac_g', 'fund_fac_h', 'fund_fac_i',
'fund_fac_j', 'fund_fac_k', 'fund_fac_l', 'fund_fac_m', 'fund_fac_n',
'fund_fac_o', 'fund_fac_p', 'fund_fac_q', 'fund_fac_r', 'fund_fac_s',
'fund_fac_t', 'fund_fac_u', 'fund_fac_v', 'fund_fac_w', 'fund_fac_x',
'fund_fac_y', 'fund_fac_z', 'group', 'group_record',
'input_file_date_time', 'input_file_extension', 'input_file_location',
'input_file_name', 'int', 'invalid', 'last_record', 'leap_year', 'len',
'ln', 'log', 'main_format_name', 'max', 'max_num_subrecords', 'message',
'min', 'mod', 'month', 'months_add', 'months_sub', 'nearest_months',
'nearest_years', 'next_record', 'nm', 'no_of_current_records',
'no_of_records', 'numval', 'ny', 'output', 'output_array_as_constants',
'output_file_path', 'output_record', 'pmdf_output', 'previous', 'rand',
're_start', 'read_generic_table', 'read_generic_table_text',
'read_input_footer', 'read_input_footer_text', 'read_input_header',
'read_input_header_text', 'record_count', 'record_suppressed', 'round',
'round_down', 'round_near', 'round_up', 'run_dcs_program', 'run_parameter',
'run_parameter_text', 'set_main_record', 'set_num_subrecords',
'sort_array', 'sort_current_records', 'sort_input', 'strval', 'substr',
'summarise', 'summarise_record', 'summarise_units',
'summarise_units_record', 'suppress_record', 'table_correct',
'table_validate', 'terminate', 'time', 'today', 'trim', 'ubound', 'year',
'years_add', 'years_sub'
),
2 => array(
'and', 'as', 'begin', 'boolean', 'byref', 'byval', 'call', 'case', 'date',
'default', 'do', 'else', 'elseif', 'end_c_code', 'endfor', 'endfunction',
'endif', 'endproc', 'endswitch', 'endwhile', 'eq',
'explicit_declarations', 'false', 'for', 'from', 'function', 'ge', 'gt',
'if', 'insert_c_code', 'integer', 'le', 'loop', 'lt', 'ne', 'not',
'number', 'or', 'private', 'proc', 'public', 'quitloop', 'return',
'short', 'step', 'switch', 'text', 'then', 'to', 'true', 'while'
),
3 => array(
// These keywords are not highlighted by the DCS IDE but we may as well
// keep track of them anyway:
'mp_file', 'odbc_file'
)
),
'SYMBOLS' => array(
'(', ')', '[', ']',
'=', '<', '>',
'+', '-', '*', '/', '^',
':', ','
),
'CASE_SENSITIVE' => array(
GESHI_COMMENTS => false,
1 => false,
2 => false,
3 => false,
),
'STYLES' => array(
'KEYWORDS' => array(
1 => 'color: red;',
2 => 'color: blue;',
3 => 'color: black;'
),
'COMMENTS' => array(
1 => 'color: black; background-color: silver;',
// Colors for highlighting embedded C code:
2 => 'color: maroon; background-color: pink;'
),
'ESCAPE_CHAR' => array(
),
'BRACKETS' => array(
0 => 'color: black;'
),
'STRINGS' => array(
0 => 'color: green;'
),
'NUMBERS' => array(
0 => 'color: green;'
),
'METHODS' => array(
),
'SYMBOLS' => array(
0 => 'color: black;'
),
'REGEXPS' => array(
),
'SCRIPT' => array(
),
),
'URLS' => array(
1 => '',
2 => '',
3 => ''
),
'OOLANG' => false,
'OBJECT_SPLITTERS' => array(
),
'REGEXPS' => array(
),
'STRICT_MODE_APPLIES' => GESHI_NEVER,
'SCRIPT_DELIMITERS' => array(
),
'HIGHLIGHT_STRICT_BLOCK' => array(
),
'TAB_WIDTH' => 4
);
?>
|
pranay22/BitsB1.1
|
include/geshi/geshi/dcs.php
|
PHP
|
gpl-2.0
| 8,004 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Class param_type</title>
<link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.76.1">
<link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../triangle_distribution.html#id3057631" title="Description">
<link rel="prev" href="../triangle_distribution.html" title="Class template triangle_distribution">
<link rel="next" href="../uniform_01.html" title="Class template uniform_01">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td>
<td align="center"><a href="../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../triangle_distribution.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../triangle_distribution.html#id3057631"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../uniform_01.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.random.triangle_distribution.param_type"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Class param_type</span></h2>
<p>boost::random::triangle_distribution::param_type</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../../boost_random/reference.html#header.boost.random.triangle_distribution_hpp" title="Header <boost/random/triangle_distribution.hpp>">boost/random/triangle_distribution.hpp</a>>
</span>
<span class="keyword">class</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">{</span>
<span class="keyword">public</span><span class="special">:</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <a class="link" href="../triangle_distribution.html" title="Class template triangle_distribution">triangle_distribution</a> <a name="boost.random.triangle_distribution.param_type.distribution_type"></a><span class="identifier">distribution_type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="param_type.html#boost.random.triangle_distribution.param_typeconstruct-copy-destruct">construct/copy/destruct</a></span>
<span class="keyword">explicit</span> <a class="link" href="param_type.html#id1282063-bb"><span class="identifier">param_type</span></a><span class="special">(</span><span class="identifier">RealType</span> <span class="special">=</span> <span class="number">0</span><span class="special">.</span><span class="number">0</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="special">=</span> <span class="number">0</span><span class="special">.</span><span class="number">5</span><span class="special">,</span> <span class="identifier">RealType</span> <span class="special">=</span> <span class="number">1</span><span class="special">.</span><span class="number">0</span><span class="special">)</span><span class="special">;</span>
<span class="comment">// <a class="link" href="param_type.html#id1282024-bb">public member functions</a></span>
<span class="identifier">RealType</span> <a class="link" href="param_type.html#id1282028-bb"><span class="identifier">a</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">RealType</span> <a class="link" href="param_type.html#id1282039-bb"><span class="identifier">b</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="identifier">RealType</span> <a class="link" href="param_type.html#id1282051-bb"><span class="identifier">c</span></a><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span>
<span class="comment">// <a class="link" href="param_type.html#id1281965-bb">friend functions</a></span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">friend</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span>
<a class="link" href="param_type.html#id1281968-bb"><span class="keyword">operator</span><span class="special"><<</span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">friend</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span>
<a class="link" href="param_type.html#id1277366-bb"><span class="keyword">operator</span><span class="special">>></span></a><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">friend</span> <span class="keyword">bool</span> <a class="link" href="param_type.html#id1277408-bb"><span class="keyword">operator</span><span class="special">==</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="keyword">friend</span> <span class="keyword">bool</span> <a class="link" href="param_type.html#id1277439-bb"><span class="keyword">operator</span><span class="special">!=</span></a><span class="special">(</span><span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="id3060237"></a><h2>Description</h2>
<div class="refsect2">
<a name="id3060241"></a><h3>
<a name="boost.random.triangle_distribution.param_typeconstruct-copy-destruct"></a><code class="computeroutput">param_type</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem">
<pre class="literallayout"><span class="keyword">explicit</span> <a name="id1282063-bb"></a><span class="identifier">param_type</span><span class="special">(</span><span class="identifier">RealType</span> a <span class="special">=</span> <span class="number">0</span><span class="special">.</span><span class="number">0</span><span class="special">,</span> <span class="identifier">RealType</span> b <span class="special">=</span> <span class="number">0</span><span class="special">.</span><span class="number">5</span><span class="special">,</span> <span class="identifier">RealType</span> c <span class="special">=</span> <span class="number">1</span><span class="special">.</span><span class="number">0</span><span class="special">)</span><span class="special">;</span></pre>
<p>Constructs the parameters of a <code class="computeroutput"><code class="computeroutput"><a class="link" href="../triangle_distribution.html" title="Class template triangle_distribution">triangle_distribution</a></code></code>. </p>
</li></ol></div>
</div>
<div class="refsect2">
<a name="id3060395"></a><h3>
<a name="id1282024-bb"></a><code class="computeroutput">param_type</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="identifier">RealType</span> <a name="id1282028-bb"></a><span class="identifier">a</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p>Returns the minimum value of the distribution. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">RealType</span> <a name="id1282039-bb"></a><span class="identifier">b</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p>Returns the mode of the distribution. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="identifier">RealType</span> <a name="id1282051-bb"></a><span class="identifier">c</span><span class="special">(</span><span class="special">)</span> <span class="keyword">const</span><span class="special">;</span></pre>
<p>Returns the maximum value of the distribution. </p>
</li>
</ol></div>
</div>
<div class="refsect2">
<a name="id3060541"></a><h3>
<a name="id1281965-bb"></a><code class="computeroutput">param_type</code> friend functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1">
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">friend</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span>
<a name="id1281968-bb"></a><span class="keyword">operator</span><span class="special"><<</span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_ostream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> os<span class="special">,</span>
<span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> param<span class="special">)</span><span class="special">;</span></pre>
<p>Writes the parameters to a <code class="computeroutput">std::ostream</code>. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> CharT<span class="special">,</span> <span class="keyword">typename</span> Traits<span class="special">></span>
<span class="keyword">friend</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span>
<a name="id1277366-bb"></a><span class="keyword">operator</span><span class="special">>></span><span class="special">(</span><span class="identifier">std</span><span class="special">::</span><span class="identifier">basic_istream</span><span class="special"><</span> <span class="identifier">CharT</span><span class="special">,</span> <span class="identifier">Traits</span> <span class="special">></span> <span class="special">&</span> is<span class="special">,</span>
<span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> param<span class="special">)</span><span class="special">;</span></pre>
<p>Reads the parameters from a <code class="computeroutput">std::istream</code>. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">friend</span> <span class="keyword">bool</span> <a name="id1277408-bb"></a><span class="keyword">operator</span><span class="special">==</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> lhs<span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> rhs<span class="special">)</span><span class="special">;</span></pre>
<p>Returns true if the two sets of parameters are equal. </p>
</li>
<li class="listitem">
<pre class="literallayout"><span class="keyword">friend</span> <span class="keyword">bool</span> <a name="id1277439-bb"></a><span class="keyword">operator</span><span class="special">!=</span><span class="special">(</span><span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> lhs<span class="special">,</span> <span class="keyword">const</span> <a class="link" href="param_type.html" title="Class param_type">param_type</a> <span class="special">&</span> rhs<span class="special">)</span><span class="special">;</span></pre>
<p>Returns true if the two sets of parameters are different. </p>
</li>
</ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2000-2005 Jens Maurer<br>Copyright © 2009, 2010 Steven Watanabe<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="../triangle_distribution.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../triangle_distribution.html#id3057631"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../uniform_01.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
|
phra/802_21
|
boost_1_49_0/doc/html/boost/random/triangle_distribution/param_type.html
|
HTML
|
gpl-2.0
| 17,237 |
/* Copyright (c) 2014-2016, 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.
*/
/*
* WWAN Transport Network Driver.
*/
#include <linux/completion.h>
#include <linux/errno.h>
#include <linux/if_arp.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/netdevice.h>
#include <linux/of_device.h>
#include <linux/string.h>
#include <linux/skbuff.h>
#include <linux/version.h>
#include <linux/workqueue.h>
#include <net/pkt_sched.h>
#include <soc/qcom/subsystem_restart.h>
#include <soc/qcom/subsystem_notif.h>
#include "ipa_qmi_service.h"
#include <linux/rmnet_ipa_fd_ioctl.h>
#include <linux/ipa.h>
#include <uapi/linux/net_map.h>
#include "ipa_trace.h"
#define WWAN_METADATA_SHFT 24
#define WWAN_METADATA_MASK 0xFF000000
#define WWAN_DATA_LEN 2000
#define IPA_RM_INACTIVITY_TIMER 100 /* IPA_RM */
#define HEADROOM_FOR_QMAP 8 /* for mux header */
#define TAILROOM 0 /* for padding by mux layer */
#define MAX_NUM_OF_MUX_CHANNEL 10 /* max mux channels */
#define UL_FILTER_RULE_HANDLE_START 69
#define DEFAULT_OUTSTANDING_HIGH_CTL 96
#define DEFAULT_OUTSTANDING_HIGH 64
#define DEFAULT_OUTSTANDING_LOW 32
#define IPA_WWAN_DEV_NAME "rmnet_ipa%d"
#define IPA_WWAN_RX_SOFTIRQ_THRESH 16
#define INVALID_MUX_ID 0xFF
#define IPA_QUOTA_REACH_ALERT_MAX_SIZE 64
#define IPA_QUOTA_REACH_IF_NAME_MAX_SIZE 64
#define IPA_UEVENT_NUM_EVNP 4 /* number of event pointers */
#define IPA_NETDEV() \
((rmnet_ipa3_ctx && rmnet_ipa3_ctx->wwan_priv) ? \
rmnet_ipa3_ctx->wwan_priv->net : NULL)
static int ipa3_wwan_add_ul_flt_rule_to_ipa(void);
static int ipa3_wwan_del_ul_flt_rule_to_ipa(void);
static void ipa3_wwan_msg_free_cb(void*, u32, u32);
static void ipa3_wake_tx_queue(struct work_struct *work);
static DECLARE_WORK(ipa3_tx_wakequeue_work, ipa3_wake_tx_queue);
static void tethering_stats_poll_queue(struct work_struct *work);
static DECLARE_DELAYED_WORK(ipa_tether_stats_poll_wakequeue_work,
tethering_stats_poll_queue);
enum ipa3_wwan_device_status {
WWAN_DEVICE_INACTIVE = 0,
WWAN_DEVICE_ACTIVE = 1
};
struct ipa3_rmnet_plat_drv_res {
bool ipa_rmnet_ssr;
bool ipa_loaduC;
bool ipa_advertise_sg_support;
};
/**
* struct ipa3_wwan_private - WWAN private data
* @net: network interface struct implemented by this driver
* @stats: iface statistics
* @outstanding_pkts: number of packets sent to IPA without TX complete ACKed
* @outstanding_high: number of outstanding packets allowed
* @outstanding_low: number of outstanding packets which shall cause
* @ch_id: channel id
* @lock: spinlock for mutual exclusion
* @device_status: holds device status
*
* WWAN private - holds all relevant info about WWAN driver
*/
struct ipa3_wwan_private {
struct net_device *net;
struct net_device_stats stats;
atomic_t outstanding_pkts;
int outstanding_high_ctl;
int outstanding_high;
int outstanding_low;
uint32_t ch_id;
spinlock_t lock;
struct completion resource_granted_completion;
enum ipa3_wwan_device_status device_status;
};
struct rmnet_ipa3_context {
struct ipa3_wwan_private *wwan_priv;
struct ipa_sys_connect_params apps_to_ipa_ep_cfg;
struct ipa_sys_connect_params ipa_to_apps_ep_cfg;
u32 qmap_hdr_hdl;
u32 dflt_v4_wan_rt_hdl;
u32 dflt_v6_wan_rt_hdl;
struct ipa3_rmnet_mux_val mux_channel[MAX_NUM_OF_MUX_CHANNEL];
int num_q6_rules;
int old_num_q6_rules;
int rmnet_index;
bool egress_set;
bool a7_ul_flt_set;
struct workqueue_struct *rm_q6_wq;
atomic_t is_initialized;
atomic_t is_ssr;
void *subsys_notify_handle;
u32 apps_to_ipa3_hdl;
u32 ipa3_to_apps_hdl;
struct mutex ipa_to_apps_pipe_handle_guard;
};
static struct rmnet_ipa3_context *rmnet_ipa3_ctx;
/**
* ipa3_setup_a7_qmap_hdr() - Setup default a7 qmap hdr
*
* Return codes:
* 0: success
* -ENOMEM: failed to allocate memory
* -EPERM: failed to add the tables
*/
static int ipa3_setup_a7_qmap_hdr(void)
{
struct ipa_ioc_add_hdr *hdr;
struct ipa_hdr_add *hdr_entry;
u32 pyld_sz;
int ret;
/* install the basic exception header */
pyld_sz = sizeof(struct ipa_ioc_add_hdr) + 1 *
sizeof(struct ipa_hdr_add);
hdr = kzalloc(pyld_sz, GFP_KERNEL);
if (!hdr) {
IPAWANERR("fail to alloc exception hdr\n");
return -ENOMEM;
}
hdr->num_hdrs = 1;
hdr->commit = 1;
hdr_entry = &hdr->hdr[0];
strlcpy(hdr_entry->name, IPA_A7_QMAP_HDR_NAME,
IPA_RESOURCE_NAME_MAX);
hdr_entry->hdr_len = IPA_QMAP_HEADER_LENGTH; /* 4 bytes */
if (ipa3_add_hdr(hdr)) {
IPAWANERR("fail to add IPA_A7_QMAP hdr\n");
ret = -EPERM;
goto bail;
}
if (hdr_entry->status) {
IPAWANERR("fail to add IPA_A7_QMAP hdr\n");
ret = -EPERM;
goto bail;
}
rmnet_ipa3_ctx->qmap_hdr_hdl = hdr_entry->hdr_hdl;
ret = 0;
bail:
kfree(hdr);
return ret;
}
static void ipa3_del_a7_qmap_hdr(void)
{
struct ipa_ioc_del_hdr *del_hdr;
struct ipa_hdr_del *hdl_entry;
u32 pyld_sz;
int ret;
pyld_sz = sizeof(struct ipa_ioc_del_hdr) + 1 *
sizeof(struct ipa_hdr_del);
del_hdr = kzalloc(pyld_sz, GFP_KERNEL);
if (!del_hdr) {
IPAWANERR("fail to alloc exception hdr_del\n");
return;
}
del_hdr->commit = 1;
del_hdr->num_hdls = 1;
hdl_entry = &del_hdr->hdl[0];
hdl_entry->hdl = rmnet_ipa3_ctx->qmap_hdr_hdl;
ret = ipa3_del_hdr(del_hdr);
if (ret || hdl_entry->status)
IPAWANERR("ipa3_del_hdr failed\n");
else
IPAWANDBG("hdrs deletion done\n");
rmnet_ipa3_ctx->qmap_hdr_hdl = 0;
kfree(del_hdr);
}
static void ipa3_del_qmap_hdr(uint32_t hdr_hdl)
{
struct ipa_ioc_del_hdr *del_hdr;
struct ipa_hdr_del *hdl_entry;
u32 pyld_sz;
int ret;
if (hdr_hdl == 0) {
IPAWANERR("Invalid hdr_hdl provided\n");
return;
}
pyld_sz = sizeof(struct ipa_ioc_del_hdr) + 1 *
sizeof(struct ipa_hdr_del);
del_hdr = kzalloc(pyld_sz, GFP_KERNEL);
if (!del_hdr) {
IPAWANERR("fail to alloc exception hdr_del\n");
return;
}
del_hdr->commit = 1;
del_hdr->num_hdls = 1;
hdl_entry = &del_hdr->hdl[0];
hdl_entry->hdl = hdr_hdl;
ret = ipa3_del_hdr(del_hdr);
if (ret || hdl_entry->status)
IPAWANERR("ipa3_del_hdr failed\n");
else
IPAWANDBG("header deletion done\n");
rmnet_ipa3_ctx->qmap_hdr_hdl = 0;
kfree(del_hdr);
}
static void ipa3_del_mux_qmap_hdrs(void)
{
int index;
for (index = 0; index < rmnet_ipa3_ctx->rmnet_index; index++) {
ipa3_del_qmap_hdr(rmnet_ipa3_ctx->mux_channel[index].hdr_hdl);
rmnet_ipa3_ctx->mux_channel[index].hdr_hdl = 0;
}
}
static int ipa3_add_qmap_hdr(uint32_t mux_id, uint32_t *hdr_hdl)
{
struct ipa_ioc_add_hdr *hdr;
struct ipa_hdr_add *hdr_entry;
char hdr_name[IPA_RESOURCE_NAME_MAX];
u32 pyld_sz;
int ret;
pyld_sz = sizeof(struct ipa_ioc_add_hdr) + 1 *
sizeof(struct ipa_hdr_add);
hdr = kzalloc(pyld_sz, GFP_KERNEL);
if (!hdr) {
IPAWANERR("fail to alloc exception hdr\n");
return -ENOMEM;
}
hdr->num_hdrs = 1;
hdr->commit = 1;
hdr_entry = &hdr->hdr[0];
snprintf(hdr_name, IPA_RESOURCE_NAME_MAX, "%s%d",
A2_MUX_HDR_NAME_V4_PREF,
mux_id);
strlcpy(hdr_entry->name, hdr_name,
IPA_RESOURCE_NAME_MAX);
hdr_entry->hdr_len = IPA_QMAP_HEADER_LENGTH; /* 4 bytes */
hdr_entry->hdr[1] = (uint8_t) mux_id;
IPAWANDBG("header (%s) with mux-id: (%d)\n",
hdr_name,
hdr_entry->hdr[1]);
if (ipa3_add_hdr(hdr)) {
IPAWANERR("fail to add IPA_QMAP hdr\n");
ret = -EPERM;
goto bail;
}
if (hdr_entry->status) {
IPAWANERR("fail to add IPA_QMAP hdr\n");
ret = -EPERM;
goto bail;
}
ret = 0;
*hdr_hdl = hdr_entry->hdr_hdl;
bail:
kfree(hdr);
return ret;
}
/**
* ipa3_setup_dflt_wan_rt_tables() - Setup default wan routing tables
*
* Return codes:
* 0: success
* -ENOMEM: failed to allocate memory
* -EPERM: failed to add the tables
*/
static int ipa3_setup_dflt_wan_rt_tables(void)
{
struct ipa_ioc_add_rt_rule *rt_rule;
struct ipa_rt_rule_add *rt_rule_entry;
rt_rule =
kzalloc(sizeof(struct ipa_ioc_add_rt_rule) + 1 *
sizeof(struct ipa_rt_rule_add), GFP_KERNEL);
if (!rt_rule) {
IPAWANERR("fail to alloc mem\n");
return -ENOMEM;
}
/* setup a default v4 route to point to Apps */
rt_rule->num_rules = 1;
rt_rule->commit = 1;
rt_rule->ip = IPA_IP_v4;
strlcpy(rt_rule->rt_tbl_name, IPA_DFLT_WAN_RT_TBL_NAME,
IPA_RESOURCE_NAME_MAX);
rt_rule_entry = &rt_rule->rules[0];
rt_rule_entry->at_rear = 1;
rt_rule_entry->rule.dst = IPA_CLIENT_APPS_WAN_CONS;
rt_rule_entry->rule.hdr_hdl = rmnet_ipa3_ctx->qmap_hdr_hdl;
if (ipa3_add_rt_rule(rt_rule)) {
IPAWANERR("fail to add dflt_wan v4 rule\n");
kfree(rt_rule);
return -EPERM;
}
IPAWANDBG("dflt v4 rt rule hdl=%x\n", rt_rule_entry->rt_rule_hdl);
rmnet_ipa3_ctx->dflt_v4_wan_rt_hdl = rt_rule_entry->rt_rule_hdl;
/* setup a default v6 route to point to A5 */
rt_rule->ip = IPA_IP_v6;
if (ipa3_add_rt_rule(rt_rule)) {
IPAWANERR("fail to add dflt_wan v6 rule\n");
kfree(rt_rule);
return -EPERM;
}
IPAWANDBG("dflt v6 rt rule hdl=%x\n", rt_rule_entry->rt_rule_hdl);
rmnet_ipa3_ctx->dflt_v6_wan_rt_hdl = rt_rule_entry->rt_rule_hdl;
kfree(rt_rule);
return 0;
}
static void ipa3_del_dflt_wan_rt_tables(void)
{
struct ipa_ioc_del_rt_rule *rt_rule;
struct ipa_rt_rule_del *rt_rule_entry;
int len;
len = sizeof(struct ipa_ioc_del_rt_rule) + 1 *
sizeof(struct ipa_rt_rule_del);
rt_rule = kzalloc(len, GFP_KERNEL);
if (!rt_rule) {
IPAWANERR("unable to allocate memory for del route rule\n");
return;
}
memset(rt_rule, 0, len);
rt_rule->commit = 1;
rt_rule->num_hdls = 1;
rt_rule->ip = IPA_IP_v4;
rt_rule_entry = &rt_rule->hdl[0];
rt_rule_entry->status = -1;
rt_rule_entry->hdl = rmnet_ipa3_ctx->dflt_v4_wan_rt_hdl;
IPAWANERR("Deleting Route hdl:(0x%x) with ip type: %d\n",
rt_rule_entry->hdl, IPA_IP_v4);
if (ipa3_del_rt_rule(rt_rule) ||
(rt_rule_entry->status)) {
IPAWANERR("Routing rule deletion failed!\n");
}
rt_rule->ip = IPA_IP_v6;
rt_rule_entry->hdl = rmnet_ipa3_ctx->dflt_v6_wan_rt_hdl;
IPAWANERR("Deleting Route hdl:(0x%x) with ip type: %d\n",
rt_rule_entry->hdl, IPA_IP_v6);
if (ipa3_del_rt_rule(rt_rule) ||
(rt_rule_entry->status)) {
IPAWANERR("Routing rule deletion failed!\n");
}
kfree(rt_rule);
}
int ipa3_copy_ul_filter_rule_to_ipa(struct ipa_install_fltr_rule_req_msg_v01
*rule_req)
{
int i, j;
if (rule_req->filter_spec_ex_list_valid == true) {
rmnet_ipa3_ctx->num_q6_rules =
rule_req->filter_spec_ex_list_len;
IPAWANDBG("Received (%d) install_flt_req\n",
rmnet_ipa3_ctx->num_q6_rules);
} else {
rmnet_ipa3_ctx->num_q6_rules = 0;
IPAWANERR("got no UL rules from modem\n");
return -EINVAL;
}
/* copy UL filter rules from Modem*/
for (i = 0; i < rmnet_ipa3_ctx->num_q6_rules; i++) {
/* check if rules overside the cache*/
if (i == MAX_NUM_Q6_RULE) {
IPAWANERR("Reaching (%d) max cache ",
MAX_NUM_Q6_RULE);
IPAWANERR(" however total (%d)\n",
rmnet_ipa3_ctx->num_q6_rules);
goto failure;
}
ipa3_qmi_ctx->q6_ul_filter_rule[i].ip =
rule_req->filter_spec_ex_list[i].ip_type;
ipa3_qmi_ctx->q6_ul_filter_rule[i].action =
rule_req->filter_spec_ex_list[i].filter_action;
if (rule_req->filter_spec_ex_list[i].
is_routing_table_index_valid == true)
ipa3_qmi_ctx->q6_ul_filter_rule[i].rt_tbl_idx =
rule_req->filter_spec_ex_list[i].route_table_index;
if (rule_req->filter_spec_ex_list[i].is_mux_id_valid == true)
ipa3_qmi_ctx->q6_ul_filter_rule[i].mux_id =
rule_req->filter_spec_ex_list[i].mux_id;
ipa3_qmi_ctx->q6_ul_filter_rule[i].rule_id =
rule_req->filter_spec_ex_list[i].rule_id;
ipa3_qmi_ctx->q6_ul_filter_rule[i].is_rule_hashable =
rule_req->filter_spec_ex_list[i].is_rule_hashable;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.rule_eq_bitmap =
rule_req->filter_spec_ex_list[i].filter_rule.
rule_eq_bitmap;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.tos_eq_present =
rule_req->filter_spec_ex_list[i].filter_rule.
tos_eq_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.tos_eq =
rule_req->filter_spec_ex_list[i].filter_rule.tos_eq;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
protocol_eq_present = rule_req->filter_spec_ex_list[i].
filter_rule.protocol_eq_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.protocol_eq =
rule_req->filter_spec_ex_list[i].filter_rule.
protocol_eq;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
num_ihl_offset_range_16 =
rule_req->filter_spec_ex_list[i].
filter_rule.num_ihl_offset_range_16;
for (j = 0; j < ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
num_ihl_offset_range_16; j++) {
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_range_16[j].offset = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_range_16[j].offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_range_16[j].range_low = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_range_16[j].range_low;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_range_16[j].range_high = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_range_16[j].range_high;
}
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.num_offset_meq_32 =
rule_req->filter_spec_ex_list[i].filter_rule.
num_offset_meq_32;
for (j = 0; j < ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
num_offset_meq_32; j++) {
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_32[j].offset =
rule_req->filter_spec_ex_list[i].
filter_rule.offset_meq_32[j].offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_32[j].mask =
rule_req->filter_spec_ex_list[i].
filter_rule.offset_meq_32[j].mask;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_32[j].value =
rule_req->filter_spec_ex_list[i].
filter_rule.offset_meq_32[j].value;
}
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.tc_eq_present =
rule_req->filter_spec_ex_list[i].
filter_rule.tc_eq_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.tc_eq =
rule_req->filter_spec_ex_list[i].filter_rule.tc_eq;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.fl_eq_present =
rule_req->filter_spec_ex_list[i].filter_rule.
flow_eq_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.fl_eq =
rule_req->filter_spec_ex_list[i].filter_rule.flow_eq;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_16_present = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_16_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_16.offset = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_16.offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_16.value = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_16.value;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_32_present = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_32_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_32.offset = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_32.offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_eq_32.value = rule_req->filter_spec_ex_list[i].
filter_rule.ihl_offset_eq_32.value;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
num_ihl_offset_meq_32 = rule_req->filter_spec_ex_list[i].
filter_rule.num_ihl_offset_meq_32;
for (j = 0; j < ipa3_qmi_ctx->q6_ul_filter_rule[i].
eq_attrib.num_ihl_offset_meq_32; j++) {
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_meq_32[j].offset = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_meq_32[j].offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_meq_32[j].mask = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_meq_32[j].mask;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ihl_offset_meq_32[j].value = rule_req->
filter_spec_ex_list[i].filter_rule.
ihl_offset_meq_32[j].value;
}
ipa3_qmi_ctx->
q6_ul_filter_rule[i].eq_attrib.num_offset_meq_128 =
rule_req->filter_spec_ex_list[i].filter_rule.
num_offset_meq_128;
for (j = 0; j < ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
num_offset_meq_128; j++) {
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_128[j].offset = rule_req->
filter_spec_ex_list[i].filter_rule.
offset_meq_128[j].offset;
memcpy(ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_128[j].mask,
rule_req->filter_spec_ex_list[i].
filter_rule.offset_meq_128[j].mask, 16);
memcpy(ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
offset_meq_128[j].value, rule_req->
filter_spec_ex_list[i].filter_rule.
offset_meq_128[j].value, 16);
}
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
metadata_meq32_present =
rule_req->filter_spec_ex_list[i].
filter_rule.metadata_meq32_present;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
metadata_meq32.offset =
rule_req->filter_spec_ex_list[i].
filter_rule.metadata_meq32.offset;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
metadata_meq32.mask = rule_req->filter_spec_ex_list[i].
filter_rule.metadata_meq32.mask;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.metadata_meq32.
value = rule_req->filter_spec_ex_list[i].filter_rule.
metadata_meq32.value;
ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib.
ipv4_frag_eq_present = rule_req->filter_spec_ex_list[i].
filter_rule.ipv4_frag_eq_present;
}
if (rule_req->xlat_filter_indices_list_valid) {
if (rule_req->xlat_filter_indices_list_len >
rmnet_ipa3_ctx->num_q6_rules) {
IPAWANERR("Number of xlat indices is not valid: %d\n",
rule_req->xlat_filter_indices_list_len);
goto failure;
}
IPAWANDBG("Receive %d XLAT indices: ",
rule_req->xlat_filter_indices_list_len);
for (i = 0; i < rule_req->xlat_filter_indices_list_len; i++)
IPAWANDBG("%d ", rule_req->xlat_filter_indices_list[i]);
IPAWANDBG("\n");
for (i = 0; i < rule_req->xlat_filter_indices_list_len; i++) {
if (rule_req->xlat_filter_indices_list[i]
>= rmnet_ipa3_ctx->num_q6_rules) {
IPAWANERR("Xlat rule idx is wrong: %d\n",
rule_req->xlat_filter_indices_list[i]);
goto failure;
} else {
ipa3_qmi_ctx->q6_ul_filter_rule
[rule_req->xlat_filter_indices_list[i]]
.is_xlat_rule = 1;
IPAWANDBG("Rule %d is xlat rule\n",
rule_req->xlat_filter_indices_list[i]);
}
}
}
goto success;
failure:
rmnet_ipa3_ctx->num_q6_rules = 0;
memset(ipa3_qmi_ctx->q6_ul_filter_rule, 0,
sizeof(ipa3_qmi_ctx->q6_ul_filter_rule));
return -EINVAL;
success:
return 0;
}
static int ipa3_wwan_add_ul_flt_rule_to_ipa(void)
{
u32 pyld_sz;
int i, retval = 0;
struct ipa_ioc_add_flt_rule *param;
struct ipa_flt_rule_add flt_rule_entry;
struct ipa_fltr_installed_notif_req_msg_v01 *req;
pyld_sz = sizeof(struct ipa_ioc_add_flt_rule) +
sizeof(struct ipa_flt_rule_add);
param = kzalloc(pyld_sz, GFP_KERNEL);
if (!param)
return -ENOMEM;
req = (struct ipa_fltr_installed_notif_req_msg_v01 *)
kzalloc(sizeof(struct ipa_fltr_installed_notif_req_msg_v01),
GFP_KERNEL);
if (!req) {
kfree(param);
return -ENOMEM;
}
param->commit = 1;
param->ep = IPA_CLIENT_APPS_LAN_WAN_PROD;
param->global = false;
param->num_rules = (uint8_t)1;
for (i = 0; i < rmnet_ipa3_ctx->num_q6_rules; i++) {
param->ip = ipa3_qmi_ctx->q6_ul_filter_rule[i].ip;
memset(&flt_rule_entry, 0, sizeof(struct ipa_flt_rule_add));
flt_rule_entry.at_rear = true;
flt_rule_entry.rule.action =
ipa3_qmi_ctx->q6_ul_filter_rule[i].action;
flt_rule_entry.rule.rt_tbl_idx
= ipa3_qmi_ctx->q6_ul_filter_rule[i].rt_tbl_idx;
flt_rule_entry.rule.retain_hdr = true;
flt_rule_entry.rule.hashable =
ipa3_qmi_ctx->q6_ul_filter_rule[i].is_rule_hashable;
flt_rule_entry.rule.rule_id =
ipa3_qmi_ctx->q6_ul_filter_rule[i].rule_id;
/* debug rt-hdl*/
IPAWANDBG("install-IPA index(%d),rt-tbl:(%d)\n",
i, flt_rule_entry.rule.rt_tbl_idx);
flt_rule_entry.rule.eq_attrib_type = true;
memcpy(&(flt_rule_entry.rule.eq_attrib),
&ipa3_qmi_ctx->q6_ul_filter_rule[i].eq_attrib,
sizeof(struct ipa_ipfltri_rule_eq));
memcpy(&(param->rules[0]), &flt_rule_entry,
sizeof(struct ipa_flt_rule_add));
if (ipa3_add_flt_rule((struct ipa_ioc_add_flt_rule *)param)) {
retval = -EFAULT;
IPAWANERR("add A7 UL filter rule(%d) failed\n", i);
} else {
/* store the rule handler */
ipa3_qmi_ctx->q6_ul_filter_rule_hdl[i] =
param->rules[0].flt_rule_hdl;
}
}
/* send ipa_fltr_installed_notif_req_msg_v01 to Q6*/
req->source_pipe_index =
ipa3_get_ep_mapping(IPA_CLIENT_APPS_LAN_WAN_PROD);
req->install_status = QMI_RESULT_SUCCESS_V01;
req->rule_id_valid = 1;
req->rule_id_len = rmnet_ipa3_ctx->num_q6_rules;
for (i = 0; i < rmnet_ipa3_ctx->num_q6_rules; i++) {
req->rule_id[i] =
ipa3_qmi_ctx->q6_ul_filter_rule[i].rule_id;
}
if (ipa3_qmi_filter_notify_send(req)) {
IPAWANDBG("add filter rule index on A7-RX failed\n");
retval = -EFAULT;
}
rmnet_ipa3_ctx->old_num_q6_rules = rmnet_ipa3_ctx->num_q6_rules;
IPAWANDBG("add (%d) filter rule index on A7-RX\n",
rmnet_ipa3_ctx->old_num_q6_rules);
kfree(param);
kfree(req);
return retval;
}
static int ipa3_wwan_del_ul_flt_rule_to_ipa(void)
{
u32 pyld_sz;
int i, retval = 0;
struct ipa_ioc_del_flt_rule *param;
struct ipa_flt_rule_del flt_rule_entry;
pyld_sz = sizeof(struct ipa_ioc_del_flt_rule) +
sizeof(struct ipa_flt_rule_del);
param = kzalloc(pyld_sz, GFP_KERNEL);
if (!param) {
IPAWANERR("kzalloc failed\n");
return -ENOMEM;
}
param->commit = 1;
param->num_hdls = (uint8_t) 1;
for (i = 0; i < rmnet_ipa3_ctx->old_num_q6_rules; i++) {
param->ip = ipa3_qmi_ctx->q6_ul_filter_rule[i].ip;
memset(&flt_rule_entry, 0, sizeof(struct ipa_flt_rule_del));
flt_rule_entry.hdl = ipa3_qmi_ctx->q6_ul_filter_rule_hdl[i];
/* debug rt-hdl*/
IPAWANDBG("delete-IPA rule index(%d)\n", i);
memcpy(&(param->hdl[0]), &flt_rule_entry,
sizeof(struct ipa_flt_rule_del));
if (ipa3_del_flt_rule((struct ipa_ioc_del_flt_rule *)param)) {
IPAWANERR("del A7 UL filter rule(%d) failed\n", i);
kfree(param);
return -EFAULT;
}
}
/* set UL filter-rule add-indication */
rmnet_ipa3_ctx->a7_ul_flt_set = false;
rmnet_ipa3_ctx->old_num_q6_rules = 0;
kfree(param);
return retval;
}
static int ipa3_find_mux_channel_index(uint32_t mux_id)
{
int i;
for (i = 0; i < MAX_NUM_OF_MUX_CHANNEL; i++) {
if (mux_id == rmnet_ipa3_ctx->mux_channel[i].mux_id)
return i;
}
return MAX_NUM_OF_MUX_CHANNEL;
}
static int find_vchannel_name_index(const char *vchannel_name)
{
int i;
for (i = 0; i < MAX_NUM_OF_MUX_CHANNEL; i++) {
if (0 == strcmp(rmnet_ipa3_ctx->mux_channel[i].vchannel_name,
vchannel_name))
return i;
}
return MAX_NUM_OF_MUX_CHANNEL;
}
static int ipa3_wwan_register_to_ipa(int index)
{
struct ipa_tx_intf tx_properties = {0};
struct ipa_ioc_tx_intf_prop tx_ioc_properties[2] = { {0}, {0} };
struct ipa_ioc_tx_intf_prop *tx_ipv4_property;
struct ipa_ioc_tx_intf_prop *tx_ipv6_property;
struct ipa_rx_intf rx_properties = {0};
struct ipa_ioc_rx_intf_prop rx_ioc_properties[2] = { {0}, {0} };
struct ipa_ioc_rx_intf_prop *rx_ipv4_property;
struct ipa_ioc_rx_intf_prop *rx_ipv6_property;
struct ipa_ext_intf ext_properties = {0};
struct ipa_ioc_ext_intf_prop *ext_ioc_properties;
u32 pyld_sz;
int ret = 0, i;
IPAWANDBG("index(%d) device[%s]:\n", index,
rmnet_ipa3_ctx->mux_channel[index].vchannel_name);
if (!rmnet_ipa3_ctx->mux_channel[index].mux_hdr_set) {
ret = ipa3_add_qmap_hdr(
rmnet_ipa3_ctx->mux_channel[index].mux_id,
&rmnet_ipa3_ctx->mux_channel[index].hdr_hdl);
if (ret) {
IPAWANERR("ipa_add_mux_hdr failed (%d)\n", index);
return ret;
}
rmnet_ipa3_ctx->mux_channel[index].mux_hdr_set = true;
}
tx_properties.prop = tx_ioc_properties;
tx_ipv4_property = &tx_properties.prop[0];
tx_ipv4_property->ip = IPA_IP_v4;
tx_ipv4_property->dst_pipe = IPA_CLIENT_APPS_WAN_CONS;
snprintf(tx_ipv4_property->hdr_name, IPA_RESOURCE_NAME_MAX, "%s%d",
A2_MUX_HDR_NAME_V4_PREF,
rmnet_ipa3_ctx->mux_channel[index].mux_id);
tx_ipv6_property = &tx_properties.prop[1];
tx_ipv6_property->ip = IPA_IP_v6;
tx_ipv6_property->dst_pipe = IPA_CLIENT_APPS_WAN_CONS;
/* no need use A2_MUX_HDR_NAME_V6_PREF, same header */
snprintf(tx_ipv6_property->hdr_name, IPA_RESOURCE_NAME_MAX, "%s%d",
A2_MUX_HDR_NAME_V4_PREF,
rmnet_ipa3_ctx->mux_channel[index].mux_id);
tx_properties.num_props = 2;
rx_properties.prop = rx_ioc_properties;
rx_ipv4_property = &rx_properties.prop[0];
rx_ipv4_property->ip = IPA_IP_v4;
rx_ipv4_property->attrib.attrib_mask |= IPA_FLT_META_DATA;
rx_ipv4_property->attrib.meta_data =
rmnet_ipa3_ctx->mux_channel[index].mux_id << WWAN_METADATA_SHFT;
rx_ipv4_property->attrib.meta_data_mask = WWAN_METADATA_MASK;
rx_ipv4_property->src_pipe = IPA_CLIENT_APPS_LAN_WAN_PROD;
rx_ipv6_property = &rx_properties.prop[1];
rx_ipv6_property->ip = IPA_IP_v6;
rx_ipv6_property->attrib.attrib_mask |= IPA_FLT_META_DATA;
rx_ipv6_property->attrib.meta_data =
rmnet_ipa3_ctx->mux_channel[index].mux_id << WWAN_METADATA_SHFT;
rx_ipv6_property->attrib.meta_data_mask = WWAN_METADATA_MASK;
rx_ipv6_property->src_pipe = IPA_CLIENT_APPS_LAN_WAN_PROD;
rx_properties.num_props = 2;
pyld_sz = rmnet_ipa3_ctx->num_q6_rules *
sizeof(struct ipa_ioc_ext_intf_prop);
ext_ioc_properties = kmalloc(pyld_sz, GFP_KERNEL);
if (!ext_ioc_properties) {
IPAWANERR("Error allocate memory\n");
return -ENOMEM;
}
ext_properties.prop = ext_ioc_properties;
ext_properties.excp_pipe_valid = true;
ext_properties.excp_pipe = IPA_CLIENT_APPS_WAN_CONS;
ext_properties.num_props = rmnet_ipa3_ctx->num_q6_rules;
for (i = 0; i < rmnet_ipa3_ctx->num_q6_rules; i++) {
memcpy(&(ext_properties.prop[i]),
&(ipa3_qmi_ctx->q6_ul_filter_rule[i]),
sizeof(struct ipa_ioc_ext_intf_prop));
ext_properties.prop[i].mux_id =
rmnet_ipa3_ctx->mux_channel[index].mux_id;
IPAWANDBG("index %d ip: %d rt-tbl:%d\n", i,
ext_properties.prop[i].ip,
ext_properties.prop[i].rt_tbl_idx);
IPAWANDBG("action: %d mux:%d\n",
ext_properties.prop[i].action,
ext_properties.prop[i].mux_id);
}
ret = ipa3_register_intf_ext(rmnet_ipa3_ctx->mux_channel[index].
vchannel_name, &tx_properties,
&rx_properties, &ext_properties);
if (ret) {
IPAWANERR("[%s]:ipa3_register_intf failed %d\n",
rmnet_ipa3_ctx->mux_channel[index].vchannel_name, ret);
goto fail;
}
rmnet_ipa3_ctx->mux_channel[index].ul_flt_reg = true;
fail:
kfree(ext_ioc_properties);
return ret;
}
static void ipa3_cleanup_deregister_intf(void)
{
int i;
int ret;
for (i = 0; i < rmnet_ipa3_ctx->rmnet_index; i++) {
if (rmnet_ipa3_ctx->mux_channel[i].ul_flt_reg) {
ret = ipa3_deregister_intf(
rmnet_ipa3_ctx->mux_channel[i].vchannel_name);
if (ret < 0) {
IPAWANERR("de-register device %s(%d) failed\n",
rmnet_ipa3_ctx->mux_channel[i].
vchannel_name,
i);
return;
}
IPAWANDBG("de-register device %s(%d) success\n",
rmnet_ipa3_ctx->mux_channel[i].vchannel_name,
i);
}
rmnet_ipa3_ctx->mux_channel[i].ul_flt_reg = false;
}
}
int ipa3_wwan_update_mux_channel_prop(void)
{
int ret = 0, i;
/* install UL filter rules */
if (rmnet_ipa3_ctx->egress_set) {
if (ipa3_qmi_ctx->modem_cfg_emb_pipe_flt == false) {
IPAWANDBG("setup UL filter rules\n");
if (rmnet_ipa3_ctx->a7_ul_flt_set) {
IPAWANDBG("del previous UL filter rules\n");
/* delete rule hdlers */
ret = ipa3_wwan_del_ul_flt_rule_to_ipa();
if (ret) {
IPAWANERR("failed to del old rules\n");
return -EINVAL;
}
IPAWANDBG("deleted old UL rules\n");
}
ret = ipa3_wwan_add_ul_flt_rule_to_ipa();
}
if (ret)
IPAWANERR("failed to install UL rules\n");
else
rmnet_ipa3_ctx->a7_ul_flt_set = true;
}
/* update Tx/Rx/Ext property */
IPAWANDBG("update Tx/Rx/Ext property in IPA\n");
if (rmnet_ipa3_ctx->rmnet_index == 0) {
IPAWANDBG("no Tx/Rx/Ext property registered in IPA\n");
return ret;
}
ipa3_cleanup_deregister_intf();
for (i = 0; i < rmnet_ipa3_ctx->rmnet_index; i++) {
ret = ipa3_wwan_register_to_ipa(i);
if (ret < 0) {
IPAWANERR("failed to re-regist %s, mux %d, index %d\n",
rmnet_ipa3_ctx->mux_channel[i].vchannel_name,
rmnet_ipa3_ctx->mux_channel[i].mux_id,
i);
return -ENODEV;
}
IPAWANERR("dev(%s) has registered to IPA\n",
rmnet_ipa3_ctx->mux_channel[i].vchannel_name);
rmnet_ipa3_ctx->mux_channel[i].ul_flt_reg = true;
}
return ret;
}
#ifdef INIT_COMPLETION
#define reinit_completion(x) INIT_COMPLETION(*(x))
#endif /* INIT_COMPLETION */
static int __ipa_wwan_open(struct net_device *dev)
{
struct ipa3_wwan_private *wwan_ptr = netdev_priv(dev);
IPAWANDBG("[%s] __wwan_open()\n", dev->name);
if (wwan_ptr->device_status != WWAN_DEVICE_ACTIVE)
reinit_completion(&wwan_ptr->resource_granted_completion);
wwan_ptr->device_status = WWAN_DEVICE_ACTIVE;
return 0;
}
/**
* wwan_open() - Opens the wwan network interface. Opens logical
* channel on A2 MUX driver and starts the network stack queue
*
* @dev: network device
*
* Return codes:
* 0: success
* -ENODEV: Error while opening logical channel on A2 MUX driver
*/
static int ipa3_wwan_open(struct net_device *dev)
{
int rc = 0;
IPAWANDBG("[%s] wwan_open()\n", dev->name);
rc = __ipa_wwan_open(dev);
if (rc == 0)
netif_start_queue(dev);
return rc;
}
static int __ipa_wwan_close(struct net_device *dev)
{
struct ipa3_wwan_private *wwan_ptr = netdev_priv(dev);
int rc = 0;
if (wwan_ptr->device_status == WWAN_DEVICE_ACTIVE) {
wwan_ptr->device_status = WWAN_DEVICE_INACTIVE;
/* do not close wwan port once up, this causes
remote side to hang if tried to open again */
reinit_completion(&wwan_ptr->resource_granted_completion);
rc = ipa3_deregister_intf(dev->name);
if (rc) {
IPAWANERR("[%s]: ipa3_deregister_intf failed %d\n",
dev->name, rc);
return rc;
}
return rc;
} else {
return -EBADF;
}
}
/**
* ipa3_wwan_stop() - Stops the wwan network interface. Closes
* logical channel on A2 MUX driver and stops the network stack
* queue
*
* @dev: network device
*
* Return codes:
* 0: success
* -ENODEV: Error while opening logical channel on A2 MUX driver
*/
static int ipa3_wwan_stop(struct net_device *dev)
{
IPAWANDBG("[%s] ipa3_wwan_stop()\n", dev->name);
__ipa_wwan_close(dev);
netif_stop_queue(dev);
return 0;
}
static int ipa3_wwan_change_mtu(struct net_device *dev, int new_mtu)
{
if (0 > new_mtu || WWAN_DATA_LEN < new_mtu)
return -EINVAL;
IPAWANDBG("[%s] MTU change: old=%d new=%d\n",
dev->name, dev->mtu, new_mtu);
dev->mtu = new_mtu;
return 0;
}
/**
* ipa3_wwan_xmit() - Transmits an skb.
*
* @skb: skb to be transmitted
* @dev: network device
*
* Return codes:
* 0: success
* NETDEV_TX_BUSY: Error while transmitting the skb. Try again
* later
* -EFAULT: Error while transmitting the skb
*/
static int ipa3_wwan_xmit(struct sk_buff *skb, struct net_device *dev)
{
int ret = 0;
bool qmap_check;
struct ipa3_wwan_private *wwan_ptr = netdev_priv(dev);
struct ipa_tx_meta meta;
if (skb->protocol != htons(ETH_P_MAP)) {
IPAWANDBG_LOW
("SW filtering out none QMAP packet received from %s",
current->comm);
return NETDEV_TX_OK;
}
qmap_check = RMNET_MAP_GET_CD_BIT(skb);
if (netif_queue_stopped(dev)) {
if (qmap_check &&
atomic_read(&wwan_ptr->outstanding_pkts) <
wwan_ptr->outstanding_high_ctl) {
pr_err("[%s]Queue stop, send ctrl pkts\n", dev->name);
goto send;
} else {
pr_err("[%s]fatal: ipa_wwan_xmit stopped\n", dev->name);
return NETDEV_TX_BUSY;
}
}
/* checking High WM hit */
if (atomic_read(&wwan_ptr->outstanding_pkts) >=
wwan_ptr->outstanding_high) {
if (!qmap_check) {
IPAWANDBG_LOW("pending(%d)/(%d)- stop(%d)\n",
atomic_read(&wwan_ptr->outstanding_pkts),
wwan_ptr->outstanding_high,
netif_queue_stopped(dev));
IPAWANDBG_LOW("qmap_chk(%d)\n", qmap_check);
netif_stop_queue(dev);
return NETDEV_TX_BUSY;
}
}
send:
/* IPA_RM checking start */
ret = ipa_rm_inactivity_timer_request_resource(
IPA_RM_RESOURCE_WWAN_0_PROD);
if (ret == -EINPROGRESS) {
netif_stop_queue(dev);
return NETDEV_TX_BUSY;
}
if (ret) {
pr_err("[%s] fatal: ipa rm timer request resource failed %d\n",
dev->name, ret);
return -EFAULT;
}
/* IPA_RM checking end */
if (RMNET_MAP_GET_CD_BIT(skb)) {
memset(&meta, 0, sizeof(meta));
meta.pkt_init_dst_ep_valid = true;
meta.pkt_init_dst_ep_remote = true;
ret = ipa3_tx_dp(IPA_CLIENT_Q6_LAN_CONS, skb, &meta);
} else {
ret = ipa3_tx_dp(IPA_CLIENT_APPS_LAN_WAN_PROD, skb, NULL);
}
if (ret) {
ret = NETDEV_TX_BUSY;
dev->stats.tx_dropped++;
goto out;
}
atomic_inc(&wwan_ptr->outstanding_pkts);
dev->stats.tx_packets++;
dev->stats.tx_bytes += skb->len;
ret = NETDEV_TX_OK;
out:
ipa_rm_inactivity_timer_release_resource(
IPA_RM_RESOURCE_WWAN_0_PROD);
return ret;
}
static void ipa3_wwan_tx_timeout(struct net_device *dev)
{
IPAWANERR("[%s] ipa3_wwan_tx_timeout(), data stall in UL\n", dev->name);
}
/**
* apps_ipa_tx_complete_notify() - Rx notify
*
* @priv: driver context
* @evt: event type
* @data: data provided with event
*
* Check that the packet is the one we sent and release it
* This function will be called in defered context in IPA wq.
*/
static void apps_ipa_tx_complete_notify(void *priv,
enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
struct net_device *dev = (struct net_device *)priv;
struct ipa3_wwan_private *wwan_ptr;
if (dev != IPA_NETDEV()) {
IPAWANDBG("Received pre-SSR packet completion\n");
dev_kfree_skb_any(skb);
return;
}
if (evt != IPA_WRITE_DONE) {
IPAWANERR("unsupported evt on Tx callback, Drop the packet\n");
dev_kfree_skb_any(skb);
dev->stats.tx_dropped++;
return;
}
wwan_ptr = netdev_priv(dev);
atomic_dec(&wwan_ptr->outstanding_pkts);
__netif_tx_lock_bh(netdev_get_tx_queue(dev, 0));
if (!atomic_read(&rmnet_ipa3_ctx->is_ssr) &&
netif_queue_stopped(wwan_ptr->net) &&
atomic_read(&wwan_ptr->outstanding_pkts) <
(wwan_ptr->outstanding_low)) {
IPAWANDBG_LOW("Outstanding low (%d) - waking up queue\n",
wwan_ptr->outstanding_low);
netif_wake_queue(wwan_ptr->net);
}
__netif_tx_unlock_bh(netdev_get_tx_queue(dev, 0));
dev_kfree_skb_any(skb);
ipa_rm_inactivity_timer_release_resource(
IPA_RM_RESOURCE_WWAN_0_PROD);
}
/**
* apps_ipa_packet_receive_notify() - Rx notify
*
* @priv: driver context
* @evt: event type
* @data: data provided with event
*
* IPA will pass a packet to the Linux network stack with skb->data
*/
static void apps_ipa_packet_receive_notify(void *priv,
enum ipa_dp_evt_type evt,
unsigned long data)
{
struct sk_buff *skb = (struct sk_buff *)data;
struct net_device *dev = (struct net_device *)priv;
int result;
unsigned int packet_len = skb->len;
IPAWANDBG_LOW("Rx packet was received");
if (evt != IPA_RECEIVE) {
IPAWANERR("A none IPA_RECEIVE event in wan_ipa_receive\n");
return;
}
skb->dev = IPA_NETDEV();
skb->protocol = htons(ETH_P_MAP);
if (dev->stats.rx_packets % IPA_WWAN_RX_SOFTIRQ_THRESH == 0) {
trace_rmnet_ipa_netifni3(dev->stats.rx_packets);
result = netif_rx_ni(skb);
} else {
trace_rmnet_ipa_netifrx3(dev->stats.rx_packets);
result = netif_rx(skb);
}
if (result) {
pr_err_ratelimited(DEV_NAME " %s:%d fail on netif_rx\n",
__func__, __LINE__);
dev->stats.rx_dropped++;
}
dev->stats.rx_packets++;
dev->stats.rx_bytes += packet_len;
}
static struct ipa3_rmnet_plat_drv_res ipa3_rmnet_res = {0, };
/**
* ipa3_wwan_ioctl() - I/O control for wwan network driver.
*
* @dev: network device
* @ifr: ignored
* @cmd: cmd to be excecuded. can be one of the following:
* IPA_WWAN_IOCTL_OPEN - Open the network interface
* IPA_WWAN_IOCTL_CLOSE - Close the network interface
*
* Return codes:
* 0: success
* NETDEV_TX_BUSY: Error while transmitting the skb. Try again
* later
* -EFAULT: Error while transmitting the skb
*/
static int ipa3_wwan_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
{
int rc = 0;
int mru = 1000, epid = 1, mux_index, len;
struct ipa_msg_meta msg_meta;
struct ipa_wan_msg *wan_msg = NULL;
struct rmnet_ioctl_extended_s extend_ioctl_data;
struct rmnet_ioctl_data_s ioctl_data;
struct ipa3_rmnet_mux_val *mux_channel;
int rmnet_index;
IPAWANDBG("rmnet_ipa got ioctl number 0x%08x", cmd);
switch (cmd) {
/* Set Ethernet protocol */
case RMNET_IOCTL_SET_LLP_ETHERNET:
break;
/* Set RAWIP protocol */
case RMNET_IOCTL_SET_LLP_IP:
break;
/* Get link protocol */
case RMNET_IOCTL_GET_LLP:
ioctl_data.u.operation_mode = RMNET_MODE_LLP_IP;
if (copy_to_user(ifr->ifr_ifru.ifru_data, &ioctl_data,
sizeof(struct rmnet_ioctl_data_s)))
rc = -EFAULT;
break;
/* Set QoS header enabled */
case RMNET_IOCTL_SET_QOS_ENABLE:
return -EINVAL;
/* Set QoS header disabled */
case RMNET_IOCTL_SET_QOS_DISABLE:
break;
/* Get QoS header state */
case RMNET_IOCTL_GET_QOS:
ioctl_data.u.operation_mode = RMNET_MODE_NONE;
if (copy_to_user(ifr->ifr_ifru.ifru_data, &ioctl_data,
sizeof(struct rmnet_ioctl_data_s)))
rc = -EFAULT;
break;
/* Get operation mode */
case RMNET_IOCTL_GET_OPMODE:
ioctl_data.u.operation_mode = RMNET_MODE_LLP_IP;
if (copy_to_user(ifr->ifr_ifru.ifru_data, &ioctl_data,
sizeof(struct rmnet_ioctl_data_s)))
rc = -EFAULT;
break;
/* Open transport port */
case RMNET_IOCTL_OPEN:
break;
/* Close transport port */
case RMNET_IOCTL_CLOSE:
break;
/* Flow enable */
case RMNET_IOCTL_FLOW_ENABLE:
IPAWANDBG("Received flow enable\n");
if (copy_from_user(&ioctl_data, ifr->ifr_ifru.ifru_data,
sizeof(struct rmnet_ioctl_data_s))) {
rc = -EFAULT;
break;
}
ipa3_flow_control(IPA_CLIENT_USB_PROD, true,
ioctl_data.u.tcm_handle);
break;
/* Flow disable */
case RMNET_IOCTL_FLOW_DISABLE:
IPAWANDBG("Received flow disable\n");
if (copy_from_user(&ioctl_data, ifr->ifr_ifru.ifru_data,
sizeof(struct rmnet_ioctl_data_s))) {
rc = -EFAULT;
break;
}
ipa3_flow_control(IPA_CLIENT_USB_PROD, false,
ioctl_data.u.tcm_handle);
break;
/* Set flow handle */
case RMNET_IOCTL_FLOW_SET_HNDL:
break;
/* Extended IOCTLs */
case RMNET_IOCTL_EXTENDED:
IPAWANDBG("get ioctl: RMNET_IOCTL_EXTENDED\n");
if (copy_from_user(&extend_ioctl_data,
(u8 *)ifr->ifr_ifru.ifru_data,
sizeof(struct rmnet_ioctl_extended_s))) {
IPAWANERR("failed to copy extended ioctl data\n");
rc = -EFAULT;
break;
}
switch (extend_ioctl_data.extended_ioctl) {
/* Get features */
case RMNET_IOCTL_GET_SUPPORTED_FEATURES:
IPAWANDBG("get RMNET_IOCTL_GET_SUPPORTED_FEATURES\n");
extend_ioctl_data.u.data =
(RMNET_IOCTL_FEAT_NOTIFY_MUX_CHANNEL |
RMNET_IOCTL_FEAT_SET_EGRESS_DATA_FORMAT |
RMNET_IOCTL_FEAT_SET_INGRESS_DATA_FORMAT);
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
break;
/* Set MRU */
case RMNET_IOCTL_SET_MRU:
mru = extend_ioctl_data.u.data;
IPAWANDBG("get MRU size %d\n",
extend_ioctl_data.u.data);
break;
/* Get MRU */
case RMNET_IOCTL_GET_MRU:
extend_ioctl_data.u.data = mru;
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
break;
/* GET SG support */
case RMNET_IOCTL_GET_SG_SUPPORT:
extend_ioctl_data.u.data =
ipa3_rmnet_res.ipa_advertise_sg_support;
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
break;
/* Get endpoint ID */
case RMNET_IOCTL_GET_EPID:
IPAWANDBG("get ioctl: RMNET_IOCTL_GET_EPID\n");
extend_ioctl_data.u.data = epid;
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
if (copy_from_user(&extend_ioctl_data,
(u8 *)ifr->ifr_ifru.ifru_data,
sizeof(struct rmnet_ioctl_extended_s))) {
IPAWANERR("copy extended ioctl data failed\n");
rc = -EFAULT;
break;
}
IPAWANDBG("RMNET_IOCTL_GET_EPID return %d\n",
extend_ioctl_data.u.data);
break;
/* Endpoint pair */
case RMNET_IOCTL_GET_EP_PAIR:
IPAWANDBG("get ioctl: RMNET_IOCTL_GET_EP_PAIR\n");
extend_ioctl_data.u.ipa_ep_pair.consumer_pipe_num =
ipa3_get_ep_mapping(IPA_CLIENT_APPS_LAN_WAN_PROD);
extend_ioctl_data.u.ipa_ep_pair.producer_pipe_num =
ipa3_get_ep_mapping(IPA_CLIENT_APPS_WAN_CONS);
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
if (copy_from_user(&extend_ioctl_data,
(u8 *)ifr->ifr_ifru.ifru_data,
sizeof(struct rmnet_ioctl_extended_s))) {
IPAWANERR("copy extended ioctl data failed\n");
rc = -EFAULT;
break;
}
IPAWANDBG("RMNET_IOCTL_GET_EP_PAIR c: %d p: %d\n",
extend_ioctl_data.u.ipa_ep_pair.consumer_pipe_num,
extend_ioctl_data.u.ipa_ep_pair.producer_pipe_num);
break;
/* Get driver name */
case RMNET_IOCTL_GET_DRIVER_NAME:
memcpy(&extend_ioctl_data.u.if_name,
IPA_NETDEV()->name,
sizeof(IFNAMSIZ));
if (copy_to_user((u8 *)ifr->ifr_ifru.ifru_data,
&extend_ioctl_data,
sizeof(struct rmnet_ioctl_extended_s)))
rc = -EFAULT;
break;
/* Add MUX ID */
case RMNET_IOCTL_ADD_MUX_CHANNEL:
mux_index = ipa3_find_mux_channel_index(
extend_ioctl_data.u.rmnet_mux_val.mux_id);
if (mux_index < MAX_NUM_OF_MUX_CHANNEL) {
IPAWANDBG("already setup mux(%d)\n",
extend_ioctl_data.u.
rmnet_mux_val.mux_id);
return rc;
}
if (rmnet_ipa3_ctx->rmnet_index
>= MAX_NUM_OF_MUX_CHANNEL) {
IPAWANERR("Exceed mux_channel limit(%d)\n",
rmnet_ipa3_ctx->rmnet_index);
return -EFAULT;
}
IPAWANDBG("ADD_MUX_CHANNEL(%d, name: %s)\n",
extend_ioctl_data.u.rmnet_mux_val.mux_id,
extend_ioctl_data.u.rmnet_mux_val.vchannel_name);
/* cache the mux name and id */
mux_channel = rmnet_ipa3_ctx->mux_channel;
rmnet_index = rmnet_ipa3_ctx->rmnet_index;
mux_channel[rmnet_index].mux_id =
extend_ioctl_data.u.rmnet_mux_val.mux_id;
memcpy(mux_channel[rmnet_index].vchannel_name,
extend_ioctl_data.u.rmnet_mux_val.vchannel_name,
sizeof(mux_channel[rmnet_index]
.vchannel_name));
IPAWANDBG("cashe device[%s:%d] in IPA_wan[%d]\n",
mux_channel[rmnet_index].vchannel_name,
mux_channel[rmnet_index].mux_id,
rmnet_index);
/* check if UL filter rules coming*/
if (rmnet_ipa3_ctx->num_q6_rules != 0) {
IPAWANERR("dev(%s) register to IPA\n",
extend_ioctl_data.u.rmnet_mux_val.
vchannel_name);
rc = ipa3_wwan_register_to_ipa(
rmnet_ipa3_ctx->rmnet_index);
if (rc < 0) {
IPAWANERR("device %s reg IPA failed\n",
extend_ioctl_data.u.
rmnet_mux_val.vchannel_name);
return -ENODEV;
}
mux_channel[rmnet_index].mux_channel_set = true;
mux_channel[rmnet_index].ul_flt_reg = true;
} else {
IPAWANDBG("dev(%s) haven't registered to IPA\n",
extend_ioctl_data.u.
rmnet_mux_val.vchannel_name);
mux_channel[rmnet_index].mux_channel_set = true;
mux_channel[rmnet_index].ul_flt_reg = false;
}
rmnet_ipa3_ctx->rmnet_index++;
break;
case RMNET_IOCTL_SET_EGRESS_DATA_FORMAT:
IPAWANDBG("get RMNET_IOCTL_SET_EGRESS_DATA_FORMAT\n");
if ((extend_ioctl_data.u.data) &
RMNET_IOCTL_EGRESS_FORMAT_CHECKSUM) {
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.hdr.hdr_len = 8;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.cfg.cs_offload_en =
IPA_ENABLE_CS_OFFLOAD_UL;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.cfg.cs_metadata_hdr_offset
= 1;
} else {
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.hdr.hdr_len = 4;
}
if ((extend_ioctl_data.u.data) &
RMNET_IOCTL_EGRESS_FORMAT_AGGREGATION)
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.aggr.aggr_en =
IPA_ENABLE_AGGR;
else
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.
ipa_ep_cfg.aggr.aggr_en =
IPA_BYPASS_AGGR;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.ipa_ep_cfg.hdr.
hdr_ofst_metadata_valid = 1;
/* modem want offset at 0! */
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.ipa_ep_cfg.hdr.
hdr_ofst_metadata = 0;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.ipa_ep_cfg.mode.
dst = IPA_CLIENT_APPS_LAN_WAN_PROD;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.ipa_ep_cfg.mode.
mode = IPA_BASIC;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.client =
IPA_CLIENT_APPS_LAN_WAN_PROD;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.notify =
apps_ipa_tx_complete_notify;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.desc_fifo_sz =
IPA_SYS_TX_DATA_DESC_FIFO_SZ;
rmnet_ipa3_ctx->apps_to_ipa_ep_cfg.priv = dev;
rc = ipa3_setup_sys_pipe(
&rmnet_ipa3_ctx->apps_to_ipa_ep_cfg,
&rmnet_ipa3_ctx->apps_to_ipa3_hdl);
if (rc)
IPAWANERR("failed to config egress endpoint\n");
if (rmnet_ipa3_ctx->num_q6_rules != 0) {
/* already got Q6 UL filter rules*/
if (ipa3_qmi_ctx->modem_cfg_emb_pipe_flt
== false)
rc = ipa3_wwan_add_ul_flt_rule_to_ipa();
else
rc = 0;
rmnet_ipa3_ctx->egress_set = true;
if (rc)
IPAWANERR("install UL rules failed\n");
else
rmnet_ipa3_ctx->a7_ul_flt_set = true;
} else {
/* wait Q6 UL filter rules*/
rmnet_ipa3_ctx->egress_set = true;
IPAWANDBG("no UL-rules, egress_set(%d)\n",
rmnet_ipa3_ctx->egress_set);
}
break;
case RMNET_IOCTL_SET_INGRESS_DATA_FORMAT:/* Set IDF */
IPAWANDBG("get RMNET_IOCTL_SET_INGRESS_DATA_FORMAT\n");
if ((extend_ioctl_data.u.data) &
RMNET_IOCTL_INGRESS_FORMAT_CHECKSUM)
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.
ipa_ep_cfg.cfg.cs_offload_en =
IPA_ENABLE_CS_OFFLOAD_DL;
if ((extend_ioctl_data.u.data) &
RMNET_IOCTL_INGRESS_FORMAT_AGG_DATA) {
IPAWANERR("get AGG size %d count %d\n",
extend_ioctl_data.u.
ingress_format.agg_size,
extend_ioctl_data.u.
ingress_format.agg_count);
if (!ipa_disable_apps_wan_cons_deaggr(
extend_ioctl_data.u.
ingress_format.agg_size,
extend_ioctl_data.
u.ingress_format.agg_count)) {
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.
ipa_ep_cfg.aggr.aggr_byte_limit =
extend_ioctl_data.u.ingress_format.
agg_size;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.
ipa_ep_cfg.aggr.aggr_pkt_limit =
extend_ioctl_data.u.ingress_format.
agg_count;
}
}
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr.
hdr_len = 4;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr.
hdr_ofst_metadata_valid = 1;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.
hdr.hdr_ofst_metadata = 1;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr.
hdr_ofst_pkt_size_valid = 1;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr.
hdr_ofst_pkt_size = 2;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr_ext.
hdr_total_len_or_pad_valid = true;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr_ext.
hdr_total_len_or_pad = 0;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr_ext.
hdr_payload_len_inc_padding = true;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr_ext.
hdr_total_len_or_pad_offset = 0;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.hdr_ext.
hdr_little_endian = 0;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.ipa_ep_cfg.
metadata_mask.metadata_mask = 0xFF000000;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.client =
IPA_CLIENT_APPS_WAN_CONS;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.notify =
apps_ipa_packet_receive_notify;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.desc_fifo_sz =
IPA_SYS_DESC_FIFO_SZ;
rmnet_ipa3_ctx->ipa_to_apps_ep_cfg.priv = dev;
mutex_lock(
&rmnet_ipa3_ctx->ipa_to_apps_pipe_handle_guard);
if (atomic_read(&rmnet_ipa3_ctx->is_ssr)) {
IPAWANDBG("In SSR sequence/recovery\n");
mutex_unlock(&rmnet_ipa3_ctx->
ipa_to_apps_pipe_handle_guard);
rc = -EFAULT;
break;
}
rc = ipa3_setup_sys_pipe(
&rmnet_ipa3_ctx->ipa_to_apps_ep_cfg,
&rmnet_ipa3_ctx->ipa3_to_apps_hdl);
mutex_unlock(&rmnet_ipa3_ctx->
ipa_to_apps_pipe_handle_guard);
if (rc)
IPAWANERR("failed to configure ingress\n");
break;
case RMNET_IOCTL_SET_XLAT_DEV_INFO:
wan_msg = kzalloc(sizeof(struct ipa_wan_msg),
GFP_KERNEL);
if (!wan_msg) {
IPAWANERR("Failed to allocate memory.\n");
return -ENOMEM;
}
len = sizeof(wan_msg->upstream_ifname) >
sizeof(extend_ioctl_data.u.if_name) ?
sizeof(extend_ioctl_data.u.if_name) :
sizeof(wan_msg->upstream_ifname);
strlcpy(wan_msg->upstream_ifname,
extend_ioctl_data.u.if_name, len);
memset(&msg_meta, 0, sizeof(struct ipa_msg_meta));
msg_meta.msg_type = WAN_XLAT_CONNECT;
msg_meta.msg_len = sizeof(struct ipa_wan_msg);
rc = ipa3_send_msg(&msg_meta, wan_msg,
ipa3_wwan_msg_free_cb);
if (rc) {
IPAWANERR("Failed to send XLAT_CONNECT msg\n");
kfree(wan_msg);
}
break;
/* Get agg count */
case RMNET_IOCTL_GET_AGGREGATION_COUNT:
break;
/* Set agg count */
case RMNET_IOCTL_SET_AGGREGATION_COUNT:
break;
/* Get agg size */
case RMNET_IOCTL_GET_AGGREGATION_SIZE:
break;
/* Set agg size */
case RMNET_IOCTL_SET_AGGREGATION_SIZE:
break;
/* Do flow control */
case RMNET_IOCTL_FLOW_CONTROL:
break;
/* For legacy use */
case RMNET_IOCTL_GET_DFLT_CONTROL_CHANNEL:
break;
/* Get HW/SW map */
case RMNET_IOCTL_GET_HWSW_MAP:
break;
/* Set RX Headroom */
case RMNET_IOCTL_SET_RX_HEADROOM:
break;
default:
IPAWANERR("[%s] unsupported extended cmd[%d]",
dev->name,
extend_ioctl_data.extended_ioctl);
rc = -EINVAL;
}
break;
default:
IPAWANERR("[%s] unsupported cmd[%d]",
dev->name, cmd);
rc = -EINVAL;
}
return rc;
}
static const struct net_device_ops ipa3_wwan_ops_ip = {
.ndo_open = ipa3_wwan_open,
.ndo_stop = ipa3_wwan_stop,
.ndo_start_xmit = ipa3_wwan_xmit,
.ndo_tx_timeout = ipa3_wwan_tx_timeout,
.ndo_do_ioctl = ipa3_wwan_ioctl,
.ndo_change_mtu = ipa3_wwan_change_mtu,
.ndo_set_mac_address = 0,
.ndo_validate_addr = 0,
};
/**
* wwan_setup() - Setups the wwan network driver.
*
* @dev: network device
*
* Return codes:
* None
*/
static void ipa3_wwan_setup(struct net_device *dev)
{
dev->netdev_ops = &ipa3_wwan_ops_ip;
ether_setup(dev);
/* set this after calling ether_setup */
dev->header_ops = 0; /* No header */
dev->type = ARPHRD_RAWIP;
dev->hard_header_len = 0;
dev->mtu = WWAN_DATA_LEN;
dev->addr_len = 0;
dev->flags &= ~(IFF_BROADCAST | IFF_MULTICAST);
dev->needed_headroom = HEADROOM_FOR_QMAP;
dev->needed_tailroom = TAILROOM;
dev->watchdog_timeo = 1000;
}
/* IPA_RM related functions start*/
static void ipa3_q6_prod_rm_request_resource(struct work_struct *work);
static DECLARE_DELAYED_WORK(ipa3_q6_con_rm_request,
ipa3_q6_prod_rm_request_resource);
static void ipa3_q6_prod_rm_release_resource(struct work_struct *work);
static DECLARE_DELAYED_WORK(ipa3_q6_con_rm_release,
ipa3_q6_prod_rm_release_resource);
static void ipa3_q6_prod_rm_request_resource(struct work_struct *work)
{
int ret = 0;
ret = ipa_rm_request_resource(IPA_RM_RESOURCE_Q6_PROD);
if (ret < 0 && ret != -EINPROGRESS) {
IPAWANERR("%s: ipa_rm_request_resource failed %d\n", __func__,
ret);
return;
}
}
static int ipa3_q6_rm_request_resource(void)
{
queue_delayed_work(rmnet_ipa3_ctx->rm_q6_wq,
&ipa3_q6_con_rm_request, 0);
return 0;
}
static void ipa3_q6_prod_rm_release_resource(struct work_struct *work)
{
int ret = 0;
ret = ipa_rm_release_resource(IPA_RM_RESOURCE_Q6_PROD);
if (ret < 0 && ret != -EINPROGRESS) {
IPAWANERR("%s: ipa_rm_release_resource failed %d\n", __func__,
ret);
return;
}
}
static int ipa3_q6_rm_release_resource(void)
{
queue_delayed_work(rmnet_ipa3_ctx->rm_q6_wq,
&ipa3_q6_con_rm_release, 0);
return 0;
}
static void ipa3_q6_rm_notify_cb(void *user_data,
enum ipa_rm_event event,
unsigned long data)
{
switch (event) {
case IPA_RM_RESOURCE_GRANTED:
IPAWANDBG_LOW("%s: Q6_PROD GRANTED CB\n", __func__);
break;
case IPA_RM_RESOURCE_RELEASED:
IPAWANDBG_LOW("%s: Q6_PROD RELEASED CB\n", __func__);
break;
default:
return;
}
}
static int ipa3_q6_initialize_rm(void)
{
struct ipa_rm_create_params create_params;
struct ipa_rm_perf_profile profile;
int result;
/* Initialize IPA_RM workqueue */
rmnet_ipa3_ctx->rm_q6_wq = create_singlethread_workqueue("clnt_req");
if (!rmnet_ipa3_ctx->rm_q6_wq)
return -ENOMEM;
memset(&create_params, 0, sizeof(create_params));
create_params.name = IPA_RM_RESOURCE_Q6_PROD;
create_params.reg_params.notify_cb = &ipa3_q6_rm_notify_cb;
result = ipa_rm_create_resource(&create_params);
if (result)
goto create_rsrc_err1;
memset(&create_params, 0, sizeof(create_params));
create_params.name = IPA_RM_RESOURCE_Q6_CONS;
create_params.release_resource = &ipa3_q6_rm_release_resource;
create_params.request_resource = &ipa3_q6_rm_request_resource;
result = ipa_rm_create_resource(&create_params);
if (result)
goto create_rsrc_err2;
/* add dependency*/
result = ipa_rm_add_dependency(IPA_RM_RESOURCE_Q6_PROD,
IPA_RM_RESOURCE_APPS_CONS);
if (result)
goto add_dpnd_err;
/* setup Performance profile */
memset(&profile, 0, sizeof(profile));
profile.max_supported_bandwidth_mbps = 100;
result = ipa_rm_set_perf_profile(IPA_RM_RESOURCE_Q6_PROD,
&profile);
if (result)
goto set_perf_err;
result = ipa_rm_set_perf_profile(IPA_RM_RESOURCE_Q6_CONS,
&profile);
if (result)
goto set_perf_err;
return result;
set_perf_err:
ipa_rm_delete_dependency(IPA_RM_RESOURCE_Q6_PROD,
IPA_RM_RESOURCE_APPS_CONS);
add_dpnd_err:
result = ipa_rm_delete_resource(IPA_RM_RESOURCE_Q6_CONS);
if (result < 0)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_Q6_CONS, result);
create_rsrc_err2:
result = ipa_rm_delete_resource(IPA_RM_RESOURCE_Q6_PROD);
if (result < 0)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_Q6_PROD, result);
create_rsrc_err1:
destroy_workqueue(rmnet_ipa3_ctx->rm_q6_wq);
return result;
}
void ipa3_q6_deinitialize_rm(void)
{
int ret;
ret = ipa_rm_delete_dependency(IPA_RM_RESOURCE_Q6_PROD,
IPA_RM_RESOURCE_APPS_CONS);
if (ret < 0)
IPAWANERR("Error deleting dependency %d->%d, ret=%d\n",
IPA_RM_RESOURCE_Q6_PROD, IPA_RM_RESOURCE_APPS_CONS,
ret);
ret = ipa_rm_delete_resource(IPA_RM_RESOURCE_Q6_CONS);
if (ret < 0)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_Q6_CONS, ret);
ret = ipa_rm_delete_resource(IPA_RM_RESOURCE_Q6_PROD);
if (ret < 0)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_Q6_PROD, ret);
destroy_workqueue(rmnet_ipa3_ctx->rm_q6_wq);
}
static void ipa3_wake_tx_queue(struct work_struct *work)
{
if (IPA_NETDEV()) {
__netif_tx_lock_bh(netdev_get_tx_queue(IPA_NETDEV(), 0));
netif_wake_queue(IPA_NETDEV());
__netif_tx_unlock_bh(netdev_get_tx_queue(IPA_NETDEV(), 0));
}
}
/**
* ipa3_rm_resource_granted() - Called upon
* IPA_RM_RESOURCE_GRANTED event. Wakes up queue is was stopped.
*
* @work: work object supplied ny workqueue
*
* Return codes:
* None
*/
static void ipa3_rm_resource_granted(void *dev)
{
IPAWANDBG_LOW("Resource Granted - starting queue\n");
schedule_work(&ipa3_tx_wakequeue_work);
}
/**
* ipa3_rm_notify() - Callback function for RM events. Handles
* IPA_RM_RESOURCE_GRANTED and IPA_RM_RESOURCE_RELEASED events.
* IPA_RM_RESOURCE_GRANTED is handled in the context of shared
* workqueue.
*
* @dev: network device
* @event: IPA RM event
* @data: Additional data provided by IPA RM
*
* Return codes:
* None
*/
static void ipa3_rm_notify(void *dev, enum ipa_rm_event event,
unsigned long data)
{
struct ipa3_wwan_private *wwan_ptr = netdev_priv(dev);
pr_debug("%s: event %d\n", __func__, event);
switch (event) {
case IPA_RM_RESOURCE_GRANTED:
if (wwan_ptr->device_status == WWAN_DEVICE_INACTIVE) {
complete_all(&wwan_ptr->resource_granted_completion);
break;
}
ipa3_rm_resource_granted(dev);
break;
case IPA_RM_RESOURCE_RELEASED:
break;
default:
pr_err("%s: unknown event %d\n", __func__, event);
break;
}
}
/* IPA_RM related functions end*/
static int ipa3_ssr_notifier_cb(struct notifier_block *this,
unsigned long code,
void *data);
static struct notifier_block ipa3_ssr_notifier = {
.notifier_call = ipa3_ssr_notifier_cb,
};
static int get_ipa_rmnet_dts_configuration(struct platform_device *pdev,
struct ipa3_rmnet_plat_drv_res *ipa_rmnet_drv_res)
{
ipa_rmnet_drv_res->ipa_rmnet_ssr =
of_property_read_bool(pdev->dev.of_node,
"qcom,rmnet-ipa-ssr");
pr_info("IPA SSR support = %s\n",
ipa_rmnet_drv_res->ipa_rmnet_ssr ? "True" : "False");
ipa_rmnet_drv_res->ipa_loaduC =
of_property_read_bool(pdev->dev.of_node,
"qcom,ipa-loaduC");
pr_info("IPA ipa-loaduC = %s\n",
ipa_rmnet_drv_res->ipa_loaduC ? "True" : "False");
ipa_rmnet_drv_res->ipa_advertise_sg_support =
of_property_read_bool(pdev->dev.of_node,
"qcom,ipa-advertise-sg-support");
pr_info("IPA SG support = %s\n",
ipa_rmnet_drv_res->ipa_advertise_sg_support ? "True" : "False");
return 0;
}
struct ipa3_rmnet_context ipa3_rmnet_ctx;
static int ipa3_wwan_probe(struct platform_device *pdev);
struct platform_device *m_pdev;
static void ipa3_delayed_probe(struct work_struct *work)
{
(void)ipa3_wwan_probe(m_pdev);
}
static DECLARE_WORK(ipa3_scheduled_probe, ipa3_delayed_probe);
static void ipa3_ready_cb(void *user_data)
{
struct platform_device *pdev = (struct platform_device *)(user_data);
m_pdev = pdev;
IPAWANDBG("IPA ready callback has been triggered!\n");
schedule_work(&ipa3_scheduled_probe);
}
/**
* ipa3_wwan_probe() - Initialized the module and registers as a
* network interface to the network stack
*
* Note: In case IPA driver hasn't initialized already, the probe function
* will return immediately after registering a callback to be invoked when
* IPA driver initialization is complete.
*
* Return codes:
* 0: success
* -ENOMEM: No memory available
* -EFAULT: Internal error
*/
static int ipa3_wwan_probe(struct platform_device *pdev)
{
int ret, i;
struct net_device *dev;
struct ipa_rm_create_params ipa_rm_params; /* IPA_RM */
struct ipa_rm_perf_profile profile; /* IPA_RM */
pr_info("rmnet_ipa3 started initialization\n");
if (!ipa3_is_ready()) {
IPAWANDBG("IPA driver not ready, registering callback\n");
ret = ipa_register_ipa_ready_cb(ipa3_ready_cb, (void *)pdev);
/*
* If we received -EEXIST, IPA has initialized. So we need
* to continue the probing process.
*/
if (ret != -EEXIST) {
if (ret)
IPAWANERR("IPA CB reg failed - %d\n", ret);
return ret;
}
}
ret = get_ipa_rmnet_dts_configuration(pdev, &ipa3_rmnet_res);
ipa3_rmnet_ctx.ipa_rmnet_ssr = ipa3_rmnet_res.ipa_rmnet_ssr;
ret = ipa3_init_q6_smem();
if (ret) {
IPAWANERR("ipa3_init_q6_smem failed!\n");
return ret;
}
/* initialize tx/rx endpoint setup */
memset(&rmnet_ipa3_ctx->apps_to_ipa_ep_cfg, 0,
sizeof(struct ipa_sys_connect_params));
memset(&rmnet_ipa3_ctx->ipa_to_apps_ep_cfg, 0,
sizeof(struct ipa_sys_connect_params));
/* initialize ex property setup */
rmnet_ipa3_ctx->num_q6_rules = 0;
rmnet_ipa3_ctx->old_num_q6_rules = 0;
rmnet_ipa3_ctx->rmnet_index = 0;
rmnet_ipa3_ctx->egress_set = false;
rmnet_ipa3_ctx->a7_ul_flt_set = false;
for (i = 0; i < MAX_NUM_OF_MUX_CHANNEL; i++)
memset(&rmnet_ipa3_ctx->mux_channel[i], 0,
sizeof(struct ipa3_rmnet_mux_val));
/* start A7 QMI service/client */
if (ipa3_rmnet_res.ipa_loaduC)
/* Android platform loads uC */
ipa3_qmi_service_init(QMI_IPA_PLATFORM_TYPE_MSM_ANDROID_V01);
else
/* LE platform not loads uC */
ipa3_qmi_service_init(QMI_IPA_PLATFORM_TYPE_LE_V01);
/* construct default WAN RT tbl for IPACM */
ret = ipa3_setup_a7_qmap_hdr();
if (ret)
goto setup_a7_qmap_hdr_err;
ret = ipa3_setup_dflt_wan_rt_tables();
if (ret)
goto setup_dflt_wan_rt_tables_err;
if (!atomic_read(&rmnet_ipa3_ctx->is_ssr)) {
/* Start transport-driver fd ioctl for ipacm for first init */
ret = ipa3_wan_ioctl_init();
if (ret)
goto wan_ioctl_init_err;
} else {
/* Enable sending QMI messages after SSR */
ipa3_wan_ioctl_enable_qmi_messages();
}
/* initialize wan-driver netdev */
dev = alloc_netdev(sizeof(struct ipa3_wwan_private),
IPA_WWAN_DEV_NAME,
NET_NAME_UNKNOWN,
ipa3_wwan_setup);
if (!dev) {
IPAWANERR("no memory for netdev\n");
ret = -ENOMEM;
goto alloc_netdev_err;
}
rmnet_ipa3_ctx->wwan_priv = netdev_priv(dev);
memset(rmnet_ipa3_ctx->wwan_priv, 0,
sizeof(*(rmnet_ipa3_ctx->wwan_priv)));
IPAWANDBG("wwan_ptr (private) = %p", rmnet_ipa3_ctx->wwan_priv);
rmnet_ipa3_ctx->wwan_priv->net = dev;
rmnet_ipa3_ctx->wwan_priv->outstanding_high = DEFAULT_OUTSTANDING_HIGH;
rmnet_ipa3_ctx->wwan_priv->outstanding_low = DEFAULT_OUTSTANDING_LOW;
atomic_set(&rmnet_ipa3_ctx->wwan_priv->outstanding_pkts, 0);
spin_lock_init(&rmnet_ipa3_ctx->wwan_priv->lock);
init_completion(
&rmnet_ipa3_ctx->wwan_priv->resource_granted_completion);
if (!atomic_read(&rmnet_ipa3_ctx->is_ssr)) {
/* IPA_RM configuration starts */
ret = ipa3_q6_initialize_rm();
if (ret) {
IPAWANERR("%s: ipa3_q6_initialize_rm failed, ret: %d\n",
__func__, ret);
goto q6_init_err;
}
}
memset(&ipa_rm_params, 0, sizeof(struct ipa_rm_create_params));
ipa_rm_params.name = IPA_RM_RESOURCE_WWAN_0_PROD;
ipa_rm_params.reg_params.user_data = dev;
ipa_rm_params.reg_params.notify_cb = ipa3_rm_notify;
ret = ipa_rm_create_resource(&ipa_rm_params);
if (ret) {
pr_err("%s: unable to create resourse %d in IPA RM\n",
__func__, IPA_RM_RESOURCE_WWAN_0_PROD);
goto create_rsrc_err;
}
ret = ipa_rm_inactivity_timer_init(IPA_RM_RESOURCE_WWAN_0_PROD,
IPA_RM_INACTIVITY_TIMER);
if (ret) {
pr_err("%s: ipa rm timer init failed %d on resourse %d\n",
__func__, ret, IPA_RM_RESOURCE_WWAN_0_PROD);
goto timer_init_err;
}
/* add dependency */
ret = ipa_rm_add_dependency(IPA_RM_RESOURCE_WWAN_0_PROD,
IPA_RM_RESOURCE_Q6_CONS);
if (ret)
goto add_dpnd_err;
/* setup Performance profile */
memset(&profile, 0, sizeof(profile));
profile.max_supported_bandwidth_mbps = IPA_APPS_MAX_BW_IN_MBPS;
ret = ipa_rm_set_perf_profile(IPA_RM_RESOURCE_WWAN_0_PROD,
&profile);
if (ret)
goto set_perf_err;
/* IPA_RM configuration ends */
/* Enable SG support in netdevice. */
if (ipa3_rmnet_res.ipa_advertise_sg_support)
dev->hw_features |= NETIF_F_SG;
ret = register_netdev(dev);
if (ret) {
IPAWANERR("unable to register ipa_netdev %d rc=%d\n",
0, ret);
goto set_perf_err;
}
IPAWANDBG("IPA-WWAN devices (%s) initialization ok :>>>>\n", dev->name);
if (ret) {
IPAWANERR("default configuration failed rc=%d\n",
ret);
goto config_err;
}
atomic_set(&rmnet_ipa3_ctx->is_initialized, 1);
if (!atomic_read(&rmnet_ipa3_ctx->is_ssr)) {
/* offline charging mode */
ipa3_proxy_clk_unvote();
}
atomic_set(&rmnet_ipa3_ctx->is_ssr, 0);
pr_info("rmnet_ipa completed initialization\n");
return 0;
config_err:
unregister_netdev(dev);
set_perf_err:
ret = ipa_rm_delete_dependency(IPA_RM_RESOURCE_WWAN_0_PROD,
IPA_RM_RESOURCE_Q6_CONS);
if (ret)
IPAWANERR("Error deleting dependency %d->%d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, IPA_RM_RESOURCE_Q6_CONS,
ret);
add_dpnd_err:
ret = ipa_rm_inactivity_timer_destroy(
IPA_RM_RESOURCE_WWAN_0_PROD); /* IPA_RM */
if (ret)
IPAWANERR("Error ipa_rm_inactivity_timer_destroy %d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, ret);
timer_init_err:
ret = ipa_rm_delete_resource(IPA_RM_RESOURCE_WWAN_0_PROD);
if (ret)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, ret);
create_rsrc_err:
ipa3_q6_deinitialize_rm();
q6_init_err:
free_netdev(dev);
rmnet_ipa3_ctx->wwan_priv = NULL;
alloc_netdev_err:
ipa3_wan_ioctl_deinit();
wan_ioctl_init_err:
ipa3_del_dflt_wan_rt_tables();
setup_dflt_wan_rt_tables_err:
ipa3_del_a7_qmap_hdr();
setup_a7_qmap_hdr_err:
ipa3_qmi_service_exit();
atomic_set(&rmnet_ipa3_ctx->is_ssr, 0);
return ret;
}
static int ipa3_wwan_remove(struct platform_device *pdev)
{
int ret;
pr_info("rmnet_ipa started deinitialization\n");
mutex_lock(&rmnet_ipa3_ctx->ipa_to_apps_pipe_handle_guard);
ret = ipa3_teardown_sys_pipe(rmnet_ipa3_ctx->ipa3_to_apps_hdl);
if (ret < 0)
IPAWANERR("Failed to teardown IPA->APPS pipe\n");
else
rmnet_ipa3_ctx->ipa3_to_apps_hdl = -1;
mutex_unlock(&rmnet_ipa3_ctx->ipa_to_apps_pipe_handle_guard);
unregister_netdev(IPA_NETDEV());
ret = ipa_rm_delete_dependency(IPA_RM_RESOURCE_WWAN_0_PROD,
IPA_RM_RESOURCE_Q6_CONS);
if (ret < 0)
IPAWANERR("Error deleting dependency %d->%d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, IPA_RM_RESOURCE_Q6_CONS,
ret);
ret = ipa_rm_inactivity_timer_destroy(IPA_RM_RESOURCE_WWAN_0_PROD);
if (ret < 0)
IPAWANERR(
"Error ipa_rm_inactivity_timer_destroy resource %d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, ret);
ret = ipa_rm_delete_resource(IPA_RM_RESOURCE_WWAN_0_PROD);
if (ret < 0)
IPAWANERR("Error deleting resource %d, ret=%d\n",
IPA_RM_RESOURCE_WWAN_0_PROD, ret);
cancel_work_sync(&ipa3_tx_wakequeue_work);
cancel_delayed_work(&ipa_tether_stats_poll_wakequeue_work);
if (IPA_NETDEV())
free_netdev(IPA_NETDEV());
rmnet_ipa3_ctx->wwan_priv = NULL;
/* No need to remove wwan_ioctl during SSR */
if (!atomic_read(&rmnet_ipa3_ctx->is_ssr))
ipa3_wan_ioctl_deinit();
ipa3_del_dflt_wan_rt_tables();
ipa3_del_a7_qmap_hdr();
ipa3_del_mux_qmap_hdrs();
if (ipa3_qmi_ctx->modem_cfg_emb_pipe_flt == false)
ipa3_wwan_del_ul_flt_rule_to_ipa();
ipa3_cleanup_deregister_intf();
atomic_set(&rmnet_ipa3_ctx->is_initialized, 0);
pr_info("rmnet_ipa completed deinitialization\n");
return 0;
}
/**
* rmnet_ipa_ap_suspend() - suspend callback for runtime_pm
* @dev: pointer to device
*
* This callback will be invoked by the runtime_pm framework when an AP suspend
* operation is invoked, usually by pressing a suspend button.
*
* Returns -EAGAIN to runtime_pm framework in case there are pending packets
* in the Tx queue. This will postpone the suspend operation until all the
* pending packets will be transmitted.
*
* In case there are no packets to send, releases the WWAN0_PROD entity.
* As an outcome, the number of IPA active clients should be decremented
* until IPA clocks can be gated.
*/
static int rmnet_ipa_ap_suspend(struct device *dev)
{
struct net_device *netdev = IPA_NETDEV();
struct ipa3_wwan_private *wwan_ptr;
IPAWANDBG_LOW("Enter...\n");
if (netdev == NULL) {
IPAWANERR("netdev is NULL.\n");
return 0;
}
wwan_ptr = netdev_priv(netdev);
if (wwan_ptr == NULL) {
IPAWANERR("wwan_ptr is NULL.\n");
return 0;
}
/* Do not allow A7 to suspend in case there are oustanding packets */
if (atomic_read(&wwan_ptr->outstanding_pkts) != 0) {
IPAWANDBG("Outstanding packets, postponing AP suspend.\n");
return -EAGAIN;
}
/* Make sure that there is no Tx operation ongoing */
netif_tx_lock_bh(netdev);
ipa_rm_release_resource(IPA_RM_RESOURCE_WWAN_0_PROD);
netif_tx_unlock_bh(netdev);
IPAWANDBG_LOW("Exit\n");
return 0;
}
/**
* rmnet_ipa_ap_resume() - resume callback for runtime_pm
* @dev: pointer to device
*
* This callback will be invoked by the runtime_pm framework when an AP resume
* operation is invoked.
*
* Enables the network interface queue and returns success to the
* runtime_pm framework.
*/
static int rmnet_ipa_ap_resume(struct device *dev)
{
struct net_device *netdev = IPA_NETDEV();
IPAWANDBG_LOW("Enter...\n");
if (netdev)
netif_wake_queue(netdev);
IPAWANDBG_LOW("Exit\n");
return 0;
}
static void ipa_stop_polling_stats(void)
{
cancel_delayed_work(&ipa_tether_stats_poll_wakequeue_work);
ipa3_rmnet_ctx.polling_interval = 0;
}
static const struct of_device_id rmnet_ipa_dt_match[] = {
{.compatible = "qcom,rmnet-ipa3"},
{},
};
MODULE_DEVICE_TABLE(of, rmnet_ipa_dt_match);
static const struct dev_pm_ops rmnet_ipa_pm_ops = {
.suspend_noirq = rmnet_ipa_ap_suspend,
.resume_noirq = rmnet_ipa_ap_resume,
};
static struct platform_driver rmnet_ipa_driver = {
.driver = {
.name = "rmnet_ipa3",
.owner = THIS_MODULE,
.pm = &rmnet_ipa_pm_ops,
.of_match_table = rmnet_ipa_dt_match,
},
.probe = ipa3_wwan_probe,
.remove = ipa3_wwan_remove,
};
static int ipa3_ssr_notifier_cb(struct notifier_block *this,
unsigned long code,
void *data)
{
if (!ipa3_rmnet_ctx.ipa_rmnet_ssr)
return NOTIFY_DONE;
switch (code) {
case SUBSYS_BEFORE_SHUTDOWN:
IPAWANINFO("IPA received MPSS BEFORE_SHUTDOWN\n");
atomic_set(&rmnet_ipa3_ctx->is_ssr, 1);
ipa3_q6_pre_shutdown_cleanup();
if (IPA_NETDEV())
netif_stop_queue(IPA_NETDEV());
ipa3_qmi_stop_workqueues();
ipa3_wan_ioctl_stop_qmi_messages();
ipa_stop_polling_stats();
if (atomic_read(&rmnet_ipa3_ctx->is_initialized))
platform_driver_unregister(&rmnet_ipa_driver);
IPAWANINFO("IPA BEFORE_SHUTDOWN handling is complete\n");
break;
case SUBSYS_AFTER_SHUTDOWN:
IPAWANINFO("IPA Received MPSS AFTER_SHUTDOWN\n");
if (atomic_read(&rmnet_ipa3_ctx->is_ssr))
ipa3_q6_post_shutdown_cleanup();
IPAWANINFO("IPA AFTER_SHUTDOWN handling is complete\n");
break;
case SUBSYS_BEFORE_POWERUP:
IPAWANINFO("IPA received MPSS BEFORE_POWERUP\n");
if (atomic_read(&rmnet_ipa3_ctx->is_ssr))
/* clean up cached QMI msg/handlers */
ipa3_qmi_service_exit();
/*hold a proxy vote for the modem*/
ipa3_proxy_clk_vote();
IPAWANINFO("IPA BEFORE_POWERUP handling is complete\n");
break;
case SUBSYS_AFTER_POWERUP:
IPAWANINFO("%s:%d IPA received MPSS AFTER_POWERUP\n",
__func__, __LINE__);
if (!atomic_read(&rmnet_ipa3_ctx->is_initialized) &&
atomic_read(&rmnet_ipa3_ctx->is_ssr))
platform_driver_register(&rmnet_ipa_driver);
IPAWANINFO("IPA AFTER_POWERUP handling is complete\n");
break;
default:
IPAWANDBG("Unsupported subsys notification, IPA received: %lu",
code);
break;
}
IPAWANDBG_LOW("Exit\n");
return NOTIFY_DONE;
}
/**
* rmnet_ipa_free_msg() - Free the msg sent to user space via ipa_send_msg
* @buff: pointer to buffer containing the message
* @len: message len
* @type: message type
*
* This function is invoked when ipa_send_msg is complete (Provided as a
* free function pointer along with the message).
*/
static void rmnet_ipa_free_msg(void *buff, u32 len, u32 type)
{
if (!buff) {
IPAWANERR("Null buffer\n");
return;
}
if (type != IPA_TETHERING_STATS_UPDATE_STATS &&
type != IPA_TETHERING_STATS_UPDATE_NETWORK_STATS) {
IPAWANERR("Wrong type given. buff %p type %d\n",
buff, type);
}
kfree(buff);
}
/**
* rmnet_ipa_get_stats_and_update() - Gets pipe stats from Modem
*
* This function queries the IPA Modem driver for the pipe stats
* via QMI, and updates the user space IPA entity.
*/
static void rmnet_ipa_get_stats_and_update(void)
{
struct ipa_get_data_stats_req_msg_v01 req;
struct ipa_get_data_stats_resp_msg_v01 *resp;
struct ipa_msg_meta msg_meta;
int rc;
resp = kzalloc(sizeof(struct ipa_get_data_stats_resp_msg_v01),
GFP_KERNEL);
if (!resp) {
IPAWANERR("Can't allocate memory for stats message\n");
return;
}
memset(&req, 0, sizeof(struct ipa_get_data_stats_req_msg_v01));
memset(resp, 0, sizeof(struct ipa_get_data_stats_resp_msg_v01));
req.ipa_stats_type = QMI_IPA_STATS_TYPE_PIPE_V01;
rc = ipa3_qmi_get_data_stats(&req, resp);
if (rc) {
IPAWANERR("ipa3_qmi_get_data_stats failed: %d\n", rc);
kfree(resp);
return;
}
memset(&msg_meta, 0, sizeof(struct ipa_msg_meta));
msg_meta.msg_type = IPA_TETHERING_STATS_UPDATE_STATS;
msg_meta.msg_len = sizeof(struct ipa_get_data_stats_resp_msg_v01);
rc = ipa_send_msg(&msg_meta, resp, rmnet_ipa_free_msg);
if (rc) {
IPAWANERR("ipa_send_msg failed: %d\n", rc);
kfree(resp);
return;
}
}
/**
* tethering_stats_poll_queue() - Stats polling function
* @work - Work entry
*
* This function is scheduled periodically (per the interval) in
* order to poll the IPA Modem driver for the pipe stats.
*/
static void tethering_stats_poll_queue(struct work_struct *work)
{
rmnet_ipa_get_stats_and_update();
/* Schedule again only if there's an active polling interval */
if (0 != ipa3_rmnet_ctx.polling_interval)
schedule_delayed_work(&ipa_tether_stats_poll_wakequeue_work,
msecs_to_jiffies(ipa3_rmnet_ctx.polling_interval*1000));
}
/**
* rmnet_ipa_get_network_stats_and_update() - Get network stats from IPA Modem
*
* This function retrieves the data usage (used quota) from the IPA Modem driver
* via QMI, and updates IPA user space entity.
*/
static void rmnet_ipa_get_network_stats_and_update(void)
{
struct ipa_get_apn_data_stats_req_msg_v01 req;
struct ipa_get_apn_data_stats_resp_msg_v01 *resp;
struct ipa_msg_meta msg_meta;
int rc;
resp = kzalloc(sizeof(struct ipa_get_apn_data_stats_resp_msg_v01),
GFP_KERNEL);
if (!resp) {
IPAWANERR("Can't allocate memory for network stats message\n");
return;
}
memset(&req, 0, sizeof(struct ipa_get_apn_data_stats_req_msg_v01));
memset(resp, 0, sizeof(struct ipa_get_apn_data_stats_resp_msg_v01));
req.mux_id_list_valid = true;
req.mux_id_list_len = 1;
req.mux_id_list[0] = ipa3_rmnet_ctx.metered_mux_id;
rc = ipa3_qmi_get_network_stats(&req, resp);
if (rc) {
IPAWANERR("ipa3_qmi_get_network_stats failed: %d\n", rc);
kfree(resp);
return;
}
memset(&msg_meta, 0, sizeof(struct ipa_msg_meta));
msg_meta.msg_type = IPA_TETHERING_STATS_UPDATE_NETWORK_STATS;
msg_meta.msg_len = sizeof(struct ipa_get_apn_data_stats_resp_msg_v01);
rc = ipa_send_msg(&msg_meta, resp, rmnet_ipa_free_msg);
if (rc) {
IPAWANERR("ipa_send_msg failed: %d\n", rc);
kfree(resp);
return;
}
}
/**
* rmnet_ipa3_poll_tethering_stats() - Tethering stats polling IOCTL handler
* @data - IOCTL data
*
* This function handles WAN_IOC_POLL_TETHERING_STATS.
* In case polling interval received is 0, polling will stop
* (If there's a polling in progress, it will allow it to finish), and then will
* fetch network stats, and update the IPA user space.
*
* Return codes:
* 0: Success
*/
int rmnet_ipa3_poll_tethering_stats(struct wan_ioctl_poll_tethering_stats *data)
{
ipa3_rmnet_ctx.polling_interval = data->polling_interval_secs;
cancel_delayed_work_sync(&ipa_tether_stats_poll_wakequeue_work);
if (0 == ipa3_rmnet_ctx.polling_interval) {
ipa3_qmi_stop_data_qouta();
rmnet_ipa_get_network_stats_and_update();
rmnet_ipa_get_stats_and_update();
return 0;
}
schedule_delayed_work(&ipa_tether_stats_poll_wakequeue_work, 0);
return 0;
}
/**
* rmnet_ipa_set_data_quota() - Data quota setting IOCTL handler
* @data - IOCTL data
*
* This function handles WAN_IOC_SET_DATA_QUOTA.
* It translates the given interface name to the Modem MUX ID and
* sends the request of the quota to the IPA Modem driver via QMI.
*
* Return codes:
* 0: Success
* -EFAULT: Invalid interface name provided
* other: See ipa_qmi_set_data_quota
*/
int rmnet_ipa3_set_data_quota(struct wan_ioctl_set_data_quota *data)
{
u32 mux_id;
int index;
struct ipa_set_data_usage_quota_req_msg_v01 req;
index = find_vchannel_name_index(data->interface_name);
IPAWANERR("iface name %s, quota %lu\n",
data->interface_name,
(unsigned long int) data->quota_mbytes);
if (index == MAX_NUM_OF_MUX_CHANNEL) {
IPAWANERR("%s is an invalid iface name\n",
data->interface_name);
return -EFAULT;
}
mux_id = rmnet_ipa3_ctx->mux_channel[index].mux_id;
ipa3_rmnet_ctx.metered_mux_id = mux_id;
memset(&req, 0, sizeof(struct ipa_set_data_usage_quota_req_msg_v01));
req.apn_quota_list_valid = true;
req.apn_quota_list_len = 1;
req.apn_quota_list[0].mux_id = mux_id;
req.apn_quota_list[0].num_Mbytes = data->quota_mbytes;
return ipa3_qmi_set_data_quota(&req);
}
/* rmnet_ipa_set_tether_client_pipe() -
* @data - IOCTL data
*
* This function handles WAN_IOC_SET_DATA_QUOTA.
* It translates the given interface name to the Modem MUX ID and
* sends the request of the quota to the IPA Modem driver via QMI.
*
* Return codes:
* 0: Success
* -EFAULT: Invalid interface name provided
* other: See ipa_qmi_set_data_quota
*/
int rmnet_ipa3_set_tether_client_pipe(
struct wan_ioctl_set_tether_client_pipe *data)
{
int number, i;
IPAWANDBG("client %d, UL %d, DL %d, reset %d\n",
data->ipa_client,
data->ul_src_pipe_len,
data->dl_dst_pipe_len,
data->reset_client);
number = data->ul_src_pipe_len;
for (i = 0; i < number; i++) {
IPAWANDBG("UL index-%d pipe %d\n", i,
data->ul_src_pipe_list[i]);
if (data->reset_client)
ipa3_set_client(data->ul_src_pipe_list[i],
0, false);
else
ipa3_set_client(data->ul_src_pipe_list[i],
data->ipa_client, true);
}
number = data->dl_dst_pipe_len;
for (i = 0; i < number; i++) {
IPAWANDBG("DL index-%d pipe %d\n", i,
data->dl_dst_pipe_list[i]);
if (data->reset_client)
ipa3_set_client(data->dl_dst_pipe_list[i],
0, false);
else
ipa3_set_client(data->dl_dst_pipe_list[i],
data->ipa_client, false);
}
return 0;
}
int rmnet_ipa3_query_tethering_stats(struct wan_ioctl_query_tether_stats *data,
bool reset)
{
struct ipa_get_data_stats_req_msg_v01 *req;
struct ipa_get_data_stats_resp_msg_v01 *resp;
int pipe_len, rc;
req = kzalloc(sizeof(struct ipa_get_data_stats_req_msg_v01),
GFP_KERNEL);
if (!req) {
IPAWANERR("Can't allocate memory for stats message\n");
return -ENOMEM;
}
resp = kzalloc(sizeof(struct ipa_get_data_stats_resp_msg_v01),
GFP_KERNEL);
if (!resp) {
IPAWANERR("Can't allocate memory for stats message\n");
kfree(req);
return -ENOMEM;
}
memset(req, 0, sizeof(struct ipa_get_data_stats_req_msg_v01));
memset(resp, 0, sizeof(struct ipa_get_data_stats_resp_msg_v01));
req->ipa_stats_type = QMI_IPA_STATS_TYPE_PIPE_V01;
if (reset) {
req->reset_stats_valid = true;
req->reset_stats = true;
IPAWANERR("reset the pipe stats\n");
} else {
/* print tethered-client enum */
IPAWANDBG_LOW("Tethered-client enum(%d)\n", data->ipa_client);
}
rc = ipa3_qmi_get_data_stats(req, resp);
if (rc) {
IPAWANERR("can't get ipa_qmi_get_data_stats\n");
kfree(req);
kfree(resp);
return rc;
} else if (reset) {
kfree(req);
kfree(resp);
return 0;
}
if (resp->dl_dst_pipe_stats_list_valid) {
for (pipe_len = 0; pipe_len < resp->dl_dst_pipe_stats_list_len;
pipe_len++) {
IPAWANDBG_LOW("Check entry(%d) dl_dst_pipe(%d)\n",
pipe_len, resp->dl_dst_pipe_stats_list
[pipe_len].pipe_index);
IPAWANDBG_LOW("dl_p_v4(%lu)v6(%lu)\n",
(unsigned long int) resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv4_packets,
(unsigned long int) resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv6_packets);
IPAWANDBG_LOW("dl_b_v4(%lu)v6(%lu)\n",
(unsigned long int) resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv4_bytes,
(unsigned long int) resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv6_bytes);
if (ipa_get_client_uplink(resp->
dl_dst_pipe_stats_list[pipe_len].
pipe_index) == false) {
if (data->ipa_client == ipa_get_client(resp->
dl_dst_pipe_stats_list[pipe_len].
pipe_index)) {
/* update the DL stats */
data->ipv4_rx_packets += resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv4_packets;
data->ipv6_rx_packets += resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv6_packets;
data->ipv4_rx_bytes += resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv4_bytes;
data->ipv6_rx_bytes += resp->
dl_dst_pipe_stats_list[pipe_len].
num_ipv6_bytes;
}
}
}
}
IPAWANDBG_LOW("v4_rx_p(%lu) v6_rx_p(%lu) v4_rx_b(%lu) v6_rx_b(%lu)\n",
(unsigned long int) data->ipv4_rx_packets,
(unsigned long int) data->ipv6_rx_packets,
(unsigned long int) data->ipv4_rx_bytes,
(unsigned long int) data->ipv6_rx_bytes);
if (resp->ul_src_pipe_stats_list_valid) {
for (pipe_len = 0; pipe_len < resp->ul_src_pipe_stats_list_len;
pipe_len++) {
IPAWANDBG_LOW("Check entry(%d) ul_dst_pipe(%d)\n",
pipe_len,
resp->ul_src_pipe_stats_list[pipe_len].
pipe_index);
IPAWANDBG_LOW("ul_p_v4(%lu)v6(%lu)\n",
(unsigned long int) resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv4_packets,
(unsigned long int) resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv6_packets);
IPAWANDBG_LOW("ul_b_v4(%lu)v6(%lu)\n",
(unsigned long int) resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv4_bytes,
(unsigned long int) resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv6_bytes);
if (ipa_get_client_uplink(resp->
ul_src_pipe_stats_list[pipe_len].
pipe_index) == true) {
if (data->ipa_client == ipa_get_client(resp->
ul_src_pipe_stats_list[pipe_len].
pipe_index)) {
/* update the DL stats */
data->ipv4_tx_packets += resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv4_packets;
data->ipv6_tx_packets += resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv6_packets;
data->ipv4_tx_bytes += resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv4_bytes;
data->ipv6_tx_bytes += resp->
ul_src_pipe_stats_list[pipe_len].
num_ipv6_bytes;
}
}
}
}
IPAWANDBG_LOW("tx_p_v4(%lu)v6(%lu)tx_b_v4(%lu) v6(%lu)\n",
(unsigned long int) data->ipv4_tx_packets,
(unsigned long int) data->ipv6_tx_packets,
(unsigned long int) data->ipv4_tx_bytes,
(unsigned long int) data->ipv6_tx_bytes);
kfree(req);
kfree(resp);
return 0;
}
/**
* ipa3_broadcast_quota_reach_ind() - Send Netlink broadcast on Quota
* @mux_id - The MUX ID on which the quota has been reached
*
* This function broadcasts a Netlink event using the kobject of the
* rmnet_ipa interface in order to alert the user space that the quota
* on the specific interface which matches the mux_id has been reached.
*
*/
void ipa3_broadcast_quota_reach_ind(u32 mux_id)
{
char alert_msg[IPA_QUOTA_REACH_ALERT_MAX_SIZE];
char iface_name_m[IPA_QUOTA_REACH_IF_NAME_MAX_SIZE];
char iface_name_l[IPA_QUOTA_REACH_IF_NAME_MAX_SIZE];
char *envp[IPA_UEVENT_NUM_EVNP] = {
alert_msg, iface_name_l, iface_name_m, NULL };
int res;
int index;
index = ipa3_find_mux_channel_index(mux_id);
if (index == MAX_NUM_OF_MUX_CHANNEL) {
IPAWANERR("%u is an mux ID\n", mux_id);
return;
}
res = snprintf(alert_msg, IPA_QUOTA_REACH_ALERT_MAX_SIZE,
"ALERT_NAME=%s", "quotaReachedAlert");
if (IPA_QUOTA_REACH_ALERT_MAX_SIZE <= res) {
IPAWANERR("message too long (%d)", res);
return;
}
/* posting msg for L-release for CNE */
res = snprintf(iface_name_l, IPA_QUOTA_REACH_IF_NAME_MAX_SIZE,
"UPSTREAM=%s", rmnet_ipa3_ctx->mux_channel[index].vchannel_name);
if (IPA_QUOTA_REACH_IF_NAME_MAX_SIZE <= res) {
IPAWANERR("message too long (%d)", res);
return;
}
/* posting msg for M-release for CNE */
res = snprintf(iface_name_m, IPA_QUOTA_REACH_IF_NAME_MAX_SIZE,
"INTERFACE=%s", rmnet_ipa3_ctx->mux_channel[index].vchannel_name);
if (IPA_QUOTA_REACH_IF_NAME_MAX_SIZE <= res) {
IPAWANERR("message too long (%d)", res);
return;
}
IPAWANERR("putting nlmsg: <%s> <%s> <%s>\n",
alert_msg, iface_name_l, iface_name_m);
kobject_uevent_env(&(IPA_NETDEV()->dev.kobj),
KOBJ_CHANGE, envp);
}
/**
* ipa3_q6_handshake_complete() - Perform operations once Q6 is up
* @ssr_bootup - Indicates whether this is a cold boot-up or post-SSR.
*
* This function is invoked once the handshake between the IPA AP driver
* and IPA Q6 driver is complete. At this point, it is possible to perform
* operations which can't be performed until IPA Q6 driver is up.
*
*/
void ipa3_q6_handshake_complete(bool ssr_bootup)
{
/* It is required to recover the network stats after SSR recovery */
if (ssr_bootup) {
/*
* In case the uC is required to be loaded by the Modem,
* the proxy vote will be removed only when uC loading is
* complete and indication is received by the AP. After SSR,
* uC is already loaded. Therefore, proxy vote can be removed
* once Modem init is complete.
*/
ipa3_proxy_clk_unvote();
/*
* It is required to recover the network stats after
* SSR recovery
*/
rmnet_ipa_get_network_stats_and_update();
}
}
static int __init ipa3_wwan_init(void)
{
rmnet_ipa3_ctx = kzalloc(sizeof(*rmnet_ipa3_ctx), GFP_KERNEL);
if (!rmnet_ipa3_ctx) {
IPAWANERR("no memory\n");
return -ENOMEM;
}
atomic_set(&rmnet_ipa3_ctx->is_initialized, 0);
atomic_set(&rmnet_ipa3_ctx->is_ssr, 0);
mutex_init(&rmnet_ipa3_ctx->ipa_to_apps_pipe_handle_guard);
rmnet_ipa3_ctx->ipa3_to_apps_hdl = -1;
/* Register for Modem SSR */
rmnet_ipa3_ctx->subsys_notify_handle = subsys_notif_register_notifier(
SUBSYS_MODEM,
&ipa3_ssr_notifier);
if (!IS_ERR(rmnet_ipa3_ctx->subsys_notify_handle))
return platform_driver_register(&rmnet_ipa_driver);
else
return (int)PTR_ERR(rmnet_ipa3_ctx->subsys_notify_handle);
}
static void __exit ipa3_wwan_cleanup(void)
{
int ret;
mutex_destroy(&rmnet_ipa3_ctx->ipa_to_apps_pipe_handle_guard);
ret = subsys_notif_unregister_notifier(
rmnet_ipa3_ctx->subsys_notify_handle, &ipa3_ssr_notifier);
if (ret)
IPAWANERR(
"Error subsys_notif_unregister_notifier system %s, ret=%d\n",
SUBSYS_MODEM, ret);
platform_driver_unregister(&rmnet_ipa_driver);
kfree(rmnet_ipa3_ctx);
rmnet_ipa3_ctx = NULL;
}
static void ipa3_wwan_msg_free_cb(void *buff, u32 len, u32 type)
{
if (!buff)
IPAWANERR("Null buffer.\n");
kfree(buff);
}
late_initcall(ipa3_wwan_init);
module_exit(ipa3_wwan_cleanup);
MODULE_DESCRIPTION("WWAN Network Interface");
MODULE_LICENSE("GPL v2");
|
jcadduono/nethunter_kernel_g5
|
drivers/platform/msm/ipa/ipa_v3/rmnet_ipa.c
|
C
|
gpl-2.0
| 85,915 |
/******************** (C) COPYRIGHT 2012 STMicroelectronics ********************
*
* File Name : fts.c
* Authors : AMS(Analog Mems Sensor) Team
* Description : FTS Capacitive touch screen controller (FingerTipS)
*
********************************************************************************
*
* 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.
*
* THE PRESENT SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, FOR THE SOLE
* PURPOSE TO SUPPORT YOUR APPLICATION DEVELOPMENT.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*
* THIS SOFTWARE IS SPECIFICALLY DESIGNED FOR EXCLUSIVE USE WITH ST PARTS.
********************************************************************************
* REVISON HISTORY
* DATE | DESCRIPTION
* 03/09/2012| First Release
* 08/11/2012| Code migration
* 23/01/2013| SEC Factory Test
* 29/01/2013| Support Hover Events
* 08/04/2013| SEC Factory Test Add more - hover_enable, glove_mode, clear_cover_mode, fast_glove_mode
* 09/04/2013| Support Blob Information
*******************************************************************************/
#include <linux/init.h>
#include <linux/errno.h>
#include <linux/platform_device.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/serio.h>
#include <linux/init.h>
#include <linux/pm.h>
#include <linux/delay.h>
#include <linux/ctype.h>
#include <linux/gpio.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
//#include "fts.h"
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/power_supply.h>
#include <linux/firmware.h>
#include <linux/regulator/consumer.h>
#include <linux/of_gpio.h>
#ifdef CONFIG_OF
#ifndef USE_OPEN_CLOSE
#define USE_OPEN_CLOSE
#undef CONFIG_HAS_EARLYSUSPEND
#undef CONFIG_PM
#endif
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif
#include <linux/input/mt.h>
#include "fts_ts.h"
static struct i2c_driver fts_i2c_driver;
static bool MutualTouchMode = false;
#ifdef CONFIG_GLOVE_TOUCH
enum TOUCH_MODE {
FTS_TM_NORMAL = 0,
FTS_TM_GLOVE,
};
#endif
static int retry_hover_enable_after_wakeup = 0;
#ifdef USE_OPEN_CLOSE
static int fts_input_open(struct input_dev *dev);
static void fts_input_close(struct input_dev *dev);
#ifdef USE_OPEN_DWORK
static void fts_open_work(struct work_struct *work);
#endif
#endif
static int fts_stop_device(struct fts_ts_info *info);
static int fts_start_device(struct fts_ts_info *info);
static int fts_irq_enable(struct fts_ts_info *info, bool enable);
#if (!defined(CONFIG_HAS_EARLYSUSPEND)) && (!defined(CONFIG_PM)) && !defined(USE_OPEN_CLOSE)
static int fts_suspend(struct i2c_client *client, pm_message_t mesg);
static int fts_resume(struct i2c_client *client);
#endif
int fts_wait_for_ready(struct fts_ts_info *info);
#ifdef CONFIG_HAS_EARLYSUSPEND
static void fts_early_suspend(struct early_suspend *h)
{
struct fts_ts_info *info;
info = container_of(h, struct fts_ts_info, early_suspend);
fts_suspend(info->client, PMSG_SUSPEND);
}
static void fts_late_resume(struct early_suspend *h)
{
struct fts_ts_info *info;
info = container_of(h, struct fts_ts_info, early_suspend);
fts_resume(info->client);
}
#endif
#ifdef FTS_SUPPORT_TA_MODE
extern void fts_register_callback(void *cb);
#endif
int fts_write_reg(struct fts_ts_info *info,
unsigned char *reg, unsigned short num_com)
{
struct i2c_msg xfer_msg[2];
int ret;
if (info->touch_stopped) {
tsp_debug_err(true, &info->client->dev, "%s: Sensor stopped\n", __func__);
goto exit;
}
mutex_lock(&info->i2c_mutex);
xfer_msg[0].addr = info->client->addr;
xfer_msg[0].len = num_com;
xfer_msg[0].flags = 0;
xfer_msg[0].buf = reg;
ret = i2c_transfer(info->client->adapter, xfer_msg, 1);
mutex_unlock(&info->i2c_mutex);
return ret;
exit:
return 0;
}
int fts_read_reg(struct fts_ts_info *info, unsigned char *reg, int cnum,
unsigned char *buf, int num)
{
struct i2c_msg xfer_msg[2];
int ret;
if (info->touch_stopped) {
tsp_debug_err(true, &info->client->dev, "%s: Sensor stopped\n", __func__);
goto exit;
}
mutex_lock(&info->i2c_mutex);
xfer_msg[0].addr = info->client->addr;
xfer_msg[0].len = cnum;
xfer_msg[0].flags = 0;
xfer_msg[0].buf = reg;
xfer_msg[1].addr = info->client->addr;
xfer_msg[1].len = num;
xfer_msg[1].flags = I2C_M_RD;
xfer_msg[1].buf = buf;
ret = i2c_transfer(info->client->adapter, xfer_msg, 2);
mutex_unlock(&info->i2c_mutex);
return ret;
exit:
return 0;
}
static void fts_delay(unsigned int ms)
{
if (ms < 20)
usleep_range(ms, ms);
else
msleep(ms);
}
void fts_command(struct fts_ts_info *info, unsigned char cmd)
{
unsigned char regAdd = 0;
int ret = 0;
regAdd = cmd;
ret = fts_write_reg(info, ®Add, 1);
tsp_debug_info(true, &info->client->dev, "FTS Command (%02X) , ret = %d \n", cmd, ret);
}
void fts_enable_feature(struct fts_ts_info *info, unsigned char cmd, int enable)
{
unsigned char regAdd[2] = {0xC1, 0x00};
int ret = 0;
if (!enable)
regAdd[0] = 0xC2;
regAdd[1] = cmd;
ret = fts_write_reg(info, ®Add[0], 2);
tsp_debug_info(true, &info->client->dev, "FTS %s Feature (%02X %02X) , ret = %d \n", (enable)?"Enable":"Disable", regAdd[0], regAdd[1], ret);
}
void fts_systemreset(struct fts_ts_info *info)
{
unsigned char regAdd[4] = { 0xB6, 0x00, 0x23, 0x01 };
tsp_debug_info(true, &info->client->dev, "FTS SystemReset\n");
fts_write_reg(info, ®Add[0], 4);
fts_delay(10);
}
static void fts_interrupt_set(struct fts_ts_info *info, int enable)
{
unsigned char regAdd[4] = { 0xB6, 0x00, 0x1C, enable };
if (enable)
tsp_debug_info(true, &info->client->dev, "FTS INT Enable\n");
else
tsp_debug_info(true, &info->client->dev, "FTS INT Disable\n");
fts_write_reg(info, ®Add[0], 4);
}
int fts_wait_for_ready(struct fts_ts_info *info)
{
int rc;
unsigned char regAdd;
unsigned char data[FTS_EVENT_SIZE];
int retry = 0;
int err_cnt=0;
memset(data, 0x0, FTS_EVENT_SIZE);
regAdd = READ_ONE_EVENT;
rc = -1;
while (fts_read_reg
(info, ®Add, 1, (unsigned char *)data, FTS_EVENT_SIZE)) {
tsp_debug_info(true, &info->client->dev, "Data : %X \n", data[0]);
if (data[0] == EVENTID_CONTROLLER_READY) {
rc = 0;
break;
}
if (data[0] == EVENTID_ERROR) {
if (err_cnt++>32) {
rc = -2;
break;
}
continue;
}
if (retry++ > FTS_RETRY_COUNT) {
rc = -1;
tsp_debug_info(true, &info->client->dev, "%s: Time Over\n", __func__);
break;
}
fts_delay(20);
}
return rc;
}
int fts_get_version_info(struct fts_ts_info *info)
{
int rc;
unsigned char regAdd[3];
unsigned char data[FTS_EVENT_SIZE];
int retry = 0;
fts_command(info, FTS_CMD_RELEASEINFO);
memset(data, 0x0, FTS_EVENT_SIZE);
regAdd[0] = READ_ONE_EVENT;
rc = -1;
while (fts_read_reg(info, ®Add[0], 1, (unsigned char *)data, FTS_EVENT_SIZE)) {
if (data[0] == EVENTID_INTERNAL_RELEASE_INFO) {
// Internal release Information
info->fw_version_of_ic = (data[3] << 8) + data[4];
info->config_version_of_ic = (data[6] << 8) + data[5];
} else if (data[0] == EVENTID_EXTERNAL_RELEASE_INFO) {
// External release Information
info->fw_main_version_of_ic = (data[1] << 8)+data[2];
rc = 0;
break;
}
if (retry++ > FTS_RETRY_COUNT) {
rc = -1;
tsp_debug_info(true, &info->client->dev, "%s: Time Over\n", __func__);
break;
}
}
tsp_debug_info(true, &info->client->dev,
"IC Firmware Version : 0x%04X "
"IC Config Version : 0x%04X "
"IC Main Version : 0x%04X\n",
info->fw_version_of_ic,
info->config_version_of_ic,
info->fw_main_version_of_ic);
return rc;
}
#ifdef FTS_SUPPORT_NOISE_PARAM
int fts_get_noise_param_address(struct fts_ts_info *info)
{
int rc;
unsigned char regAdd[3];
struct fts_noise_param *noise_param;
int i;
noise_param = (struct fts_noise_param *)&info->noise_param;
regAdd[0] = 0xd0;
regAdd[1] = 0x00;
regAdd[2] = 32 * 2;
rc = fts_read_reg(info, regAdd, 3, (unsigned char *)noise_param->pAddr, 2);
for (i = 1; i < MAX_NOISE_PARAM; i++) {
noise_param->pAddr[i] = noise_param->pAddr[0] + i * 2;
}
for (i = 0; i < MAX_NOISE_PARAM; i++) {
tsp_debug_dbg(true, &info->client->dev, "Get Noise Param%d Address = 0x%4x\n", i,
noise_param->pAddr[i]);
}
return rc;
}
static int fts_get_noise_param(struct fts_ts_info *info)
{
int rc;
unsigned char regAdd[3];
unsigned char data[MAX_NOISE_PARAM * 2];
struct fts_noise_param *noise_param;
int i;
unsigned char buf[3];
noise_param = (struct fts_noise_param *)&info->noise_param;
memset(data, 0x0, MAX_NOISE_PARAM * 2);
for (i = 0; i < MAX_NOISE_PARAM; i++) {
regAdd[0] = 0xb3;
regAdd[1] = 0x00;
regAdd[2] = 0x10;
fts_write_reg(info, regAdd, 3);
regAdd[0] = 0xb1;
regAdd[1] = (noise_param->pAddr[i] >> 8) & 0xff;
regAdd[2] = noise_param->pAddr[i] & 0xff;
rc = fts_read_reg(info, regAdd, 3, &buf[0], 3);
noise_param->pData[i] = buf[1]+(buf[2]<<8);
//tsp_debug_info(true, &info->client->dev, "0x%2x%2x%2x 0x%2x 0x%2x\n", regAdd[0],regAdd[1],regAdd[2], buf[1], buf[2]);
}
for (i = 0; i < MAX_NOISE_PARAM; i++) {
tsp_debug_dbg(true, &info->client->dev, "Get Noise Param%d Address [ 0x%04x ] = 0x%04x\n", i,
noise_param->pAddr[i], noise_param->pData[i]);
}
return rc;
}
static int fts_set_noise_param(struct fts_ts_info *info)
{
int i;
unsigned char regAdd[5];
struct fts_noise_param *noise_param;
noise_param = (struct fts_noise_param *)&info->noise_param;
for (i = 0; i < MAX_NOISE_PARAM; i++) {
regAdd[0] = 0xb3;
regAdd[1] = 0x00;
regAdd[2] = 0x10;
fts_write_reg(info, regAdd, 3);
regAdd[0] = 0xb1;
regAdd[1] = (noise_param->pAddr[i] >> 8) & 0xff;
regAdd[2] = noise_param->pAddr[i] & 0xff;
regAdd[3] = noise_param->pData[i] & 0xff;
regAdd[4] = (noise_param->pData[i] >> 8) & 0xff;
fts_write_reg(info, regAdd, 5);
}
for (i = 0; i < MAX_NOISE_PARAM; i++) {
tsp_debug_dbg(true, &info->client->dev, "Set Noise Param%d Address [ 0x%04x ] = 0x%04x\n", i,
noise_param->pAddr[i], noise_param->pData[i]);
}
return 0;
}
#endif// FTS_SUPPORT_NOISE_PARAM
#ifdef TOUCH_BOOSTER_DVFS
int useing_in_tsp_or_epen = 0;
static void fts_change_dvfs_lock(struct work_struct *work)
{
struct fts_ts_info *info =
container_of(work, struct fts_ts_info, work_dvfs_chg.work);
int retval = 0;
mutex_lock(&info->dvfs_lock);
if (info->dvfs_boost_mode == DVFS_STAGE_DUAL) {
if (info->stay_awake) {
dev_info(&info->client->dev,
"%s: do fw update, do not change cpu frequency.\n",
__func__);
} else {
retval = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT_SECOND);
info->dvfs_freq = MIN_TOUCH_LIMIT_SECOND;
}
} else if (info->dvfs_boost_mode == DVFS_STAGE_SINGLE ||
info->dvfs_boost_mode == DVFS_STAGE_TRIPLE) {
retval = set_freq_limit(DVFS_TOUCH_ID, -1);
info->dvfs_freq = -1;
}
else if (info->dvfs_boost_mode == DVFS_STAGE_NINTH){
retval = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT_SECOND_9LEVEL);
info->dvfs_freq = MIN_TOUCH_LIMIT_SECOND_9LEVEL;
}
if (retval < 0)
dev_err(&info->client->dev,
"%s: booster change failed(%d).\n",
__func__, retval);
mutex_unlock(&info->dvfs_lock);
}
static void fts_set_dvfs_off(struct work_struct *work)
{
struct fts_ts_info *info =
container_of(work, struct fts_ts_info, work_dvfs_off.work);
int retval;
if (info->stay_awake) {
dev_info(&info->client->dev,
"%s: do fw update, do not change cpu frequency.\n",
__func__);
} else {
mutex_lock(&info->dvfs_lock);
if((useing_in_tsp_or_epen & 0x01)== 0x01){
useing_in_tsp_or_epen = 0x01;
retval = 0;
}else{
retval = set_freq_limit(DVFS_TOUCH_ID, -1);
useing_in_tsp_or_epen = 0;
}
info->dvfs_freq = -1;
if (retval < 0)
dev_err(&info->client->dev,
"%s: booster stop failed(%d).\n",
__func__, retval);
info->dvfs_lock_status = false;
mutex_unlock(&info->dvfs_lock);
}
}
static void fts_set_dvfs_lock(struct fts_ts_info *info, int on)
{
int ret = 0;
if (info->dvfs_boost_mode == DVFS_STAGE_NONE) {
dev_dbg(&info->client->dev,
"%s: DVFS stage is none(%d)\n",
__func__, info->dvfs_boost_mode);
return;
}
mutex_lock(&info->dvfs_lock);
if (on == 0) {
if (info->dvfs_lock_status){
if(info->dvfs_boost_mode == DVFS_STAGE_NINTH)
schedule_delayed_work(&info->work_dvfs_off,
msecs_to_jiffies(INPUT_BOOSTER_HIGH_OFF_TIME_TSP));
else
schedule_delayed_work(&info->work_dvfs_off,
msecs_to_jiffies(TOUCH_BOOSTER_OFF_TIME));
}
} else if (on > 0) {
cancel_delayed_work(&info->work_dvfs_off);
if ((!info->dvfs_lock_status) || (info->dvfs_old_stauts < on)) {
cancel_delayed_work(&info->work_dvfs_chg);
useing_in_tsp_or_epen = useing_in_tsp_or_epen | 0x2;
if(info->dvfs_boost_mode == DVFS_STAGE_NINTH){
if (info->dvfs_freq != MIN_TOUCH_HIGH_LIMIT) {
ret = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_HIGH_LIMIT);
info->dvfs_freq = MIN_TOUCH_HIGH_LIMIT;
}
schedule_delayed_work(&info->work_dvfs_chg,
msecs_to_jiffies(INPUT_BOOSTER_HIGH_CHG_TIME_TSP));
}
else
{
if (info->dvfs_freq != MIN_TOUCH_LIMIT) {
if (info->dvfs_boost_mode == DVFS_STAGE_TRIPLE)
ret = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT_SECOND);
else
ret = set_freq_limit(DVFS_TOUCH_ID,
MIN_TOUCH_LIMIT);
info->dvfs_freq = MIN_TOUCH_LIMIT;
}
schedule_delayed_work(&info->work_dvfs_chg,
msecs_to_jiffies(TOUCH_BOOSTER_CHG_TIME));
}
if (ret < 0)
dev_err(&info->client->dev,
"%s: cpu first lock failed(%d)\n",
__func__, ret);
info->dvfs_lock_status = true;
}
} else if (on < 0) {
if (info->dvfs_lock_status) {
cancel_delayed_work(&info->work_dvfs_off);
cancel_delayed_work(&info->work_dvfs_chg);
schedule_work(&info->work_dvfs_off.work);
}
}
info->dvfs_old_stauts = on;
mutex_unlock(&info->dvfs_lock);
}
static int fts_init_dvfs(struct fts_ts_info *info)
{
mutex_init(&info->dvfs_lock);
info->dvfs_boost_mode = DVFS_STAGE_DUAL;
INIT_DELAYED_WORK(&info->work_dvfs_off, fts_set_dvfs_off);
INIT_DELAYED_WORK(&info->work_dvfs_chg, fts_change_dvfs_lock);
info->dvfs_lock_status = false;
return 0;
}
#endif
/* Added for samsung dependent codes such as Factory test,
* Touch booster, Related debug sysfs.
*/
#include "fts_sec.c"
static int fts_init(struct fts_ts_info *info)
{
unsigned char val[16];
unsigned char regAdd[8];
int rc;
fts_delay(200);
// TS Chip ID
regAdd[0] = 0xB6;
regAdd[1] = 0x00;
regAdd[2] = 0x07;
rc = fts_read_reg(info, regAdd, 3, (unsigned char *)val, 7);
tsp_debug_info(true, &info->client->dev, "FTS %02X%02X%02X = %02X %02X %02X %02X / %02X %02X \n",
regAdd[0], regAdd[1], regAdd[2], val[1], val[2], val[3], val[4], val[5], val[6]);
if (val[1] != FTS_ID0 || val[2] != FTS_ID1)
return 1;
fts_systemreset(info);
rc=fts_wait_for_ready(info);
if (rc==-2) {
info->fw_version_of_ic =0;
info->config_version_of_ic=0;
info->fw_main_version_of_ic=0;
} else
fts_get_version_info(info);
if ((rc = fts_fw_update_on_probe(info)) < 0) {
if (rc != -2)
tsp_debug_err(true, info->dev, "%s: Failed to firmware update\n",
__func__);
}
info->touch_count = 0;
fts_command(info, SLEEPOUT);
fts_command(info, SENSEON);
#ifdef FTS_SUPPORT_NOISE_PARAM
fts_get_noise_param_address(info);
#endif
info->hover_enabled = false;
info->hover_ready = false;
info->slow_report_rate = false;
info->flip_enable = false;
#ifdef SEC_TSP_FACTORY_TEST
rc = getChannelInfo(info);
if (rc >= 0) {
tsp_debug_info(true, &info->client->dev, "FTS Sense(%02d) Force(%02d)\n",
info->SenseChannelLength, info->ForceChannelLength);
} else {
tsp_debug_info(true, &info->client->dev, "FTS read failed rc = %d\n", rc);
tsp_debug_info(true, &info->client->dev, "FTS Initialise Failed\n");
return 1;
}
info->pFrame =
kzalloc(info->SenseChannelLength * info->ForceChannelLength * 2,
GFP_KERNEL);
if (info->pFrame == NULL) {
tsp_debug_info(true, &info->client->dev, "FTS pFrame kzalloc Failed\n");
return 1;
}
#endif
fts_command(info, FORCECALIBRATION);
fts_command(info, FLUSHBUFFER);
fts_interrupt_set(info, INT_ENABLE);
memset(val, 0x0, 4);
regAdd[0] = READ_STATUS;
fts_read_reg(info, regAdd, 1, (unsigned char *)val, 4);
tsp_debug_info(true, &info->client->dev, "FTS ReadStatus(0x84) : %02X %02X %02X %02X\n", val[0],
val[1], val[2], val[3]);
MutualTouchMode = false;
tsp_debug_info(true, &info->client->dev, "FTS Initialized\n");
return 0;
}
static void fts_unknown_event_handler(struct fts_ts_info *info,
unsigned char data[])
{
tsp_debug_dbg(true, &info->client->dev,
"FTS Unknown Event %02X %02X %02X %02X %02X %02X %02X %02X\n",
data[0], data[1], data[2], data[3], data[4], data[5], data[6],
data[7]);
}
static unsigned char fts_event_handler_type_b(struct fts_ts_info *info,
unsigned char data[],
unsigned char LeftEvent)
{
unsigned char EventNum = 0;
unsigned char NumTouches = 0;
unsigned char TouchID = 0, EventID = 0;
unsigned char LastLeftEvent = 0;
int x = 0, y = 0, z = 0;
int bw = 0, bh = 0, palm = 0, sumsize = 0;
for (EventNum = 0; EventNum < LeftEvent; EventNum++) {
/*tsp_debug_info(true, &info->client->dev, "%d %2x %2x %2x %2x %2x %2x %2x %2x\n", EventNum,
data[EventNum * FTS_EVENT_SIZE],
data[EventNum * FTS_EVENT_SIZE+1],
data[EventNum * FTS_EVENT_SIZE+2],
data[EventNum * FTS_EVENT_SIZE+3],
data[EventNum * FTS_EVENT_SIZE+4],
data[EventNum * FTS_EVENT_SIZE+5],
data[EventNum * FTS_EVENT_SIZE+6],
data[EventNum * FTS_EVENT_SIZE+7]); */
EventID = data[EventNum * FTS_EVENT_SIZE] & 0x0F;
if ((EventID >= 3) && (EventID <= 5)) {
LastLeftEvent = 0;
NumTouches = 1;
TouchID = (data[EventNum * FTS_EVENT_SIZE] >> 4) & 0x0F;
} else {
LastLeftEvent =
data[7 + EventNum * FTS_EVENT_SIZE] & 0x0F;
NumTouches =
(data[1 + EventNum * FTS_EVENT_SIZE] & 0xF0) >> 4;
TouchID = data[1 + EventNum * FTS_EVENT_SIZE] & 0x0F;
EventID = data[EventNum * FTS_EVENT_SIZE] & 0xFF;
}
switch (EventID) {
case EVENTID_NO_EVENT:
break;
case EVENTID_ERROR:
if (data[1 + EventNum * FTS_EVENT_SIZE] == 0x08) { // Get Auto tune fail event
if (data[2 + EventNum * FTS_EVENT_SIZE] == 0x00) {
tsp_debug_info(true, &info->client->dev, "[FTS] Fail Mutual Auto tune\n");
}
else if (data[2 + EventNum * FTS_EVENT_SIZE] == 0x01) {
tsp_debug_info(true, &info->client->dev, "[FTS] Fail Self Auto tune\n");
}
}
break;
case EVENTID_HOVER_ENTER_POINTER:
case EVENTID_HOVER_MOTION_POINTER:
x = ((data[4 + EventNum * FTS_EVENT_SIZE] & 0xF0) >> 4)
| ((data[2 + EventNum * FTS_EVENT_SIZE]) << 4);
y = ((data[4 + EventNum * FTS_EVENT_SIZE] & 0x0F) |
((data[3 + EventNum * FTS_EVENT_SIZE]) << 4));
z = data[5 + EventNum * FTS_EVENT_SIZE];
input_mt_slot(info->input_dev, 0);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER, 1);
input_report_key(info->input_dev, BTN_TOUCH, 0);
input_report_key(info->input_dev, BTN_TOOL_FINGER, 1);
input_report_abs(info->input_dev, ABS_MT_POSITION_X, x);
input_report_abs(info->input_dev, ABS_MT_POSITION_Y, y);
input_report_abs(info->input_dev, ABS_MT_DISTANCE, 255 - z);
break;
case EVENTID_HOVER_LEAVE_POINTER:
input_mt_slot(info->input_dev, 0);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER, 0);
break;
case EVENTID_ENTER_POINTER:
info->touch_count++;
case EVENTID_MOTION_POINTER:
x = data[1 + EventNum * FTS_EVENT_SIZE] +
((data[2 + EventNum * FTS_EVENT_SIZE] &
0x0f) << 8);
y = ((data[2 + EventNum * FTS_EVENT_SIZE] &
0xf0) >> 4) + (data[3 +
EventNum *
FTS_EVENT_SIZE] << 4);
bw = data[4 + EventNum * FTS_EVENT_SIZE];
bh = data[5 + EventNum * FTS_EVENT_SIZE];
palm = (data[6 + EventNum * FTS_EVENT_SIZE] >> 7) & 0x01;
sumsize = (data[6 + EventNum * FTS_EVENT_SIZE] & 0x7f) << 1;
z = data[7 + EventNum * FTS_EVENT_SIZE];
input_mt_slot(info->input_dev, TouchID);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER,
1 + (palm << 1));
input_report_key(info->input_dev, BTN_TOUCH, 1);
input_report_key(info->input_dev,
BTN_TOOL_FINGER, 1);
input_report_abs(info->input_dev,
ABS_MT_POSITION_X, x);
input_report_abs(info->input_dev,
ABS_MT_POSITION_Y, y);
input_report_abs(info->input_dev,
ABS_MT_TOUCH_MAJOR, max(bw,
bh));
input_report_abs(info->input_dev,
ABS_MT_TOUCH_MINOR, min(bw,
bh));
input_report_abs(info->input_dev,
ABS_MT_SUMSIZE, sumsize);
input_report_abs(info->input_dev, ABS_MT_PALM,
palm);
break;
case EVENTID_LEAVE_POINTER:
info->touch_count--;
input_mt_slot(info->input_dev, TouchID);
input_mt_report_slot_state(info->input_dev,
MT_TOOL_FINGER, 0);
if (info->touch_count == 0) {
input_report_key(info->input_dev, BTN_TOUCH, 0);
}
break;
case EVENTID_STATUS_EVENT:
if (data[1 + EventNum * FTS_EVENT_SIZE] == 0x0C) {
#ifdef CONFIG_GLOVE_TOUCH
int tm;
if (data[2 + EventNum * FTS_EVENT_SIZE] == 0x01)
info->touch_mode = FTS_TM_GLOVE;
else
info->touch_mode = FTS_TM_NORMAL;
tm = info->touch_mode;
input_report_switch(info->input_dev, SW_GLOVE, tm);
#endif
} else if ((data[1 + EventNum * FTS_EVENT_SIZE] & 0x0f) == 0x0d) {
unsigned char regAdd[4] = {0xB0, 0x01, 0x29, 0x01};
fts_write_reg(info, ®Add[0], 4);
info->hover_ready = true;
tsp_debug_info(true, &info->client->dev, "[FTS] Received the Hover Raw Data Ready Event\n");
} else {
fts_unknown_event_handler(info,
&data[EventNum *
FTS_EVENT_SIZE]);
}
break;
#ifdef SEC_TSP_FACTORY_TEST
case EVENTID_RESULT_READ_REGISTER:
procedure_cmd_event(info, &data[EventNum * FTS_EVENT_SIZE]);
break;
#endif
default:
fts_unknown_event_handler(info,
&data[EventNum *
FTS_EVENT_SIZE]);
continue;
}
#if !defined(CONFIG_SAMSUNG_PRODUCT_SHIP)
if (EventID == EVENTID_ENTER_POINTER)
tsp_debug_info(true, &info->client->dev,
"[P] tID:%d x:%d y:%d w:%d h:%d z:%d s:%d p:%d tc:%d tm:%d\n",
TouchID, x, y, bw, bh, z, sumsize, palm, info->touch_count, info->touch_mode);
else if (EventID == EVENTID_HOVER_ENTER_POINTER)
tsp_debug_dbg(true, &info->client->dev,
"[HP] tID:%d x:%d y:%d z:%d\n",
TouchID, x, y, z);
#else
if (EventID == EVENTID_ENTER_POINTER)
tsp_debug_info(true, &info->client->dev,
"[P] tID:%d tc:%d tm:%d\n",
TouchID, info->touch_count, info->touch_mode);
else if (EventID == EVENTID_HOVER_ENTER_POINTER)
tsp_debug_dbg(true, &info->client->dev,
"[HP] tID:%d\n", TouchID);
#endif
else if (EventID == EVENTID_LEAVE_POINTER) {
tsp_debug_info(true, &info->client->dev,
"[R] tID:%d mc: %d tc:%d Ver[%02X%04X%01X%01X]\n",
TouchID, info->finger[TouchID].mcount, info->touch_count,
info->panel_revision, info->fw_main_version_of_ic,
info->flip_enable, info->mshover_enabled);
info->finger[TouchID].mcount = 0;
} else if (EventID == EVENTID_HOVER_LEAVE_POINTER) {
tsp_debug_dbg(true, &info->client->dev,
"[HR] tID:%d Ver[%02X%04X%01X%01X]\n",
TouchID,
info->panel_revision, info->fw_main_version_of_ic,
info->flip_enable, info->mshover_enabled);
info->finger[TouchID].mcount = 0;
} else if (EventID == EVENTID_MOTION_POINTER)
info->finger[TouchID].mcount++;
if ((EventID == EVENTID_ENTER_POINTER) ||
(EventID == EVENTID_MOTION_POINTER) ||
(EventID == EVENTID_LEAVE_POINTER))
info->finger[TouchID].state = EventID;
}
input_sync(info->input_dev);
#ifdef TOUCH_BOOSTER_DVFS
if ((EventID == EVENTID_ENTER_POINTER)
|| (EventID == EVENTID_LEAVE_POINTER)) {
fts_set_dvfs_lock(info, info->touch_count);
}
#endif
return LastLeftEvent;
}
#ifdef FTS_SUPPORT_TA_MODE
static void fts_ta_cb(struct fts_callbacks *cb, int ta_status)
{
struct fts_ts_info *info =
container_of(cb, struct fts_ts_info, callbacks);
pr_err("[TSP]%s: ta:%d\n", __func__, ta_status);
if (ta_status == 0x01 || ta_status == 0x03) {
fts_command(info, FTS_CMD_CHARGER_PLUGGED);
info->TA_Pluged = true;
tsp_debug_info(true, &info->client->dev,
"%s: device_control : CHARGER CONNECTED, ta_status : %x\n",
__func__, ta_status);
} else {
fts_command(info, FTS_CMD_CHARGER_UNPLUGGED);
info->TA_Pluged = false;
tsp_debug_info(true, &info->client->dev,
"%s: device_control : CHARGER DISCONNECTED, ta_status : %x\n",
__func__, ta_status);
}
}
#endif
/**
* fts_interrupt_handler()
*
* Called by the kernel when an interrupt occurs (when the sensor
* asserts the attention irq).
*
* This function is the ISR thread and handles the acquisition
* and the reporting of finger data when the presence of fingers
* is detected.
*/
static irqreturn_t fts_interrupt_handler(int irq, void *handle)
{
struct fts_ts_info *info = handle;
unsigned char regAdd[4] = {0xb6, 0x00, 0x45, READ_ALL_EVENT};
unsigned short evtcount = 0;
evtcount = 0;
fts_read_reg(info, ®Add[0], 3, (unsigned char *)&evtcount, 2);
evtcount = evtcount >> 10;
if (evtcount > FTS_FIFO_MAX)
evtcount = FTS_FIFO_MAX;
if (evtcount > 0) {
memset(info->data, 0x0, FTS_EVENT_SIZE * evtcount);
fts_read_reg(info, ®Add[3], 1, (unsigned char *)info->data,
FTS_EVENT_SIZE * evtcount);
fts_event_handler_type_b(info, info->data, evtcount);
}
return IRQ_HANDLED;
}
static int fts_irq_enable(struct fts_ts_info *info,
bool enable)
{
int retval = 0;
if (enable) {
if (info->irq_enabled)
return retval;
retval = request_threaded_irq(info->irq, NULL,
fts_interrupt_handler, info->board->irq_type,
FTS_TS_DRV_NAME, info);
if (retval < 0) {
tsp_debug_info(true, &info->client->dev,
"%s: Failed to create irq thread %d\n",
__func__, retval);
return retval;
}
info->irq_enabled = true;
} else {
if (info->irq_enabled) {
disable_irq(info->irq);
free_irq(info->irq, info);
info->irq_enabled = false;
}
}
return retval;
}
#ifdef CONFIG_OF
u32 gpio_ldo_en_p = 31;
struct regulator *i2c_vddo_vreg = NULL;
struct regulator_bulk_data *fts_supplies;
int fts_vdd_on(bool onoff)
{
pr_err("[TSP]%s: gpio:%d, vdd en:%d\n", __func__, gpio_ldo_en_p, onoff);
{
int retval;
if(onoff){
if (regulator_is_enabled(fts_supplies[0].consumer)) {
pr_err("%s: %s is already enabled\n", __func__, fts_supplies[0].supply);
}else {
retval = regulator_enable(fts_supplies[0].consumer);
if (retval) {
pr_err("%s: Fail to enable regulator %s[%d]\n", __func__, fts_supplies[0].supply, retval);
}
pr_err("%s: %s is enabled[OK]\n", __func__, fts_supplies[0].supply);
}
}else{
if (regulator_is_enabled(fts_supplies[0].consumer)) {
retval = regulator_disable(fts_supplies[0].consumer);
if (retval) {
pr_err("%s: Fail to disable regulator %s[%d]\n", __func__, fts_supplies[0].supply, retval);
}
pr_err("%s: %s is disabled[OK]\n", __func__, fts_supplies[0].supply);
}else {
pr_err("%s: %s is already disabled\n", __func__, fts_supplies[0].supply);
}
}
}
if(i2c_vddo_vreg != NULL){
if(onoff){
regulator_enable(i2c_vddo_vreg);
}else{
regulator_disable(i2c_vddo_vreg);
}
}else{
pr_err("[TSP]%s: i2c_vddo_vreg is null vdd en:%d\n", __func__, onoff);
}
if(gpio_ldo_en_p > 0){
gpio_direction_output(gpio_ldo_en_p, onoff);
}
msleep(50);
return 1;
}
void fts_init_gpio(struct fts_ts_info *info, struct fts_ts_platform_data *pdata)
{
int ret;
pr_err("[TSP] %s, %d \n",__func__, __LINE__ );
if(pdata->tsp_id > 0)
gpio_tlmm_config(GPIO_CFG(pdata->tsp_id, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_DOWN, GPIO_CFG_2MA), 1);
gpio_tlmm_config(GPIO_CFG(pdata->scl_gpio, 3, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), 1);
gpio_tlmm_config(GPIO_CFG(pdata->sda_gpio, 3, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), 1);
gpio_tlmm_config(GPIO_CFG(pdata->gpio_int, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), 1);
if(pdata->gpio_ldo_en > 0){
ret = gpio_request(pdata->gpio_ldo_en, "fts_gpio_ldo_en");
if(ret) {
tsp_debug_err(true, &info->client->dev, "[TSP]%s: unable to request fts_gpio_ldo_en [%d]\n", __func__, pdata->gpio_ldo_en);
return;
}
gpio_tlmm_config(GPIO_CFG(pdata->gpio_ldo_en, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE);
}
}
static int fts_parse_dt(struct device *dev, struct fts_ts_platform_data *pdata)
{
struct device_node *np = dev->of_node;
//u32 temp;
pdata->gpio_ldo_en = of_get_named_gpio(np, "fts,vdd_en-gpio", 0);
pdata->gpio_int = of_get_named_gpio(np, "fts,irq-gpio", 0);
printk(KERN_INFO "[TSP]%s: en_vdd:%d, irq:%d \n", __func__, pdata->gpio_ldo_en, pdata->gpio_int);
pdata->tsp_id = of_get_named_gpio(np, "fts,id-gpio", 0);
pdata->scl_gpio = of_get_named_gpio(np, "fts,scl-gpio", 0);
pdata->sda_gpio = of_get_named_gpio(np, "fts,sda-gpio", 0);
pdata->gpio_ldo_en = 0;
{
int rc;
pdata->name_of_supply = kzalloc(sizeof(char *), GFP_KERNEL);
rc = of_property_read_string(np, "fts,supply-name", &pdata->name_of_supply);
if (rc && (rc != -EINVAL)) {
printk(KERN_INFO "%s: Unable to read %s\n", __func__,"fts,supply-name");
return rc;
}
dev_info(dev, "%s: supply: %s\n", __func__, pdata->name_of_supply);
}
return 0;
}
#endif
static int fts_probe(struct i2c_client *client, const struct i2c_device_id *idp)
{
int retval;
struct fts_ts_info *info = NULL;
#ifdef CONFIG_OF
static struct fts_i2c_platform_data *board_p;
struct fts_ts_platform_data *pdata;
#endif
static char fts_ts_phys[64] = { 0 };
int i = 0;
#ifdef SEC_TSP_FACTORY_TEST
int ret;
#endif
tsp_debug_info(true, &client->dev, "FTS Driver [12%s] %s %s\n",
FTS_TS_DRV_VERSION, __DATE__, __TIME__);
if (!i2c_check_functionality(client->adapter, I2C_FUNC_I2C)) {
tsp_debug_err(true, &client->dev, "FTS err = EIO!\n");
return -EIO;
}
#ifdef CONFIG_OF
if (client->dev.of_node) {
pdata = devm_kzalloc(&client->dev,
sizeof(struct fts_ts_platform_data), GFP_KERNEL);
if (!pdata) {
tsp_debug_err(true, &client->dev, "Failed to allocate memory\n");
return -ENOMEM;
}
ret = fts_parse_dt(&client->dev, pdata);
if (ret) {
tsp_debug_err(true, &client->dev, "Error parsing dt %d\n", ret);
return ret;
}
fts_init_gpio(info, pdata);
gpio_ldo_en_p = pdata->gpio_ldo_en;
}else{
tsp_debug_err(true, &client->dev, "%s, of-node error %d\n",__func__,__LINE__);
return -ENOMEM;
}
#endif
info = kzalloc(sizeof(struct fts_ts_info), GFP_KERNEL);
if (!info) {
tsp_debug_err(true, &client->dev, "FTS err = ENOMEM!\n");
return -ENOMEM;
}
#ifdef USE_OPEN_DWORK
INIT_DELAYED_WORK(&info->open_work, fts_open_work);
#endif
#ifdef CONFIG_OF
info->client = client;
info->pdata = pdata;
//info->board = client->dev.platform_data;
board_p = kzalloc(sizeof(struct fts_i2c_platform_data), GFP_KERNEL);
if (!board_p) {
tsp_debug_err(true, &client->dev, "board_p err = ENOMEM!\n");
return -ENOMEM;
}
board_p->max_x = 720;
board_p->max_y = 1280;
board_p->project_name = "G850X";
board_p->max_width = 28;
board_p->support_hover = true;
board_p->support_mshover = true;
board_p->firmware_name = "tsp_stm/stm_s.fw";
board_p->power = fts_vdd_on;
board_p->irq_type = IRQF_TRIGGER_LOW | IRQF_ONESHOT;
board_p->gpio = pdata->gpio_int; //GPIO_TSP_INT;
info->board = board_p;
#endif
if (info->board->support_hover) {
tsp_debug_info(true, &info->client->dev, "FTS Support Hover Event \n");
} else {
tsp_debug_info(true, &info->client->dev, "FTS Not support Hover Event \n");
}
#if defined(CONFIG_OF)
i2c_vddo_vreg = regulator_get(&info->client->dev,"vddo");
if (IS_ERR(i2c_vddo_vreg)){
i2c_vddo_vreg = NULL;
pr_err("[TSP]%s: i2c_vddo_vreg is error , %d \n", __func__, __LINE__);
}
#endif
fts_supplies = kzalloc(sizeof(struct regulator_bulk_data), GFP_KERNEL);
if (!fts_supplies) {
pr_err("%s: Failed to alloc mem for supplies\n", __func__);
retval = -ENOMEM;
goto err_input_allocate_device;
}
fts_supplies[0].supply = pdata->name_of_supply;
retval = regulator_bulk_get(&client->dev, 1, fts_supplies);
if (retval)
goto err_get_regulator;
if (info->board->power)
info->board->power(true);
info->dev = &info->client->dev;
info->input_dev = input_allocate_device();
if (!info->input_dev) {
tsp_debug_info(true, &info->client->dev, "FTS err = ENOMEM!\n");
retval = -ENOMEM;
goto err_input_allocate_device;
}
info->input_dev->dev.parent = &client->dev;
info->input_dev->name = "sec_touchscreen";
snprintf(fts_ts_phys, sizeof(fts_ts_phys), "%s/input1",
info->input_dev->name);
info->input_dev->phys = fts_ts_phys;
info->input_dev->id.bustype = BUS_I2C;
client->irq = gpio_to_irq(pdata->gpio_int);
printk(KERN_ERR "%s: tsp : gpio_to_irq : %d\n", __func__, client->irq);
info->irq = client->irq;
info->irq_type = info->board->irq_type;
info->irq_enabled = false;
info->touch_stopped = false;
info->panel_revision = info->board->panel_revision;
info->stop_device = fts_stop_device;
info->start_device = fts_start_device;
info->fts_command = fts_command;
info->fts_read_reg = fts_read_reg;
info->fts_write_reg = fts_write_reg;
info->fts_systemreset = fts_systemreset;
info->fts_get_version_info = fts_get_version_info;
info->fts_wait_for_ready = fts_wait_for_ready;
info->fts_enable_feature = fts_enable_feature;
#ifdef FTS_SUPPORT_NOISE_PARAM
info->fts_get_noise_param_address = fts_get_noise_param_address;
#endif
#ifdef USE_OPEN_CLOSE
info->input_dev->open = fts_input_open;
info->input_dev->close = fts_input_close;
#endif
#ifdef CONFIG_GLOVE_TOUCH
input_set_capability(info->input_dev, EV_SW, SW_GLOVE);
#endif
set_bit(EV_SYN, info->input_dev->evbit);
set_bit(EV_KEY, info->input_dev->evbit);
set_bit(EV_ABS, info->input_dev->evbit);
#ifdef INPUT_PROP_DIRECT
set_bit(INPUT_PROP_DIRECT, info->input_dev->propbit);
#endif
set_bit(BTN_TOUCH, info->input_dev->keybit);
set_bit(BTN_TOOL_FINGER, info->input_dev->keybit);
input_mt_init_slots(info->input_dev, FINGER_MAX);
input_set_abs_params(info->input_dev, ABS_MT_POSITION_X,
0, info->board->max_x, 0, 0);
input_set_abs_params(info->input_dev, ABS_MT_POSITION_Y,
0, info->board->max_y, 0, 0);
mutex_init(&info->lock);
mutex_init(&(info->device_mutex));
mutex_init(&info->i2c_mutex);
info->enabled = false;
mutex_lock(&info->lock);
retval = fts_init(info);
mutex_unlock(&info->lock);
if (retval) {
tsp_debug_err(true, &info->client->dev, "FTS fts_init fail!\n");
goto err_fts_init;
}
input_set_abs_params(info->input_dev, ABS_MT_TOUCH_MAJOR,
0, 255, 0, 0);
input_set_abs_params(info->input_dev, ABS_MT_TOUCH_MINOR,
0, 255, 0, 0);
input_set_abs_params(info->input_dev, ABS_MT_SUMSIZE,
0, 255, 0, 0);
input_set_abs_params(info->input_dev, ABS_MT_PALM, 0, 1, 0, 0);
input_set_abs_params(info->input_dev, ABS_MT_DISTANCE,
0, 255, 0, 0);
input_set_drvdata(info->input_dev, info);
i2c_set_clientdata(client, info);
retval = input_register_device(info->input_dev);
if (retval) {
tsp_debug_err(true, &info->client->dev, "FTS input_register_device fail!\n");
goto err_register_input;
}
for (i = 0; i < FINGER_MAX; i++) {
info->finger[i].state = EVENTID_LEAVE_POINTER;
info->finger[i].mcount = 0;
}
info->enabled = true;
retval = fts_irq_enable(info, true);
if (retval < 0) {
tsp_debug_info(true, &info->client->dev,
"%s: Failed to enable attention interrupt\n",
__func__);
goto err_enable_irq;
}
#ifdef TOUCH_BOOSTER_DVFS
fts_init_dvfs(info);
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
info->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1;
info->early_suspend.suspend = fts_early_suspend;
info->early_sfts_start_deviceuspend.resume = fts_late_resume;
register_early_suspend(&info->early_suspend);
#endif
#ifdef FTS_SUPPORT_TA_MODE
info->register_cb = fts_register_callback;
info->callbacks.inform_charger = fts_ta_cb;
if (info->register_cb)
info->register_cb(&info->callbacks);
#endif
#ifdef SEC_TSP_FACTORY_TEST
INIT_LIST_HEAD(&info->cmd_list_head);
info->cmd_buffer_size = 0;
for (i = 0; i < ARRAY_SIZE(ft_cmds); i++){
list_add_tail(&ft_cmds[i].list, &info->cmd_list_head);
if(ft_cmds[i].cmd_name)
info->cmd_buffer_size += strlen(ft_cmds[i].cmd_name) + 1;
}
info->cmd_result = kzalloc(info->cmd_buffer_size, GFP_KERNEL);
if(!info->cmd_result){
tsp_debug_err(true, &info->client->dev, "FTS Failed to allocate cmd result\n");
goto err_alloc_cmd_result;
}
mutex_init(&info->cmd_lock);
info->cmd_is_running = false;
info->fac_dev_ts = device_create(sec_class, NULL, FTS_ID0, info, "tsp");
if (IS_ERR(info->fac_dev_ts)) {
tsp_debug_err(true, &info->client->dev, "FTS Failed to create device for the sysfs\n");
goto err_sysfs;
}
dev_set_drvdata(info->fac_dev_ts, info);
ret = sysfs_create_group(&info->fac_dev_ts->kobj,
&sec_touch_factory_attr_group);
if (ret < 0) {
tsp_debug_err(true, &info->client->dev, "FTS Failed to create sysfs group\n");
goto err_sysfs;
}
ret = sysfs_create_link(&info->fac_dev_ts->kobj,
&info->input_dev->dev.kobj, "input");
if (ret < 0) {
tsp_debug_err(true, &info->client->dev,
"%s: Failed to create link\n", __func__);
goto err_sysfs;
}
#endif
pr_err("[TSP] %s, end, %d \n",__func__, __LINE__ );
return 0;
#ifdef SEC_TSP_FACTORY_TEST
err_sysfs:
kfree(info->cmd_result);
err_alloc_cmd_result:
if (info->irq_enabled)
fts_irq_enable(info, false);
#endif
err_enable_irq:
input_unregister_device(info->input_dev);
info->input_dev = NULL;
err_register_input:
if (info->input_dev)
input_free_device(info->input_dev);
err_fts_init:
err_get_regulator:
kfree(fts_supplies);
err_input_allocate_device:
info->board->power(false);
kfree(info);
return retval;
}
static int fts_remove(struct i2c_client *client)
{
struct fts_ts_info *info = i2c_get_clientdata(client);
tsp_debug_info(true, &info->client->dev, "FTS removed \n");
#ifdef CONFIG_HAS_EARLYSUSPEND
unregister_early_suspend(&info->early_suspend);
#endif
fts_interrupt_set(info, INT_DISABLE);
fts_command(info, FLUSHBUFFER);
fts_irq_enable(info, false);
input_mt_destroy_slots(info->input_dev);
#ifdef SEC_TSP_FACTORY_TEST
sysfs_remove_link(&info->fac_dev_ts->kobj, "input");
sysfs_remove_group(&info->fac_dev_ts->kobj,
&sec_touch_factory_attr_group);
device_destroy(sec_class, FTS_ID0);
if (info->cmd_result)
kfree(info->cmd_result);
list_del(&info->cmd_list_head);
mutex_destroy(&info->cmd_lock);
if (info->pFrame)
kfree(info->pFrame);
#endif
mutex_destroy(&info->lock);
input_unregister_device(info->input_dev);
info->input_dev = NULL;
info->board->power(false);
kfree(info);
kfree(fts_supplies);
return 0;
}
#ifdef USE_OPEN_CLOSE
#ifdef USE_OPEN_DWORK
static void fts_open_work(struct work_struct *work)
{
int retval;
struct fts_ts_info *info = container_of(work, struct fts_ts_info,
open_work.work);
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
retval = fts_start_device(info);
if (retval < 0)
tsp_debug_err(true, &info->client->dev,
"%s: Failed to start device\n", __func__);
}
#endif
static int fts_input_open(struct input_dev *dev)
{
struct fts_ts_info *info = input_get_drvdata(dev);
int retval;
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
#ifdef USE_OPEN_DWORK
schedule_delayed_work(&info->open_work,
msecs_to_jiffies(TOUCH_OPEN_DWORK_TIME));
#else
retval = fts_start_device(info);
if (retval < 0){
tsp_debug_err(true, &info->client->dev,
"%s: Failed to start device\n", __func__);
goto out;
}
#endif
tsp_debug_err(true, &info->client->dev, "FTS cmd after wakeup : h%d\n",
retry_hover_enable_after_wakeup);
if(retry_hover_enable_after_wakeup == 1){
unsigned char regAdd[4] = {0xB0, 0x01, 0x29, 0x41};
fts_write_reg(info, ®Add[0], 4);
fts_command(info, FTS_CMD_HOVER_ON);
info->hover_ready = false;
info->hover_enabled = true;
}
out:
return 0;
}
static void fts_input_close(struct input_dev *dev)
{
struct fts_ts_info *info = input_get_drvdata(dev);
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
#ifdef USE_OPEN_DWORK
cancel_delayed_work(&info->open_work);
#endif
fts_stop_device(info);
retry_hover_enable_after_wakeup = 0;
}
#endif
#ifdef CONFIG_SEC_FACTORY
#include <linux/uaccess.h>
#define LCD_LDI_FILE_PATH "/sys/class/lcd/panel/window_type"
static int fts_get_panel_revision(struct fts_ts_info *info)
{
int iRet = 0;
mm_segment_t old_fs;
struct file *window_type;
unsigned char lcdtype[4] = {0,};
old_fs = get_fs();
set_fs(KERNEL_DS);
window_type = filp_open(LCD_LDI_FILE_PATH, O_RDONLY, 0666);
if (IS_ERR(window_type)) {
iRet = PTR_ERR(window_type);
if (iRet != -ENOENT)
tsp_debug_err(true, &info->client->dev, "%s: window_type file open fail\n", __func__);
set_fs(old_fs);
goto exit;
}
iRet = window_type->f_op->read(window_type, (u8 *)lcdtype, sizeof(u8) * 4, &window_type->f_pos);
if (iRet != (sizeof(u8) * 4)) {
tsp_debug_err(true, &info->client->dev, "%s: Can't read the lcd ldi data\n", __func__);
iRet = -EIO;
}
/* The variable of lcdtype has ASCII values(40 81 45) at 0x08 OCTA,
* so if someone need a TSP panel revision then to read third parameter.*/
info->panel_revision = lcdtype[3] & 0x0F;
tsp_debug_info(true, &info->client->dev,
"%s: update panel_revision 0x%02X\n", __func__, info->panel_revision);
filp_close(window_type, current->files);
set_fs(old_fs);
exit:
return iRet;
}
static void fts_reinit_fac(struct fts_ts_info *info)
{
int rc;
info->touch_count = 0;
fts_command(info, SLEEPOUT);
fts_delay(50);
fts_command(info, SENSEON);
fts_delay(50);
if (info->slow_report_rate)
fts_command(info, FTS_CMD_SLOW_SCAN);
#ifdef FTS_SUPPORT_NOISE_PARAM
fts_get_noise_param_address(info);
#endif
if (info->flip_enable)
fts_enable_feature(info, FTS_FEATURE_COVER_GLASS, true);
else if (info->fast_mshover_enabled)
fts_command(info, FTS_CMD_SET_FAST_GLOVE_MODE);
else if (info->mshover_enabled)
fts_command(info, FTS_CMD_MSHOVER_ON);
rc = getChannelInfo(info);
if (rc >= 0) {
tsp_debug_info(true, &info->client->dev, "FTS Sense(%02d) Force(%02d)\n",
info->SenseChannelLength, info->ForceChannelLength);
} else {
tsp_debug_info(true, &info->client->dev, "FTS read failed rc = %d\n", rc);
tsp_debug_info(true, &info->client->dev, "FTS Initialise Failed\n");
return;
}
info->pFrame =
kzalloc(info->SenseChannelLength * info->ForceChannelLength * 2,
GFP_KERNEL);
if (info->pFrame == NULL) {
tsp_debug_info(true, &info->client->dev, "FTS pFrame kzalloc Failed\n");
return;
}
fts_command(info, FORCECALIBRATION);
fts_command(info, FLUSHBUFFER);
fts_interrupt_set(info, INT_ENABLE);
tsp_debug_info(true, &info->client->dev, "FTS Re-Initialised\n");
}
#endif
static void fts_reinit(struct fts_ts_info *info)
{
fts_wait_for_ready(info);
fts_systemreset(info);
fts_wait_for_ready(info);
#ifdef CONFIG_SEC_FACTORY
/* Read firmware version from IC when every power up IC.
* During Factory process touch panel can be changed manually.
*/
{
unsigned short orig_fw_main_version_of_ic = info->fw_main_version_of_ic;
fts_get_panel_revision(info);
fts_get_version_info(info);
if (info->fw_main_version_of_ic != orig_fw_main_version_of_ic) {
fts_fw_init(info);
fts_reinit_fac(info);
return;
}
}
#endif
#ifdef FTS_SUPPORT_NOISE_PARAM
fts_set_noise_param(info);
#endif
fts_command(info, SLEEPOUT);
fts_delay(50);
fts_command(info, SENSEON);
fts_delay(50);
if (info->slow_report_rate)
fts_command(info, FTS_CMD_SLOW_SCAN);
if (info->flip_enable)
fts_enable_feature(info, FTS_FEATURE_COVER_GLASS, true);
else if (info->fast_mshover_enabled)
fts_command(info, FTS_CMD_SET_FAST_GLOVE_MODE);
else if (info->mshover_enabled)
fts_command(info, FTS_CMD_MSHOVER_ON);
#ifdef FTS_SUPPORT_TA_MODE
if (info->TA_Pluged)
fts_command(info, FTS_CMD_CHARGER_PLUGGED);
#endif
info->touch_count = 0;
fts_command(info, FLUSHBUFFER);
fts_interrupt_set(info, INT_ENABLE);
}
void fts_release_all_finger(struct fts_ts_info *info)
{
int i;
for (i = 0; i < FINGER_MAX; i++) {
input_mt_slot(info->input_dev, i);
input_mt_report_slot_state(info->input_dev, MT_TOOL_FINGER, 0);
if ((info->finger[i].state == EVENTID_ENTER_POINTER) ||
(info->finger[i].state == EVENTID_MOTION_POINTER)) {
info->touch_count--;
if (info->touch_count < 0)
info->touch_count = 0;
tsp_debug_info(true, &info->client->dev,
"[RA] tID:%d mc: %d tc:%d Ver[%02X%04X%01X%01X]\n",
i, info->finger[i].mcount, info->touch_count,
info->panel_revision, info->fw_main_version_of_ic,
info->flip_enable, info->mshover_enabled);
}
info->finger[i].state = EVENTID_LEAVE_POINTER;
info->finger[i].mcount = 0;
}
input_report_key(info->input_dev, BTN_TOUCH, 0);
#ifdef CONFIG_GLOVE_TOUCH
input_report_switch(info->input_dev, SW_GLOVE, false);
info->touch_mode = FTS_TM_NORMAL;
#endif
input_sync(info->input_dev);
#ifdef TOUCH_BOOSTER_DVFS
fts_set_dvfs_lock(info, -1);
#endif
}
static int fts_stop_device(struct fts_ts_info *info)
{
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
mutex_lock(&info->device_mutex);
if (info->touch_stopped) {
tsp_debug_err(true, &info->client->dev, "%s already power off\n", __func__);
goto out;
}
fts_interrupt_set(info, INT_DISABLE);
disable_irq(info->irq);
fts_command(info, FLUSHBUFFER);
fts_command(info, SLEEPIN);
fts_release_all_finger(info);
#ifdef FTS_SUPPORT_NOISE_PARAM
fts_get_noise_param(info);
#endif
info->touch_stopped = true;
if (info->board->power)
info->board->power(false);
out:
mutex_unlock(&info->device_mutex);
return 0;
}
static int fts_start_device(struct fts_ts_info *info)
{
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
mutex_lock(&info->device_mutex);
if (!info->touch_stopped) {
tsp_debug_err(true, &info->client->dev, "%s already power on\n", __func__);
info->reinit_done = true;
goto out;
}
if (info->board->power)
info->board->power(true);
info->touch_stopped = false;
info->reinit_done = false;
fts_reinit(info);
info->reinit_done = true;
enable_irq(info->irq);
out:
mutex_unlock(&info->device_mutex);
return 0;
}
#ifdef CONFIG_PM
static int fts_pm_suspend(struct device *dev)
{
struct fts_ts_info *info = dev_get_drvdata(dev);
tsp_debug_dbg(false, &info->client->dev, "%s\n", __func__);;
mutex_lock(&info->input_dev->mutex);
if (info->input_dev->users)
fts_stop_device(info);
mutex_unlock(&info->input_dev->mutex);
return 0;
}
static int fts_pm_resume(struct device *dev)
{
struct fts_ts_info *info = dev_get_drvdata(dev);
tsp_debug_dbg(false, &info->client->dev, "%s\n", __func__);
mutex_lock(&info->input_dev->mutex);
if (info->input_dev->users)
fts_start_device(info);
mutex_unlock(&info->input_dev->mutex);
return 0;
}
#endif
#if (!defined(CONFIG_HAS_EARLYSUSPEND)) && (!defined(CONFIG_PM)) && !defined(USE_OPEN_CLOSE)
static int fts_suspend(struct i2c_client *client, pm_message_t mesg)
{
struct fts_ts_info *info = i2c_get_clientdata(client);
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
fts_stop_device(info);
return 0;
}
static int fts_resume(struct i2c_client *client)
{
struct fts_ts_info *info = i2c_get_clientdata(client);
tsp_debug_info(true, &info->client->dev, "%s\n", __func__);
fts_start_device(info);
return 0;
}
#endif
static const struct i2c_device_id fts_device_id[] = {
{FTS_TS_DRV_NAME, 0},
{}
};
#if defined(CONFIG_PM) && !defined(USE_OPEN_CLOSE)
static const struct dev_pm_ops fts_dev_pm_ops = {
.suspend = fts_pm_suspend,
.resume = fts_pm_resume,
};
#endif
#ifdef CONFIG_OF
static struct of_device_id fts_match_table[] = {
{ .compatible = "stm,fts_touch",},
{ },
};
#else
#define fts_match_table NULL
#endif
static struct i2c_driver fts_i2c_driver = {
.driver = {
.name = FTS_TS_DRV_NAME,
.owner = THIS_MODULE,
#ifdef CONFIG_OF
.of_match_table = fts_match_table,
#endif
#if defined(CONFIG_PM) && !defined(USE_OPEN_CLOSE)
.pm = &fts_dev_pm_ops,
#endif
},
.probe = fts_probe,
.remove = fts_remove,
#if (!defined(CONFIG_HAS_EARLYSUSPEND)) && (!defined(CONFIG_PM)) && !defined(USE_OPEN_CLOSE)
.suspend = fts_suspend,
.resume = fts_resume,
#endif
.id_table = fts_device_id,
};
static int __init fts_driver_init(void)
{
extern int poweroff_charging;
pr_err("[TSP] %s : init !!\n", __func__);
if (poweroff_charging) {
pr_err("%s : LPM Charging Mode!!\n", __func__);
return 0;
}
else
return i2c_add_driver(&fts_i2c_driver);
}
static void __exit fts_driver_exit(void)
{
i2c_del_driver(&fts_i2c_driver);
}
MODULE_DESCRIPTION("STMicroelectronics MultiTouch IC Driver");
MODULE_AUTHOR("STMicroelectronics, Inc.");
MODULE_LICENSE("GPL v2");
module_init(fts_driver_init);
module_exit(fts_driver_exit);
|
Dm47021/android_kernel_afyonlte
|
drivers/input/touchscreen/stm_s/fts_ts.c
|
C
|
gpl-2.0
| 49,856 |
/*
* Created on 20 févr. 2004
*
* Firemox is a turn based strategy simulator
* Copyright (C) 2003-2007 Fabrice Daugan
*
* 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
*/
package net.sf.firemox.action;
import net.sf.firemox.action.handler.StandardAction;
import net.sf.firemox.clickable.ability.Ability;
import net.sf.firemox.event.UpdatedLife;
import net.sf.firemox.event.context.ContextEventListener;
/**
* Raise the 'updatelife' event that should be captured by an defined ability of
* play. This action raise ONLY this event, and should be called at the end of
* any ability dealting damages to update player status.
*
* @author <a href="mailto:[email protected]">Fabrice Daugan </a>
* @since 0.63
* @see net.sf.firemox.event.Event#ID__UPDATE_LIFE
*/
final class UpdateLife extends UserAction implements StandardAction {
/**
*/
private UpdateLife() {
super((String) null);
}
@Override
public Actiontype getIdAction() {
return Actiontype.UPDATE_LIFE;
}
public boolean play(ContextEventListener context, Ability ability) {
UpdatedLife.dispatchEvent();
return true;
}
/**
* return the string representation of this action
*
* @param ability
* is the ability owning this test. The card component of this
* ability should correspond to the card owning this test too.
* @return the string representation of this action
* @see Object#toString()
*/
@Override
public String toString(Ability ability) {
return "Update the player's life";
}
/**
* Return the unique instance of this class.
*
* @return the unique instance of this class
*/
public static UserAction getInstance() {
if (instance == null) {
instance = new UpdateLife();
}
return instance;
}
/**
* The unique instance of this class
*/
private static UserAction instance;
}
|
JoeyLeeuwinga/Firemox
|
src/main/java/net/sf/firemox/action/UpdateLife.java
|
Java
|
gpl-2.0
| 2,619 |
/*
* Copyright (C) 2004 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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.
*/
#ifndef KJS_BINDINGS_OBJC_UTILITY_H
#define KJS_BINDINGS_OBJC_UTILITY_H
#include <CoreFoundation/CoreFoundation.h>
#include "objc_header.h"
#include <runtime/Error.h>
#include <runtime/JSObject.h>
OBJC_CLASS NSString;
namespace JSC {
namespace Bindings {
typedef union {
ObjectStructPtr objectValue;
bool booleanValue;
char charValue;
short shortValue;
int intValue;
long longValue;
long long longLongValue;
float floatValue;
double doubleValue;
} ObjcValue;
typedef enum {
ObjcVoidType,
ObjcObjectType,
ObjcCharType,
ObjcUnsignedCharType,
ObjcShortType,
ObjcUnsignedShortType,
ObjcIntType,
ObjcUnsignedIntType,
ObjcLongType,
ObjcUnsignedLongType,
ObjcLongLongType,
ObjcUnsignedLongLongType,
ObjcFloatType,
ObjcDoubleType,
ObjcBoolType,
ObjcInvalidType
} ObjcValueType;
class RootObject;
ObjcValue convertValueToObjcValue(ExecState*, JSValue, ObjcValueType);
JSValue convertNSStringToString(ExecState* exec, NSString *nsstring);
JSValue convertObjcValueToValue(ExecState*, void* buffer, ObjcValueType, RootObject*);
ObjcValueType objcValueTypeForType(const char *type);
JSObject *throwError(ExecState*, ThrowScope&, NSString *message);
} // namespace Bindings
} // namespace JSC
#endif
|
Debian/openjfx
|
modules/web/src/main/native/Source/WebCore/bridge/objc/objc_utility.h
|
C
|
gpl-2.0
| 2,630 |
spike_generators = {}
spike_detectors = {}
multimeters = {}
startsimulate = 0
endsimulate = 0
all_parts = tuple()
SYNAPSES = 0 # synapse number
NEURONS = 0 # neurons number
times = [] # store time simulation
|
research-team/NEUCOGAR
|
NEST/cube/dopamine/3d_Hodkin-Huxley_model/scripts/globals.py
|
Python
|
gpl-2.0
| 215 |
/*
KeePass Password Safe - The Open-Source Password Manager
Copyright (C) 2003-2015 Dominik Reichl <[email protected]>
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 St, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.Globalization;
using System.Diagnostics;
using KeePass.Resources;
using KeePassLib;
using KeePassLib.Serialization;
using KeePassLib.Utility;
namespace KeePass.UI
{
/// <summary>
/// MRU handler interface. An MRU handler must support executing an MRU
/// item and clearing the MRU list.
/// </summary>
public interface IMruExecuteHandler
{
/// <summary>
/// Function that is called when an MRU item is executed (i.e. when
/// the user has clicked the menu item).
/// </summary>
void OnMruExecute(string strDisplayName, object oTag,
ToolStripMenuItem tsmiParent);
/// <summary>
/// Function to clear the MRU (for example all menu items must be
/// removed from the menu).
/// </summary>
void OnMruClear();
}
public sealed class MruList
{
private List<KeyValuePair<string, object>> m_vItems =
new List<KeyValuePair<string, object>>();
private IMruExecuteHandler m_handler = null;
private List<ToolStripMenuItem> m_lContainers =
new List<ToolStripMenuItem>();
private ToolStripMenuItem m_tsmiClear = null;
private List<ToolStripMenuItem> m_lMruMenuItems =
new List<ToolStripMenuItem>();
private enum MruMenuItemType
{
None = 0,
Item,
Clear
}
// private Font m_fItalic = null;
private uint m_uMaxItemCount = 0;
public uint MaxItemCount
{
get { return m_uMaxItemCount; }
set { m_uMaxItemCount = value; }
}
private bool m_bMarkOpened = false;
public bool MarkOpened
{
get { return m_bMarkOpened; }
set { m_bMarkOpened = value; }
}
public uint ItemCount
{
get { return (uint)m_vItems.Count; }
}
public bool IsValid
{
get { return (m_handler != null); }
}
public MruList()
{
}
public void Initialize(IMruExecuteHandler handler,
params ToolStripMenuItem[] vContainers)
{
Release();
Debug.Assert(handler != null); // No throw
m_handler = handler;
if(vContainers != null)
{
foreach(ToolStripMenuItem tsmi in vContainers)
{
if(tsmi != null)
{
m_lContainers.Add(tsmi);
tsmi.DropDownOpening += this.OnDropDownOpening;
}
}
}
}
public void Release()
{
ReleaseMenuItems();
foreach(ToolStripMenuItem tsmi in m_lContainers)
{
tsmi.DropDownOpening -= this.OnDropDownOpening;
}
m_lContainers.Clear();
m_handler = null;
}
private void ReleaseMenuItems()
{
if(m_tsmiClear != null)
{
m_tsmiClear.Click -= this.ClearHandler;
m_tsmiClear = null;
}
foreach(ToolStripMenuItem tsmi in m_lMruMenuItems)
{
tsmi.Click -= this.ClickHandler;
}
m_lMruMenuItems.Clear();
}
public void Clear()
{
m_vItems.Clear();
}
[Obsolete]
public void AddItem(string strDisplayName, object oTag, bool bUpdateMenu)
{
AddItem(strDisplayName, oTag);
}
public void AddItem(string strDisplayName, object oTag)
{
Debug.Assert(strDisplayName != null);
if(strDisplayName == null) throw new ArgumentNullException("strDisplayName");
// oTag may be null
bool bExists = false;
foreach(KeyValuePair<string, object> kvp in m_vItems)
{
Debug.Assert(kvp.Key != null);
if(kvp.Key.Equals(strDisplayName, StrUtil.CaseIgnoreCmp))
{
bExists = true;
break;
}
}
if(bExists) MoveItemToTop(strDisplayName, oTag);
else
{
m_vItems.Insert(0, new KeyValuePair<string, object>(
strDisplayName, oTag));
if(m_vItems.Count > m_uMaxItemCount)
m_vItems.RemoveAt(m_vItems.Count - 1);
}
// if(bUpdateMenu) UpdateMenu();
}
private void MoveItemToTop(string strName, object oNewTag)
{
for(int i = 0; i < m_vItems.Count; ++i)
{
if(m_vItems[i].Key.Equals(strName, StrUtil.CaseIgnoreCmp))
{
KeyValuePair<string, object> t =
new KeyValuePair<string, object>(strName, oNewTag);
m_vItems.RemoveAt(i);
m_vItems.Insert(0, t);
return;
}
}
Debug.Assert(false);
}
[Obsolete]
public void UpdateMenu()
{
}
private void UpdateMenu(object oContainer)
{
ToolStripMenuItem tsmiContainer = (oContainer as ToolStripMenuItem);
if(tsmiContainer == null) { Debug.Assert(false); return; }
if(!m_lContainers.Contains(tsmiContainer)) { Debug.Assert(false); return; }
tsmiContainer.DropDown.SuspendLayout();
// Verify that the popup arrow has been drawn (i.e. items existed)
Debug.Assert(tsmiContainer.DropDownItems.Count > 0);
ReleaseMenuItems();
tsmiContainer.DropDownItems.Clear();
uint uAccessKey = 1, uNull = 0;
if(m_vItems.Count > 0)
{
foreach(KeyValuePair<string, object> kvp in m_vItems)
{
AddMenuItem(tsmiContainer, MruMenuItemType.Item,
StrUtil.EncodeMenuText(kvp.Key), null, kvp.Value,
true, ref uAccessKey);
}
tsmiContainer.DropDownItems.Add(new ToolStripSeparator());
AddMenuItem(tsmiContainer, MruMenuItemType.Clear, KPRes.ClearMru,
Properties.Resources.B16x16_EditDelete, null, true, ref uNull);
}
else
{
AddMenuItem(tsmiContainer, MruMenuItemType.None, "(" +
KPRes.Empty + ")", null, null, false, ref uNull);
}
tsmiContainer.DropDown.ResumeLayout(true);
}
private void AddMenuItem(ToolStripMenuItem tsmiParent, MruMenuItemType t,
string strText, Image img, object oTag, bool bEnabled,
ref uint uAccessKey)
{
ToolStripMenuItem tsmi = CreateMenuItem(t, strText, img, oTag,
bEnabled, uAccessKey);
tsmiParent.DropDownItems.Add(tsmi);
if(t == MruMenuItemType.Item)
m_lMruMenuItems.Add(tsmi);
else if(t == MruMenuItemType.Clear)
{
Debug.Assert(m_tsmiClear == null);
m_tsmiClear = tsmi;
}
if(uAccessKey != 0) ++uAccessKey;
}
private ToolStripMenuItem CreateMenuItem(MruMenuItemType t, string strText,
Image img, object oTag, bool bEnabled, uint uAccessKey)
{
string strItem = strText;
if(uAccessKey >= 1)
{
NumberFormatInfo nfi = NumberFormatInfo.InvariantInfo;
if(uAccessKey < 10)
strItem = @"&" + uAccessKey.ToString(nfi) + " " + strItem;
else if(uAccessKey == 10)
strItem = @"1&0 " + strItem;
else strItem = uAccessKey.ToString(nfi) + " " + strItem;
}
ToolStripMenuItem tsmi = new ToolStripMenuItem(strItem);
if(img != null) tsmi.Image = img;
if(oTag != null) tsmi.Tag = oTag;
IOConnectionInfo ioc = (oTag as IOConnectionInfo);
if(m_bMarkOpened && (ioc != null) && (Program.MainForm != null))
{
foreach(PwDatabase pd in Program.MainForm.DocumentManager.GetOpenDatabases())
{
if(pd.IOConnectionInfo.GetDisplayName().Equals(
ioc.GetDisplayName(), StrUtil.CaseIgnoreCmp))
{
// if(m_fItalic == null)
// {
// Font f = tsi.Font;
// if(f != null)
// m_fItalic = FontUtil.CreateFont(f, FontStyle.Italic);
// else { Debug.Assert(false); }
// }
// if(m_fItalic != null) tsmi.Font = m_fItalic;
// 153, 51, 153
tsmi.ForeColor = Color.FromArgb(64, 64, 255);
tsmi.Text += " [" + KPRes.Opened + "]";
break;
}
}
}
if(t == MruMenuItemType.Item)
tsmi.Click += this.ClickHandler;
else if(t == MruMenuItemType.Clear)
tsmi.Click += this.ClearHandler;
// t == MruMenuItemType.None needs no handler
if(!bEnabled) tsmi.Enabled = false;
return tsmi;
}
public KeyValuePair<string, object> GetItem(uint uIndex)
{
Debug.Assert(uIndex < (uint)m_vItems.Count);
if(uIndex >= (uint)m_vItems.Count) throw new ArgumentException();
return m_vItems[(int)uIndex];
}
public bool RemoveItem(string strDisplayName)
{
Debug.Assert(strDisplayName != null);
if(strDisplayName == null) throw new ArgumentNullException("strDisplayName");
for(int i = 0; i < m_vItems.Count; ++i)
{
KeyValuePair<string, object> kvp = m_vItems[i];
if(kvp.Key.Equals(strDisplayName, StrUtil.CaseIgnoreCmp))
{
m_vItems.RemoveAt(i);
return true;
}
}
return false;
}
private void ClickHandler(object sender, EventArgs args)
{
ToolStripMenuItem tsmi = (sender as ToolStripMenuItem);
if(tsmi == null) { Debug.Assert(false); return; }
Debug.Assert(m_lMruMenuItems.Contains(tsmi));
ToolStripMenuItem tsmiParent = (tsmi.OwnerItem as ToolStripMenuItem);
if(tsmiParent == null) { Debug.Assert(false); return; }
if(!m_lContainers.Contains(tsmiParent)) { Debug.Assert(false); return; }
if(m_handler == null) { Debug.Assert(false); return; }
string strName = tsmi.Text;
object oTag = tsmi.Tag;
m_handler.OnMruExecute(strName, oTag, tsmiParent);
// MoveItemToTop(strName);
}
private void ClearHandler(object sender, EventArgs e)
{
if(m_handler != null) m_handler.OnMruClear();
else { Debug.Assert(false); }
}
private void OnDropDownOpening(object sender, EventArgs e)
{
UpdateMenu(sender);
}
}
}
|
haro-freezd/KeePass
|
KeePass/UI/MruList.cs
|
C#
|
gpl-2.0
| 9,744 |
/*
* INET An implementation of the TCP/IP protocol suite for the LINUX
* operating system. INET is implemented using the BSD Socket
* interface as the means of communication with the user level.
*
* PACKET - implements raw packet sockets.
*
* Authors: Ross Biro
* Fred N. van Kempen, <[email protected]>
* Alan Cox, <[email protected]>
*
* Fixes:
* Alan Cox : verify_area() now used correctly
* Alan Cox : new skbuff lists, look ma no backlogs!
* Alan Cox : tidied skbuff lists.
* Alan Cox : Now uses generic datagram routines I
* added. Also fixed the peek/read crash
* from all old Linux datagram code.
* Alan Cox : Uses the improved datagram code.
* Alan Cox : Added NULL's for socket options.
* Alan Cox : Re-commented the code.
* Alan Cox : Use new kernel side addressing
* Rob Janssen : Correct MTU usage.
* Dave Platt : Counter leaks caused by incorrect
* interrupt locking and some slightly
* dubious gcc output. Can you read
* compiler: it said _VOLATILE_
* Richard Kooijman : Timestamp fixes.
* Alan Cox : New buffers. Use sk->mac.raw.
* Alan Cox : sendmsg/recvmsg support.
* Alan Cox : Protocol setting support
* Alexey Kuznetsov : Untied from IPv4 stack.
* Cyrus Durgin : Fixed kerneld for kmod.
* Michal Ostrowski : Module initialization cleanup.
* Ulises Alonso : Frame number limit removal and
* packet_set_ring memory leak.
* Eric Biederman : Allow for > 8 byte hardware addresses.
* The convention is that longer addresses
* will simply extend the hardware address
* byte arrays at the end of sockaddr_ll
* and packet_mreq.
* Johann Baudy : Added TX RING.
* Chetan Loke : Implemented TPACKET_V3 block abstraction
* layer.
* Copyright (C) 2011, <[email protected]>
*
*
* 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/types.h>
#include <linux/mm.h>
#include <linux/capability.h>
#include <linux/fcntl.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/if_packet.h>
#include <linux/wireless.h>
#include <linux/kernel.h>
#include <linux/kmod.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <net/net_namespace.h>
#include <net/ip.h>
#include <net/protocol.h>
#include <linux/skbuff.h>
#include <net/sock.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <asm/uaccess.h>
#include <asm/ioctls.h>
#include <asm/page.h>
#include <asm/cacheflush.h>
#include <asm/io.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/poll.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
#include <linux/if_vlan.h>
#include <linux/virtio_net.h>
#include <linux/errqueue.h>
#include <linux/net_tstamp.h>
#ifdef CONFIG_INET
#include <net/inet_common.h>
#endif
#include "internal.h"
/*
Assumptions:
- if device has no dev->hard_header routine, it adds and removes ll header
inside itself. In this case ll header is invisible outside of device,
but higher levels still should reserve dev->hard_header_len.
Some devices are enough clever to reallocate skb, when header
will not fit to reserved space (tunnel), another ones are silly
(PPP).
- packet socket receives packets with pulled ll header,
so that SOCK_RAW should push it back.
On receive:
-----------
Incoming, dev->hard_header!=NULL
mac_header -> ll header
data -> data
Outgoing, dev->hard_header!=NULL
mac_header -> ll header
data -> ll header
Incoming, dev->hard_header==NULL
mac_header -> UNKNOWN position. It is very likely, that it points to ll
header. PPP makes it, that is wrong, because introduce
assymetry between rx and tx paths.
data -> data
Outgoing, dev->hard_header==NULL
mac_header -> data. ll header is still not built!
data -> data
Resume
If dev->hard_header==NULL we are unlikely to restore sensible ll header.
On transmit:
------------
dev->hard_header != NULL
mac_header -> ll header
data -> ll header
dev->hard_header == NULL (ll header is added by device, we cannot control it)
mac_header -> data
data -> data
We should set nh.raw on output to correct posistion,
packet classifier depends on it.
*/
/* Private packet socket structures. */
/* identical to struct packet_mreq except it has
* a longer address field.
*/
struct packet_mreq_max {
int mr_ifindex;
unsigned short mr_type;
unsigned short mr_alen;
unsigned char mr_address[MAX_ADDR_LEN];
};
union tpacket_uhdr {
struct tpacket_hdr *h1;
struct tpacket2_hdr *h2;
struct tpacket3_hdr *h3;
void *raw;
};
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring);
#define V3_ALIGNMENT (8)
#define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
#define BLK_PLUS_PRIV(sz_of_priv) \
(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
#define PGV_FROM_VMALLOC 1
#define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
#define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
#define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
#define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
#define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
#define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
#define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
struct packet_sock;
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev);
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status);
static void packet_increment_head(struct packet_ring_buffer *buff);
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
struct packet_sock *);
static void prb_retire_current_block(struct tpacket_kbdq_core *,
struct packet_sock *, unsigned int status);
static int prb_queue_frozen(struct tpacket_kbdq_core *);
static void prb_open_block(struct tpacket_kbdq_core *,
struct tpacket_block_desc *);
static void prb_retire_rx_blk_timer_expired(unsigned long);
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
static void prb_init_blk_timer(struct packet_sock *,
struct tpacket_kbdq_core *,
void (*func) (unsigned long));
static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
static void prb_clear_rxhash(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
struct tpacket3_hdr *);
static void packet_flush_mclist(struct sock *sk);
struct packet_skb_cb {
unsigned int origlen;
union {
struct sockaddr_pkt pkt;
struct sockaddr_ll ll;
} sa;
};
#define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
#define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
#define GET_PBLOCK_DESC(x, bid) \
((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
#define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
#define GET_NEXT_PRB_BLK_NUM(x) \
(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
((x)->kactive_blk_num+1) : 0)
static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
static void __fanout_link(struct sock *sk, struct packet_sock *po);
static struct net_device *packet_cached_dev_get(struct packet_sock *po)
{
struct net_device *dev;
rcu_read_lock();
dev = rcu_dereference(po->cached_dev);
if (likely(dev))
dev_hold(dev);
rcu_read_unlock();
return dev;
}
static void packet_cached_dev_assign(struct packet_sock *po,
struct net_device *dev)
{
rcu_assign_pointer(po->cached_dev, dev);
}
static void packet_cached_dev_reset(struct packet_sock *po)
{
RCU_INIT_POINTER(po->cached_dev, NULL);
}
/* register_prot_hook must be invoked with the po->bind_lock held,
* or from a context in which asynchronous accesses to the packet
* socket is not possible (packet_create()).
*/
static void register_prot_hook(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
if (!po->running) {
if (po->fanout)
__fanout_link(sk, po);
else
dev_add_pack(&po->prot_hook);
sock_hold(sk);
po->running = 1;
}
}
/* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
* held. If the sync parameter is true, we will temporarily drop
* the po->bind_lock and do a synchronize_net to make sure no
* asynchronous packet processing paths still refer to the elements
* of po->prot_hook. If the sync parameter is false, it is the
* callers responsibility to take care of this.
*/
static void __unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
po->running = 0;
if (po->fanout)
__fanout_unlink(sk, po);
else
__dev_remove_pack(&po->prot_hook);
__sock_put(sk);
if (sync) {
spin_unlock(&po->bind_lock);
synchronize_net();
spin_lock(&po->bind_lock);
}
}
static void unregister_prot_hook(struct sock *sk, bool sync)
{
struct packet_sock *po = pkt_sk(sk);
if (po->running)
__unregister_prot_hook(sk, sync);
}
static inline __pure struct page *pgv_to_page(void *addr)
{
if (is_vmalloc_addr(addr))
return vmalloc_to_page(addr);
return virt_to_page(addr);
}
static void __packet_set_status(struct packet_sock *po, void *frame, int status)
{
union tpacket_uhdr h;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
break;
case TPACKET_V2:
h.h2->tp_status = status;
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
smp_wmb();
}
static int __packet_get_status(struct packet_sock *po, void *frame)
{
union tpacket_uhdr h;
smp_rmb();
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
flush_dcache_page(pgv_to_page(&h.h1->tp_status));
return h.h1->tp_status;
case TPACKET_V2:
flush_dcache_page(pgv_to_page(&h.h2->tp_status));
return h.h2->tp_status;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return 0;
}
}
static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
unsigned int flags)
{
struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
if (shhwtstamps) {
if ((flags & SOF_TIMESTAMPING_SYS_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->syststamp, ts))
return TP_STATUS_TS_SYS_HARDWARE;
if ((flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
return TP_STATUS_TS_RAW_HARDWARE;
}
if (ktime_to_timespec_cond(skb->tstamp, ts))
return TP_STATUS_TS_SOFTWARE;
return 0;
}
static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
struct sk_buff *skb)
{
union tpacket_uhdr h;
struct timespec ts;
__u32 ts_status;
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
return 0;
h.raw = frame;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
break;
case TPACKET_V2:
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
break;
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
}
/* one flush is safe, as both fields always lie on the same cacheline */
flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
smp_wmb();
return ts_status;
}
static void *packet_lookup_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int position,
int status)
{
unsigned int pg_vec_pos, frame_offset;
union tpacket_uhdr h;
pg_vec_pos = position / rb->frames_per_block;
frame_offset = position % rb->frames_per_block;
h.raw = rb->pg_vec[pg_vec_pos].buffer +
(frame_offset * rb->frame_size);
if (status != __packet_get_status(po, h.raw))
return NULL;
return h.raw;
}
static void *packet_current_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
return packet_lookup_frame(po, rb, rb->head, status);
}
static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
del_timer_sync(&pkc->retire_blk_timer);
}
static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
int tx_ring,
struct sk_buff_head *rb_queue)
{
struct tpacket_kbdq_core *pkc;
pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
spin_lock_bh(&rb_queue->lock);
pkc->delete_blk_timer = 1;
spin_unlock_bh(&rb_queue->lock);
prb_del_retire_blk_timer(pkc);
}
static void prb_init_blk_timer(struct packet_sock *po,
struct tpacket_kbdq_core *pkc,
void (*func) (unsigned long))
{
init_timer(&pkc->retire_blk_timer);
pkc->retire_blk_timer.data = (long)po;
pkc->retire_blk_timer.function = func;
pkc->retire_blk_timer.expires = jiffies;
}
static void prb_setup_retire_blk_timer(struct packet_sock *po, int tx_ring)
{
struct tpacket_kbdq_core *pkc;
if (tx_ring)
BUG();
pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
}
static int prb_calc_retire_blk_tmo(struct packet_sock *po,
int blk_size_in_bytes)
{
struct net_device *dev;
unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
struct ethtool_cmd ecmd;
int err;
u32 speed;
rtnl_lock();
dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
if (unlikely(!dev)) {
rtnl_unlock();
return DEFAULT_PRB_RETIRE_TOV;
}
err = __ethtool_get_settings(dev, &ecmd);
speed = ethtool_cmd_speed(&ecmd);
rtnl_unlock();
if (!err) {
/*
* If the link speed is so slow you don't really
* need to worry about perf anyways
*/
if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
return DEFAULT_PRB_RETIRE_TOV;
} else {
msec = 1;
div = speed / 1000;
}
}
mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
if (div)
mbits /= div;
tmo = mbits * msec;
if (div)
return tmo+1;
return tmo;
}
static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
union tpacket_req_u *req_u)
{
p1->feature_req_word = req_u->req3.tp_feature_req_word;
}
static void init_prb_bdqc(struct packet_sock *po,
struct packet_ring_buffer *rb,
struct pgv *pg_vec,
union tpacket_req_u *req_u, int tx_ring)
{
struct tpacket_kbdq_core *p1 = &rb->prb_bdqc;
struct tpacket_block_desc *pbd;
memset(p1, 0x0, sizeof(*p1));
p1->knxt_seq_num = 1;
p1->pkbdq = pg_vec;
pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
p1->pkblk_start = pg_vec[0].buffer;
p1->kblk_size = req_u->req3.tp_block_size;
p1->knum_blocks = req_u->req3.tp_block_nr;
p1->hdrlen = po->tp_hdrlen;
p1->version = po->tp_version;
p1->last_kactive_blk_num = 0;
po->stats.stats3.tp_freeze_q_cnt = 0;
if (req_u->req3.tp_retire_blk_tov)
p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
else
p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
req_u->req3.tp_block_size);
p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
prb_init_ft_ops(p1, req_u);
prb_setup_retire_blk_timer(po, tx_ring);
prb_open_block(p1, pbd);
}
/* Do NOT update the last_blk_num first.
* Assumes sk_buff_head lock is held.
*/
static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
{
mod_timer(&pkc->retire_blk_timer,
jiffies + pkc->tov_in_jiffies);
pkc->last_kactive_blk_num = pkc->kactive_blk_num;
}
/*
* Timer logic:
* 1) We refresh the timer only when we open a block.
* By doing this we don't waste cycles refreshing the timer
* on packet-by-packet basis.
*
* With a 1MB block-size, on a 1Gbps line, it will take
* i) ~8 ms to fill a block + ii) memcpy etc.
* In this cut we are not accounting for the memcpy time.
*
* So, if the user sets the 'tmo' to 10ms then the timer
* will never fire while the block is still getting filled
* (which is what we want). However, the user could choose
* to close a block early and that's fine.
*
* But when the timer does fire, we check whether or not to refresh it.
* Since the tmo granularity is in msecs, it is not too expensive
* to refresh the timer, lets say every '8' msecs.
* Either the user can set the 'tmo' or we can derive it based on
* a) line-speed and b) block-size.
* prb_calc_retire_blk_tmo() calculates the tmo.
*
*/
static void prb_retire_rx_blk_timer_expired(unsigned long data)
{
struct packet_sock *po = (struct packet_sock *)data;
struct tpacket_kbdq_core *pkc = &po->rx_ring.prb_bdqc;
unsigned int frozen;
struct tpacket_block_desc *pbd;
spin_lock(&po->sk.sk_receive_queue.lock);
frozen = prb_queue_frozen(pkc);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
if (unlikely(pkc->delete_blk_timer))
goto out;
/* We only need to plug the race when the block is partially filled.
* tpacket_rcv:
* lock(); increment BLOCK_NUM_PKTS; unlock()
* copy_bits() is in progress ...
* timer fires on other cpu:
* we can't retire the current block because copy_bits
* is in progress.
*
*/
if (BLOCK_NUM_PKTS(pbd)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
if (!frozen) {
prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
if (!prb_dispatch_next_block(pkc, po))
goto refresh_timer;
else
goto out;
} else {
/* Case 1. Queue was frozen because user-space was
* lagging behind.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/*
* Ok, user-space is still behind.
* So just refresh the timer.
*/
goto refresh_timer;
} else {
/* Case 2. queue was frozen,user-space caught up,
* now the link went idle && the timer fired.
* We don't have a block to close.So we open this
* block and restart the timer.
* opening a block thaws the queue,restarts timer
* Thawing/timer-refresh is a side effect.
*/
prb_open_block(pkc, pbd);
goto out;
}
}
}
refresh_timer:
_prb_refresh_rx_retire_blk_timer(pkc);
out:
spin_unlock(&po->sk.sk_receive_queue.lock);
}
static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1, __u32 status)
{
/* Flush everything minus the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
u8 *start, *end;
start = (u8 *)pbd1;
/* Skip the block header(we know header WILL fit in 4K) */
start += PAGE_SIZE;
end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
for (; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
/* Now update the block status. */
BLOCK_STATUS(pbd1) = status;
/* Flush the block header */
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
start = (u8 *)pbd1;
flush_dcache_page(pgv_to_page(start));
smp_wmb();
#endif
}
/*
* Side effect:
*
* 1) flush the block
* 2) Increment active_blk_num
*
* Note:We DONT refresh the timer on purpose.
* Because almost always the next block will be opened.
*/
static void prb_close_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1,
struct packet_sock *po, unsigned int stat)
{
__u32 status = TP_STATUS_USER | stat;
struct tpacket3_hdr *last_pkt;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
if (po->stats.stats3.tp_drops)
status |= TP_STATUS_LOSING;
last_pkt = (struct tpacket3_hdr *)pkc1->prev;
last_pkt->tp_next_offset = 0;
/* Get the ts of the last pkt */
if (BLOCK_NUM_PKTS(pbd1)) {
h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
} else {
/* Ok, we tmo'd - so get the current time */
struct timespec ts;
getnstimeofday(&ts);
h1->ts_last_pkt.ts_sec = ts.tv_sec;
h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
}
smp_wmb();
/* Flush the block */
prb_flush_block(pkc1, pbd1, status);
pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
}
static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
{
pkc->reset_pending_on_curr_blk = 0;
}
/*
* Side effect of opening a block:
*
* 1) prb_queue is thawed.
* 2) retire_blk_timer is refreshed.
*
*/
static void prb_open_block(struct tpacket_kbdq_core *pkc1,
struct tpacket_block_desc *pbd1)
{
struct timespec ts;
struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
smp_rmb();
/* We could have just memset this but we will lose the
* flexibility of making the priv area sticky
*/
BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
BLOCK_NUM_PKTS(pbd1) = 0;
BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
getnstimeofday(&ts);
h1->ts_first_pkt.ts_sec = ts.tv_sec;
h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
pkc1->pkblk_start = (char *)pbd1;
pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
pbd1->version = pkc1->version;
pkc1->prev = pkc1->nxt_offset;
pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
prb_thaw_queue(pkc1);
_prb_refresh_rx_retire_blk_timer(pkc1);
smp_wmb();
}
/*
* Queue freeze logic:
* 1) Assume tp_block_nr = 8 blocks.
* 2) At time 't0', user opens Rx ring.
* 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
* 4) user-space is either sleeping or processing block '0'.
* 5) tpacket_rcv is currently filling block '7', since there is no space left,
* it will close block-7,loop around and try to fill block '0'.
* call-flow:
* __packet_lookup_frame_in_block
* prb_retire_current_block()
* prb_dispatch_next_block()
* |->(BLOCK_STATUS == USER) evaluates to true
* 5.1) Since block-0 is currently in-use, we just freeze the queue.
* 6) Now there are two cases:
* 6.1) Link goes idle right after the queue is frozen.
* But remember, the last open_block() refreshed the timer.
* When this timer expires,it will refresh itself so that we can
* re-open block-0 in near future.
* 6.2) Link is busy and keeps on receiving packets. This is a simple
* case and __packet_lookup_frame_in_block will check if block-0
* is free and can now be re-used.
*/
static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
pkc->reset_pending_on_curr_blk = 1;
po->stats.stats3.tp_freeze_q_cnt++;
}
#define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
/*
* If the next block is free then we will dispatch it
* and return a good offset.
* Else, we will freeze the queue.
* So, caller must check the return value.
*/
static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po)
{
struct tpacket_block_desc *pbd;
smp_rmb();
/* 1. Get current block num */
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* 2. If this block is currently in_use then freeze the queue */
if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
prb_freeze_queue(pkc, po);
return NULL;
}
/*
* 3.
* open this block and return the offset where the first packet
* needs to get stored.
*/
prb_open_block(pkc, pbd);
return (void *)pkc->nxt_offset;
}
static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
struct packet_sock *po, unsigned int status)
{
struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* retire/close the current block */
if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
/*
* Plug the case where copy_bits() is in progress on
* cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
* have space to copy the pkt in the current block and
* called prb_retire_current_block()
*
* We don't need to worry about the TMO case because
* the timer-handler already handled this case.
*/
if (!(status & TP_STATUS_BLK_TMO)) {
while (atomic_read(&pkc->blk_fill_in_prog)) {
/* Waiting for skb_copy_bits to finish... */
cpu_relax();
}
}
prb_close_block(pkc, pbd, po, status);
return;
}
}
static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd)
{
return TP_STATUS_USER & BLOCK_STATUS(pbd);
}
static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
{
return pkc->reset_pending_on_curr_blk;
}
static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
atomic_dec(&pkc->blk_fill_in_prog);
}
static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = skb_get_rxhash(pkc->skb);
}
static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
ppd->hv1.tp_rxhash = 0;
}
static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
if (vlan_tx_tag_present(pkc->skb)) {
ppd->hv1.tp_vlan_tci = vlan_tx_tag_get(pkc->skb);
ppd->tp_status = TP_STATUS_VLAN_VALID;
} else {
ppd->hv1.tp_vlan_tci = 0;
ppd->tp_status = TP_STATUS_AVAILABLE;
}
}
static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
struct tpacket3_hdr *ppd)
{
prb_fill_vlan_info(pkc, ppd);
if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
prb_fill_rxhash(pkc, ppd);
else
prb_clear_rxhash(pkc, ppd);
}
static void prb_fill_curr_block(char *curr,
struct tpacket_kbdq_core *pkc,
struct tpacket_block_desc *pbd,
unsigned int len)
{
struct tpacket3_hdr *ppd;
ppd = (struct tpacket3_hdr *)curr;
ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
pkc->prev = curr;
pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
BLOCK_NUM_PKTS(pbd) += 1;
atomic_inc(&pkc->blk_fill_in_prog);
prb_run_all_ft_ops(pkc, ppd);
}
/* Assumes caller has the sk->rx_queue.lock */
static void *__packet_lookup_frame_in_block(struct packet_sock *po,
struct sk_buff *skb,
int status,
unsigned int len
)
{
struct tpacket_kbdq_core *pkc;
struct tpacket_block_desc *pbd;
char *curr, *end;
pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
/* Queue is frozen when user space is lagging behind */
if (prb_queue_frozen(pkc)) {
/*
* Check if that last block which caused the queue to freeze,
* is still in_use by user-space.
*/
if (prb_curr_blk_in_use(pkc, pbd)) {
/* Can't record this packet */
return NULL;
} else {
/*
* Ok, the block was released by user-space.
* Now let's open that block.
* opening a block also thaws the queue.
* Thawing is a side effect.
*/
prb_open_block(pkc, pbd);
}
}
smp_mb();
curr = pkc->nxt_offset;
pkc->skb = skb;
end = (char *)pbd + pkc->kblk_size;
/* first try the current block */
if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/* Ok, close the current block */
prb_retire_current_block(pkc, po, 0);
/* Now, try to dispatch the next block */
curr = (char *)prb_dispatch_next_block(pkc, po);
if (curr) {
pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
prb_fill_curr_block(curr, pkc, pbd, len);
return (void *)curr;
}
/*
* No free blocks are available.user_space hasn't caught up yet.
* Queue was just frozen and now this packet will get dropped.
*/
return NULL;
}
static void *packet_current_rx_frame(struct packet_sock *po,
struct sk_buff *skb,
int status, unsigned int len)
{
char *curr = NULL;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
curr = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head, status);
return curr;
case TPACKET_V3:
return __packet_lookup_frame_in_block(po, skb, status, len);
default:
WARN(1, "TPACKET version not supported\n");
BUG();
return NULL;
}
}
static void *prb_lookup_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
unsigned int idx,
int status)
{
struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
if (status != BLOCK_STATUS(pbd))
return NULL;
return pbd;
}
static int prb_previous_blk_num(struct packet_ring_buffer *rb)
{
unsigned int prev;
if (rb->prb_bdqc.kactive_blk_num)
prev = rb->prb_bdqc.kactive_blk_num-1;
else
prev = rb->prb_bdqc.knum_blocks-1;
return prev;
}
/* Assumes caller has held the rx_queue.lock */
static void *__prb_previous_block(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = prb_previous_blk_num(rb);
return prb_lookup_block(po, rb, previous, status);
}
static void *packet_previous_rx_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
if (po->tp_version <= TPACKET_V2)
return packet_previous_frame(po, rb, status);
return __prb_previous_block(po, rb, status);
}
static void packet_increment_rx_head(struct packet_sock *po,
struct packet_ring_buffer *rb)
{
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
return packet_increment_head(rb);
case TPACKET_V3:
default:
WARN(1, "TPACKET version not supported.\n");
BUG();
return;
}
}
static void *packet_previous_frame(struct packet_sock *po,
struct packet_ring_buffer *rb,
int status)
{
unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
return packet_lookup_frame(po, rb, previous, status);
}
static void packet_increment_head(struct packet_ring_buffer *buff)
{
buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
}
static bool packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
{
struct sock *sk = &po->sk;
bool has_room;
if (po->prot_hook.func != tpacket_rcv)
return (atomic_read(&sk->sk_rmem_alloc) + skb->truesize)
<= sk->sk_rcvbuf;
spin_lock(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3)
has_room = prb_lookup_block(po, &po->rx_ring,
po->rx_ring.prb_bdqc.kactive_blk_num,
TP_STATUS_KERNEL);
else
has_room = packet_lookup_frame(po, &po->rx_ring,
po->rx_ring.head,
TP_STATUS_KERNEL);
spin_unlock(&sk->sk_receive_queue.lock);
return has_room;
}
static void packet_sock_destruct(struct sock *sk)
{
skb_queue_purge(&sk->sk_error_queue);
WARN_ON(atomic_read(&sk->sk_rmem_alloc));
WARN_ON(atomic_read(&sk->sk_wmem_alloc));
if (!sock_flag(sk, SOCK_DEAD)) {
WARN(1, "Attempt to release alive packet socket: %p\n", sk);
return;
}
sk_refcnt_debug_dec(sk);
}
static unsigned int fanout_demux_hash(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return (((u64)skb->rxhash) * num) >> 32;
}
static unsigned int fanout_demux_lb(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
unsigned int val = atomic_inc_return(&f->rr_cur);
return val % num;
}
static unsigned int fanout_demux_cpu(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int num)
{
return smp_processor_id() % num;
}
static unsigned int fanout_demux_rollover(struct packet_fanout *f,
struct sk_buff *skb,
unsigned int idx, unsigned int skip,
unsigned int num)
{
unsigned int i, j;
i = j = min_t(int, f->next[idx], num - 1);
do {
if (i != skip && packet_rcv_has_room(pkt_sk(f->arr[i]), skb)) {
if (i != j)
f->next[idx] = i;
return i;
}
if (++i == num)
i = 0;
} while (i != j);
return idx;
}
static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
{
return f->flags & (flag >> 8);
}
static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct packet_fanout *f = pt->af_packet_priv;
unsigned int num = ACCESS_ONCE(f->num_members);
struct packet_sock *po;
unsigned int idx;
if (!net_eq(dev_net(dev), read_pnet(&f->net)) ||
!num) {
kfree_skb(skb);
return 0;
}
switch (f->type) {
case PACKET_FANOUT_HASH:
default:
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
skb = ip_check_defrag(skb, IP_DEFRAG_AF_PACKET);
if (!skb)
return 0;
}
skb_get_rxhash(skb);
idx = fanout_demux_hash(f, skb, num);
break;
case PACKET_FANOUT_LB:
idx = fanout_demux_lb(f, skb, num);
break;
case PACKET_FANOUT_CPU:
idx = fanout_demux_cpu(f, skb, num);
break;
case PACKET_FANOUT_ROLLOVER:
idx = fanout_demux_rollover(f, skb, 0, (unsigned int) -1, num);
break;
}
po = pkt_sk(f->arr[idx]);
if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER) &&
unlikely(!packet_rcv_has_room(po, skb))) {
idx = fanout_demux_rollover(f, skb, idx, idx, num);
po = pkt_sk(f->arr[idx]);
}
return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
}
DEFINE_MUTEX(fanout_mutex);
EXPORT_SYMBOL_GPL(fanout_mutex);
static LIST_HEAD(fanout_list);
static void __fanout_link(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
spin_lock(&f->lock);
f->arr[f->num_members] = sk;
smp_wmb();
f->num_members++;
spin_unlock(&f->lock);
}
static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
{
struct packet_fanout *f = po->fanout;
int i;
spin_lock(&f->lock);
for (i = 0; i < f->num_members; i++) {
if (f->arr[i] == sk)
break;
}
BUG_ON(i >= f->num_members);
f->arr[i] = f->arr[f->num_members - 1];
f->num_members--;
spin_unlock(&f->lock);
}
static bool match_fanout_group(struct packet_type *ptype, struct sock * sk)
{
if (ptype->af_packet_priv == (void*)((struct packet_sock *)sk)->fanout)
return true;
return false;
}
static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f, *match;
u8 type = type_flags & 0xff;
u8 flags = type_flags >> 8;
int err;
switch (type) {
case PACKET_FANOUT_ROLLOVER:
if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
return -EINVAL;
case PACKET_FANOUT_HASH:
case PACKET_FANOUT_LB:
case PACKET_FANOUT_CPU:
break;
default:
return -EINVAL;
}
if (!po->running)
return -EINVAL;
if (po->fanout)
return -EALREADY;
mutex_lock(&fanout_mutex);
match = NULL;
list_for_each_entry(f, &fanout_list, list) {
if (f->id == id &&
read_pnet(&f->net) == sock_net(sk)) {
match = f;
break;
}
}
err = -EINVAL;
if (match && match->flags != flags)
goto out;
if (!match) {
err = -ENOMEM;
match = kzalloc(sizeof(*match), GFP_KERNEL);
if (!match)
goto out;
write_pnet(&match->net, sock_net(sk));
match->id = id;
match->type = type;
match->flags = flags;
atomic_set(&match->rr_cur, 0);
INIT_LIST_HEAD(&match->list);
spin_lock_init(&match->lock);
atomic_set(&match->sk_ref, 0);
match->prot_hook.type = po->prot_hook.type;
match->prot_hook.dev = po->prot_hook.dev;
match->prot_hook.func = packet_rcv_fanout;
match->prot_hook.af_packet_priv = match;
match->prot_hook.id_match = match_fanout_group;
dev_add_pack(&match->prot_hook);
list_add(&match->list, &fanout_list);
}
err = -EINVAL;
if (match->type == type &&
match->prot_hook.type == po->prot_hook.type &&
match->prot_hook.dev == po->prot_hook.dev) {
err = -ENOSPC;
if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
__dev_remove_pack(&po->prot_hook);
po->fanout = match;
atomic_inc(&match->sk_ref);
__fanout_link(sk, po);
err = 0;
}
}
out:
mutex_unlock(&fanout_mutex);
return err;
}
static void fanout_release(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_fanout *f;
f = po->fanout;
if (!f)
return;
mutex_lock(&fanout_mutex);
po->fanout = NULL;
if (atomic_dec_and_test(&f->sk_ref)) {
list_del(&f->list);
dev_remove_pack(&f->prot_hook);
kfree(f);
}
mutex_unlock(&fanout_mutex);
}
static const struct proto_ops packet_ops;
static const struct proto_ops packet_ops_spkt;
static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_pkt *spkt;
/*
* When we registered the protocol we saved the socket in the data
* field for just this event.
*/
sk = pt->af_packet_priv;
/*
* Yank back the headers [hope the device set this
* right or kerboom...]
*
* Incoming packets have ll header pulled,
* push it back.
*
* For outgoing ones skb->data == skb_mac_header(skb)
* so that this procedure is noop.
*/
if (skb->pkt_type == PACKET_LOOPBACK)
goto out;
if (!net_eq(dev_net(dev), sock_net(sk)))
goto out;
skb = skb_share_check(skb, GFP_ATOMIC);
if (skb == NULL)
goto oom;
/* drop any routing info */
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spkt = &PACKET_SKB_CB(skb)->sa.pkt;
skb_push(skb, skb->data - skb_mac_header(skb));
/*
* The SOCK_PACKET socket receives _all_ frames.
*/
spkt->spkt_family = dev->type;
strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
spkt->spkt_protocol = skb->protocol;
/*
* Charge the memory to the socket. This is done specifically
* to prevent sockets using all the memory up.
*/
if (sock_queue_rcv_skb(sk, skb) == 0)
return 0;
out:
kfree_skb(skb);
oom:
return 0;
}
/*
* Output a raw packet to a device layer. This bypasses all the other
* protocol layers and you must therefore supply it with a complete frame
*/
static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
struct sk_buff *skb = NULL;
struct net_device *dev;
__be16 proto = 0;
int err;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (saddr) {
if (msg->msg_namelen < sizeof(struct sockaddr))
return -EINVAL;
if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
proto = saddr->spkt_protocol;
} else
return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
/*
* Find the device first to size check it
*/
saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
retry:
rcu_read_lock();
dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
err = -ENODEV;
if (dev == NULL)
goto out_unlock;
err = -ENETDOWN;
if (!(dev->flags & IFF_UP))
goto out_unlock;
/*
* You may not queue a frame bigger than the mtu. This is the lowest level
* raw protocol and you must do your own fragmentation at this level.
*/
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
goto out_unlock;
if (!skb) {
size_t reserved = LL_RESERVED_SPACE(dev);
int tlen = dev->needed_tailroom;
unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
rcu_read_unlock();
skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
if (skb == NULL)
return -ENOBUFS;
/* FIXME: Save some space for broken drivers that write a hard
* header at transmission time by themselves. PPP is the notable
* one here. This should really be fixed at the driver level.
*/
skb_reserve(skb, reserved);
skb_reset_network_header(skb);
/* Try to align data part correctly */
if (hhlen) {
skb->data -= hhlen;
skb->tail -= hhlen;
if (len < hhlen)
skb_reset_network_header(skb);
}
err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
if (err)
goto out_free;
goto retry;
}
if (len > (dev->mtu + dev->hard_header_len + extra_len)) {
/* Earlier code assumed this would be a VLAN pkt,
* double-check this now that we have the actual
* packet in hand.
*/
struct ethhdr *ehdr;
skb_reset_mac_header(skb);
ehdr = eth_hdr(skb);
if (ehdr->h_proto != htons(ETH_P_8021Q)) {
err = -EMSGSIZE;
goto out_unlock;
}
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
skb_probe_transport_header(skb, 0);
dev_queue_xmit(skb);
rcu_read_unlock();
return len;
out_unlock:
rcu_read_unlock();
out_free:
kfree_skb(skb);
return err;
}
static unsigned int run_filter(const struct sk_buff *skb,
const struct sock *sk,
unsigned int res)
{
struct sk_filter *filter;
rcu_read_lock();
filter = rcu_dereference(sk->sk_filter);
if (filter != NULL)
res = SK_RUN_FILTER(filter, skb);
rcu_read_unlock();
return res;
}
/*
* This function makes lazy skb cloning in hope that most of packets
* are discarded by BPF.
*
* Note tricky part: we DO mangle shared skb! skb->data, skb->len
* and skb->cb are mangled. It works because (and until) packets
* falling here are owned by current CPU. Output packets are cloned
* by dev_queue_xmit_nit(), input packets are processed by net_bh
* sequencially, so that if we return skb to original state on exit,
* we will not harm anyone.
*/
static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct sockaddr_ll *sll;
struct packet_sock *po;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
skb->dev = dev;
if (dev->header_ops) {
/* The device has an explicit notion of ll header,
* exported to higher levels.
*
* Otherwise, the device hides details of its frame
* structure, so that corresponding packet head is
* never delivered to user.
*/
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
goto drop_n_acct;
if (skb_shared(skb)) {
struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
if (nskb == NULL)
goto drop_n_acct;
if (skb_head != skb->data) {
skb->data = skb_head;
skb->len = skb_len;
}
consume_skb(skb);
skb = nskb;
}
BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
sizeof(skb->cb));
sll = &PACKET_SKB_CB(skb)->sa.ll;
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
PACKET_SKB_CB(skb)->origlen = skb->len;
if (pskb_trim(skb, snaplen))
goto drop_n_acct;
skb_set_owner_r(skb, sk);
skb->dev = NULL;
skb_dst_drop(skb);
/* drop conntrack reference */
nf_reset(skb);
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_packets++;
skb->dropcount = atomic_read(&sk->sk_drops);
__skb_queue_tail(&sk->sk_receive_queue, skb);
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
return 0;
drop_n_acct:
spin_lock(&sk->sk_receive_queue.lock);
po->stats.stats1.tp_drops++;
atomic_inc(&sk->sk_drops);
spin_unlock(&sk->sk_receive_queue.lock);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
consume_skb(skb);
return 0;
}
static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct sock *sk;
struct packet_sock *po;
struct sockaddr_ll *sll;
union tpacket_uhdr h;
u8 *skb_head = skb->data;
int skb_len = skb->len;
unsigned int snaplen, res;
unsigned long status = TP_STATUS_USER;
unsigned short macoff, netoff, hdrlen;
struct sk_buff *copy_skb = NULL;
struct timespec ts;
__u32 ts_status;
if (skb->pkt_type == PACKET_LOOPBACK)
goto drop;
sk = pt->af_packet_priv;
po = pkt_sk(sk);
if (!net_eq(dev_net(dev), sock_net(sk)))
goto drop;
if (dev->header_ops) {
if (sk->sk_type != SOCK_DGRAM)
skb_push(skb, skb->data - skb_mac_header(skb));
else if (skb->pkt_type == PACKET_OUTGOING) {
/* Special case: outgoing packets have ll header at head */
skb_pull(skb, skb_network_offset(skb));
}
}
if (skb->ip_summed == CHECKSUM_PARTIAL)
status |= TP_STATUS_CSUMNOTREADY;
snaplen = skb->len;
res = run_filter(skb, sk, snaplen);
if (!res)
goto drop_n_restore;
if (snaplen > res)
snaplen = res;
if (sk->sk_type == SOCK_DGRAM) {
macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
po->tp_reserve;
} else {
unsigned int maclen = skb_network_offset(skb);
netoff = TPACKET_ALIGN(po->tp_hdrlen +
(maclen < 16 ? 16 : maclen)) +
po->tp_reserve;
macoff = netoff - maclen;
}
if (po->tp_version <= TPACKET_V2) {
if (macoff + snaplen > po->rx_ring.frame_size) {
if (po->copy_thresh &&
atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
if (skb_shared(skb)) {
copy_skb = skb_clone(skb, GFP_ATOMIC);
} else {
copy_skb = skb_get(skb);
skb_head = skb->data;
}
if (copy_skb)
skb_set_owner_r(copy_skb, sk);
}
snaplen = po->rx_ring.frame_size - macoff;
if ((int)snaplen < 0)
snaplen = 0;
}
} else if (unlikely(macoff + snaplen >
GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
u32 nval;
nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
snaplen, nval, macoff);
snaplen = nval;
if (unlikely((int)snaplen < 0)) {
snaplen = 0;
macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
}
}
spin_lock(&sk->sk_receive_queue.lock);
h.raw = packet_current_rx_frame(po, skb,
TP_STATUS_KERNEL, (macoff+snaplen));
if (!h.raw)
goto ring_is_full;
if (po->tp_version <= TPACKET_V2) {
packet_increment_rx_head(po, &po->rx_ring);
/*
* LOSING will be reported till you read the stats,
* because it's COR - Clear On Read.
* Anyways, moving it for V1/V2 only as V3 doesn't need this
* at packet level.
*/
if (po->stats.stats1.tp_drops)
status |= TP_STATUS_LOSING;
}
po->stats.stats1.tp_packets++;
if (copy_skb) {
status |= TP_STATUS_COPY;
__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
}
spin_unlock(&sk->sk_receive_queue.lock);
skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
getnstimeofday(&ts);
status |= ts_status;
switch (po->tp_version) {
case TPACKET_V1:
h.h1->tp_len = skb->len;
h.h1->tp_snaplen = snaplen;
h.h1->tp_mac = macoff;
h.h1->tp_net = netoff;
h.h1->tp_sec = ts.tv_sec;
h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
hdrlen = sizeof(*h.h1);
break;
case TPACKET_V2:
h.h2->tp_len = skb->len;
h.h2->tp_snaplen = snaplen;
h.h2->tp_mac = macoff;
h.h2->tp_net = netoff;
h.h2->tp_sec = ts.tv_sec;
h.h2->tp_nsec = ts.tv_nsec;
if (vlan_tx_tag_present(skb)) {
h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
status |= TP_STATUS_VLAN_VALID;
} else {
h.h2->tp_vlan_tci = 0;
}
h.h2->tp_padding = 0;
hdrlen = sizeof(*h.h2);
break;
case TPACKET_V3:
/* tp_nxt_offset,vlan are already populated above.
* So DONT clear those fields here
*/
h.h3->tp_status |= status;
h.h3->tp_len = skb->len;
h.h3->tp_snaplen = snaplen;
h.h3->tp_mac = macoff;
h.h3->tp_net = netoff;
h.h3->tp_sec = ts.tv_sec;
h.h3->tp_nsec = ts.tv_nsec;
hdrlen = sizeof(*h.h3);
break;
default:
BUG();
}
sll = h.raw + TPACKET_ALIGN(hdrlen);
sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
sll->sll_family = AF_PACKET;
sll->sll_hatype = dev->type;
sll->sll_protocol = skb->protocol;
sll->sll_pkttype = skb->pkt_type;
if (unlikely(po->origdev))
sll->sll_ifindex = orig_dev->ifindex;
else
sll->sll_ifindex = dev->ifindex;
smp_mb();
#if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
{
u8 *start, *end;
if (po->tp_version <= TPACKET_V2) {
end = (u8 *)PAGE_ALIGN((unsigned long)h.raw
+ macoff + snaplen);
for (start = h.raw; start < end; start += PAGE_SIZE)
flush_dcache_page(pgv_to_page(start));
}
smp_wmb();
}
#endif
if (po->tp_version <= TPACKET_V2)
__packet_set_status(po, h.raw, status);
else
prb_clear_blk_fill_status(&po->rx_ring);
sk->sk_data_ready(sk);
drop_n_restore:
if (skb_head != skb->data && skb_shared(skb)) {
skb->data = skb_head;
skb->len = skb_len;
}
drop:
kfree_skb(skb);
return 0;
ring_is_full:
po->stats.stats1.tp_drops++;
spin_unlock(&sk->sk_receive_queue.lock);
sk->sk_data_ready(sk);
kfree_skb(copy_skb);
goto drop_n_restore;
}
static void tpacket_destruct_skb(struct sk_buff *skb)
{
struct packet_sock *po = pkt_sk(skb->sk);
void *ph;
if (likely(po->tx_ring.pg_vec)) {
__u32 ts;
ph = skb_shinfo(skb)->destructor_arg;
BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
atomic_dec(&po->tx_ring.pending);
ts = __packet_set_timestamp(po, ph, skb);
__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
}
sock_wfree(skb);
}
static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
void *frame, struct net_device *dev, int size_max,
__be16 proto, unsigned char *addr, int hlen)
{
union tpacket_uhdr ph;
int to_write, offset, len, tp_len, nr_frags, len_max;
struct socket *sock = po->sk.sk_socket;
struct page *page;
void *data;
int err;
ph.raw = frame;
skb->protocol = proto;
skb->dev = dev;
skb->priority = po->sk.sk_priority;
skb->mark = po->sk.sk_mark;
sock_tx_timestamp(&po->sk, &skb_shinfo(skb)->tx_flags);
skb_shinfo(skb)->destructor_arg = ph.raw;
switch (po->tp_version) {
case TPACKET_V2:
tp_len = ph.h2->tp_len;
break;
default:
tp_len = ph.h1->tp_len;
break;
}
if (unlikely(tp_len > size_max)) {
pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
return -EMSGSIZE;
}
skb_reserve(skb, hlen);
skb_reset_network_header(skb);
skb_probe_transport_header(skb, 0);
if (po->tp_tx_has_off) {
int off_min, off_max, off;
off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
off_max = po->tx_ring.frame_size - tp_len;
if (sock->type == SOCK_DGRAM) {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_net;
break;
default:
off = ph.h1->tp_net;
break;
}
} else {
switch (po->tp_version) {
case TPACKET_V2:
off = ph.h2->tp_mac;
break;
default:
off = ph.h1->tp_mac;
break;
}
}
if (unlikely((off < off_min) || (off_max < off)))
return -EINVAL;
data = ph.raw + off;
} else {
data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
}
to_write = tp_len;
if (sock->type == SOCK_DGRAM) {
err = dev_hard_header(skb, dev, ntohs(proto), addr,
NULL, tp_len);
if (unlikely(err < 0))
return -EINVAL;
} else if (dev->hard_header_len) {
/* net device doesn't like empty head */
if (unlikely(tp_len <= dev->hard_header_len)) {
pr_err("packet size is too short (%d < %d)\n",
tp_len, dev->hard_header_len);
return -EINVAL;
}
skb_push(skb, dev->hard_header_len);
err = skb_store_bits(skb, 0, data,
dev->hard_header_len);
if (unlikely(err))
return err;
data += dev->hard_header_len;
to_write -= dev->hard_header_len;
}
offset = offset_in_page(data);
len_max = PAGE_SIZE - offset;
len = ((to_write > len_max) ? len_max : to_write);
skb->data_len = to_write;
skb->len += to_write;
skb->truesize += to_write;
atomic_add(to_write, &po->sk.sk_wmem_alloc);
while (likely(to_write)) {
nr_frags = skb_shinfo(skb)->nr_frags;
if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
pr_err("Packet exceed the number of skb frags(%lu)\n",
MAX_SKB_FRAGS);
return -EFAULT;
}
page = pgv_to_page(data);
data += len;
flush_dcache_page(page);
get_page(page);
skb_fill_page_desc(skb, nr_frags, page, offset, len);
to_write -= len;
offset = 0;
len_max = PAGE_SIZE;
len = ((to_write > len_max) ? len_max : to_write);
}
return tp_len;
}
static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
{
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
int err, reserve = 0;
void *ph;
struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
int tp_len, size_max;
unsigned char *addr;
int len_sum = 0;
int status = TP_STATUS_AVAILABLE;
int hlen, tlen;
mutex_lock(&po->pg_vec_lock);
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen
+ offsetof(struct sockaddr_ll,
sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_put;
reserve = dev->hard_header_len;
size_max = po->tx_ring.frame_size
- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
if (size_max > dev->mtu + reserve)
size_max = dev->mtu + reserve;
do {
ph = packet_current_frame(po, &po->tx_ring,
TP_STATUS_SEND_REQUEST);
if (unlikely(ph == NULL)) {
schedule();
continue;
}
status = TP_STATUS_SEND_REQUEST;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = sock_alloc_send_skb(&po->sk,
hlen + tlen + sizeof(struct sockaddr_ll),
0, &err);
if (unlikely(skb == NULL))
goto out_status;
tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
addr, hlen);
if (unlikely(tp_len < 0)) {
if (po->tp_loss) {
__packet_set_status(po, ph,
TP_STATUS_AVAILABLE);
packet_increment_head(&po->tx_ring);
kfree_skb(skb);
continue;
} else {
status = TP_STATUS_WRONG_FORMAT;
err = tp_len;
goto out_status;
}
}
skb->destructor = tpacket_destruct_skb;
__packet_set_status(po, ph, TP_STATUS_SENDING);
atomic_inc(&po->tx_ring.pending);
status = TP_STATUS_SEND_REQUEST;
err = dev_queue_xmit(skb);
if (unlikely(err > 0)) {
err = net_xmit_errno(err);
if (err && __packet_get_status(po, ph) ==
TP_STATUS_AVAILABLE) {
/* skb was destructed already */
skb = NULL;
goto out_status;
}
/*
* skb was dropped but not destructed yet;
* let's treat it like congestion or err < 0
*/
err = 0;
}
packet_increment_head(&po->tx_ring);
len_sum += tp_len;
} while (likely((ph != NULL) ||
((!(msg->msg_flags & MSG_DONTWAIT)) &&
(atomic_read(&po->tx_ring.pending))))
);
err = len_sum;
goto out_put;
out_status:
__packet_set_status(po, ph, status);
kfree_skb(skb);
out_put:
dev_put(dev);
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
size_t reserve, size_t len,
size_t linear, int noblock,
int *err)
{
struct sk_buff *skb;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
err);
if (!skb)
return NULL;
skb_reserve(skb, reserve);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
static int packet_snd(struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
struct sk_buff *skb;
struct net_device *dev;
__be16 proto;
unsigned char *addr;
int err, reserve = 0;
struct virtio_net_hdr vnet_hdr = { 0 };
int offset = 0;
int vnet_hdr_len;
struct packet_sock *po = pkt_sk(sk);
unsigned short gso_type = 0;
int hlen, tlen;
int extra_len = 0;
/*
* Get and verify the address.
*/
if (likely(saddr == NULL)) {
dev = packet_cached_dev_get(po);
proto = po->num;
addr = NULL;
} else {
err = -EINVAL;
if (msg->msg_namelen < sizeof(struct sockaddr_ll))
goto out;
if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
goto out;
proto = saddr->sll_protocol;
addr = saddr->sll_addr;
dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
}
err = -ENXIO;
if (unlikely(dev == NULL))
goto out_unlock;
err = -ENETDOWN;
if (unlikely(!(dev->flags & IFF_UP)))
goto out_unlock;
if (sock->type == SOCK_RAW)
reserve = dev->hard_header_len;
if (po->has_vnet_hdr) {
vnet_hdr_len = sizeof(vnet_hdr);
err = -EINVAL;
if (len < vnet_hdr_len)
goto out_unlock;
len -= vnet_hdr_len;
err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
vnet_hdr_len);
if (err < 0)
goto out_unlock;
if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
(vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
vnet_hdr.hdr_len))
vnet_hdr.hdr_len = vnet_hdr.csum_start +
vnet_hdr.csum_offset + 2;
err = -EINVAL;
if (vnet_hdr.hdr_len > len)
goto out_unlock;
if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
case VIRTIO_NET_HDR_GSO_TCPV4:
gso_type = SKB_GSO_TCPV4;
break;
case VIRTIO_NET_HDR_GSO_TCPV6:
gso_type = SKB_GSO_TCPV6;
break;
case VIRTIO_NET_HDR_GSO_UDP:
gso_type = SKB_GSO_UDP;
break;
default:
goto out_unlock;
}
if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
gso_type |= SKB_GSO_TCP_ECN;
if (vnet_hdr.gso_size == 0)
goto out_unlock;
}
}
if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
if (!netif_supports_nofcs(dev)) {
err = -EPROTONOSUPPORT;
goto out_unlock;
}
extra_len = 4; /* We're doing our own CRC */
}
err = -EMSGSIZE;
if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
goto out_unlock;
err = -ENOBUFS;
hlen = LL_RESERVED_SPACE(dev);
tlen = dev->needed_tailroom;
skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, vnet_hdr.hdr_len,
msg->msg_flags & MSG_DONTWAIT, &err);
if (skb == NULL)
goto out_unlock;
skb_set_network_header(skb, reserve);
err = -EINVAL;
if (sock->type == SOCK_DGRAM &&
(offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
goto out_free;
/* Returns -EFAULT on error */
err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
if (err)
goto out_free;
sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
if (!gso_type && (len > dev->mtu + reserve + extra_len)) {
/* Earlier code assumed this would be a VLAN pkt,
* double-check this now that we have the actual
* packet in hand.
*/
struct ethhdr *ehdr;
skb_reset_mac_header(skb);
ehdr = eth_hdr(skb);
if (ehdr->h_proto != htons(ETH_P_8021Q)) {
err = -EMSGSIZE;
goto out_free;
}
}
skb->protocol = proto;
skb->dev = dev;
skb->priority = sk->sk_priority;
skb->mark = sk->sk_mark;
if (po->has_vnet_hdr) {
if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
vnet_hdr.csum_offset)) {
err = -EINVAL;
goto out_free;
}
}
skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
skb_shinfo(skb)->gso_type = gso_type;
/* Header must be checked, and gso_segs computed. */
skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
skb_shinfo(skb)->gso_segs = 0;
len += vnet_hdr_len;
}
skb_probe_transport_header(skb, reserve);
if (unlikely(extra_len == 4))
skb->no_fcs = 1;
/*
* Now send it
*/
err = dev_queue_xmit(skb);
if (err > 0 && (err = net_xmit_errno(err)) != 0)
goto out_unlock;
dev_put(dev);
return len;
out_free:
kfree_skb(skb);
out_unlock:
if (dev)
dev_put(dev);
out:
return err;
}
static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
if (po->tx_ring.pg_vec)
return tpacket_snd(po, msg);
else
return packet_snd(sock, msg, len);
}
/*
* Close a PACKET socket. This is fairly simple. We immediately go
* to 'closed' state and remove our protocol entry in the device list.
*/
static int packet_release(struct socket *sock)
{
struct sock *sk = sock->sk;
struct packet_sock *po;
struct net *net;
union tpacket_req_u req_u;
if (!sk)
return 0;
net = sock_net(sk);
po = pkt_sk(sk);
mutex_lock(&net->packet.sklist_lock);
sk_del_node_init_rcu(sk);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, sk->sk_prot, -1);
preempt_enable();
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, false);
packet_cached_dev_reset(po);
if (po->prot_hook.dev) {
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
packet_flush_mclist(sk);
if (po->rx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 0);
}
if (po->tx_ring.pg_vec) {
memset(&req_u, 0, sizeof(req_u));
packet_set_ring(sk, &req_u, 1, 1);
}
fanout_release(sk);
synchronize_net();
/*
* Now the socket is dead. No more input will appear.
*/
sock_orphan(sk);
sock->sk = NULL;
/* Purge queues */
skb_queue_purge(&sk->sk_receive_queue);
sk_refcnt_debug_release(sk);
sock_put(sk);
return 0;
}
/*
* Attach a packet hook.
*/
static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
{
struct packet_sock *po = pkt_sk(sk);
if (po->fanout) {
if (dev)
dev_put(dev);
return -EINVAL;
}
lock_sock(sk);
spin_lock(&po->bind_lock);
unregister_prot_hook(sk, true);
po->num = protocol;
po->prot_hook.type = protocol;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = dev;
po->ifindex = dev ? dev->ifindex : 0;
packet_cached_dev_assign(po, dev);
if (protocol == 0)
goto out_unlock;
if (!dev || (dev->flags & IFF_UP)) {
register_prot_hook(sk);
} else {
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
out_unlock:
spin_unlock(&po->bind_lock);
release_sock(sk);
return 0;
}
/*
* Bind a packet socket to a device
*/
static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
int addr_len)
{
struct sock *sk = sock->sk;
char name[15];
struct net_device *dev;
int err = -ENODEV;
/*
* Check legality
*/
if (addr_len != sizeof(struct sockaddr))
return -EINVAL;
strlcpy(name, uaddr->sa_data, sizeof(name));
dev = dev_get_by_name(sock_net(sk), name);
if (dev)
err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
return err;
}
static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
{
struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
struct sock *sk = sock->sk;
struct net_device *dev = NULL;
int err;
/*
* Check legality
*/
if (addr_len < sizeof(struct sockaddr_ll))
return -EINVAL;
if (sll->sll_family != AF_PACKET)
return -EINVAL;
if (sll->sll_ifindex) {
err = -ENODEV;
dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
if (dev == NULL)
goto out;
}
err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
out:
return err;
}
static struct proto packet_proto = {
.name = "PACKET",
.owner = THIS_MODULE,
.obj_size = sizeof(struct packet_sock),
};
/*
* Create a packet of type SOCK_PACKET.
*/
static int packet_create(struct net *net, struct socket *sock, int protocol,
int kern)
{
struct sock *sk;
struct packet_sock *po;
__be16 proto = (__force __be16)protocol; /* weird, but documented */
int err;
if (!ns_capable(net->user_ns, CAP_NET_RAW))
return -EPERM;
if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
sock->type != SOCK_PACKET)
return -ESOCKTNOSUPPORT;
sock->state = SS_UNCONNECTED;
err = -ENOBUFS;
sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
if (sk == NULL)
goto out;
sock->ops = &packet_ops;
if (sock->type == SOCK_PACKET)
sock->ops = &packet_ops_spkt;
sock_init_data(sock, sk);
po = pkt_sk(sk);
sk->sk_family = PF_PACKET;
po->num = proto;
packet_cached_dev_reset(po);
sk->sk_destruct = packet_sock_destruct;
sk_refcnt_debug_inc(sk);
/*
* Attach a protocol block
*/
spin_lock_init(&po->bind_lock);
mutex_init(&po->pg_vec_lock);
po->prot_hook.func = packet_rcv;
if (sock->type == SOCK_PACKET)
po->prot_hook.func = packet_rcv_spkt;
po->prot_hook.af_packet_priv = sk;
if (proto) {
po->prot_hook.type = proto;
register_prot_hook(sk);
}
mutex_lock(&net->packet.sklist_lock);
sk_add_node_rcu(sk, &net->packet.sklist);
mutex_unlock(&net->packet.sklist_lock);
preempt_disable();
sock_prot_inuse_add(net, &packet_proto, 1);
preempt_enable();
return 0;
out:
return err;
}
static int packet_recv_error(struct sock *sk, struct msghdr *msg, int len)
{
struct sock_exterr_skb *serr;
struct sk_buff *skb, *skb2;
int copied, err;
err = -EAGAIN;
skb = skb_dequeue(&sk->sk_error_queue);
if (skb == NULL)
goto out;
copied = skb->len;
if (copied > len) {
msg->msg_flags |= MSG_TRUNC;
copied = len;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto out_free_skb;
sock_recv_timestamp(msg, sk, skb);
serr = SKB_EXT_ERR(skb);
put_cmsg(msg, SOL_PACKET, PACKET_TX_TIMESTAMP,
sizeof(serr->ee), &serr->ee);
msg->msg_flags |= MSG_ERRQUEUE;
err = copied;
/* Reset and regenerate socket error */
spin_lock_bh(&sk->sk_error_queue.lock);
sk->sk_err = 0;
if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) {
sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno;
spin_unlock_bh(&sk->sk_error_queue.lock);
sk->sk_error_report(sk);
} else
spin_unlock_bh(&sk->sk_error_queue.lock);
out_free_skb:
kfree_skb(skb);
out:
return err;
}
/*
* Pull a packet from our receive queue and hand it to the user.
* If necessary we block.
*/
static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
struct msghdr *msg, size_t len, int flags)
{
struct sock *sk = sock->sk;
struct sk_buff *skb;
int copied, err;
int vnet_hdr_len = 0;
err = -EINVAL;
if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
goto out;
#if 0
/* What error should we return now? EUNATTACH? */
if (pkt_sk(sk)->ifindex < 0)
return -ENODEV;
#endif
if (flags & MSG_ERRQUEUE) {
err = packet_recv_error(sk, msg, len);
goto out;
}
/*
* Call the generic datagram receiver. This handles all sorts
* of horrible races and re-entrancy so we can forget about it
* in the protocol layers.
*
* Now it will return ENETDOWN, if device have just gone down,
* but then it will block.
*/
skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
/*
* An error occurred so return it. Because skb_recv_datagram()
* handles the blocking we don't see and worry about blocking
* retries.
*/
if (skb == NULL)
goto out;
if (pkt_sk(sk)->has_vnet_hdr) {
struct virtio_net_hdr vnet_hdr = { 0 };
err = -EINVAL;
vnet_hdr_len = sizeof(vnet_hdr);
if (len < vnet_hdr_len)
goto out_free;
len -= vnet_hdr_len;
if (skb_is_gso(skb)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
/* This is a hint as to how much should be linear. */
vnet_hdr.hdr_len = skb_headlen(skb);
vnet_hdr.gso_size = sinfo->gso_size;
if (sinfo->gso_type & SKB_GSO_TCPV4)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
else if (sinfo->gso_type & SKB_GSO_TCPV6)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
else if (sinfo->gso_type & SKB_GSO_UDP)
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
else if (sinfo->gso_type & SKB_GSO_FCOE)
goto out_free;
else
BUG();
if (sinfo->gso_type & SKB_GSO_TCP_ECN)
vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
} else
vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
if (skb->ip_summed == CHECKSUM_PARTIAL) {
vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
vnet_hdr.csum_start = skb_checksum_start_offset(skb);
vnet_hdr.csum_offset = skb->csum_offset;
} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
} /* else everything is zero */
err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
vnet_hdr_len);
if (err < 0)
goto out_free;
}
/* You lose any data beyond the buffer you gave. If it worries
* a user program they can ask the device for its MTU
* anyway.
*/
copied = skb->len;
if (copied > len) {
copied = len;
msg->msg_flags |= MSG_TRUNC;
}
err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
if (err)
goto out_free;
sock_recv_ts_and_drops(msg, sk, skb);
if (msg->msg_name) {
/* If the address length field is there to be filled
* in, we fill it in now.
*/
if (sock->type == SOCK_PACKET) {
msg->msg_namelen = sizeof(struct sockaddr_pkt);
} else {
struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
msg->msg_namelen = sll->sll_halen +
offsetof(struct sockaddr_ll, sll_addr);
}
memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
msg->msg_namelen);
}
if (pkt_sk(sk)->auxdata) {
struct tpacket_auxdata aux;
aux.tp_status = TP_STATUS_USER;
if (skb->ip_summed == CHECKSUM_PARTIAL)
aux.tp_status |= TP_STATUS_CSUMNOTREADY;
aux.tp_len = PACKET_SKB_CB(skb)->origlen;
aux.tp_snaplen = skb->len;
aux.tp_mac = 0;
aux.tp_net = skb_network_offset(skb);
if (vlan_tx_tag_present(skb)) {
aux.tp_vlan_tci = vlan_tx_tag_get(skb);
aux.tp_status |= TP_STATUS_VLAN_VALID;
} else {
aux.tp_vlan_tci = 0;
}
aux.tp_padding = 0;
put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
}
/*
* Free or return the buffer as appropriate. Again this
* hides all the races and re-entrancy issues from us.
*/
err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
out_free:
skb_free_datagram(sk, skb);
out:
return err;
}
static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
if (peer)
return -EOPNOTSUPP;
uaddr->sa_family = AF_PACKET;
memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
if (dev)
strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
rcu_read_unlock();
*uaddr_len = sizeof(*uaddr);
return 0;
}
static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
int *uaddr_len, int peer)
{
struct net_device *dev;
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
if (peer)
return -EOPNOTSUPP;
sll->sll_family = AF_PACKET;
sll->sll_ifindex = po->ifindex;
sll->sll_protocol = po->num;
sll->sll_pkttype = 0;
rcu_read_lock();
dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
if (dev) {
sll->sll_hatype = dev->type;
sll->sll_halen = dev->addr_len;
memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
} else {
sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
sll->sll_halen = 0;
}
rcu_read_unlock();
*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
return 0;
}
static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
int what)
{
switch (i->type) {
case PACKET_MR_MULTICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_mc_add(dev, i->addr);
else
return dev_mc_del(dev, i->addr);
break;
case PACKET_MR_PROMISC:
return dev_set_promiscuity(dev, what);
break;
case PACKET_MR_ALLMULTI:
return dev_set_allmulti(dev, what);
break;
case PACKET_MR_UNICAST:
if (i->alen != dev->addr_len)
return -EINVAL;
if (what > 0)
return dev_uc_add(dev, i->addr);
else
return dev_uc_del(dev, i->addr);
break;
default:
break;
}
return 0;
}
static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
{
for ( ; i; i = i->next) {
if (i->ifindex == dev->ifindex)
packet_dev_mc(dev, i, what);
}
}
static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml, *i;
struct net_device *dev;
int err;
rtnl_lock();
err = -ENODEV;
dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
if (!dev)
goto done;
err = -EINVAL;
if (mreq->mr_alen > dev->addr_len)
goto done;
err = -ENOBUFS;
i = kmalloc(sizeof(*i), GFP_KERNEL);
if (i == NULL)
goto done;
err = 0;
for (ml = po->mclist; ml; ml = ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
ml->count++;
/* Free the new element ... */
kfree(i);
goto done;
}
}
i->type = mreq->mr_type;
i->ifindex = mreq->mr_ifindex;
i->alen = mreq->mr_alen;
memcpy(i->addr, mreq->mr_address, i->alen);
memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
i->count = 1;
i->next = po->mclist;
po->mclist = i;
err = packet_dev_mc(dev, i, 1);
if (err) {
po->mclist = i->next;
kfree(i);
}
done:
rtnl_unlock();
return err;
}
static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
{
struct packet_mclist *ml, **mlp;
rtnl_lock();
for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
if (ml->ifindex == mreq->mr_ifindex &&
ml->type == mreq->mr_type &&
ml->alen == mreq->mr_alen &&
memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
if (--ml->count == 0) {
struct net_device *dev;
*mlp = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
return 0;
}
}
rtnl_unlock();
return -EADDRNOTAVAIL;
}
static void packet_flush_mclist(struct sock *sk)
{
struct packet_sock *po = pkt_sk(sk);
struct packet_mclist *ml;
if (!po->mclist)
return;
rtnl_lock();
while ((ml = po->mclist) != NULL) {
struct net_device *dev;
po->mclist = ml->next;
dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
if (dev != NULL)
packet_dev_mc(dev, ml, -1);
kfree(ml);
}
rtnl_unlock();
}
static int
packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
int ret;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
switch (optname) {
case PACKET_ADD_MEMBERSHIP:
case PACKET_DROP_MEMBERSHIP:
{
struct packet_mreq_max mreq;
int len = optlen;
memset(&mreq, 0, sizeof(mreq));
if (len < sizeof(struct packet_mreq))
return -EINVAL;
if (len > sizeof(mreq))
len = sizeof(mreq);
if (copy_from_user(&mreq, optval, len))
return -EFAULT;
if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
return -EINVAL;
if (optname == PACKET_ADD_MEMBERSHIP)
ret = packet_mc_add(sk, &mreq);
else
ret = packet_mc_drop(sk, &mreq);
return ret;
}
case PACKET_RX_RING:
case PACKET_TX_RING:
{
union tpacket_req_u req_u;
int len;
switch (po->tp_version) {
case TPACKET_V1:
case TPACKET_V2:
len = sizeof(req_u.req);
break;
case TPACKET_V3:
default:
len = sizeof(req_u.req3);
break;
}
if (optlen < len)
return -EINVAL;
if (pkt_sk(sk)->has_vnet_hdr)
return -EINVAL;
if (copy_from_user(&req_u.req, optval, len))
return -EFAULT;
return packet_set_ring(sk, &req_u, 0,
optname == PACKET_TX_RING);
}
case PACKET_COPY_THRESH:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
pkt_sk(sk)->copy_thresh = val;
return 0;
}
case PACKET_VERSION:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
switch (val) {
case TPACKET_V1:
case TPACKET_V2:
case TPACKET_V3:
po->tp_version = val;
return 0;
default:
return -EINVAL;
}
}
case PACKET_RESERVE:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_reserve = val;
return 0;
}
case PACKET_LOSS:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_loss = !!val;
return 0;
}
case PACKET_AUXDATA:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->auxdata = !!val;
return 0;
}
case PACKET_ORIGDEV:
{
int val;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->origdev = !!val;
return 0;
}
case PACKET_VNET_HDR:
{
int val;
if (sock->type != SOCK_RAW)
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (optlen < sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->has_vnet_hdr = !!val;
return 0;
}
case PACKET_TIMESTAMP:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tstamp = val;
return 0;
}
case PACKET_FANOUT:
{
int val;
if (optlen != sizeof(val))
return -EINVAL;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
return fanout_add(sk, val & 0xffff, val >> 16);
}
case PACKET_TX_HAS_OFF:
{
unsigned int val;
if (optlen != sizeof(val))
return -EINVAL;
if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
return -EBUSY;
if (copy_from_user(&val, optval, sizeof(val)))
return -EFAULT;
po->tp_tx_has_off = !!val;
return 0;
}
default:
return -ENOPROTOOPT;
}
}
static int packet_getsockopt(struct socket *sock, int level, int optname,
char __user *optval, int __user *optlen)
{
int len;
int val, lv = sizeof(val);
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
void *data = &val;
union tpacket_stats_u st;
if (level != SOL_PACKET)
return -ENOPROTOOPT;
if (get_user(len, optlen))
return -EFAULT;
if (len < 0)
return -EINVAL;
switch (optname) {
case PACKET_STATISTICS:
spin_lock_bh(&sk->sk_receive_queue.lock);
memcpy(&st, &po->stats, sizeof(st));
memset(&po->stats, 0, sizeof(po->stats));
spin_unlock_bh(&sk->sk_receive_queue.lock);
if (po->tp_version == TPACKET_V3) {
lv = sizeof(struct tpacket_stats_v3);
st.stats3.tp_packets += st.stats3.tp_drops;
data = &st.stats3;
} else {
lv = sizeof(struct tpacket_stats);
st.stats1.tp_packets += st.stats1.tp_drops;
data = &st.stats1;
}
break;
case PACKET_AUXDATA:
val = po->auxdata;
break;
case PACKET_ORIGDEV:
val = po->origdev;
break;
case PACKET_VNET_HDR:
val = po->has_vnet_hdr;
break;
case PACKET_VERSION:
val = po->tp_version;
break;
case PACKET_HDRLEN:
if (len > sizeof(int))
len = sizeof(int);
if (copy_from_user(&val, optval, len))
return -EFAULT;
switch (val) {
case TPACKET_V1:
val = sizeof(struct tpacket_hdr);
break;
case TPACKET_V2:
val = sizeof(struct tpacket2_hdr);
break;
case TPACKET_V3:
val = sizeof(struct tpacket3_hdr);
break;
default:
return -EINVAL;
}
break;
case PACKET_RESERVE:
val = po->tp_reserve;
break;
case PACKET_LOSS:
val = po->tp_loss;
break;
case PACKET_TIMESTAMP:
val = po->tp_tstamp;
break;
case PACKET_FANOUT:
val = (po->fanout ?
((u32)po->fanout->id |
((u32)po->fanout->type << 16) |
((u32)po->fanout->flags << 24)) :
0);
break;
case PACKET_TX_HAS_OFF:
val = po->tp_tx_has_off;
break;
default:
return -ENOPROTOOPT;
}
if (len > lv)
len = lv;
if (put_user(len, optlen))
return -EFAULT;
if (copy_to_user(optval, data, len))
return -EFAULT;
return 0;
}
static int packet_notifier(struct notifier_block *this, unsigned long msg, void *data)
{
struct sock *sk;
struct net_device *dev = data;
struct net *net = dev_net(dev);
rcu_read_lock();
sk_for_each_rcu(sk, &net->packet.sklist) {
struct packet_sock *po = pkt_sk(sk);
switch (msg) {
case NETDEV_UNREGISTER:
if (po->mclist)
packet_dev_mclist(dev, po->mclist, -1);
/* fallthrough */
case NETDEV_DOWN:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->running) {
__unregister_prot_hook(sk, false);
sk->sk_err = ENETDOWN;
if (!sock_flag(sk, SOCK_DEAD))
sk->sk_error_report(sk);
}
if (msg == NETDEV_UNREGISTER) {
packet_cached_dev_reset(po);
po->ifindex = -1;
if (po->prot_hook.dev)
dev_put(po->prot_hook.dev);
po->prot_hook.dev = NULL;
}
spin_unlock(&po->bind_lock);
}
break;
case NETDEV_UP:
if (dev->ifindex == po->ifindex) {
spin_lock(&po->bind_lock);
if (po->num)
register_prot_hook(sk);
spin_unlock(&po->bind_lock);
}
break;
}
}
rcu_read_unlock();
return NOTIFY_DONE;
}
static int packet_ioctl(struct socket *sock, unsigned int cmd,
unsigned long arg)
{
struct sock *sk = sock->sk;
switch (cmd) {
case SIOCOUTQ:
{
int amount = sk_wmem_alloc_get(sk);
return put_user(amount, (int __user *)arg);
}
case SIOCINQ:
{
struct sk_buff *skb;
int amount = 0;
spin_lock_bh(&sk->sk_receive_queue.lock);
skb = skb_peek(&sk->sk_receive_queue);
if (skb)
amount = skb->len;
spin_unlock_bh(&sk->sk_receive_queue.lock);
return put_user(amount, (int __user *)arg);
}
case SIOCGSTAMP:
return sock_get_timestamp(sk, (struct timeval __user *)arg);
case SIOCGSTAMPNS:
return sock_get_timestampns(sk, (struct timespec __user *)arg);
#ifdef CONFIG_INET
case SIOCADDRT:
case SIOCDELRT:
case SIOCDARP:
case SIOCGARP:
case SIOCSARP:
case SIOCGIFADDR:
case SIOCSIFADDR:
case SIOCGIFBRDADDR:
case SIOCSIFBRDADDR:
case SIOCGIFNETMASK:
case SIOCSIFNETMASK:
case SIOCGIFDSTADDR:
case SIOCSIFDSTADDR:
case SIOCSIFFLAGS:
return inet_dgram_ops.ioctl(sock, cmd, arg);
#endif
default:
return -ENOIOCTLCMD;
}
return 0;
}
static unsigned int packet_poll(struct file *file, struct socket *sock,
poll_table *wait)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned int mask = datagram_poll(file, sock, wait);
spin_lock_bh(&sk->sk_receive_queue.lock);
if (po->rx_ring.pg_vec) {
if (!packet_previous_rx_frame(po, &po->rx_ring,
TP_STATUS_KERNEL))
mask |= POLLIN | POLLRDNORM;
}
spin_unlock_bh(&sk->sk_receive_queue.lock);
spin_lock_bh(&sk->sk_write_queue.lock);
if (po->tx_ring.pg_vec) {
if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
mask |= POLLOUT | POLLWRNORM;
}
spin_unlock_bh(&sk->sk_write_queue.lock);
return mask;
}
/* Dirty? Well, I still did not learn better way to account
* for user mmaps.
*/
static void packet_mm_open(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_inc(&pkt_sk(sk)->mapped);
}
static void packet_mm_close(struct vm_area_struct *vma)
{
struct file *file = vma->vm_file;
struct socket *sock = file->private_data;
struct sock *sk = sock->sk;
if (sk)
atomic_dec(&pkt_sk(sk)->mapped);
}
static const struct vm_operations_struct packet_mmap_ops = {
.open = packet_mm_open,
.close = packet_mm_close,
};
static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
unsigned int len)
{
int i;
for (i = 0; i < len; i++) {
if (likely(pg_vec[i].buffer)) {
if (is_vmalloc_addr(pg_vec[i].buffer))
vfree(pg_vec[i].buffer);
else
free_pages((unsigned long)pg_vec[i].buffer,
order);
pg_vec[i].buffer = NULL;
}
}
kfree(pg_vec);
}
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer = NULL;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/*
* __get_free_pages failed, fall back to vmalloc
*/
buffer = vzalloc((1 << order) * PAGE_SIZE);
if (buffer)
return buffer;
/*
* vmalloc failed, lets dig into swap here
*/
gfp_flags &= ~__GFP_NORETRY;
buffer = (char *)__get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
/*
* complete and utter failure
*/
return NULL;
}
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
int closing, int tx_ring)
{
struct pgv *pg_vec = NULL;
struct packet_sock *po = pkt_sk(sk);
int was_running, order = 0;
struct packet_ring_buffer *rb;
struct sk_buff_head *rb_queue;
__be16 num;
int err = -EINVAL;
/* Added to avoid minimal code churn */
struct tpacket_req *req = &req_u->req;
/* Opening a Tx-ring is NOT supported in TPACKET_V3 */
if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
WARN(1, "Tx-ring is not supported.\n");
goto out;
}
rb = tx_ring ? &po->tx_ring : &po->rx_ring;
rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
err = -EBUSY;
if (!closing) {
if (atomic_read(&po->mapped))
goto out;
if (atomic_read(&rb->pending))
goto out;
}
if (req->tp_block_nr) {
/* Sanity tests and some calculations */
err = -EBUSY;
if (unlikely(rb->pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V1:
po->tp_hdrlen = TPACKET_HDRLEN;
break;
case TPACKET_V2:
po->tp_hdrlen = TPACKET2_HDRLEN;
break;
case TPACKET_V3:
po->tp_hdrlen = TPACKET3_HDRLEN;
break;
}
err = -EINVAL;
if (unlikely((int)req->tp_block_size <= 0))
goto out;
if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
goto out;
if (po->tp_version >= TPACKET_V3 &&
(int)(req->tp_block_size -
BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0)
goto out;
if (unlikely(req->tp_frame_size < po->tp_hdrlen +
po->tp_reserve))
goto out;
if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
goto out;
rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
if (unlikely(rb->frames_per_block <= 0))
goto out;
if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
req->tp_frame_nr))
goto out;
err = -ENOMEM;
order = get_order(req->tp_block_size);
pg_vec = alloc_pg_vec(req, order);
if (unlikely(!pg_vec))
goto out;
switch (po->tp_version) {
case TPACKET_V3:
/* Transmit path is not supported. We checked
* it above but just being paranoid
*/
if (!tx_ring)
init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring);
break;
default:
break;
}
}
/* Done */
else {
err = -EINVAL;
if (unlikely(req->tp_frame_nr))
goto out;
}
lock_sock(sk);
/* Detach socket from network */
spin_lock(&po->bind_lock);
was_running = po->running;
num = po->num;
if (was_running) {
po->num = 0;
__unregister_prot_hook(sk, false);
}
spin_unlock(&po->bind_lock);
synchronize_net();
err = -EBUSY;
mutex_lock(&po->pg_vec_lock);
if (closing || atomic_read(&po->mapped) == 0) {
err = 0;
spin_lock_bh(&rb_queue->lock);
swap(rb->pg_vec, pg_vec);
rb->frame_max = (req->tp_frame_nr - 1);
rb->head = 0;
rb->frame_size = req->tp_frame_size;
spin_unlock_bh(&rb_queue->lock);
swap(rb->pg_vec_order, order);
swap(rb->pg_vec_len, req->tp_block_nr);
rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
po->prot_hook.func = (po->rx_ring.pg_vec) ?
tpacket_rcv : packet_rcv;
skb_queue_purge(rb_queue);
if (atomic_read(&po->mapped))
pr_err("packet_mmap: vma is busy: %d\n",
atomic_read(&po->mapped));
}
mutex_unlock(&po->pg_vec_lock);
spin_lock(&po->bind_lock);
if (was_running) {
po->num = num;
register_prot_hook(sk);
}
spin_unlock(&po->bind_lock);
if (closing && (po->tp_version > TPACKET_V2)) {
/* Because we don't support block-based V3 on tx-ring */
if (!tx_ring)
prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue);
}
release_sock(sk);
if (pg_vec)
free_pg_vec(pg_vec, order, req->tp_block_nr);
out:
return err;
}
static int packet_mmap(struct file *file, struct socket *sock,
struct vm_area_struct *vma)
{
struct sock *sk = sock->sk;
struct packet_sock *po = pkt_sk(sk);
unsigned long size, expected_size;
struct packet_ring_buffer *rb;
unsigned long start;
int err = -EINVAL;
int i;
if (vma->vm_pgoff)
return -EINVAL;
mutex_lock(&po->pg_vec_lock);
expected_size = 0;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec) {
expected_size += rb->pg_vec_len
* rb->pg_vec_pages
* PAGE_SIZE;
}
}
if (expected_size == 0)
goto out;
size = vma->vm_end - vma->vm_start;
if (size != expected_size)
goto out;
start = vma->vm_start;
for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
if (rb->pg_vec == NULL)
continue;
for (i = 0; i < rb->pg_vec_len; i++) {
struct page *page;
void *kaddr = rb->pg_vec[i].buffer;
int pg_num;
for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
page = pgv_to_page(kaddr);
err = vm_insert_page(vma, start, page);
if (unlikely(err))
goto out;
start += PAGE_SIZE;
kaddr += PAGE_SIZE;
}
}
}
atomic_inc(&po->mapped);
vma->vm_ops = &packet_mmap_ops;
err = 0;
out:
mutex_unlock(&po->pg_vec_lock);
return err;
}
static const struct proto_ops packet_ops_spkt = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind_spkt,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname_spkt,
.poll = datagram_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = sock_no_setsockopt,
.getsockopt = sock_no_getsockopt,
.sendmsg = packet_sendmsg_spkt,
.recvmsg = packet_recvmsg,
.mmap = sock_no_mmap,
.sendpage = sock_no_sendpage,
};
static const struct proto_ops packet_ops = {
.family = PF_PACKET,
.owner = THIS_MODULE,
.release = packet_release,
.bind = packet_bind,
.connect = sock_no_connect,
.socketpair = sock_no_socketpair,
.accept = sock_no_accept,
.getname = packet_getname,
.poll = packet_poll,
.ioctl = packet_ioctl,
.listen = sock_no_listen,
.shutdown = sock_no_shutdown,
.setsockopt = packet_setsockopt,
.getsockopt = packet_getsockopt,
.sendmsg = packet_sendmsg,
.recvmsg = packet_recvmsg,
.mmap = packet_mmap,
.sendpage = sock_no_sendpage,
};
static const struct net_proto_family packet_family_ops = {
.family = PF_PACKET,
.create = packet_create,
.owner = THIS_MODULE,
};
static struct notifier_block packet_netdev_notifier = {
.notifier_call = packet_notifier,
};
#ifdef CONFIG_PROC_FS
static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
struct net *net = seq_file_net(seq);
rcu_read_lock();
return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
}
static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct net *net = seq_file_net(seq);
return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
}
static void packet_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int packet_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
else {
struct sock *s = sk_entry(v);
const struct packet_sock *po = pkt_sk(s);
seq_printf(seq,
"%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
s,
atomic_read(&s->sk_refcnt),
s->sk_type,
ntohs(po->num),
po->ifindex,
po->running,
atomic_read(&s->sk_rmem_alloc),
from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
sock_i_ino(s));
}
return 0;
}
static const struct seq_operations packet_seq_ops = {
.start = packet_seq_start,
.next = packet_seq_next,
.stop = packet_seq_stop,
.show = packet_seq_show,
};
static int packet_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &packet_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations packet_seq_fops = {
.owner = THIS_MODULE,
.open = packet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
#endif
static int __net_init packet_net_init(struct net *net)
{
mutex_init(&net->packet.sklist_lock);
INIT_HLIST_HEAD(&net->packet.sklist);
if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
return -ENOMEM;
return 0;
}
static void __net_exit packet_net_exit(struct net *net)
{
remove_proc_entry("packet", net->proc_net);
}
static struct pernet_operations packet_net_ops = {
.init = packet_net_init,
.exit = packet_net_exit,
};
static void __exit packet_exit(void)
{
unregister_netdevice_notifier(&packet_netdev_notifier);
unregister_pernet_subsys(&packet_net_ops);
sock_unregister(PF_PACKET);
proto_unregister(&packet_proto);
}
static int __init packet_init(void)
{
int rc = proto_register(&packet_proto, 0);
if (rc != 0)
goto out;
sock_register(&packet_family_ops);
register_pernet_subsys(&packet_net_ops);
register_netdevice_notifier(&packet_netdev_notifier);
out:
return rc;
}
module_init(packet_init);
module_exit(packet_exit);
MODULE_LICENSE("GPL");
MODULE_ALIAS_NETPROTO(PF_PACKET);
|
muhviehstah/N915FY-MM-Kernel
|
net/packet/af_packet.c
|
C
|
gpl-2.0
| 94,243 |
// Load modules
var ChildProcess = require('child_process');
// Declare internals
var internals = {
linters: {
eslint: __dirname + '/linters/eslint/index.js',
jslint: __dirname + '/linters/jslint/index.js'
}
};
exports.lint = function (settings, callback) {
var child = ChildProcess.fork(internals.linters[settings.linter],
settings['lint-options'] ? [ settings['lint-options'] ] : [],
{ cwd: settings.lintingPath });
child.once('message', function (message) {
child.kill();
return callback(null, { lint: message });
});
};
|
gvishnu06/insolent-wookie
|
node_modules/lab/lib/lint.js
|
JavaScript
|
gpl-2.0
| 652 |
console.log("LIBPATH:"+_ROOT_URL_);
document.write("<script type='text/javascript' src='"+_ROOT_URL_+"libcode/js/serviceInterface.js'></script>");
document.write("<script type='text/javascript' src='"+_ROOT_URL_+"weixin/js/wxjssdk.js'></script>");
/*
* 测试接口
*
*/
function aipTestInterface()
{
console.log("aipTestInterface");
apiMenuShareAppMessage("分享测试","aflajfla","www.baidu.com","www.baidu.com",function(status,res){
console.log("status:"+status +"res:"+res);
});
// apiIsPosition("116.474338","40.000726");
}
|
yonglinchen/shopping
|
webapi/test/apiTestDemo.js
|
JavaScript
|
gpl-2.0
| 554 |
using System.Collections.Generic;
using System.Linq;
using MrCMS.Services;
namespace MrCMS.Website.Optimization
{
public class AppStylesheetBundle : IStylesheetBundle
{
public const string VirtualUrl = "~/stylesheets/apps";
private readonly IEnumerable<IAppStylesheetList> _stylesheetLists;
public AppStylesheetBundle(IEnumerable<IAppStylesheetList> stylesheetLists)
{
_stylesheetLists = stylesheetLists;
}
public string Url { get { return VirtualUrl; } }
public IEnumerable<string> Files
{
get { return _stylesheetLists.SelectMany(list => list.UIStylesheets); }
}
}
}
|
MaiLT/Ecommerce
|
MrCMS/Website/Optimization/AppStylesheetBundle.cs
|
C#
|
gpl-2.0
| 683 |
/******************************************************************************
*
* 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
*
* 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 <[email protected]>
* 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
* 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/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/dma-mapping.h>
#include <linux/pci_ids.h>
#include <net/net_namespace.h>
#include <linux/netdevice.h>
#include <net/cfg80211.h>
#include <net/mac80211.h>
#include <net/netlink.h>
#include "iwl-drv.h"
#include "mvm.h"
#include "iwl-prph.h"
#include "iwl-csr.h"
#include "iwl-fh.h"
#include "iwl-io.h"
#include "iwl-trans.h"
#include "iwl-op-mode.h"
#include "iwl-tm-infc.h"
#include "iwl-tm-gnl.h"
int iwl_mvm_testmode_send_cmd(struct iwl_op_mode *op_mode,
struct iwl_host_cmd *cmd)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
return iwl_mvm_send_cmd(mvm, cmd);
}
bool iwl_mvm_testmode_valid_hw_addr(u32 addr)
{
/* TODO need to implement */
return true;
}
u32 iwl_mvm_testmode_get_fw_ver(struct iwl_op_mode *op_mode)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
return mvm->fw->ucode_ver;
}
struct sk_buff *iwl_mvm_testmode_alloc_reply(struct iwl_op_mode *op_mode,
int len)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
return cfg80211_testmode_alloc_reply_skb(mvm->hw->wiphy, len);
}
int iwl_mvm_testmode_reply(struct iwl_op_mode *op_mode, struct sk_buff *skb)
{
return cfg80211_testmode_reply(skb);
}
struct sk_buff *iwl_mvm_testmode_alloc_event(struct iwl_op_mode *op_mode,
int len)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
return cfg80211_testmode_alloc_event_skb(mvm->hw->wiphy, len,
GFP_ATOMIC);
}
void iwl_mvm_testmode_event(struct iwl_op_mode *op_mode, struct sk_buff *skb)
{
cfg80211_testmode_event(skb, GFP_ATOMIC);
}
static int iwl_mvm_tm_send_hcmd(struct iwl_mvm *mvm,
struct iwl_tm_data *data_in,
struct iwl_tm_data *data_out)
{
struct iwl_tm_cmd_request *hcmd_req = data_in->data;
struct iwl_tm_cmd_request *cmd_resp;
u32 reply_len, resp_size;
struct iwl_rx_packet *pkt;
struct iwl_host_cmd host_cmd = {
.id = hcmd_req->id,
.data[0] = hcmd_req->data,
.len[0] = hcmd_req->len,
.dataflags[0] = IWL_HCMD_DFL_NOCOPY,
};
int ret;
if (hcmd_req->want_resp)
host_cmd.flags |= CMD_WANT_SKB;
mutex_lock(&mvm->mutex);
ret = iwl_mvm_send_cmd(mvm, &host_cmd);
mutex_unlock(&mvm->mutex);
if (ret)
return ret;
/* if no reply is required, we are done */
if (!(host_cmd.flags & CMD_WANT_SKB))
return 0;
/* Retrieve response packet */
pkt = host_cmd.resp_pkt;
if (!pkt) {
IWL_ERR(mvm->trans, "HCMD received a null response packet\n");
return -ENOMSG;
}
reply_len = iwl_rx_packet_len(pkt);
/* Set response data */
resp_size = sizeof(struct iwl_tm_cmd_request) + reply_len;
cmd_resp = kzalloc(resp_size, GFP_KERNEL);
if (!cmd_resp) {
iwl_free_resp(&host_cmd);
return -ENOMEM;
}
cmd_resp->id = hcmd_req->id;
cmd_resp->len = reply_len;
memcpy(cmd_resp->data, &(pkt->hdr), reply_len);
iwl_free_resp(&host_cmd);
data_out->data = cmd_resp;
data_out->len = resp_size;
return 0;
}
static void iwl_mvm_tm_execute_reg_ops(struct iwl_trans *trans,
struct iwl_tm_regs_request *request,
struct iwl_tm_regs_request *result)
{
struct iwl_tm_reg_op *cur_op;
u32 idx, read_idx;
for (idx = 0, read_idx = 0; idx < request->num; idx++) {
cur_op = &request->reg_ops[idx];
if (cur_op->op_type == IWL_TM_REG_OP_READ) {
cur_op->value = iwl_read32(trans, cur_op->address);
memcpy(&result->reg_ops[read_idx], cur_op,
sizeof(*cur_op));
read_idx++;
} else {
/* IWL_TM_REG_OP_WRITE is the only possible option */
iwl_write32(trans, cur_op->address, cur_op->value);
}
}
}
static int iwl_mvm_tm_reg_ops(struct iwl_trans *trans,
struct iwl_tm_data *data_in,
struct iwl_tm_data *data_out)
{
struct iwl_tm_reg_op *cur_op;
struct iwl_tm_regs_request *request = data_in->data;
struct iwl_tm_regs_request *result;
u32 result_size;
u32 idx, read_idx;
bool is_grab_nic_access_required = true;
unsigned long flags;
/* Calculate result size (result is returned only for read ops) */
for (idx = 0, read_idx = 0; idx < request->num; idx++) {
if (request->reg_ops[idx].op_type == IWL_TM_REG_OP_READ)
read_idx++;
/* check if there is an operation that it is not */
/* in the CSR range (0x00000000 - 0x000003FF) */
/* and not in the AL range */
cur_op = &request->reg_ops[idx];
if (IS_AL_ADDR(cur_op->address) ||
(cur_op->address < HBUS_BASE))
is_grab_nic_access_required = false;
}
result_size = sizeof(struct iwl_tm_regs_request) +
read_idx*sizeof(struct iwl_tm_reg_op);
result = kzalloc(result_size, GFP_KERNEL);
if (!result)
return -ENOMEM;
result->num = read_idx;
if (is_grab_nic_access_required) {
if (!iwl_trans_grab_nic_access(trans, false, &flags)) {
kfree(result);
return -EBUSY;
}
iwl_mvm_tm_execute_reg_ops(trans, request, result);
iwl_trans_release_nic_access(trans, &flags);
} else {
iwl_mvm_tm_execute_reg_ops(trans, request, result);
}
data_out->data = result;
data_out->len = result_size;
return 0;
}
static int iwl_tm_get_dev_info(struct iwl_mvm *mvm,
struct iwl_tm_data *data_out)
{
struct iwl_tm_dev_info *dev_info;
const u8 driver_ver[] = BACKPORTS_GIT_TRACKED;
dev_info = kzalloc(sizeof(struct iwl_tm_dev_info) +
(strlen(driver_ver)+1)*sizeof(u8), GFP_KERNEL);
if (!dev_info)
return -ENOMEM;
dev_info->dev_id = mvm->trans->hw_id;
dev_info->fw_ver = mvm->fw->ucode_ver;
dev_info->vendor_id = PCI_VENDOR_ID_INTEL;
dev_info->silicon_step = CSR_HW_REV_STEP(mvm->trans->hw_rev);
/* TODO: Assign real value when feature is implemented */
dev_info->build_ver = 0x00;
strcpy(dev_info->driver_ver, driver_ver);
data_out->data = dev_info;
data_out->len = sizeof(*dev_info);
return 0;
}
static int iwl_tm_indirect_read(struct iwl_mvm *mvm,
struct iwl_tm_data *data_in,
struct iwl_tm_data *data_out)
{
struct iwl_trans *trans = mvm->trans;
struct iwl_tm_sram_read_request *cmd_in = data_in->data;
u32 addr = cmd_in->offset;
u32 size = cmd_in->length;
u32 *buf32, size32, i;
unsigned long flags;
if (size & (sizeof(u32)-1))
return -EINVAL;
data_out->data = kmalloc(size, GFP_KERNEL);
if (!data_out->data)
return -ENOMEM;
data_out->len = size;
size32 = size / sizeof(u32);
buf32 = data_out->data;
mutex_lock(&mvm->mutex);
/* Hard-coded periphery absolute address */
if (IWL_ABS_PRPH_START <= addr &&
addr < IWL_ABS_PRPH_START + PRPH_END) {
if (!iwl_trans_grab_nic_access(trans, false, &flags)) {
mutex_unlock(&mvm->mutex);
return -EBUSY;
}
for (i = 0; i < size32; i++)
buf32[i] = iwl_trans_read_prph(trans,
addr + i * sizeof(u32));
iwl_trans_release_nic_access(trans, &flags);
} else {
/* target memory (SRAM) */
iwl_trans_read_mem(trans, addr, buf32, size32);
}
mutex_unlock(&mvm->mutex);
return 0;
}
static int iwl_tm_indirect_write(struct iwl_mvm *mvm,
struct iwl_tm_data *data_in)
{
struct iwl_trans *trans = mvm->trans;
struct iwl_tm_sram_write_request *cmd_in = data_in->data;
u32 addr = cmd_in->offset;
u32 size = cmd_in->len;
u8 *buf = cmd_in->buffer;
u32 *buf32 = (u32 *)buf, size32 = size / sizeof(u32);
unsigned long flags;
u32 val, i;
mutex_lock(&mvm->mutex);
if (IWL_ABS_PRPH_START <= addr &&
addr < IWL_ABS_PRPH_START + PRPH_END) {
/* Periphery writes can be 1-3 bytes long, or DWORDs */
if (size < 4) {
memcpy(&val, buf, size);
if (!iwl_trans_grab_nic_access(trans, false, &flags)) {
mutex_unlock(&mvm->mutex);
return -EBUSY;
}
iwl_write32(trans, HBUS_TARG_PRPH_WADDR,
(addr & 0x000FFFFF) | ((size - 1) << 24));
iwl_write32(trans, HBUS_TARG_PRPH_WDAT, val);
iwl_trans_release_nic_access(trans, &flags);
} else {
if (size % sizeof(u32)) {
mutex_unlock(&mvm->mutex);
return -EINVAL;
}
for (i = 0; i < size32; i++)
iwl_write_prph(trans, addr + i*sizeof(u32),
buf32[i]);
}
} else {
iwl_trans_write_mem(trans, addr, buf32, size32);
}
mutex_unlock(&mvm->mutex);
return 0;
}
/**
* iwl_mvm_tm_cmd_execute - Implementation of test command executor callback
* @op_mode: Specific device's operation mode
* @cmd: User space command's index
* @data_in: Input data. "data" field is to be casted to relevant
* data structure. All verification must be done in the
* caller function, therefor assuming that input data
* length is valid.
* @data_out: Will be allocated inside, freeing is in the caller's
* responsibility
*/
int iwl_mvm_tm_cmd_execute(struct iwl_op_mode *op_mode, u32 cmd,
struct iwl_tm_data *data_in,
struct iwl_tm_data *data_out)
{
struct iwl_mvm *mvm = IWL_OP_MODE_GET_MVM(op_mode);
int ret;
if (WARN_ON_ONCE(!op_mode || !data_in))
return -EINVAL;
ret = iwl_mvm_ref_sync(mvm, IWL_MVM_REF_TM_CMD);
if (ret)
return ret;
switch (cmd) {
case IWL_TM_USER_CMD_HCMD:
ret = iwl_mvm_tm_send_hcmd(mvm, data_in, data_out);
break;
case IWL_TM_USER_CMD_REG_ACCESS:
ret = iwl_mvm_tm_reg_ops(mvm->trans, data_in, data_out);
break;
case IWL_TM_USER_CMD_SRAM_WRITE:
ret = iwl_tm_indirect_write(mvm, data_in);
break;
case IWL_TM_USER_CMD_SRAM_READ:
ret = iwl_tm_indirect_read(mvm, data_in, data_out);
break;
case IWL_TM_USER_CMD_GET_DEVICE_INFO:
ret = iwl_tm_get_dev_info(mvm, data_out);
break;
default:
ret = -EOPNOTSUPP;
break;
}
iwl_mvm_unref(mvm, IWL_MVM_REF_TM_CMD);
return ret;
}
#ifdef CPTCFG_NL80211_TESTMODE
/**
* iwl_tm_mvm_retrieve_monitor() - trigger monitor retrieve event
*/
int iwl_tm_mvm_retrieve_monitor(struct ieee80211_hw *hw,
struct ieee80211_tx_thrshld_md *md)
{
struct iwl_mvm *mvm = IWL_MAC80211_GET_MVM(hw);
struct iwl_tm_thrshld_md tm_md;
if (!md)
return -1;
tm_md.mode = md->mode;
tm_md.monitor_collec_wind = md->monitor_collec_wind;
tm_md.seq = md->seq;
tm_md.pkt_start = md->pkt_start;
tm_md.pkt_end = md->pkt_end;
tm_md.msrmnt = md->msrmnt;
tm_md.tid = md->tid;
return iwl_tm_gnl_send_msg(mvm->trans,
IWL_TM_USER_CMD_NOTIF_RETRIEVE_MONITOR,
false, &tm_md, sizeof(tm_md),
GFP_ATOMIC);
}
#endif
/**
* iwl_tm_mvm_send_rx() - Send a spontaneous rx message to user
* @mvm: mvm opmode pointer
* @rxb: Contains rx packet to be sent
*/
void iwl_tm_mvm_send_rx(struct iwl_mvm *mvm, struct iwl_rx_cmd_buffer *rxb)
{
struct iwl_rx_packet *pkt = rxb_addr(rxb);
int length = iwl_rx_packet_len(pkt);
/* the length doesn't include len_n_flags field, so add it manually */
length += sizeof(__le32);
iwl_tm_gnl_send_msg(mvm->trans, IWL_TM_USER_CMD_NOTIF_UCODE_RX_PKT,
true, (void *)pkt, length, GFP_ATOMIC);
}
|
tank0412/android_kernel_xiaomi_latte
|
uefi/cht/modules/iwlwifi/drivers/net/wireless/iwlwifi/mvm/testmode.c
|
C
|
gpl-2.0
| 13,633 |
/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/cpu_id.h"
#if defined(_MSC_VER)
#include <intrin.h> // For __cpuidex()
#endif
#if !defined(__pnacl__) && !defined(__CLR_VER) && \
!defined(__native_client__) && (defined(_M_IX86) || defined(_M_X64)) && \
defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
#include <immintrin.h> // For _xgetbv()
#endif
#if !defined(__native_client__)
#include <stdlib.h> // For getenv()
#endif
// For ArmCpuCaps() but unittested on all platforms
#include <stdio.h>
#include <string.h>
#include "libyuv/basic_types.h" // For CPU_X86
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// For functions that use the stack and have runtime checks for overflow,
// use SAFEBUFFERS to avoid additional check.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219) && \
!defined(__clang__)
#define SAFEBUFFERS __declspec(safebuffers)
#else
#define SAFEBUFFERS
#endif
// cpu_info_ variable for SIMD instruction sets detected.
LIBYUV_API int cpu_info_ = 0;
// TODO(fbarchard): Consider using int for cpuid so casting is not needed.
// Low level cpuid for X86.
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER)
LIBYUV_API
void CpuId(int info_eax, int info_ecx, int* cpu_info) {
#if defined(_MSC_VER)
// Visual C version uses intrinsic or inline x86 assembly.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
__cpuidex(cpu_info, info_eax, info_ecx);
#elif defined(_M_IX86)
__asm {
mov eax, info_eax
mov ecx, info_ecx
mov edi, cpu_info
cpuid
mov [edi], eax
mov [edi + 4], ebx
mov [edi + 8], ecx
mov [edi + 12], edx
}
#else // Visual C but not x86
if (info_ecx == 0) {
__cpuid(cpu_info, info_eax);
} else {
cpu_info[3] = cpu_info[2] = cpu_info[1] = cpu_info[0] = 0u;
}
#endif
// GCC version uses inline x86 assembly.
#else // defined(_MSC_VER)
int info_ebx, info_edx;
asm volatile(
#if defined(__i386__) && defined(__PIC__)
// Preserve ebx for fpic 32 bit.
"mov %%ebx, %%edi \n"
"cpuid \n"
"xchg %%edi, %%ebx \n"
: "=D"(info_ebx),
#else
"cpuid \n"
: "=b"(info_ebx),
#endif // defined( __i386__) && defined(__PIC__)
"+a"(info_eax), "+c"(info_ecx), "=d"(info_edx));
cpu_info[0] = info_eax;
cpu_info[1] = info_ebx;
cpu_info[2] = info_ecx;
cpu_info[3] = info_edx;
#endif // defined(_MSC_VER)
}
#else // (defined(_M_IX86) || defined(_M_X64) ...
LIBYUV_API
void CpuId(int eax, int ecx, int* cpu_info) {
(void)eax;
(void)ecx;
cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0;
}
#endif
// For VS2010 and earlier emit can be used:
// _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0 // For VS2010 and earlier.
// __asm {
// xor ecx, ecx // xcr 0
// xgetbv
// mov xcr0, eax
// }
// For VS2013 and earlier 32 bit, the _xgetbv(0) optimizer produces bad code.
// https://code.google.com/p/libyuv/issues/detail?id=529
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", off)
#endif
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER) && !defined(__native_client__)
// X86 CPUs have xgetbv to detect OS saves high parts of ymm registers.
int GetXCR0() {
int xcr0 = 0;
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
xcr0 = _xgetbv(0); // VS2010 SP1 required.
#elif defined(__i386__) || defined(__x86_64__)
asm(".byte 0x0f, 0x01, 0xd0" : "=a"(xcr0) : "c"(0) : "%edx");
#endif // defined(__i386__) || defined(__x86_64__)
return xcr0;
}
#else
// xgetbv unavailable to query for OSSave support. Return 0.
#define GetXCR0() 0
#endif // defined(_M_IX86) || defined(_M_X64) ..
// Return optimization to previous setting.
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", on)
#endif
// based on libvpx arm_cpudetect.c
// For Arm, but public to allow testing on any CPU
LIBYUV_API SAFEBUFFERS int ArmCpuCaps(const char* cpuinfo_name) {
char cpuinfo_line[512];
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// Assume Neon if /proc/cpuinfo is unavailable.
// This will occur for Chrome sandbox for Pepper or Render process.
return kCpuHasNEON;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "Features", 8) == 0) {
char* p = strstr(cpuinfo_line, " neon");
if (p && (p[5] == ' ' || p[5] == '\n')) {
fclose(f);
return kCpuHasNEON;
}
// aarch64 uses asimd for Neon.
p = strstr(cpuinfo_line, " asimd");
if (p) {
fclose(f);
return kCpuHasNEON;
}
}
}
fclose(f);
return 0;
}
// TODO(fbarchard): Consider read_msa_ir().
// TODO(fbarchard): Add unittest.
LIBYUV_API SAFEBUFFERS int MipsCpuCaps(const char* cpuinfo_name,
const char ase[]) {
char cpuinfo_line[512];
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// ase enabled if /proc/cpuinfo is unavailable.
if (strcmp(ase, " msa") == 0) {
return kCpuHasMSA;
}
return kCpuHasDSPR2;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "ASEs implemented", 16) == 0) {
char* p = strstr(cpuinfo_line, ase);
if (p) {
fclose(f);
if (strcmp(ase, " msa") == 0) {
return kCpuHasMSA;
}
return kCpuHasDSPR2;
}
}
}
fclose(f);
return 0;
}
// Test environment variable for disabling CPU features. Any non-zero value
// to disable. Zero ignored to make it easy to set the variable on/off.
#if !defined(__native_client__) && !defined(_M_ARM)
static LIBYUV_BOOL TestEnv(const char* name) {
const char* var = getenv(name);
if (var) {
if (var[0] != '0') {
return LIBYUV_TRUE;
}
}
return LIBYUV_FALSE;
}
#else // nacl does not support getenv().
static LIBYUV_BOOL TestEnv(const char*) {
return LIBYUV_FALSE;
}
#endif
static SAFEBUFFERS int GetCpuFlags(void) {
int cpu_info = 0;
#if !defined(__pnacl__) && !defined(__CLR_VER) && defined(CPU_X86)
int cpu_info0[4] = {0, 0, 0, 0};
int cpu_info1[4] = {0, 0, 0, 0};
int cpu_info7[4] = {0, 0, 0, 0};
CpuId(0, 0, cpu_info0);
CpuId(1, 0, cpu_info1);
if (cpu_info0[0] >= 7) {
CpuId(7, 0, cpu_info7);
}
cpu_info = kCpuHasX86 | ((cpu_info1[3] & 0x04000000) ? kCpuHasSSE2 : 0) |
((cpu_info1[2] & 0x00000200) ? kCpuHasSSSE3 : 0) |
((cpu_info1[2] & 0x00080000) ? kCpuHasSSE41 : 0) |
((cpu_info1[2] & 0x00100000) ? kCpuHasSSE42 : 0) |
((cpu_info7[1] & 0x00000200) ? kCpuHasERMS : 0);
// AVX requires OS saves YMM registers.
if (((cpu_info1[2] & 0x1c000000) == 0x1c000000) && // AVX and OSXSave
((GetXCR0() & 6) == 6)) { // Test OS saves YMM registers
cpu_info |= kCpuHasAVX | ((cpu_info7[1] & 0x00000020) ? kCpuHasAVX2 : 0) |
((cpu_info1[2] & 0x00001000) ? kCpuHasFMA3 : 0) |
((cpu_info1[2] & 0x20000000) ? kCpuHasF16C : 0);
// Detect AVX512bw
if ((GetXCR0() & 0xe0) == 0xe0) {
cpu_info |= (cpu_info7[1] & 0x40000000) ? kCpuHasAVX3 : 0;
}
}
// Environment variable overrides for testing.
if (TestEnv("LIBYUV_DISABLE_X86")) {
cpu_info &= ~kCpuHasX86;
}
if (TestEnv("LIBYUV_DISABLE_SSE2")) {
cpu_info &= ~kCpuHasSSE2;
}
if (TestEnv("LIBYUV_DISABLE_SSSE3")) {
cpu_info &= ~kCpuHasSSSE3;
}
if (TestEnv("LIBYUV_DISABLE_SSE41")) {
cpu_info &= ~kCpuHasSSE41;
}
if (TestEnv("LIBYUV_DISABLE_SSE42")) {
cpu_info &= ~kCpuHasSSE42;
}
if (TestEnv("LIBYUV_DISABLE_AVX")) {
cpu_info &= ~kCpuHasAVX;
}
if (TestEnv("LIBYUV_DISABLE_AVX2")) {
cpu_info &= ~kCpuHasAVX2;
}
if (TestEnv("LIBYUV_DISABLE_ERMS")) {
cpu_info &= ~kCpuHasERMS;
}
if (TestEnv("LIBYUV_DISABLE_FMA3")) {
cpu_info &= ~kCpuHasFMA3;
}
if (TestEnv("LIBYUV_DISABLE_AVX3")) {
cpu_info &= ~kCpuHasAVX3;
}
if (TestEnv("LIBYUV_DISABLE_F16C")) {
cpu_info &= ~kCpuHasF16C;
}
#endif
#if defined(__mips__) && defined(__linux__)
#if defined(__mips_dspr2)
cpu_info |= kCpuHasDSPR2;
#endif
#if defined(__mips_msa)
cpu_info = MipsCpuCaps("/proc/cpuinfo", " msa");
#endif
cpu_info |= kCpuHasMIPS;
if (getenv("LIBYUV_DISABLE_DSPR2")) {
cpu_info &= ~kCpuHasDSPR2;
}
if (getenv("LIBYUV_DISABLE_MSA")) {
cpu_info &= ~kCpuHasMSA;
}
#endif
#if defined(__arm__) || defined(__aarch64__)
// gcc -mfpu=neon defines __ARM_NEON__
// __ARM_NEON__ generates code that requires Neon. NaCL also requires Neon.
// For Linux, /proc/cpuinfo can be tested but without that assume Neon.
#if defined(__ARM_NEON__) || defined(__native_client__) || !defined(__linux__)
cpu_info = kCpuHasNEON;
// For aarch64(arm64), /proc/cpuinfo's feature is not complete, e.g. no neon
// flag in it.
// So for aarch64, neon enabling is hard coded here.
#endif
#if defined(__aarch64__)
cpu_info = kCpuHasNEON;
#else
// Linux arm parse text file for neon detect.
cpu_info = ArmCpuCaps("/proc/cpuinfo");
#endif
cpu_info |= kCpuHasARM;
if (TestEnv("LIBYUV_DISABLE_NEON")) {
cpu_info &= ~kCpuHasNEON;
}
#endif // __arm__
if (TestEnv("LIBYUV_DISABLE_ASM")) {
cpu_info = 0;
}
cpu_info |= kCpuInitialized;
return cpu_info;
}
// Note that use of this function is not thread safe.
LIBYUV_API
int MaskCpuFlags(int enable_flags) {
int cpu_info = GetCpuFlags() & enable_flags;
#ifdef __ATOMIC_RELAXED
__atomic_store_n(&cpu_info_, cpu_info, __ATOMIC_RELAXED);
#else
cpu_info_ = cpu_info;
#endif
return cpu_info;
}
LIBYUV_API
int InitCpuFlags(void) {
return MaskCpuFlags(-1);
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
|
svn2github/pjsip
|
third_party/yuv/source/cpu_id.cc
|
C++
|
gpl-2.0
| 10,430 |
<html lang="en">
<head>
<title>fmax - Untitled</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Untitled">
<meta name="generator" content="makeinfo 4.8">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Math.html#Math" title="Math">
<link rel="prev" href="fma.html#fma" title="fma">
<link rel="next" href="fmin.html#fmin" title="fmin">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">
<meta http-equiv="Content-Style-Type" content="text/css">
<style type="text/css"><!--
pre.display { font-family:inherit }
pre.format { font-family:inherit }
pre.smalldisplay { font-family:inherit; font-size:smaller }
pre.smallformat { font-family:inherit; font-size:smaller }
pre.smallexample { font-size:smaller }
pre.smalllisp { font-size:smaller }
span.sc { font-variant:small-caps }
span.roman { font-family:serif; font-weight:normal; }
span.sansserif { font-family:sans-serif; font-weight:normal; }
--></style>
</head>
<body>
<div class="node">
<p>
<a name="fmax"></a>
Next: <a rel="next" accesskey="n" href="fmin.html#fmin">fmin</a>,
Previous: <a rel="previous" accesskey="p" href="fma.html#fma">fma</a>,
Up: <a rel="up" accesskey="u" href="Math.html#Math">Math</a>
<hr>
</div>
<h3 class="section">1.23 <code>fmax</code>, <code>fmaxf</code>–maximum</h3>
<p><a name="index-fmax-57"></a><a name="index-fmaxf-58"></a><strong>Synopsis</strong>
<pre class="example"> #include <math.h>
double fmax(double <var>x</var>, double <var>y</var>);
float fmaxf(float <var>x</var>, float <var>y</var>);
</pre>
<p><strong>Description</strong><br>
The <code>fmax</code> functions determine the maximum numeric value of their arguments.
NaN arguments are treated as missing data: if one argument is a NaN and the
other numeric, then the <code>fmax</code> functions choose the numeric value.
<pre class="sp">
</pre>
<strong>Returns</strong><br>
The <code>fmax</code> functions return the maximum numeric value of their arguments.
<pre class="sp">
</pre>
<strong>Portability</strong><br>
ANSI C, POSIX.
<pre class="sp">
</pre>
</body></html>
|
jocelynmass/nrf51
|
toolchain/deprecated/arm_cm0_4.9/share/doc/gcc-arm-none-eabi/html/libm/fmax.html
|
HTML
|
gpl-2.0
| 2,234 |
<?php
/**
* @package com_zoo
* @author YOOtheme http://www.yootheme.com
* @copyright Copyright (C) YOOtheme GmbH
* @license http://www.gnu.org/licenses/gpl.html GNU/GPL
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
?>
<div id="tag-area">
<input type="text" value="<?php echo implode(', ', $tags) ?>" placeholder="<?php echo JText::_('Add tag') ?>" />
<p><?php echo JText::_('Choose from the most used tags') ?>:</p>
<?php if (count($most)) : ?>
<div class="tag-cloud">
<?php foreach ($most as $tag) : ?>
<a title="<?php echo $tag->items . ' item' . ($tag->items != 1 ? 's' : '') ?>"><?php echo $tag->name ?></a>
<?php endforeach ?>
</div>
<?php endif ?>
</div>
<script type="text/javascript">
jQuery(function($) {
$('#tag-area').Tag({url: '<?php echo $link ?>', inputName: '<?php echo $this->getControlName('value', true) ?>'});
});
</script>
|
xmarlem/BM_stage
|
media/zoo/elements/itemtag/tmpl/submission.php
|
PHP
|
gpl-2.0
| 955 |
<?php
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
* @package Kaltura
* @subpackage Client
*/
class Kaltura_Client_Enum_AccessControlActionType
{
const BLOCK = "1";
const PREVIEW = "2";
const LIMIT_FLAVORS = "3";
}
|
CoordCulturaDigital-Minc/culturadigital.br
|
wp-content/plugins/all-in-one-video-pack/lib/Kaltura/Client/Enum/AccessControlActionType.php
|
PHP
|
gpl-2.0
| 1,515 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_33) on Thu Jun 20 16:29:00 PDT 2013 -->
<TITLE>
WordStemmer (Stanford JavaNLP API)
</TITLE>
<META NAME="date" CONTENT="2013-06-20">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="WordStemmer (Stanford JavaNLP API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/stanford/nlp/trees/WordNetConnection.html" title="interface in edu.stanford.nlp.trees"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/stanford/nlp/trees/WordStemmer.html" target="_top"><B>FRAMES</B></A>
<A HREF="WordStemmer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
edu.stanford.nlp.trees</FONT>
<BR>
Class WordStemmer</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../resources/inherit.gif" ALT="extended by "><B>edu.stanford.nlp.trees.WordStemmer</B>
</PRE>
<DL>
<DT><B>All Implemented Interfaces:</B> <DD><A HREF="../../../../edu/stanford/nlp/trees/TreeVisitor.html" title="interface in edu.stanford.nlp.trees">TreeVisitor</A></DD>
</DL>
<HR>
<DL>
<DT><PRE>public class <B>WordStemmer</B><DT>extends java.lang.Object<DT>implements <A HREF="../../../../edu/stanford/nlp/trees/TreeVisitor.html" title="interface in edu.stanford.nlp.trees">TreeVisitor</A></DL>
</PRE>
<P>
Stems the Words in a Tree using Morphology.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>Huy Nguyen ([email protected])</DD>
</DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../edu/stanford/nlp/trees/WordStemmer.html#WordStemmer()">WordStemmer</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>static void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/stanford/nlp/trees/WordStemmer.html#main(java.lang.String[])">main</A></B>(java.lang.String[] args)</CODE>
<BR>
Reads, stems, and prints the trees in the file.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../edu/stanford/nlp/trees/WordStemmer.html#visitTree(edu.stanford.nlp.trees.Tree)">visitTree</A></B>(<A HREF="../../../../edu/stanford/nlp/trees/Tree.html" title="class in edu.stanford.nlp.trees">Tree</A> t)</CODE>
<BR>
Does whatever one needs to do to a particular parse tree.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="WordStemmer()"><!-- --></A><H3>
WordStemmer</H3>
<PRE>
public <B>WordStemmer</B>()</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="visitTree(edu.stanford.nlp.trees.Tree)"><!-- --></A><H3>
visitTree</H3>
<PRE>
public void <B>visitTree</B>(<A HREF="../../../../edu/stanford/nlp/trees/Tree.html" title="class in edu.stanford.nlp.trees">Tree</A> t)</PRE>
<DL>
<DD><B>Description copied from interface: <CODE><A HREF="../../../../edu/stanford/nlp/trees/TreeVisitor.html#visitTree(edu.stanford.nlp.trees.Tree)">TreeVisitor</A></CODE></B></DD>
<DD>Does whatever one needs to do to a particular parse tree.
<P>
<DD><DL>
<DT><B>Specified by:</B><DD><CODE><A HREF="../../../../edu/stanford/nlp/trees/TreeVisitor.html#visitTree(edu.stanford.nlp.trees.Tree)">visitTree</A></CODE> in interface <CODE><A HREF="../../../../edu/stanford/nlp/trees/TreeVisitor.html" title="interface in edu.stanford.nlp.trees">TreeVisitor</A></CODE></DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>t</CODE> - A tree. Classes implementing this interface can assume
that the tree passed in is not <code>null</code>.</DL>
</DD>
</DL>
<HR>
<A NAME="main(java.lang.String[])"><!-- --></A><H3>
main</H3>
<PRE>
public static void <B>main</B>(java.lang.String[] args)</PRE>
<DL>
<DD>Reads, stems, and prints the trees in the file.
<P>
<DD><DL>
</DL>
</DD>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>args</CODE> - Usage: WordStemmer file</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../edu/stanford/nlp/trees/WordNetConnection.html" title="interface in edu.stanford.nlp.trees"><B>PREV CLASS</B></A>
NEXT CLASS</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../index.html?edu/stanford/nlp/trees/WordStemmer.html" target="_top"><B>FRAMES</B></A>
<A HREF="WordStemmer.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<FONT SIZE=2><A HREF="http://nlp.stanford.edu">Stanford NLP Group</A></FONT>
</BODY>
</HTML>
|
jaimeguzman/data_mining
|
stanford-postagger/stanford-postagger-3.2.0/stanford-postagger-3.2.0-javadoc/src/edu/stanford/nlp/trees/WordStemmer.html
|
HTML
|
gpl-2.0
| 11,552 |
// license:GPL-2.0+
// copyright-holders:Raphael Nabet, Robbbert
/*
Experimental tm990/189 ("University Module") driver.
The tm990/189 is a simple board built around a tms9980 at 2.0 MHz.
The board features:
* a calculator-like alphanumeric keyboard, a 10-digit 8-segment display,
a sound buzzer and 4 status LEDs
* a 4kb ROM socket (0x3000-0x3fff), and a 2kb ROM socket (0x0800-0x0fff)
* 1kb of RAM expandable to 2kb (0x0000-0x03ff and 0x0400-0x07ff)
* a tms9901 controlling a custom parallel I/O port (available for
expansion)
* an optional on-board serial interface (either TTY or RS232): TI ROMs
support a terminal connected to this port
* an optional tape interface
* an optional bus extension port for adding additional custom devices (TI
sold a video controller expansion built around a tms9918, which was
supported by University Basic)
One tms9901 is set up so that it handles tms9980 interrupts. The other
tms9901, the tms9902, and extension cards can trigger interrupts on the
interrupt-handling tms9901.
TI sold two ROM sets for this machine: a monitor and assembler ("UNIBUG",
packaged as one 4kb EPROM) and a Basic interpreter ("University BASIC",
packaged as a 4kb and a 2kb EPROM). Users could burn and install custom
ROM sets, too.
This board was sold to universities to learn either assembly language or
BASIC programming.
A few hobbyists may have bought one of these, too. This board can actually
be used as a development kit for the tms9980, but it was not supported as
such (there was no EPROM programmer or mass storage system for the
tm990/189, though you could definitively design your own and attach them to
the extension port).
- Raphael Nabet 2003
Bug - The input buffer of character segments isn't fully cleared. If you
press Shift, then Z enough times, garbage appears. This is because
the boot process should have set 18C-1CB to FF, but only sets up to 1B3.
Need a dump of the UNIBUG rom.
Demo programs for the 990189v: You can get impressive colour displays (with
sprites) from the 4 included demos. Press the Enter key after each instruction,
and wait for the READY prompt before proceeding to the next.
NEW
LOADx (where x = 0,1,2,3)
RUN
University BASIC fully supports the tms9918 videocard option. For example, enter
COLOR x (where x = 1 to 15), to get a coloured background.
- Robbbert 2011
******************************************************************************************/
#include "emu.h"
#include "cpu/tms9900/tms9980a.h"
#include "machine/tms9901.h"
#include "machine/tms9902.h"
#include "video/tms9928a.h"
#include "imagedev/cassette.h"
#include "sound/speaker.h"
#include "sound/wave.h"
#include "tm990189.lh"
#include "tm990189v.lh"
#define TMS9901_0_TAG "tms9901_usr"
#define TMS9901_1_TAG "tms9901_sys"
class tm990189_state : public driver_device
{
public:
tm990189_state(const machine_config &mconfig, device_type type, const char *tag)
: driver_device(mconfig, type, tag),
m_tms9980a(*this, "maincpu"),
m_speaker(*this, "speaker"),
m_cass(*this, "cassette"),
m_tms9918(*this, "tms9918" ),
m_maincpu(*this, "maincpu"),
m_cassette(*this, "cassette"),
m_tms9901_usr(*this, TMS9901_0_TAG),
m_tms9901_sys(*this, TMS9901_1_TAG) { }
required_device<tms9980a_device> m_tms9980a;
required_device<speaker_sound_device> m_speaker;
required_device<cassette_image_device> m_cass;
optional_device<tms9918_device> m_tms9918;
DECLARE_READ8_MEMBER(video_vdp_r);
DECLARE_WRITE8_MEMBER(video_vdp_w);
DECLARE_READ8_MEMBER(video_joy_r);
DECLARE_WRITE8_MEMBER(video_joy_w);
int m_load_state;
int m_digitsel;
int m_segment;
emu_timer *m_displayena_timer;
UINT8 m_segment_state[10];
UINT8 m_old_segment_state[10];
UINT8 m_LED_state;
emu_timer *m_joy1x_timer;
emu_timer *m_joy1y_timer;
emu_timer *m_joy2x_timer;
emu_timer *m_joy2y_timer;
device_image_interface *m_rs232_fp;
UINT8 m_rs232_rts;
emu_timer *m_rs232_input_timer;
UINT8 m_bogus_read_save;
DECLARE_WRITE8_MEMBER( external_operation );
DECLARE_INPUT_CHANGED_MEMBER( load_interrupt );
DECLARE_WRITE_LINE_MEMBER(usr9901_led0_w);
DECLARE_WRITE_LINE_MEMBER(usr9901_led1_w);
DECLARE_WRITE_LINE_MEMBER(usr9901_led2_w);
DECLARE_WRITE_LINE_MEMBER(usr9901_led3_w);
DECLARE_WRITE8_MEMBER(usr9901_interrupt_callback);
DECLARE_WRITE8_MEMBER(sys9901_interrupt_callback);
DECLARE_READ8_MEMBER(sys9901_r);
DECLARE_WRITE_LINE_MEMBER(sys9901_digitsel0_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_digitsel1_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_digitsel2_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_digitsel3_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment0_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment1_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment2_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment3_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment4_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment5_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment6_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_segment7_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_dsplytrgr_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_shiftlight_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_spkrdrive_w);
DECLARE_WRITE_LINE_MEMBER(sys9901_tapewdata_w);
DECLARE_WRITE8_MEMBER( xmit_callback );
DECLARE_MACHINE_START(tm990_189);
DECLARE_MACHINE_RESET(tm990_189);
DECLARE_MACHINE_START(tm990_189_v);
DECLARE_MACHINE_RESET(tm990_189_v);
TIMER_DEVICE_CALLBACK_MEMBER(display_callback);
TIMER_CALLBACK_MEMBER(clear_load);
void hold_load();
private:
void draw_digit(void);
void led_set(int number, bool state);
void segment_set(int offset, bool state);
void digitsel(int offset, bool state);
required_device<cpu_device> m_maincpu;
required_device<cassette_image_device> m_cassette;
required_device<tms9901_device> m_tms9901_usr;
required_device<tms9901_device> m_tms9901_sys;
};
#define displayena_duration attotime::from_usec(4500) /* Can anyone confirm this? 74LS123 connected to C=0.1uF and R=100kOhm */
MACHINE_RESET_MEMBER(tm990189_state,tm990_189)
{
m_tms9980a->set_ready(ASSERT_LINE);
m_tms9980a->set_hold(CLEAR_LINE);
hold_load();
}
MACHINE_START_MEMBER(tm990189_state,tm990_189)
{
m_displayena_timer = machine().scheduler().timer_alloc(FUNC_NULL);
}
MACHINE_START_MEMBER(tm990189_state,tm990_189_v)
{
m_displayena_timer = machine().scheduler().timer_alloc(FUNC_NULL);
m_joy1x_timer = machine().scheduler().timer_alloc(FUNC_NULL);
m_joy1y_timer = machine().scheduler().timer_alloc(FUNC_NULL);
m_joy2x_timer = machine().scheduler().timer_alloc(FUNC_NULL);
m_joy2y_timer = machine().scheduler().timer_alloc(FUNC_NULL);
}
MACHINE_RESET_MEMBER(tm990189_state,tm990_189_v)
{
m_tms9980a->set_ready(ASSERT_LINE);
m_tms9980a->set_hold(CLEAR_LINE);
hold_load();
}
/*
hold and debounce load line (emulation is inaccurate)
*/
TIMER_CALLBACK_MEMBER(tm990189_state::clear_load)
{
m_load_state = FALSE;
m_tms9980a->set_input_line(INT_9980A_LOAD, CLEAR_LINE);
}
void tm990189_state::hold_load()
{
m_load_state = TRUE;
m_tms9980a->set_input_line(INT_9980A_LOAD, ASSERT_LINE);
machine().scheduler().timer_set(attotime::from_msec(100), timer_expired_delegate(FUNC(tm990189_state::clear_load),this));
}
/*
LOAD interrupt switch
*/
INPUT_CHANGED_MEMBER( tm990189_state::load_interrupt )
{
// When depressed, fire LOAD (neg logic)
if (newval==CLEAR_LINE) hold_load();
}
/*
tm990_189 video emulation.
Has an integrated 10 digit 8-segment display.
Supports EIA and TTY terminals, and an optional 9918 controller.
*/
void tm990189_state::draw_digit()
{
m_segment_state[m_digitsel] |= ~m_segment;
}
TIMER_DEVICE_CALLBACK_MEMBER(tm990189_state::display_callback)
{
UINT8 i;
char ledname[8];
// since the segment data is cleared after being used, the old_segment is there
// in case the segment data hasn't been refreshed yet.
for (i = 0; i < 10; i++)
{
m_old_segment_state[i] |= m_segment_state[i];
sprintf(ledname,"digit%d",i);
output().set_digit_value(i, m_old_segment_state[i]);
m_old_segment_state[i] = m_segment_state[i];
m_segment_state[i] = 0;
}
for (i = 0; i < 7; i++)
{
sprintf(ledname,"led%d",i);
output().set_value(ledname, !BIT(m_LED_state, i));
}
}
/*
tms9901 code
*/
WRITE8_MEMBER( tm990189_state::usr9901_interrupt_callback )
{
// Triggered by internal timer (set by ROM to 1.6 ms cycle) on level 3
// or by keyboard interrupt (level 6)
if (!m_load_state)
{
m_tms9980a->set_input_line(offset & 7, ASSERT_LINE);
}
}
void tm990189_state::led_set(int offset, bool state)
{
if (state)
m_LED_state |= (1 << offset);
else
m_LED_state &= ~(1 << offset);
}
WRITE_LINE_MEMBER( tm990189_state::usr9901_led0_w )
{
led_set(0, state);
}
WRITE_LINE_MEMBER( tm990189_state::usr9901_led1_w )
{
led_set(1, state);
}
WRITE_LINE_MEMBER( tm990189_state::usr9901_led2_w )
{
led_set(2, state);
}
WRITE_LINE_MEMBER( tm990189_state::usr9901_led3_w )
{
led_set(3, state);
}
WRITE8_MEMBER( tm990189_state::sys9901_interrupt_callback )
{
// machine().device<tms9901_device>("tms9901_0")->set_single_int(5, (data!=0)? ASSERT_LINE:CLEAR_LINE);
// TODO: Check this
m_tms9901_usr->set_single_int(5, (data!=0)? ASSERT_LINE:CLEAR_LINE);
}
READ8_MEMBER( tm990189_state::sys9901_r )
{
UINT8 data = 0;
if (offset == TMS9901_CB_INT7)
{
static const char *const keynames[] = { "LINE0", "LINE1", "LINE2", "LINE3", "LINE4", "LINE5", "LINE6", "LINE7", "LINE8" };
/* keyboard read */
if (m_digitsel < 9)
data |= ioport(keynames[m_digitsel])->read() << 1;
/* tape input */
if (m_cass->input() > 0.0)
data |= 0x40;
}
return data;
}
void tm990189_state::digitsel(int offset, bool state)
{
if (state)
m_digitsel |= 1 << offset;
else
m_digitsel &= ~ (1 << offset);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_digitsel0_w )
{
digitsel(0, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_digitsel1_w )
{
digitsel(1, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_digitsel2_w )
{
digitsel(2, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_digitsel3_w )
{
digitsel(3, state);
}
void tm990189_state::segment_set(int offset, bool state)
{
if (state)
m_segment |= 1 << offset;
else
{
m_segment &= ~ (1 << offset);
if ((m_displayena_timer->remaining() > attotime::zero) && (m_digitsel < 10))
draw_digit();
}
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment0_w )
{
segment_set(0, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment1_w )
{
segment_set(1, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment2_w )
{
segment_set(2, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment3_w )
{
segment_set(3, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment4_w )
{
segment_set(4, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment5_w )
{
segment_set(5, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment6_w )
{
segment_set(6, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_segment7_w )
{
segment_set(7, state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_dsplytrgr_w )
{
if ((!state) && (m_digitsel < 10))
{
m_displayena_timer->reset(displayena_duration);
draw_digit();
}
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_shiftlight_w )
{
if (state)
m_LED_state |= 0x10;
else
m_LED_state &= ~0x10;
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_spkrdrive_w )
{
m_speaker->level_w(state);
}
WRITE_LINE_MEMBER( tm990189_state::sys9901_tapewdata_w )
{
m_cassette->output(state ? +1.0 : -1.0);
}
class tm990_189_rs232_image_device : public device_t,
public device_image_interface
{
public:
// construction/destruction
tm990_189_rs232_image_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock);
// image-level overrides
virtual iodevice_t image_type() const override { return IO_SERIAL; }
virtual bool is_readable() const override { return 1; }
virtual bool is_writeable() const override { return 1; }
virtual bool is_creatable() const override { return 1; }
virtual bool must_be_loaded() const override { return 0; }
virtual bool is_reset_on_load() const override { return 0; }
virtual const char *image_interface() const override { return nullptr; }
virtual const char *file_extensions() const override { return ""; }
virtual const option_guide *create_option_guide() const override { return nullptr; }
virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr) override;
virtual bool call_load() override;
virtual void call_unload() override;
protected:
// device-level overrides
virtual void device_config_complete() override;
virtual void device_start() override;
};
const device_type TM990_189_RS232 = &device_creator<tm990_189_rs232_image_device>;
tm990_189_rs232_image_device::tm990_189_rs232_image_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock)
: device_t(mconfig, TM990_189_RS232, "TM990/189 RS232 port", tag, owner, clock, "tm990_189_rs232_image", __FILE__),
device_image_interface(mconfig, *this)
{
}
void tm990_189_rs232_image_device::device_config_complete()
{
update_names();
}
void tm990_189_rs232_image_device::device_start()
{
}
void tm990_189_rs232_image_device::device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr)
{
//tm990189_state *state = machine.driver_data<tm990189_state>();
UINT8 buf;
if (/*state->m_rs232_rts &&*/ /*(mame_ftell(state->m_rs232_fp) < mame_fsize(state->m_rs232_fp))*/1)
{
tms9902_device* tms9902 = static_cast<tms9902_device*>(machine().device("tms9902"));
if (fread(&buf, 1) == 1)
tms9902->rcv_data(buf);
}
}
bool tm990_189_rs232_image_device::call_load()
{
tm990189_state *state = machine().driver_data<tm990189_state>();
tms9902_device* tms9902 = static_cast<tms9902_device*>(machine().device("tms9902"));
tms9902->rcv_dsr(ASSERT_LINE);
state->m_rs232_input_timer = timer_alloc();
state->m_rs232_input_timer->adjust(attotime::zero, 0, attotime::from_msec(10));
return IMAGE_INIT_PASS;
}
void tm990_189_rs232_image_device::call_unload()
{
tm990189_state *state = machine().driver_data<tm990189_state>();
tms9902_device* tms9902 = static_cast<tms9902_device*>(machine().device("tms9902"));
tms9902->rcv_dsr(CLEAR_LINE);
state->m_rs232_input_timer->reset(); /* FIXME - timers should only be allocated once */
}
#define MCFG_TM990_189_RS232_ADD(_tag) \
MCFG_DEVICE_ADD(_tag, TM990_189_RS232, 0)
/* static TMS9902_RTS_CALLBACK( rts_callback )
{
tm990189 *state = device->machine().driver_data<tm990189>();
state->m_rs232_rts = RTS;
tms9902->set_cts(RTS);
} */
WRITE8_MEMBER( tm990189_state::xmit_callback )
{
UINT8 buf = data;
if (m_rs232_fp) m_rs232_fp->fwrite(&buf, 1);
}
/*
External instruction decoding
*/
WRITE8_MEMBER( tm990189_state::external_operation )
{
switch (offset)
{
case 2: // IDLE
if (data)
m_LED_state |= 0x40;
else
m_LED_state &= ~0x40;
break;
case 3: // RSET
// Not used on the default board
break;
case 5: // CKON: set DECKCONTROL
m_LED_state |= 0x20;
m_cass->change_state(CASSETTE_MOTOR_ENABLED,CASSETTE_MASK_MOTOR);
break;
case 6: // CKOF: clear DECKCONTROL
m_LED_state &= ~0x20;
m_cass->change_state(CASSETTE_MOTOR_DISABLED,CASSETTE_MASK_MOTOR);
break;
case 7: // LREX: trigger LOAD
hold_load();
break;
default: // undefined
break;
}
}
/*
Video Board handling
*/
READ8_MEMBER( tm990189_state::video_vdp_r )
{
int reply = 0;
/* When the tms9980 reads @>2000 or @>2001, it actually does a word access:
it reads @>2000 first, then @>2001. According to schematics, both access
are decoded to the VDP: read accesses are therefore bogus, all the more so
since the two reads are too close (1us) for the VDP to be able to reload
the read buffer: the read address pointer is probably incremented by 2, but
only the first byte is valid. There is a work around for this problem: all
you need is reloading the address pointer before each read. However,
software always uses the second byte, which is very weird, particularly
for the status port. Presumably, since the read buffer has not been
reloaded, the second byte read from the memory read port is equal to the
first; however, this explanation is not very convincing for the status
port. Still, I do not have any better explanation, so I will stick with
it. */
if (offset & 2)
reply = m_tms9918->register_read(space, 0);
else
reply = m_tms9918->vram_read(space, 0);
if (!(offset & 1))
m_bogus_read_save = reply;
else
reply = m_bogus_read_save;
return reply;
}
WRITE8_MEMBER( tm990189_state::video_vdp_w )
{
if (offset & 1)
{
if (offset & 2)
m_tms9918->register_write(space, 0, data);
else
m_tms9918->vram_write(space, 0, data);
}
}
READ8_MEMBER( tm990189_state::video_joy_r )
{
UINT8 data = ioport("BUTTONS")->read();
if (m_joy1x_timer->remaining() < attotime::zero)
data |= 0x01;
if (m_joy1y_timer->remaining() < attotime::zero)
data |= 0x02;
if (m_joy2x_timer->remaining() < attotime::zero)
data |= 0x08;
if (m_joy2y_timer->remaining() < attotime::zero)
data |= 0x10;
return data;
}
WRITE8_MEMBER( tm990189_state::video_joy_w )
{
m_joy1x_timer->reset(attotime::from_usec(ioport("JOY1_X")->read()*28+28));
m_joy1y_timer->reset(attotime::from_usec(ioport("JOY1_Y")->read()*28+28));
m_joy2x_timer->reset(attotime::from_usec(ioport("JOY2_X")->read()*28+28));
m_joy2y_timer->reset(attotime::from_usec(ioport("JOY2_Y")->read()*28+28));
}
/*
// user tms9901 setup
static const tms9901_interface usr9901reset_param =
{
TMS9901_INT1 | TMS9901_INT2 | TMS9901_INT3 | TMS9901_INT4 | TMS9901_INT5 | TMS9901_INT6, // only input pins whose state is always known
// Read handler. Covers all input lines (see tms9901.h)
DEVCB_NOOP,
// write handlers
{
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, usr9901_led0_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, usr9901_led1_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, usr9901_led2_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, usr9901_led3_w),
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP,
DEVCB_NOOP
},
// interrupt handler
DEVCB_DRIVER_MEMBER(tm990189_state, usr9901_interrupt_callback)
};
*/
/*
// system tms9901 setup
static const tms9901_interface sys9901reset_param =
{
0, // only input pins whose state is always known
// Read handler. Covers all input lines (see tms9901.h)
DEVCB_DRIVER_MEMBER(tm990189_state, sys9901_r),
// write handlers
{
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_digitsel0_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_digitsel1_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_digitsel2_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_digitsel3_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment0_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment1_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment2_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment3_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment4_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment5_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment6_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_segment7_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_dsplytrgr_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_shiftlight_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_spkrdrive_w),
DEVCB_DRIVER_LINE_MEMBER(tm990189_state, sys9901_tapewdata_w)
},
// interrupt handler
DEVCB_DRIVER_MEMBER(tm990189_state, sys9901_interrupt_callback)
};
*/
/*
Memory map:
0x0000-0x03ff: 1kb RAM
0x0400-0x07ff: 1kb onboard expansion RAM
0x0800-0x0bff or 0x0800-0x0fff: 1kb or 2kb onboard expansion ROM
0x1000-0x2fff: reserved for offboard expansion
Only known card: Color Video Board
0x1000-0x17ff (R): Video board ROM 1
0x1800-0x1fff (R): Video board ROM 2
0x2000-0x27ff (R): tms9918 read ports (bogus)
(address & 2) == 0: data port (bogus)
(address & 2) == 1: status register (bogus)
0x2800-0x2fff (R): joystick read port
d2: joy 2 switch
d3: joy 2 Y (length of pulse after retrigger is proportional to axis position)
d4: joy 2 X (length of pulse after retrigger is proportional to axis position)
d2: joy 1 switch
d3: joy 1 Y (length of pulse after retrigger is proportional to axis position)
d4: joy 1 X (length of pulse after retrigger is proportional to axis position)
0x1801-0x1fff ((address & 1) == 1) (W): joystick write port (retrigger)
0x2801-0x2fff ((address & 1) == 1) (W): tms9918 write ports
(address & 2) == 0: data port
(address & 2) == 1: control register
0x3000-0x3fff: 4kb onboard ROM
*/
static ADDRESS_MAP_START( tm990_189_memmap, AS_PROGRAM, 8, tm990189_state )
AM_RANGE(0x0000, 0x07ff) AM_RAM /* RAM */
AM_RANGE(0x0800, 0x0fff) AM_ROM /* extra ROM - application programs with unibug, remaining 2kb of program for university basic */
AM_RANGE(0x1000, 0x2fff) AM_NOP /* reserved for expansion (RAM and/or tms9918 video controller) */
AM_RANGE(0x3000, 0x3fff) AM_ROM /* main ROM - unibug or university basic */
ADDRESS_MAP_END
static ADDRESS_MAP_START( tm990_189_v_memmap, AS_PROGRAM, 8, tm990189_state )
AM_RANGE(0x0000, 0x07ff) AM_RAM /* RAM */
AM_RANGE(0x0800, 0x0fff) AM_ROM /* extra ROM - application programs with unibug, remaining 2kb of program for university basic */
AM_RANGE(0x1000, 0x17ff) AM_ROM AM_WRITENOP /* video board ROM 1 */
AM_RANGE(0x1800, 0x1fff) AM_ROM AM_WRITE(video_joy_w) /* video board ROM 2 and joystick write port*/
AM_RANGE(0x2000, 0x27ff) AM_READ(video_vdp_r) AM_WRITENOP /* video board tms9918 read ports (bogus) */
AM_RANGE(0x2800, 0x2fff) AM_READWRITE(video_joy_r, video_vdp_w) /* video board joystick read port and tms9918 write ports */
AM_RANGE(0x3000, 0x3fff) AM_ROM /* main ROM - unibug or university basic */
ADDRESS_MAP_END
/*
CRU map
The board features one tms9901 for keyboard and sound I/O, another tms9901
to drive the parallel port and a few LEDs and handle tms9980 interrupts,
and one optional tms9902 for serial I/O.
* bits >000->1ff (R12=>000->3fe): first TMS9901: parallel port, a few LEDs,
interrupts
- CRU bits 1-5: UINT1* through UINT5* (jumper connectable to parallel
port or COMINT from tms9902)
- CRU bit 6: KBINT (interrupt request from second tms9901)
- CRU bits 7-15: mirrors P15-P7
- CRU bits 16-31: P0-P15 (parallel port)
(bits 16, 17, 18 and 19 control LEDs numbered 1, 2, 3 and 4, too)
* bits >200->3ff (R12=>400->7fe): second TMS9901: display, keyboard and
sound
- CRU bits 1-5: KB1*-KB5* (inputs from current keyboard row)
- CRU bit 6: RDATA (tape in)
- CRU bits 7-15: mirrors P15-P7
- CRU bits 16-19: DIGITSELA-DIGITSELD (select current display digit and
keyboard row)
- CRU bits 20-27: SEGMENTA*-SEGMENTG* and SEGMENTP* (drives digit
segments)
- CRU bit 28: DSPLYTRGR*: used as an alive signal for a watchdog circuit
which turns off the display when the program hangs and
LED segments would continuously emit light
- bit 29: SHIFTLIGHT (controls shift light)
- bit 30: SPKRDRIVE (controls buzzer)
- bit 31: WDATA (tape out)
* bits >400->5ff (R12=>800->bfe): optional TMS9902
* bits >600->7ff (R12=>c00->ffe): reserved for expansion
* write 0 to bits >1000->17ff: IDLE: flash IDLE LED
* write 0 to bits >1800->1fff: RSET: not connected, but it is decoded and
hackers can connect any device they like to this pin
* write 1 to bits >0800->0fff: CKON: light FWD LED and activates
DECKCONTROL* signal (part of tape interface)
* write 1 to bits >1000->17ff: CKOF: light off FWD LED and deactivates
DECKCONTROL* signal (part of tape interface)
* write 1 to bits >1800->1fff: LREX: trigger load interrupt
Keyboard map: see input ports
Display segment designation:
a
___
| |
f| |b
|___|
| g |
e| |c
|___| .p
d
*/
static ADDRESS_MAP_START( tm990_189_cru_map, AS_IO, 8, tm990189_state )
AM_RANGE(0x0000, 0x003f) AM_DEVREAD(TMS9901_0_TAG, tms9901_device, read) /* user I/O tms9901 */
AM_RANGE(0x0040, 0x006f) AM_DEVREAD(TMS9901_1_TAG, tms9901_device, read) /* system I/O tms9901 */
AM_RANGE(0x0080, 0x00cf) AM_DEVREAD("tms9902", tms9902_device, cruread) /* optional tms9902 */
AM_RANGE(0x0000, 0x01ff) AM_DEVWRITE(TMS9901_0_TAG, tms9901_device, write) /* user I/O tms9901 */
AM_RANGE(0x0200, 0x03ff) AM_DEVWRITE(TMS9901_1_TAG, tms9901_device, write) /* system I/O tms9901 */
AM_RANGE(0x0400, 0x05ff) AM_DEVWRITE("tms9902", tms9902_device, cruwrite) /* optional tms9902 */
ADDRESS_MAP_END
static MACHINE_CONFIG_START( tm990_189, tm990189_state )
/* basic machine hardware */
MCFG_TMS99xx_ADD("maincpu", TMS9980A, 2000000, tm990_189_memmap, tm990_189_cru_map)
MCFG_TMS99xx_EXTOP_HANDLER( WRITE8(tm990189_state, external_operation) )
MCFG_MACHINE_START_OVERRIDE(tm990189_state, tm990_189 )
MCFG_MACHINE_RESET_OVERRIDE(tm990189_state, tm990_189 )
/* Video hardware */
MCFG_DEFAULT_LAYOUT(layout_tm990189)
/* sound hardware */
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0)
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.50)
/* Devices */
MCFG_CASSETTE_ADD( "cassette" )
MCFG_DEVICE_ADD(TMS9901_0_TAG, TMS9901, 2000000)
MCFG_TMS9901_P0_HANDLER( WRITELINE( tm990189_state, usr9901_led0_w) )
MCFG_TMS9901_P1_HANDLER( WRITELINE( tm990189_state, usr9901_led1_w) )
MCFG_TMS9901_P2_HANDLER( WRITELINE( tm990189_state, usr9901_led2_w) )
MCFG_TMS9901_P3_HANDLER( WRITELINE( tm990189_state, usr9901_led3_w) )
MCFG_TMS9901_INTLEVEL_HANDLER( WRITE8( tm990189_state, usr9901_interrupt_callback) )
MCFG_DEVICE_ADD(TMS9901_1_TAG, TMS9901, 2000000)
MCFG_TMS9901_READBLOCK_HANDLER( READ8(tm990189_state, sys9901_r) )
MCFG_TMS9901_P0_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel0_w) )
MCFG_TMS9901_P1_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel1_w) )
MCFG_TMS9901_P2_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel2_w) )
MCFG_TMS9901_P3_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel3_w) )
MCFG_TMS9901_P4_HANDLER( WRITELINE( tm990189_state, sys9901_segment0_w) )
MCFG_TMS9901_P5_HANDLER( WRITELINE( tm990189_state, sys9901_segment1_w) )
MCFG_TMS9901_P6_HANDLER( WRITELINE( tm990189_state, sys9901_segment2_w) )
MCFG_TMS9901_P7_HANDLER( WRITELINE( tm990189_state, sys9901_segment3_w) )
MCFG_TMS9901_P8_HANDLER( WRITELINE( tm990189_state, sys9901_segment4_w) )
MCFG_TMS9901_P9_HANDLER( WRITELINE( tm990189_state, sys9901_segment5_w) )
MCFG_TMS9901_P10_HANDLER( WRITELINE( tm990189_state, sys9901_segment6_w) )
MCFG_TMS9901_P11_HANDLER( WRITELINE( tm990189_state, sys9901_segment7_w) )
MCFG_TMS9901_P12_HANDLER( WRITELINE( tm990189_state, sys9901_dsplytrgr_w) )
MCFG_TMS9901_P13_HANDLER( WRITELINE( tm990189_state, sys9901_shiftlight_w) )
MCFG_TMS9901_P14_HANDLER( WRITELINE( tm990189_state, sys9901_spkrdrive_w) )
MCFG_TMS9901_P15_HANDLER( WRITELINE( tm990189_state, sys9901_tapewdata_w) )
MCFG_TMS9901_INTLEVEL_HANDLER( WRITE8( tm990189_state, sys9901_interrupt_callback) )
MCFG_DEVICE_ADD("tms9902", TMS9902, 2000000) // MZ: needs to be fixed once the RS232 support is complete
MCFG_TMS9902_XMIT_CB(WRITE8(tm990189_state, xmit_callback)) /* called when a character is transmitted */
MCFG_TM990_189_RS232_ADD("rs232")
MCFG_TIMER_DRIVER_ADD_PERIODIC("display_timer", tm990189_state, display_callback, attotime::from_hz(30))
// Need to delay the timer, or it will spoil the initial LOAD
// TODO: Fix this, probably inside CPU
MCFG_TIMER_START_DELAY(attotime::from_msec(150))
MACHINE_CONFIG_END
static MACHINE_CONFIG_START( tm990_189_v, tm990189_state )
/* basic machine hardware */
MCFG_TMS99xx_ADD("maincpu", TMS9980A, 2000000, tm990_189_v_memmap, tm990_189_cru_map)
MCFG_TMS99xx_EXTOP_HANDLER( WRITE8(tm990189_state, external_operation) )
MCFG_MACHINE_START_OVERRIDE(tm990189_state, tm990_189_v )
MCFG_MACHINE_RESET_OVERRIDE(tm990189_state, tm990_189_v )
/* video hardware */
MCFG_DEVICE_ADD( "tms9918", TMS9918, XTAL_10_738635MHz / 2 )
MCFG_TMS9928A_VRAM_SIZE(0x4000)
MCFG_TMS9928A_SCREEN_ADD_NTSC( "screen" )
MCFG_SCREEN_UPDATE_DEVICE( "tms9918", tms9918_device, screen_update )
MCFG_DEFAULT_LAYOUT(layout_tm990189v)
/* sound hardware */
MCFG_SPEAKER_STANDARD_MONO("mono")
MCFG_SOUND_WAVE_ADD(WAVE_TAG, "cassette")
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.25)
MCFG_SOUND_ADD("speaker", SPEAKER_SOUND, 0) /* one two-level buzzer */
MCFG_SOUND_ROUTE(ALL_OUTPUTS, "mono", 0.50)
/* Devices */
MCFG_CASSETTE_ADD( "cassette" )
MCFG_DEVICE_ADD(TMS9901_0_TAG, TMS9901, 2000000)
MCFG_TMS9901_P0_HANDLER( WRITELINE( tm990189_state, usr9901_led0_w) )
MCFG_TMS9901_P1_HANDLER( WRITELINE( tm990189_state, usr9901_led1_w) )
MCFG_TMS9901_P2_HANDLER( WRITELINE( tm990189_state, usr9901_led2_w) )
MCFG_TMS9901_P3_HANDLER( WRITELINE( tm990189_state, usr9901_led3_w) )
MCFG_TMS9901_INTLEVEL_HANDLER( WRITE8( tm990189_state, usr9901_interrupt_callback) )
MCFG_DEVICE_ADD(TMS9901_1_TAG, TMS9901, 2000000)
MCFG_TMS9901_READBLOCK_HANDLER( READ8(tm990189_state, sys9901_r) )
MCFG_TMS9901_P0_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel0_w) )
MCFG_TMS9901_P1_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel1_w) )
MCFG_TMS9901_P2_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel2_w) )
MCFG_TMS9901_P3_HANDLER( WRITELINE( tm990189_state, sys9901_digitsel3_w) )
MCFG_TMS9901_P4_HANDLER( WRITELINE( tm990189_state, sys9901_segment0_w) )
MCFG_TMS9901_P5_HANDLER( WRITELINE( tm990189_state, sys9901_segment1_w) )
MCFG_TMS9901_P6_HANDLER( WRITELINE( tm990189_state, sys9901_segment2_w) )
MCFG_TMS9901_P7_HANDLER( WRITELINE( tm990189_state, sys9901_segment3_w) )
MCFG_TMS9901_P8_HANDLER( WRITELINE( tm990189_state, sys9901_segment4_w) )
MCFG_TMS9901_P9_HANDLER( WRITELINE( tm990189_state, sys9901_segment5_w) )
MCFG_TMS9901_P10_HANDLER( WRITELINE( tm990189_state, sys9901_segment6_w) )
MCFG_TMS9901_P11_HANDLER( WRITELINE( tm990189_state, sys9901_segment7_w) )
MCFG_TMS9901_P12_HANDLER( WRITELINE( tm990189_state, sys9901_dsplytrgr_w) )
MCFG_TMS9901_P13_HANDLER( WRITELINE( tm990189_state, sys9901_shiftlight_w) )
MCFG_TMS9901_P14_HANDLER( WRITELINE( tm990189_state, sys9901_spkrdrive_w) )
MCFG_TMS9901_P15_HANDLER( WRITELINE( tm990189_state, sys9901_tapewdata_w) )
MCFG_TMS9901_INTLEVEL_HANDLER( WRITE8( tm990189_state, sys9901_interrupt_callback) )
MCFG_DEVICE_ADD("tms9902", TMS9902, 2000000) // MZ: needs to be fixed once the RS232 support is complete
MCFG_TMS9902_XMIT_CB(WRITE8(tm990189_state, xmit_callback)) /* called when a character is transmitted */
MCFG_TM990_189_RS232_ADD("rs232")
MCFG_TIMER_DRIVER_ADD_PERIODIC("display_timer", tm990189_state, display_callback, attotime::from_hz(30))
MCFG_TIMER_START_DELAY(attotime::from_msec(150))
MACHINE_CONFIG_END
/*
ROM loading
*/
ROM_START(990189)
/*CPU memory space*/
ROM_REGION(0x4000, "maincpu", 0 )
/* extra ROM */
ROM_LOAD("990-469.u32", 0x0800, 0x0800, CRC(08df7edb) SHA1(fa9751fd2e3e5d7ae03819fc9c7099e2ddd9fb53))
/* boot ROM */
ROM_LOAD("990-469.u33", 0x3000, 0x1000, CRC(e9b4ac1b) SHA1(96e88f4cb7a374033cdf3af0dc26ca5b1d55b9f9))
ROM_END
ROM_START(990189v)
/*CPU memory space*/
ROM_REGION(0x4000, "maincpu", 0 )
/* extra ROM */
ROM_LOAD("990-469.u32", 0x0800, 0x0800, CRC(08df7edb) SHA1(fa9751fd2e3e5d7ae03819fc9c7099e2ddd9fb53))
/* extension ROM */
ROM_LOAD_OPTIONAL("demo1000.u13", 0x1000, 0x0800, CRC(c0e16685) SHA1(d0d314134c42fa4682aafbace67f539f67f6ba65))
/* extension ROM */
ROM_LOAD_OPTIONAL("demo1800.u11", 0x1800, 0x0800, CRC(8737dc4b) SHA1(b87da7aa4d3f909e70f885c4b36999cc1abf5764))
/* boot ROM */
ROM_LOAD("990-469.u33", 0x3000, 0x1000, CRC(e9b4ac1b) SHA1(96e88f4cb7a374033cdf3af0dc26ca5b1d55b9f9))
/*ROM_LOAD("unibasic.bin", 0x3000, 0x1000, CRC(de4d9744))*/ /* older, partial dump of university BASIC */
ROM_END
#define JOYSTICK_DELTA 10
#define JOYSTICK_SENSITIVITY 100
static INPUT_PORTS_START(tm990_189)
PORT_START( "LOADINT ")
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Load interrupt") PORT_CODE(KEYCODE_PRTSCR) PORT_CHANGED_MEMBER(DEVICE_SELF, tm990189_state, load_interrupt, 1)
/* 45-key calculator-like alphanumeric keyboard... */
PORT_START("LINE0") /* row 0 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Shift") PORT_CODE(KEYCODE_LSHIFT) PORT_CODE(KEYCODE_RSHIFT) PORT_CHAR(UCHAR_SHIFT_1)
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Sp *") PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_CHAR('*')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Ret '") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13) PORT_CHAR('\'')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("$ =") PORT_CODE(KEYCODE_STOP) PORT_CHAR('$') PORT_CHAR('=')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME(", <") PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<')
PORT_START("LINE1") /* row 1 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("+ (") PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR('+') PORT_CHAR('(')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("- )") PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR('-') PORT_CHAR(')')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("@ /") PORT_CODE(KEYCODE_MINUS) PORT_CHAR('@') PORT_CHAR('/')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("> %") PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('>') PORT_CHAR('%')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("0 ^") PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR('^')
PORT_START("LINE2") /* row 2 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("1 .") PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('.')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("2 ;") PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR(';')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("3 :") PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR(':')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("4 ?") PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('?')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("5 !") PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('!')
PORT_START("LINE3") /* row 3 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("6 _") PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR('_')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("7 \"") PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('\"')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("8 #") PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('#')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("9 (ESC)") PORT_CODE(KEYCODE_9) PORT_CHAR('9')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("A (SOH)") PORT_CODE(KEYCODE_A) PORT_CHAR('A')
PORT_START("LINE4") /* row 4 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("B (STH)") PORT_CODE(KEYCODE_B) PORT_CHAR('B')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("C (ETX)") PORT_CODE(KEYCODE_C) PORT_CHAR('C')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("D (EOT)") PORT_CODE(KEYCODE_D) PORT_CHAR('D')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("E (ENQ)") PORT_CODE(KEYCODE_E) PORT_CHAR('E')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("F (ACK)") PORT_CODE(KEYCODE_F) PORT_CHAR('F')
PORT_START("LINE5") /* row 5 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("G (BEL)") PORT_CODE(KEYCODE_G) PORT_CHAR('G')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("H (BS)") PORT_CODE(KEYCODE_H) PORT_CHAR('H')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("I (HT)") PORT_CODE(KEYCODE_I) PORT_CHAR('I')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("J (LF)") PORT_CODE(KEYCODE_J) PORT_CHAR('J')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("K (VT)") PORT_CODE(KEYCODE_K) PORT_CHAR('K')
PORT_START("LINE6") /* row 6 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("L (FF)") PORT_CODE(KEYCODE_L) PORT_CHAR('L')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("M (DEL)") PORT_CODE(KEYCODE_M) PORT_CHAR('M')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("N (SO)") PORT_CODE(KEYCODE_N) PORT_CHAR('N')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("O (SI)") PORT_CODE(KEYCODE_O) PORT_CHAR('O')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("P (DLE)") PORT_CODE(KEYCODE_P) PORT_CHAR('P')
PORT_START("LINE7") /* row 7 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Q (DC1)") PORT_CODE(KEYCODE_Q) PORT_CHAR('Q')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("R (DC2)") PORT_CODE(KEYCODE_R) PORT_CHAR('R')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("S (DC3)") PORT_CODE(KEYCODE_S) PORT_CHAR('S')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("T (DC4)") PORT_CODE(KEYCODE_T) PORT_CHAR('T')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("U (NAK)") PORT_CODE(KEYCODE_U) PORT_CHAR('U')
PORT_START("LINE8") /* row 8 */
PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("V <-D") PORT_CODE(KEYCODE_V) PORT_CHAR('V')
PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("W (ETB)") PORT_CODE(KEYCODE_W) PORT_CHAR('W')
PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("X (CAN)") PORT_CODE(KEYCODE_X) PORT_CHAR('X')
PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Y (EM)") PORT_CODE(KEYCODE_Y) PORT_CHAR('Y')
PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Z ->D") PORT_CODE(KEYCODE_Z) PORT_CHAR('Z')
/* analog joysticks (video board only) */
PORT_START("BUTTONS") /* joystick 1 & 2 buttons */
PORT_BIT(0x0004, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_PLAYER(1)
PORT_BIT(0x0020, IP_ACTIVE_HIGH, IPT_BUTTON1) PORT_PLAYER(2)
PORT_START("JOY1_X") /* joystick 1, X axis */
PORT_BIT( 0x3ff, 0x1aa, IPT_AD_STICK_X) PORT_SENSITIVITY(JOYSTICK_SENSITIVITY) PORT_KEYDELTA(JOYSTICK_DELTA) PORT_MINMAX(0xd2,0x282 ) PORT_PLAYER(1)
PORT_START("JOY1_Y") /* joystick 1, Y axis */
PORT_BIT( 0x3ff, 0x1aa, IPT_AD_STICK_Y) PORT_SENSITIVITY(JOYSTICK_SENSITIVITY) PORT_KEYDELTA(JOYSTICK_DELTA) PORT_MINMAX(0xd2,0x282 ) PORT_PLAYER(1) PORT_REVERSE
PORT_START("JOY2_X") /* joystick 2, X axis */
PORT_BIT( 0x3ff, 0x180, IPT_AD_STICK_X) PORT_SENSITIVITY(JOYSTICK_SENSITIVITY) PORT_KEYDELTA(JOYSTICK_DELTA) PORT_MINMAX(0xd2,0x180 ) PORT_PLAYER(2)
PORT_START("JOY2_Y") /* joystick 2, Y axis */
PORT_BIT( 0x3ff, 0x1aa, IPT_AD_STICK_Y) PORT_SENSITIVITY(JOYSTICK_SENSITIVITY) PORT_KEYDELTA(JOYSTICK_DELTA) PORT_MINMAX(0xd2,0x282 ) PORT_PLAYER(2) PORT_REVERSE
INPUT_PORTS_END
/* YEAR NAME PARENT COMPAT MACHINE INPUT INIT COMPANY FULLNAME */
COMP( 1978, 990189, 0, 0, tm990_189, tm990_189, driver_device, 0, "Texas Instruments", "TM 990/189 University Board microcomputer" , 0)
COMP( 1980, 990189v, 990189, 0, tm990_189_v, tm990_189, driver_device, 0, "Texas Instruments", "TM 990/189 University Board microcomputer with Video Board Interface" , 0)
|
Unrepentant-Atheist/mame
|
src/mame/drivers/tm990189.cpp
|
C++
|
gpl-2.0
| 40,301 |
<?php
/**
* This file is part of the "dibi" - smart database abstraction layer.
* Copyright (c) 2005 David Grudl (http://davidgrudl.com)
*/
/**
* dibi connection.
*
* @author David Grudl
* @package dibi
*
* @property-read bool $connected
* @property-read mixed $config
* @property-read IDibiDriver $driver
* @property-read int $affectedRows
* @property-read int $insertId
* @property-read DibiDatabaseInfo $databaseInfo
*/
class DibiConnection extends DibiObject
{
/** @var array of function(DibiEvent $event); Occurs after query is executed */
public $onEvent;
/** @var array Current connection configuration */
private $config;
/** @var IDibiDriver */
private $driver;
/** @var DibiTranslator */
private $translator;
/** @var bool Is connected? */
private $connected = FALSE;
/** @var DibiHashMap Substitutes for identifiers */
private $substitutes;
/**
* Connection options: (see driver-specific options too)
* - lazy (bool) => if TRUE, connection will be established only when required
* - result (array) => result set options
* - formatDateTime => date-time format (if empty, DateTime objects will be returned)
* - profiler (array or bool)
* - run (bool) => enable profiler?
* - file => file to log
* - substitutes (array) => map of driver specific substitutes (under development)
* @param mixed connection parameters
* @param string connection name
* @throws DibiException
*/
public function __construct($config, $name = NULL)
{
if (is_string($config)) {
parse_str($config, $config);
} elseif ($config instanceof Traversable) {
$tmp = array();
foreach ($config as $key => $val) {
$tmp[$key] = $val instanceof Traversable ? iterator_to_array($val) : $val;
}
$config = $tmp;
} elseif (!is_array($config)) {
throw new InvalidArgumentException('Configuration must be array, string or object.');
}
self::alias($config, 'username', 'user');
self::alias($config, 'password', 'pass');
self::alias($config, 'host', 'hostname');
self::alias($config, 'result|formatDate', 'resultDate');
self::alias($config, 'result|formatDateTime', 'resultDateTime');
if (!isset($config['driver'])) {
$config['driver'] = dibi::$defaultDriver;
}
$class = preg_replace(array('#\W#', '#sql#'), array('_', 'Sql'), ucfirst(strtolower($config['driver'])));
$class = "Dibi{$class}Driver";
if (!class_exists($class)) {
include_once dirname(__FILE__) . "/../drivers/$class.php";
if (!class_exists($class, FALSE)) {
throw new DibiException("Unable to create instance of dibi driver '$class'.");
}
}
$config['name'] = $name;
$this->config = $config;
$this->driver = new $class;
$this->translator = new DibiTranslator($this);
// profiler
$profilerCfg = & $config['profiler'];
if (is_scalar($profilerCfg)) {
$profilerCfg = array('run' => (bool) $profilerCfg);
}
if (!empty($profilerCfg['run'])) {
$filter = isset($profilerCfg['filter']) ? $profilerCfg['filter'] : DibiEvent::QUERY;
if (isset($profilerCfg['file'])) {
$this->onEvent[] = array(new DibiFileLogger($profilerCfg['file'], $filter), 'logEvent');
}
if (DibiFirePhpLogger::isAvailable()) {
$this->onEvent[] = array(new DibiFirePhpLogger($filter), 'logEvent');
}
if (!interface_exists('Tracy\IBarPanel') && (interface_exists('Nette\Diagnostics\IBarPanel') || interface_exists('IBarPanel'))) {
$panel = new DibiNettePanel(isset($profilerCfg['explain']) ? $profilerCfg['explain'] : TRUE, $filter);
$panel->register($this);
}
}
$this->substitutes = new DibiHashMap(create_function('$expr', 'return ":$expr:";'));
if (!empty($config['substitutes'])) {
foreach ($config['substitutes'] as $key => $value) {
$this->substitutes->$key = $value;
}
}
if (empty($config['lazy'])) {
$this->connect();
}
}
/**
* Automatically frees the resources allocated for this result set.
* @return void
*/
public function __destruct()
{
// disconnects and rolls back transaction - do not rely on auto-disconnect and rollback!
$this->connected && $this->driver->getResource() && $this->disconnect();
}
/**
* Connects to a database.
* @return void
*/
final public function connect()
{
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::CONNECT) : NULL;
try {
$this->driver->connect($this->config);
$this->connected = TRUE;
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
}
/**
* Disconnects from a database.
* @return void
*/
final public function disconnect()
{
$this->driver->disconnect();
$this->connected = FALSE;
}
/**
* Returns TRUE when connection was established.
* @return bool
*/
final public function isConnected()
{
return $this->connected;
}
/**
* Returns configuration variable. If no $key is passed, returns the entire array.
* @see self::__construct
* @param string
* @param mixed default value to use if key not found
* @return mixed
*/
final public function getConfig($key = NULL, $default = NULL)
{
if ($key === NULL) {
return $this->config;
} elseif (isset($this->config[$key])) {
return $this->config[$key];
} else {
return $default;
}
}
/**
* Apply configuration alias or default values.
* @param array connect configuration
* @param string key
* @param string alias key
* @return void
*/
public static function alias(& $config, $key, $alias)
{
$foo = & $config;
foreach (explode('|', $key) as $key) {
$foo = & $foo[$key];
}
if (!isset($foo) && isset($config[$alias])) {
$foo = $config[$alias];
unset($config[$alias]);
}
}
/**
* Returns the driver and connects to a database in lazy mode.
* @return IDibiDriver
*/
final public function getDriver()
{
$this->connected || $this->connect();
return $this->driver;
}
/**
* Generates (translates) and executes SQL query.
* @param array|mixed one or more arguments
* @return DibiResult|int result set object (if any)
* @throws DibiException
*/
final public function query($args)
{
$args = func_get_args();
return $this->nativeQuery($this->translateArgs($args));
}
/**
* Generates SQL query.
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
final public function translate($args)
{
$args = func_get_args();
return $this->translateArgs($args);
}
/**
* Generates and prints SQL query.
* @param array|mixed one or more arguments
* @return bool
*/
final public function test($args)
{
$args = func_get_args();
try {
dibi::dump($this->translateArgs($args));
return TRUE;
} catch (DibiException $e) {
if ($e->getSql()) {
dibi::dump($e->getSql());
} else {
echo get_class($e) . ': ' . $e->getMessage() . (PHP_SAPI === 'cli' ? "\n" : '<br>');
}
return FALSE;
}
}
/**
* Generates (translates) and returns SQL query as DibiDataSource.
* @param array|mixed one or more arguments
* @return DibiDataSource
* @throws DibiException
*/
final public function dataSource($args)
{
$args = func_get_args();
return new DibiDataSource($this->translateArgs($args), $this);
}
/**
* Generates SQL query.
* @param array
* @return string
*/
private function translateArgs($args)
{
$this->connected || $this->connect();
return $this->translator->translate($args);
}
/**
* Executes the SQL query.
* @param string SQL statement.
* @return DibiResult|int result set object (if any)
* @throws DibiException
*/
final public function nativeQuery($sql)
{
$this->connected || $this->connect();
dibi::$sql = $sql;
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::QUERY, $sql) : NULL;
try {
$res = $this->driver->query($sql);
} catch (DibiException $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
if ($res) {
$res = $this->createResultSet($res);
} else {
$res = $this->driver->getAffectedRows();
}
$event && $this->onEvent($event->done($res));
return $res;
}
/**
* Gets the number of affected rows by the last INSERT, UPDATE or DELETE query.
* @return int number of rows
* @throws DibiException
*/
public function getAffectedRows()
{
$this->connected || $this->connect();
$rows = $this->driver->getAffectedRows();
if (!is_int($rows) || $rows < 0) {
throw new DibiException('Cannot retrieve number of affected rows.');
}
return $rows;
}
/**
* Gets the number of affected rows. Alias for getAffectedRows().
* @return int number of rows
* @throws DibiException
*/
public function affectedRows()
{
return $this->getAffectedRows();
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column by the previous INSERT query.
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public function getInsertId($sequence = NULL)
{
$this->connected || $this->connect();
$id = $this->driver->getInsertId($sequence);
if ($id < 1) {
throw new DibiException('Cannot retrieve last generated ID.');
}
return (int) $id;
}
/**
* Retrieves the ID generated for an AUTO_INCREMENT column. Alias for getInsertId().
* @param string optional sequence name
* @return int
* @throws DibiException
*/
public function insertId($sequence = NULL)
{
return $this->getInsertId($sequence);
}
/**
* Begins a transaction (if supported).
* @param string optional savepoint name
* @return void
*/
public function begin($savepoint = NULL)
{
$this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::BEGIN, $savepoint) : NULL;
try {
$this->driver->begin($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
}
/**
* Commits statements in a transaction.
* @param string optional savepoint name
* @return void
*/
public function commit($savepoint = NULL)
{
$this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::COMMIT, $savepoint) : NULL;
try {
$this->driver->commit($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
}
/**
* Rollback changes in a transaction.
* @param string optional savepoint name
* @return void
*/
public function rollback($savepoint = NULL)
{
$this->connected || $this->connect();
$event = $this->onEvent ? new DibiEvent($this, DibiEvent::ROLLBACK, $savepoint) : NULL;
try {
$this->driver->rollback($savepoint);
$event && $this->onEvent($event->done());
} catch (DibiException $e) {
$event && $this->onEvent($event->done($e));
throw $e;
}
}
/**
* Result set factory.
* @param IDibiResultDriver
* @return DibiResult
*/
public function createResultSet(IDibiResultDriver $resultDriver)
{
$res = new DibiResult($resultDriver);
return $res->setFormat(dibi::DATE, $this->config['result']['formatDate'])
->setFormat(dibi::DATETIME, $this->config['result']['formatDateTime']);
}
/********************* fluent SQL builders ****************d*g**/
/**
* @return DibiFluent
*/
public function command()
{
return new DibiFluent($this);
}
/**
* @param string column name
* @return DibiFluent
*/
public function select($args)
{
$args = func_get_args();
return $this->command()->__call('select', $args);
}
/**
* @param string table
* @param array
* @return DibiFluent
*/
public function update($table, $args)
{
if (!(is_array($args) || $args instanceof Traversable)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.');
}
return $this->command()->update('%n', $table)->set($args);
}
/**
* @param string table
* @param array
* @return DibiFluent
*/
public function insert($table, $args)
{
if ($args instanceof Traversable) {
$args = iterator_to_array($args);
} elseif (!is_array($args)) {
throw new InvalidArgumentException('Arguments must be array or Traversable.');
}
return $this->command()->insert()
->into('%n', $table, '(%n)', array_keys($args))->values('%l', $args);
}
/**
* @param string table
* @return DibiFluent
*/
public function delete($table)
{
return $this->command()->delete()->from('%n', $table);
}
/********************* substitutions ****************d*g**/
/**
* Returns substitution hashmap.
* @return DibiHashMap
*/
public function getSubstitutes()
{
return $this->substitutes;
}
/**
* Provides substitution.
* @return string
*/
public function substitute($value)
{
return strpos($value, ':') === FALSE ? $value : preg_replace_callback('#:([^:\s]*):#', array($this, 'subCb'), $value);
}
/**
* Substitution callback.
*/
private function subCb($m)
{
return $this->substitutes->{$m[1]};
}
/********************* shortcuts ****************d*g**/
/**
* Executes SQL query and fetch result - shortcut for query() & fetch().
* @param array|mixed one or more arguments
* @return DibiRow
* @throws DibiException
*/
public function fetch($args)
{
$args = func_get_args();
return $this->query($args)->fetch();
}
/**
* Executes SQL query and fetch results - shortcut for query() & fetchAll().
* @param array|mixed one or more arguments
* @return DibiRow[]
* @throws DibiException
*/
public function fetchAll($args)
{
$args = func_get_args();
return $this->query($args)->fetchAll();
}
/**
* Executes SQL query and fetch first column - shortcut for query() & fetchSingle().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
public function fetchSingle($args)
{
$args = func_get_args();
return $this->query($args)->fetchSingle();
}
/**
* Executes SQL query and fetch pairs - shortcut for query() & fetchPairs().
* @param array|mixed one or more arguments
* @return string
* @throws DibiException
*/
public function fetchPairs($args)
{
$args = func_get_args();
return $this->query($args)->fetchPairs();
}
/********************* misc ****************d*g**/
/**
* Import SQL dump from file - extreme fast!
* @param string filename
* @return int count of sql commands
*/
public function loadFile($file)
{
$this->connected || $this->connect();
@set_time_limit(0); // intentionally @
$handle = @fopen($file, 'r'); // intentionally @
if (!$handle) {
throw new RuntimeException("Cannot open file '$file'.");
}
$count = 0;
$delimiter = ';';
$sql = '';
while (!feof($handle)) {
$s = rtrim(fgets($handle));
if (substr($s, 0, 10) === 'DELIMITER ') {
$delimiter = substr($s, 10);
} elseif (substr($s, -strlen($delimiter)) === $delimiter) {
$sql .= substr($s, 0, -strlen($delimiter));
$this->driver->query($sql);
$sql = '';
$count++;
} else {
$sql .= $s . "\n";
}
}
if (trim($sql) !== '') {
$this->driver->query($sql);
$count++;
}
fclose($handle);
return $count;
}
/**
* Gets a information about the current database.
* @return DibiDatabaseInfo
*/
public function getDatabaseInfo()
{
$this->connected || $this->connect();
return new DibiDatabaseInfo($this->driver->getReflector(), isset($this->config['database']) ? $this->config['database'] : NULL);
}
/**
* Prevents unserialization.
*/
public function __wakeup()
{
throw new DibiNotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
}
/**
* Prevents serialization.
*/
public function __sleep()
{
throw new DibiNotSupportedException('You cannot serialize or unserialize ' . $this->getClass() . ' instances.');
}
}
|
beerscrub/sandbox
|
vendor/dg/dibi/dibi/libs/DibiConnection.php
|
PHP
|
gpl-2.0
| 15,988 |
<?php
/**
* Members: Change Avatar screen handler
*
* @package BuddyPress
* @subpackage MembersScreens
* @since 6.0.0
*/
/**
* Handle the display of the profile Change Avatar page by loading the correct template file.
*
* @since 6.0.0
*/
function bp_members_screen_change_avatar() {
// Bail if not the correct screen.
if ( ! bp_is_my_profile() && ! bp_current_user_can( 'bp_moderate' ) ) {
return false;
}
// Bail if there are action variables.
if ( bp_action_variables() ) {
bp_do_404();
return;
}
$bp = buddypress();
if ( ! isset( $bp->avatar_admin ) ) {
$bp->avatar_admin = new stdClass();
}
$bp->avatar_admin->step = 'upload-image';
if ( !empty( $_FILES ) ) {
// Check the nonce.
check_admin_referer( 'bp_avatar_upload' );
// Pass the file to the avatar upload handler.
if ( bp_core_avatar_handle_upload( $_FILES, 'bp_members_avatar_upload_dir' ) ) {
$bp->avatar_admin->step = 'crop-image';
// Make sure we include the jQuery jCrop file for image cropping.
add_action( 'wp_print_scripts', 'bp_core_add_jquery_cropper' );
}
}
// If the image cropping is done, crop the image and save a full/thumb version.
if ( isset( $_POST['avatar-crop-submit'] ) ) {
// Check the nonce.
check_admin_referer( 'bp_avatar_cropstore' );
$args = array(
'item_id' => bp_displayed_user_id(),
'original_file' => $_POST['image_src'],
'crop_x' => $_POST['x'],
'crop_y' => $_POST['y'],
'crop_w' => $_POST['w'],
'crop_h' => $_POST['h']
);
if ( ! bp_core_avatar_handle_crop( $args ) ) {
bp_core_add_message( __( 'There was a problem cropping your profile photo.', 'buddypress' ), 'error' );
} else {
/** This action is documented in wp-includes/deprecated.php */
do_action_deprecated( 'xprofile_avatar_uploaded', array( (int) $args['item_id'], 'crop' ), '6.0.0', 'bp_members_avatar_uploaded' );
/**
* Fires right before the redirect, after processing a new avatar.
*
* @since 6.0.0
*
* @param string $item_id Inform about the user id the avatar was set for.
* @param string $value Inform about the way the avatar was set ('crop').
*/
do_action( 'bp_members_avatar_uploaded', (int) $args['item_id'], 'crop' );
bp_core_add_message( __( 'Your new profile photo was uploaded successfully.', 'buddypress' ) );
bp_core_redirect( bp_displayed_user_domain() );
}
}
/** This action is documented in wp-includes/deprecated.php */
do_action_deprecated( 'xprofile_screen_change_avatar', array(), '6.0.0', 'bp_members_screen_change_avatar' );
/**
* Fires right before the loading of the Member Change Avatar screen template file.
*
* @since 6.0.0
*/
do_action( 'bp_members_screen_change_avatar' );
/** This filter is documented in wp-includes/deprecated.php */
$template = apply_filters_deprecated( 'xprofile_template_change_avatar', array( 'members/single/home' ), '6.0.0', 'bp_members_template_change_avatar' );
/**
* Filters the template to load for the Member Change Avatar page screen.
*
* @since 6.0.0
*
* @param string $template Path to the Member template to load.
*/
bp_core_load_template( apply_filters( 'bp_members_template_change_avatar', $template ) );
}
|
rolandinsh/buddypress
|
bp-members/screens/change-avatar.php
|
PHP
|
gpl-2.0
| 3,248 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Sun Apr 21 20:31:46 CEST 2013 -->
<title>Uses of Class org.lwjgl.opengles.QCOMWriteonlyRendering (LWJGL API)</title>
<meta name="date" content="2013-04-21">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.lwjgl.opengles.QCOMWriteonlyRendering (LWJGL API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/lwjgl/opengles/QCOMWriteonlyRendering.html" title="class in org.lwjgl.opengles">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/lwjgl/opengles/class-use/QCOMWriteonlyRendering.html" target="_top">Frames</a></li>
<li><a href="QCOMWriteonlyRendering.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.lwjgl.opengles.QCOMWriteonlyRendering" class="title">Uses of Class<br>org.lwjgl.opengles.QCOMWriteonlyRendering</h2>
</div>
<div class="classUseContainer">No usage of org.lwjgl.opengles.QCOMWriteonlyRendering</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../org/lwjgl/opengles/QCOMWriteonlyRendering.html" title="class in org.lwjgl.opengles">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../../../../overview-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/lwjgl/opengles/class-use/QCOMWriteonlyRendering.html" target="_top">Frames</a></li>
<li><a href="QCOMWriteonlyRendering.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><i>Copyright © 2002-2009 lwjgl.org. All Rights Reserved.</i></small></p>
</body>
</html>
|
fh3/flaming-octo-ironman
|
flaming-octo-ironman/doc/lwjgl-docs-2.9.0/javadoc/org/lwjgl/opengles/class-use/QCOMWriteonlyRendering.html
|
HTML
|
gpl-2.0
| 4,398 |
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
class Ui_Dialog2b(object):
def setupUi(self, Dialog2):
Dialog2.setObjectName("Dialog2")
Dialog2.resize(472, 300)
self.buttonBox = QtGui.QDialogButtonBox(Dialog2)
self.buttonBox.setGeometry(QtCore.QRect(110, 250, 341, 32))
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.comboBox = QtGui.QComboBox(Dialog2)
self.comboBox.setGeometry(QtCore.QRect(110, 20, 101, 22))
self.comboBox.setObjectName("comboBox")
self.label = QtGui.QLabel(Dialog2)
self.label.setGeometry(QtCore.QRect(20, 18, 81, 16))
self.label.setObjectName("label")
self.label_2 = QtGui.QLabel(Dialog2)
self.label_2.setGeometry(QtCore.QRect(20, 28, 81, 20))
self.label_2.setObjectName("label_2")
self.label_3 = QtGui.QLabel(Dialog2)
self.label_3.setGeometry(QtCore.QRect(260, 18, 81, 16))
self.label_3.setObjectName("label_3")
self.comboBox_2 = QtGui.QComboBox(Dialog2)
self.comboBox_2.setGeometry(QtCore.QRect(350, 20, 101, 22))
self.comboBox_2.setObjectName("comboBox_2")
self.label_4 = QtGui.QLabel(Dialog2)
self.label_4.setGeometry(QtCore.QRect(260, 30, 81, 20))
self.label_4.setObjectName("label_4")
self.label_5 = QtGui.QLabel(Dialog2)
self.label_5.setGeometry(QtCore.QRect(20, 83, 101, 16))
self.label_5.setObjectName("label_5")
self.comboBox_3 = QtGui.QComboBox(Dialog2)
self.comboBox_3.setGeometry(QtCore.QRect(130, 80, 51, 21))
self.comboBox_3.setObjectName("comboBox_3")
self.comboBox_4 = QtGui.QComboBox(Dialog2)
self.comboBox_4.setGeometry(QtCore.QRect(130, 140, 51, 21))
self.comboBox_4.setObjectName("comboBox_4")
self.label_6 = QtGui.QLabel(Dialog2)
self.label_6.setGeometry(QtCore.QRect(20, 143, 101, 16))
self.label_6.setObjectName("label_6")
self.comboBox_5 = QtGui.QComboBox(Dialog2)
self.comboBox_5.setGeometry(QtCore.QRect(350, 140, 101, 22))
self.comboBox_5.setObjectName("comboBox_5")
self.label_7 = QtGui.QLabel(Dialog2)
self.label_7.setGeometry(QtCore.QRect(220, 143, 121, 16))
self.label_7.setObjectName("label_7")
self.label_8 = QtGui.QLabel(Dialog2)
self.label_8.setGeometry(QtCore.QRect(20, 203, 121, 16))
self.label_8.setObjectName("label_8")
self.comboBox_6 = QtGui.QComboBox(Dialog2)
self.comboBox_6.setGeometry(QtCore.QRect(90, 200, 171, 22))
self.comboBox_6.setObjectName("comboBox_6")
self.retranslateUi(Dialog2)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog2.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog2.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog2)
def retranslateUi(self, Dialog2):
Dialog2.setWindowTitle(QtGui.QApplication.translate("Dialog2", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog2", "Start nodes", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("Dialog2", "field", None, QtGui.QApplication.UnicodeUTF8))
self.label_3.setText(QtGui.QApplication.translate("Dialog2", "End nodes", None, QtGui.QApplication.UnicodeUTF8))
self.label_4.setText(QtGui.QApplication.translate("Dialog2", "field", None, QtGui.QApplication.UnicodeUTF8))
self.label_5.setText(QtGui.QApplication.translate("Dialog2", "Directed network ?", None, QtGui.QApplication.UnicodeUTF8))
self.label_6.setText(QtGui.QApplication.translate("Dialog2", "Weighted network ?", None, QtGui.QApplication.UnicodeUTF8))
self.label_7.setText(QtGui.QApplication.translate("Dialog2", "Weight field (optional)", None, QtGui.QApplication.UnicodeUTF8))
self.label_8.setText(QtGui.QApplication.translate("Dialog2", "Algorithm", None, QtGui.QApplication.UnicodeUTF8))
|
sergelhomme/Network_Analysis
|
Network_Analysis_1_4/network_analysis/tools/ui_test2b.py
|
Python
|
gpl-2.0
| 4,277 |
#include "gtest/gtest.h"
#include "Node.h"
TEST(NodeTest, Construction)
{
Node* node = new Node();
Node* leftNode = new Node();
Node* rightNode = new Node();
Node* ancNode = new Node();
EXPECT_EQ("", node->getName());
node->setName("TestNode");
EXPECT_EQ("TestNode", node->getName());
EXPECT_EQ(NULL, node->getLfDesc());
node->setLfDesc(leftNode);
EXPECT_EQ(leftNode, node->getLfDesc());
EXPECT_EQ(NULL, node->getRtDesc());
node->setRtDesc(rightNode);
EXPECT_EQ(rightNode, node->getRtDesc());
EXPECT_EQ(NULL, node->getAnc());
node->setAnc(ancNode);
EXPECT_EQ(ancNode, node->getAnc());
EXPECT_EQ(0, node->getIndex());
node->setIndex(10);
EXPECT_EQ(10, node->getIndex());
EXPECT_EQ(0.0, node->getTime());
node->setTime(1.0);
EXPECT_EQ(1.0, node->getTime());
EXPECT_EQ(0.0, node->getBrlen());
node->setBrlen(1.0);
EXPECT_EQ(1.0, node->getBrlen());
EXPECT_EQ(0, node->getTipDescCount());
node->setTipDescCount(10);
EXPECT_EQ(10, node->getTipDescCount());
EXPECT_EQ(false, node->getExtantStatus());
node->setExtantStatus(true);
EXPECT_EQ(true, node->getExtantStatus());
EXPECT_EQ(false, node->getIsTip());
node->setIsTip(true);
EXPECT_EQ(true, node->getIsTip());
EXPECT_EQ(false, node->getIsConstant());
node->setIsConstant(true);
EXPECT_EQ(true, node->getIsConstant());
EXPECT_EQ(false, node->getIsLivingTip());
node->setIsLivingTip(true);
EXPECT_EQ(true, node->getIsLivingTip());
EXPECT_EQ(0.0, node->getMapStart());
node->setMapStart(1.0);
EXPECT_EQ(1.0, node->getMapStart());
EXPECT_EQ(0.0, node->getMapEnd());
node->setMapEnd(1.0);
EXPECT_EQ(1.0, node->getMapEnd());
delete ancNode;
delete rightNode;
delete leftNode;
delete node;
}
|
macroevolution/bamm
|
tests/NodeTest.cpp
|
C++
|
gpl-2.0
| 1,854 |
// libTorrent - BitTorrent library
// Copyright (C) 2005-2007, Jari Sundell
//
// 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
//
// In addition, as a special exception, the copyright holders give
// permission to link the code of portions of this program with the
// OpenSSL library under certain conditions as described in each
// individual source file, and distribute linked combinations
// including the two.
//
// You must obey the GNU General Public License in all respects for
// all of the code used other than OpenSSL. If you modify file(s)
// with this exception, you may extend this exception to your version
// of the file(s), but you are not obligated to do so. If you do not
// wish to do so, delete this exception statement from your version.
// If you delete this exception statement from all source files in the
// program, then also delete it here.
//
// Contact: Jari Sundell <[email protected]>
//
// Skomakerveien 33
// 3185 Skoppum, NORWAY
#ifndef LIBTORRENT_GLOBALS_H
#define LIBTORRENT_GLOBALS_H
#include <rak/timer.h>
#include <rak/priority_queue_default.h>
namespace torrent {
extern rak::priority_queue_default taskScheduler;
extern rak::timer cachedTime;
}
#endif
|
cleverca22/libtorrent
|
src/globals.h
|
C
|
gpl-2.0
| 1,905 |
<?php
/**
* @package EasySocial
* @copyright Copyright (C) 2010 - 2014 Stack Ideas Sdn Bhd. All rights reserved.
* @license GNU/GPL, see LICENSE.php
* EasySocial is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
*/
defined( '_JEXEC' ) or die( 'Unauthorized Access' );
?>
<tr>
<td style="text-align: center;padding: 40px 10px 0;">
<div style="margin-bottom:15px;">
<div style="font-family:Arial;font-size:32px;font-weight:normal;color:#333;display:block; margin: 4px 0">
<?php echo JText::_('COM_EASYSOCIAL_EMAILS_GROUP_JOIN_APPLICATION_APPROVED_HEADING'); ?>
</div>
</div>
</td>
</tr>
<tr>
<td style="font-size:12px;color:#888;padding: 0 30px;">
<div style="margin:30px auto;text-align:center;display:block">
<img src="<?php echo rtrim( JURI::root() , '/' );?>/components/com_easysocial/themes/wireframe/images/emails/divider.png" alt="<?php echo JText::_( 'divider' );?>" />
</div>
<p>
<?php echo JText::_('COM_EASYSOCIAL_EMAILS_HELLO'); ?> <?php echo $recipientName; ?>,<br />
</p>
<p>
<?php echo JText::_('COM_EASYSOCIAL_EMAILS_GROUP_JOIN_APPLICATION_APPROVED'); ?>
</p>
<table align="center" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed;width:100%;">
<tr>
<td align="center">
<table width="540" align="center" style="margin: 20px auto 0;padding:15px 20px;" border="0" cellspacing="0" cellpadding="0">
<tr>
<td valign="top">
<table style="font-size: 14px;margin: 0 auto 10px 20px; text-align:center;color:#798796;width:100%;" align="center">
<tr>
<td align="center">
<a href="<?php echo $groupLink;?>" style="
display:inline-block;
text-decoration:none;
font-weight:bold;
margin-top: 5px;
padding:4px 15px;
line-height:20px;
color:#fff;font-size: 12px;
background-color: #83B3DD;
background-image: linear-gradient(to bottom, #91C2EA, #6D9CCA);
background-repeat: repeat-x;
border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25);
border-style: solid;
border-width: 1px;
box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2) inset, 0 1px 2px rgba(0, 0, 0, 0.05);
border-radius:2px; -moz-border-radius:2px; -webkit-border-radius:2px;
">
<?php echo JText::_('COM_EASYSOCIAL_EMAILS_VIEW_GROUP_BUTTON');?> →
</a>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
|
BetterBetterBetter/WheresWalden
|
components/com_easysocial/themes/wireframe/emails/html/group/user.approved.php
|
PHP
|
gpl-2.0
| 2,982 |
"""Subclass of CommitGit, which is generated by wxFormBuilder."""
import wx
from beatle.lib import wxx
from beatle.activity.git.ui import ui
# Implementing CommitGit
class CommitGitDialog(ui.CommitGit):
"""
This dialog allows to commit the git repository
"""
@wxx.SetInfo(__doc__)
def __init__(self, parent):
"""Initialize the dialog"""
super(CommitGitDialog, self).__init__(parent)
def Validate(self):
"""Do dialog validation"""
self._message = self.m_richText39.GetValue().strip()
if len(self._message) == 0:
wx.MessageBox("The commit message must be non empty", "Error",
wx.OK | wx.CENTER | wx.ICON_ERROR, self)
return False
return True
# Handlers for CommitGit events.
def OnCancel(self, event):
"""Cancel the commit process"""
self.EndModal(wx.ID_CANCEL)
def OnOK(self, event):
"""Do the git process"""
if self.Validate():
self.EndModal(wx.ID_OK)
|
melviso/phycpp
|
beatle/activity/git/ui/dlg/CommitGit.py
|
Python
|
gpl-2.0
| 1,027 |
/*
* Copyright (C) 2014 SeamlessStack
*
* This file is part of SeamlessStack distributed file system.
*
* SeamlessStack distributed file system 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.
*
* SeamlessStack distributed file system 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 SeamlessStack distributed file system. If not,
* see <http://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sstack_log.h>
#define DEBUG 1
extern log_ctx_t *sfs_ctx;
static char *
get_ip_str(const struct sockaddr *sa, char *s, unsigned int maxlen)
{
switch(sa->sa_family) {
case AF_INET:
inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),s,
maxlen);
break;
case AF_INET6:
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr), s,
maxlen);
break;
default:
strncpy(s, "Unknown AF", maxlen);
return NULL;
}
return s;
}
/*
* sfs_traceroute - Find number of hops between sfs and given sfsd's address
*
* dest_hostname - hostname/IPaddr of the sfsd host . Should be non-NULL.
* num_hops - Output parameter that returns number of hops between sfs & sfsd
*
* Returns 0 on success and -1 on failure.
*/
int
sfs_traceroute(char* dest_hostname, int *num_hops)
{
struct addrinfo* dest_addrinfo_collection = NULL;
struct addrinfo* dest_addrinfo_item = NULL;
struct sockaddr* dest_addr = NULL;
struct sockaddr_in nexthop_addr_in;
struct timeval tv;
int recv_socket;
int send_socket;
char buf[512];
char nexthop_hostname[NI_MAXHOST];
char dest_addr_str[INET_ADDRSTRLEN];
char nexthop_addr_str[INET_ADDRSTRLEN];
unsigned int nexthop_addr_in_len;
unsigned short iter;
socklen_t ttl = 1;
long error = -1;
socklen_t maxhops = 64;
// Parameter validation
if (NULL == dest_addr || NULL == num_hops) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Invalid parameter specified \n",
__FUNCTION__);
errno = EINVAL;
return -1;
}
/* resolve the domain name into a list of addresses */
error = getaddrinfo(dest_hostname, NULL, NULL, &dest_addrinfo_collection);
if (error != 0) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Error in getaddrinfo: %s\n",
__FUNCTION__, gai_strerror((int)error));
return -1;
}
/* loop over returned results */
for (dest_addrinfo_item = dest_addrinfo_collection, iter=1;
dest_addrinfo_item != NULL;
dest_addrinfo_item = dest_addrinfo_item->ai_next, iter++){
if(iter==1) {
dest_addr = dest_addrinfo_item->ai_addr;
get_ip_str(dest_addr, dest_addr_str, INET_ADDRSTRLEN);
} else {
// Destination URL has multiple addresses.
// Use the first one
break;
}
}
tv.tv_sec = 5;
tv.tv_usec = 0;
while (1) {
fd_set fds;
int error = -1;
struct sockaddr_in *dest_addr_in = NULL;
FD_ZERO(&fds);
recv_socket = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP);
if (recv_socket == -1) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Cannot create receive socket. "
"Error = %d \n", __FUNCTION__, errno);
freeaddrinfo(dest_addrinfo_collection);
return -1;
}
FD_SET(recv_socket, &fds);
send_socket = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (send_socket == -1) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Cannot create send socket."
"Error = %d \n", __FUNCTION__, errno);
freeaddrinfo(dest_addrinfo_collection);
return -1;
}
error = setsockopt(send_socket, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
if (error != 0) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Error setting socket options. "
"Error = %d \n", __FUNCTION__, errno);
freeaddrinfo(dest_addrinfo_collection);
return -1;
}
dest_addr_in = (struct sockaddr_in*) dest_addr;
dest_addr_in->sin_family = PF_INET;
dest_addr_in->sin_port = htons(33434);
error = sendto(send_socket, &buf, sizeof(buf),
0, (struct sockaddr *)dest_addr_in, sizeof(*dest_addr_in));
if (error == -1) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Error sending data to destination."
" Error = %d\n", __FUNCTION__, errno);
freeaddrinfo(dest_addrinfo_collection);
return -1;
}
error = select(recv_socket+1, &fds, NULL, NULL, &tv);
if (error == -1) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Select error. Error = %d \n",
__FUNCTION__, errno);
freeaddrinfo(dest_addrinfo_collection);
return -1;
} else if (error == 0) {
fflush(stdin);
} else {
if (FD_ISSET(recv_socket, &fds)) {
nexthop_addr_in_len = sizeof(nexthop_addr_in);
recvfrom(recv_socket, buf, sizeof(buf),
0, (struct sockaddr *)&nexthop_addr_in,
&nexthop_addr_in_len);
get_ip_str((struct sockaddr *)&nexthop_addr_in,
nexthop_addr_str, INET_ADDRSTRLEN);
error = getnameinfo((struct sockaddr *)&nexthop_addr_in,
nexthop_addr_in_len,
nexthop_hostname, sizeof(nexthop_hostname),
NULL, 0, NI_NAMEREQD);
if (error != 0) {
error = getnameinfo((struct sockaddr *)&nexthop_addr_in,
nexthop_addr_in_len,
nexthop_hostname, sizeof(nexthop_hostname),
NULL, 0, NI_NUMERICHOST);
if (error != 0) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Error in getnameinfo: "
"%s \n", __FUNCTION__, gai_strerror(error));
freeaddrinfo(dest_addrinfo_collection);
return -1;
}
}
}
}
if (ttl == maxhops) {
sfs_log(sfs_ctx, SFS_ERR, "%s: Max hops reached. Unable to find "
"the destination host \n", __FUNCTION__);
freeaddrinfo(dest_addrinfo_collection);
close(recv_socket);
close(send_socket);
return -1;
}
close(recv_socket);
close(send_socket);
if (!strcmp(dest_addr_str, nexthop_addr_str)) {
sfs_log(sfs_ctx, SFS_INFO, "%s: Destination reached in %d "
"hops \n", __FUNCTION__, ttl);
break;
}
ttl++;
}
freeaddrinfo(dest_addrinfo_collection);
*num_hops = ttl;
return EXIT_SUCCESS;
}
#ifdef TRACEROUTE_TEST
int
main(int argc, char* argv[]){
int hops = 0;
char* ipaddr = NULL;
int ret = -1;
if(argc!=2){
fprintf(stderr, "\nusage: traceroute host");
return EXIT_FAILURE;
}
ipaddr = argv[1];
ret = traceroute(ipaddr, &hops);
printf("%s: Number of hops to %s is %d \n", argv[0], ipaddr, hops);
return ret;
}
#endif // TRACEROUTE_TEST
|
shubhros/SeamlessStack
|
sfs/src/sfs_traceroute.c
|
C
|
gpl-2.0
| 6,941 |
#ifndef _MT_SECURE_API_H_
#define _MT_SECURE_API_H_
#include <mach/sync_write.h>
/* Use the arch_extension sec pseudo op before switching to secure world */
#if defined(__GNUC__) && \
defined(__GNUC_MINOR__) && \
defined(__GNUC_PATCHLEVEL__) && \
((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)) \
>= 40502
#define MC_ARCH_EXTENSION_SEC
#endif
/*
* return code for fastcalls
*/
#define MC_FC_RET_OK 0
#define MC_FC_RET_ERR_INVALID 1
/* t-base fastcall */
/*
* Command to inform SW that we will enter in Power Sleep (Dormant).
* Parameters:
* - param0, the NW wakeup addr (phys).
* - param1, the cpuID who will sleep
* - param2, unused.
* Return:
* - Cannot fail, always MC_FC_RET_OK.
*/
#define MC_FC_SLEEP -3
/*
* Command to write NW reset addr for Slave cpus.
* Parameters:
* - param0, the NW reset addr (phys).
* - param1, the cpuID.
* - param2, unused.
* Return:
* - Cannot fail, always MC_FC_RET_OK.
*/
#define MC_FC_SET_RESET_VECTOR -301
/*
* Command to switch off BootRom.
* Parameters:
* - param0, unused.
* - param1, unsued.
* - param2, unused.
* Return:
* - Cannot fail, always MC_FC_RET_OK.
*/
#define MC_FC_TURN_OFF_BOOTROM -302
/*
* Command to cancel a sleep command in case of Dormant abort.
* Parameters:
* - param0, unused.
* - param1, unsued.
* - param2, unused.
* Return:
* - Cannot fail, always MC_FC_RET_OK.
*/
#define MC_FC_SLEEP_CANCELLED -303
#define MC_FC_MTK_AEEDUMP -306
#if defined(CONFIG_ARM_PSCI)
/* Error Code */
#define SIP_SVC_E_SUCCESS 0
#define SIP_SVC_E_NOT_SUPPORTED -1
#define SIP_SVC_E_INVALID_PARAMS -2
#define SIP_SVC_E_INVALID_Range -3
#define SIP_SVC_E_PERMISSION_DENY -4
#ifdef CONFIG_ARM64
/* SIP SMC Call 64 */
#define MTK_SIP_KERNEL_MCUSYS_WRITE 0xC2000201
#define MTK_SIP_KERNEL_MCUSYS_ACCESS_COUNT 0xC2000202
#else
#include <asm/opcodes-sec.h>
#include <asm/opcodes-virt.h>
/* SIP SMC Call 32 */
#define MTK_SIP_KERNEL_MCUSYS_WRITE 0x82000201
#define MTK_SIP_KERNEL_MCUSYS_ACCESS_COUNT 0x82000202
#endif
#endif
/*
static noinline int mt_secure_call(u32 function_id, u32 arg0, u32 arg1, u32 arg2)
{
register u32 reg0 __asm__("r0") = function_id;
register u32 reg1 __asm__("r1") = arg0;
register u32 reg2 __asm__("r2") = arg1;
register u32 reg3 __asm__("r3") = arg2;
int ret = 0;
asm volatile(
__SMC(0)
: "+r" (reg0), "+r" (reg1), "+r" (reg2), "+r" (reg3));
ret = reg0;
return ret;
}
*/
/*
* mt_secure_call
* Parameters:
* - cmd, the command we want to execute.
* - param0, param1, param2: the parameters used for this command.
* Return:
* - Error code of the command (MC_FC_RET_OK in case of success).
*/
static inline int mt_secure_call(uint32_t cmd, uint32_t param0, uint32_t param1, uint32_t param2)
{
/* SMC expect values in r0-r3 */
register u32 reg0 __asm__("r0") = cmd;
register u32 reg1 __asm__("r1") = param0;
register u32 reg2 __asm__("r2") = param1;
register u32 reg3 __asm__("r3") = param2;
int ret = 0;
__asm__ volatile (
#ifdef MC_ARCH_EXTENSION_SEC
/* This pseudo op is supported and required from
* binutils 2.21 on */
".arch_extension sec\n"
#endif
"smc 0\n"
: "+r"(reg0), "+r"(reg1), "+r"(reg2), "+r"(reg3)
);
/* set response */
ret = reg0;
return ret;
}
#define CONFIG_MCUSYS_WRITE_PROTECT
#if defined(CONFIG_MCUSYS_WRITE_PROTECT) && defined(CONFIG_ARM_PSCI)
#define SMC_IO_VIRT_TO_PHY(addr) (addr-0xF0000000+0x10000000)
#define mcusys_smc_write(addr, val) \
mt_secure_call(MTK_SIP_KERNEL_MCUSYS_WRITE, SMC_IO_VIRT_TO_PHY(addr), val, 0)
#define mcusys_access_count() \
mt_secure_call(MTK_SIP_KERNEL_MCUSYS_ACCESS_COUNT, 0, 0, 0)
#else
#define mcusys_smc_write(addr, val) mt_reg_sync_writel(val, addr)
#define mcusys_access_count() (0)
#endif
#endif /* _MT_SECURE_API_H_ */
|
rock12/ALPS.L1.MP6.V2.19_CENON6580_WE_1_L_KERNEL
|
drivers/misc/mediatek/mach/mt6580/include/mach/mt_secure_api.h
|
C
|
gpl-2.0
| 3,949 |
/*
* IrNET protocol module : Synchronous PPP over an IrDA socket.
*
* Jean II - HPL `00 - <[email protected]>
*
* This file contains all definitions and declarations necessary for the
* IRDA part of the IrNET module (dealing with IrTTP, IrIAS and co).
* This file is a private header, so other modules don't want to know
* what's in there...
*/
#ifndef IRNET_IRDA_H
#define IRNET_IRDA_H
/***************************** INCLUDES *****************************/
/* Please add other headers in irnet.h */
#include "irnet.h" /* Module global include */
/************************ CONSTANTS & MACROS ************************/
/*
* Name of the service (socket name) used by IrNET
*/
/* IAS object name (or part of it) */
#define IRNET_SERVICE_NAME "IrNetv1"
/* IAS attribute */
#define IRNET_IAS_VALUE "IrDA:TinyTP:LsapSel"
/* LMP notify name for client (only for /proc/net/irda/irlmp) */
#define IRNET_NOTIFY_NAME "IrNET socket"
/* LMP notify name for server (only for /proc/net/irda/irlmp) */
#define IRNET_NOTIFY_NAME_SERV "IrNET server"
/****************************** TYPES ******************************/
/*
* This is the main structure where we store all the data pertaining to
* the IrNET server (listen for connection requests) and the root
* of the IrNET socket list
*/
typedef struct irnet_root
{
irnet_socket s; /* To pretend we are a client... */
/* Generic stuff */
int magic; /* Paranoia */
int running; /* Are we operational ? */
/* Link list of all IrNET instances opened */
hashbin_t * list;
spinlock_t spinlock; /* Serialize access to the list */
/* Note : the way hashbin has been designed is absolutely not
* reentrant, beware... So, we blindly protect all with spinlock */
/* Handle for the hint bit advertised in IrLMP */
void * skey;
/* Server socket part */
struct ias_object * ias_obj; /* Our service name + lsap in IAS */
} irnet_root;
/**************************** PROTOTYPES ****************************/
/* ----------------------- CONTROL CHANNEL ----------------------- */
static void
irnet_post_event(irnet_socket *,
irnet_event,
__u32,
__u32,
char *,
__u16);
/* ----------------------- IRDA SUBROUTINES ----------------------- */
static inline int
irnet_open_tsap(irnet_socket *);
static inline __u8
irnet_ias_to_tsap(irnet_socket *,
int,
struct ias_value *);
static inline int
irnet_find_lsap_sel(irnet_socket *);
static inline int
irnet_connect_tsap(irnet_socket *);
static inline int
irnet_discover_next_daddr(irnet_socket *);
static inline int
irnet_discover_daddr_and_lsap_sel(irnet_socket *);
static inline int
irnet_dname_to_daddr(irnet_socket *);
/* ------------------------ SERVER SOCKET ------------------------ */
static inline int
irnet_daddr_to_dname(irnet_socket *);
static inline irnet_socket *
irnet_find_socket(irnet_socket *);
static inline int
irnet_connect_socket(irnet_socket *,
irnet_socket *,
struct qos_info *,
__u32,
__u8);
static inline void
irnet_disconnect_server(irnet_socket *,
struct sk_buff *);
static inline int
irnet_setup_server(void);
static inline void
irnet_destroy_server(void);
/* ---------------------- IRDA-TTP CALLBACKS ---------------------- */
static int
irnet_data_indication(void *, /* instance */
void *, /* sap */
struct sk_buff *);
static void
irnet_disconnect_indication(void *,
void *,
LM_REASON,
struct sk_buff *);
static void
irnet_connect_confirm(void *,
void *,
struct qos_info *,
__u32,
__u8,
struct sk_buff *);
static void
irnet_flow_indication(void *,
void *,
LOCAL_FLOW);
static void
irnet_status_indication(void *,
LINK_STATUS,
LOCK_STATUS);
static void
irnet_connect_indication(void *,
void *,
struct qos_info *,
__u32,
__u8,
struct sk_buff *);
/* -------------------- IRDA-IAS/LMP CALLBACKS -------------------- */
static void
irnet_getvalue_confirm(int,
__u16,
struct ias_value *,
void *);
static void
irnet_discovervalue_confirm(int,
__u16,
struct ias_value *,
void *);
#ifdef DISCOVERY_EVENTS
static void
irnet_discovery_indication(discinfo_t *,
DISCOVERY_MODE,
void *);
static void
irnet_expiry_indication(discinfo_t *,
DISCOVERY_MODE,
void *);
#endif
/**************************** VARIABLES ****************************/
/*
* The IrNET server. Listen to connection requests and co...
*/
static struct irnet_root irnet_server;
/* Control channel stuff (note : extern) */
struct irnet_ctrl_channel irnet_events;
/* The /proc/net/irda directory, defined elsewhere... */
#ifdef CONFIG_PROC_FS
extern struct proc_dir_entry *proc_irda;
#endif /* CONFIG_PROC_FS */
#endif /* IRNET_IRDA_H */
|
andi34/kernel_samsung_espresso-cm
|
net/irda/irnet/irnet_irda.h
|
C
|
gpl-2.0
| 4,854 |
/*
Theme Name: seniorsoutdoors
Layout: Sidebar-Content
*/
.content-area {
float: right;
margin: 0 0 0 -25%;
width: 100%;
}
.site-main {
margin: 0 0 0 25%;
}
.site-content .widget-area {
float: left;
overflow: hidden;
width: 25%;
}
.site-footer {
clear: both;
width: 100%;
}
|
lizbur10/js_finalproject
|
wp-content/themes/seniorsoutdoors/layouts/sidebar-content.css
|
CSS
|
gpl-2.0
| 283 |
<?php
/**
* @copyright Copyright (C) 2009-2011 ACYBA SARL - All rights reserved.
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL
*/
defined('_JEXEC') or die('Restricted access');
?>
<div id="acy_content" >
<div id="iframedoc"></div>
<form action="index.php" method="post" name="adminForm" enctype="multipart/form-data">
<table width="100%">
<tr>
<td valign="top">
<?php include(dirname(__FILE__).DS.'info.'.basename(__FILE__)); ?>
<fieldset class="adminform" width="100%" id="htmlfieldset">
<legend><?php echo JText::_( 'HTML_VERSION' ); ?></legend>
<?php echo $this->editor->display(); ?>
</fieldset>
<fieldset class="adminform" id="textfieldset">
<legend><?php echo JText::_( 'TEXT_VERSION' ); ?></legend>
<textarea style="width:100%" rows="20" name="data[mail][altbody]" id="altbody" ><?php echo @$this->mail->altbody; ?></textarea>
</fieldset>
</td>
<td width="400" valign="top">
<?php include(dirname(__FILE__).DS.'param.'.basename(__FILE__)); ?>
</td>
</tr>
</table>
<div class="clr"></div>
<input type="hidden" name="cid[]" value="<?php echo @$this->mail->mailid; ?>" />
<input type="hidden" id="tempid" name="data[mail][tempid]" value="<?php echo @$this->mail->tempid; ?>" />
<input type="hidden" name="option" value="<?php echo ACYMAILING_COMPONENT; ?>" />
<input type="hidden" name="data[mail][type]" value="news" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="ctrl" value="newsletter" />
<?php echo JHTML::_( 'form.token' ); ?>
</form>
</div>
|
pacoqueen/callao_chico
|
components/com_acymailing/back/views/newsletter/tmpl/form.php
|
PHP
|
gpl-2.0
| 1,569 |
<?php
/**
* @version $Id$
* @package VS_Library
* @author InnoGears Team <[email protected]>
* @copyright Copyright (C) 2012 InnoGears.com. All Rights Reserved.
* @license GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
*
* Websites: http://www.innogears.com
*/
if ( ! class_exists( 'VS_Init_Plugin' ) ) :
/**
* VS Library initialization.
*
* @package VS_Library
* @since 1.0.0
*/
class VS_Init_Plugin {
/**
* Define Ajax actions.
*
* @var array
*/
protected static $actions = array( 'vs-addons-management' );
/**
* Initialize VS Library.
*
* @return void
*/
public static function init() {
global $pagenow;
if ( 'admin-ajax.php' == $pagenow && isset( $_GET['action'] ) && in_array( $_GET['action'], self::$actions ) ) {
// Init WordPress Filesystem Abstraction
VS_Init_File_System::get_instance();
// Register Ajax actions
switch ( $_GET['action'] ) {
case 'vs-addons-management' :
VS_Product_Addons::hook();
break;
}
}
// Add filter to fine-tune uploaded file name
add_filter( 'wp_handle_upload_prefilter', array( __CLASS__, 'wp_handle_upload_prefilter' ) );
// Do 'vs_init' action
do_action( 'vs_init' );
}
/**
* Apply 'wp_handle_upload_prefilter' filter.
*
* @param array $file Array containing uploaded file details.
*
* @return string
*/
public static function wp_handle_upload_prefilter( $file ) {
if ( $name = iconv( 'utf-8', 'ascii//TRANSLIT//IGNORE', $file['name'] ) ) {
$file['name'] = $name;
}
return $file;
}
/**
* Register action to initialize VS Library.
*
* @return void
*/
public static function hook() {
// Register action to initialize VS Library
static $registered;
if ( ! isset( $registered ) ) {
add_action( 'init', array( __CLASS__, 'init' ) );
$registered = true;
}
}
}
endif;
|
ningmo/lyc
|
wp-content/themes/kornio/functions/pagebuilder/core/init/plugin.php
|
PHP
|
gpl-2.0
| 1,882 |
/*
==============================================================================
This file is part of the juce_core module of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
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.
------------------------------------------------------------------------------
NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
All other JUCE modules are covered by a dual GPL/commercial license, so if you are
using any other modules, be sure to check that you also comply with their license.
For more details, visit www.juce.com
==============================================================================
*/
MemoryBlock::MemoryBlock() noexcept
: size (0)
{
}
MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
{
if (initialSize > 0)
{
size = initialSize;
data.allocate (initialSize, initialiseToZero);
}
else
{
size = 0;
}
}
MemoryBlock::MemoryBlock (const MemoryBlock& other)
: size (other.size)
{
if (size > 0)
{
jassert (other.data != nullptr);
data.malloc (size);
memcpy (data, other.data, size);
}
}
MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
: size (sizeInBytes)
{
jassert (((ssize_t) sizeInBytes) >= 0);
if (size > 0)
{
jassert (dataToInitialiseFrom != nullptr); // non-zero size, but a zero pointer passed-in?
data.malloc (size);
if (dataToInitialiseFrom != nullptr)
memcpy (data, dataToInitialiseFrom, size);
}
}
MemoryBlock::~MemoryBlock() noexcept
{
}
MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
{
if (this != &other)
{
setSize (other.size, false);
memcpy (data, other.data, size);
}
return *this;
}
#if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
MemoryBlock::MemoryBlock (MemoryBlock&& other) noexcept
: data (static_cast <HeapBlock<char>&&> (other.data)),
size (other.size)
{
}
MemoryBlock& MemoryBlock::operator= (MemoryBlock&& other) noexcept
{
data = static_cast <HeapBlock<char>&&> (other.data);
size = other.size;
return *this;
}
#endif
//==============================================================================
bool MemoryBlock::operator== (const MemoryBlock& other) const noexcept
{
return matches (other.data, other.size);
}
bool MemoryBlock::operator!= (const MemoryBlock& other) const noexcept
{
return ! operator== (other);
}
bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const noexcept
{
return size == dataSize
&& memcmp (data, dataToCompare, size) == 0;
}
//==============================================================================
// this will resize the block to this size
void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
{
if (size != newSize)
{
if (newSize <= 0)
{
reset();
}
else
{
if (data != nullptr)
{
data.realloc (newSize);
if (initialiseToZero && (newSize > size))
zeromem (data + size, newSize - size);
}
else
{
data.allocate (newSize, initialiseToZero);
}
size = newSize;
}
}
}
void MemoryBlock::reset()
{
data.free();
size = 0;
}
void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
{
if (size < minimumSize)
setSize (minimumSize, initialiseToZero);
}
void MemoryBlock::swapWith (MemoryBlock& other) noexcept
{
std::swap (size, other.size);
data.swapWith (other.data);
}
//==============================================================================
void MemoryBlock::fillWith (const uint8 value) noexcept
{
memset (data, (int) value, size);
}
void MemoryBlock::append (const void* const srcData, const size_t numBytes)
{
if (numBytes > 0)
{
jassert (srcData != nullptr); // this must not be null!
const size_t oldSize = size;
setSize (size + numBytes);
memcpy (data + oldSize, srcData, numBytes);
}
}
void MemoryBlock::replaceWith (const void* const srcData, const size_t numBytes)
{
if (numBytes > 0)
{
jassert (srcData != nullptr); // this must not be null!
setSize (numBytes);
memcpy (data, srcData, numBytes);
}
}
void MemoryBlock::insert (const void* const srcData, const size_t numBytes, size_t insertPosition)
{
if (numBytes > 0)
{
jassert (srcData != nullptr); // this must not be null!
insertPosition = jmin (size, insertPosition);
const size_t trailingDataSize = size - insertPosition;
setSize (size + numBytes, false);
if (trailingDataSize > 0)
memmove (data + insertPosition + numBytes,
data + insertPosition,
trailingDataSize);
memcpy (data + insertPosition, srcData, numBytes);
}
}
void MemoryBlock::removeSection (const size_t startByte, const size_t numBytesToRemove)
{
if (startByte + numBytesToRemove >= size)
{
setSize (startByte);
}
else if (numBytesToRemove > 0)
{
memmove (data + startByte,
data + startByte + numBytesToRemove,
size - (startByte + numBytesToRemove));
setSize (size - numBytesToRemove);
}
}
void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) noexcept
{
const char* d = static_cast<const char*> (src);
if (offset < 0)
{
d -= offset;
num += (size_t) -offset;
offset = 0;
}
if ((size_t) offset + num > size)
num = size - (size_t) offset;
if (num > 0)
memcpy (data + offset, d, num);
}
void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const noexcept
{
char* d = static_cast<char*> (dst);
if (offset < 0)
{
zeromem (d, (size_t) -offset);
d -= offset;
num -= (size_t) -offset;
offset = 0;
}
if ((size_t) offset + num > size)
{
const size_t newNum = size - (size_t) offset;
zeromem (d + newNum, num - newNum);
num = newNum;
}
if (num > 0)
memcpy (d, data + offset, num);
}
String MemoryBlock::toString() const
{
return String::fromUTF8 (data, (int) size);
}
//==============================================================================
int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const noexcept
{
int res = 0;
size_t byte = bitRangeStart >> 3;
size_t offsetInByte = bitRangeStart & 7;
size_t bitsSoFar = 0;
while (numBits > 0 && (size_t) byte < size)
{
const size_t bitsThisTime = jmin (numBits, 8 - offsetInByte);
const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
bitsSoFar += bitsThisTime;
numBits -= bitsThisTime;
++byte;
offsetInByte = 0;
}
return res;
}
void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) noexcept
{
size_t byte = bitRangeStart >> 3;
size_t offsetInByte = bitRangeStart & 7;
uint32 mask = ~((((uint32) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
while (numBits > 0 && (size_t) byte < size)
{
const size_t bitsThisTime = jmin (numBits, 8 - offsetInByte);
const uint32 tempMask = (mask << offsetInByte) | ~((((uint32) 0xffffffff) >> offsetInByte) << offsetInByte);
const uint32 tempBits = (uint32) bitsToSet << offsetInByte;
data[byte] = (char) (((uint32) data[byte] & tempMask) | tempBits);
++byte;
numBits -= bitsThisTime;
bitsToSet >>= bitsThisTime;
mask >>= bitsThisTime;
offsetInByte = 0;
}
}
//==============================================================================
void MemoryBlock::loadFromHexString (StringRef hex)
{
ensureSize ((size_t) hex.length() >> 1);
char* dest = data;
String::CharPointerType t (hex.text);
for (;;)
{
int byte = 0;
for (int loop = 2; --loop >= 0;)
{
byte <<= 4;
for (;;)
{
const juce_wchar c = t.getAndAdvance();
if (c >= '0' && c <= '9') { byte |= c - '0'; break; }
if (c >= 'a' && c <= 'z') { byte |= c - ('a' - 10); break; }
if (c >= 'A' && c <= 'Z') { byte |= c - ('A' - 10); break; }
if (c == 0)
{
setSize (static_cast <size_t> (dest - data));
return;
}
}
}
*dest++ = (char) byte;
}
}
//==============================================================================
static const char base64EncodingTable[] = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
String MemoryBlock::toBase64Encoding() const
{
const size_t numChars = ((size << 3) + 5) / 6;
String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
const int initialLen = destString.length();
destString.preallocateBytes (sizeof (String::CharPointerType::CharType) * (size_t) initialLen + 2 + numChars);
String::CharPointerType d (destString.getCharPointer());
d += initialLen;
d.write ('.');
for (size_t i = 0; i < numChars; ++i)
d.write ((juce_wchar) (uint8) base64EncodingTable [getBitRange (i * 6, 6)]);
d.writeNull();
return destString;
}
static const char base64DecodingTable[] =
{
63, 0, 0, 0, 0, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 0, 0, 0, 0, 0, 0, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
0, 0, 0, 0, 0, 0, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52
};
bool MemoryBlock::fromBase64Encoding (StringRef s)
{
String::CharPointerType dot (CharacterFunctions::find (s.text, (juce_wchar) '.'));
if (dot.isEmpty())
return false;
const int numBytesNeeded = String (s.text, dot).getIntValue();
setSize ((size_t) numBytesNeeded, true);
String::CharPointerType srcChars (dot + 1);
int pos = 0;
for (;;)
{
int c = (int) srcChars.getAndAdvance();
if (c == 0)
return true;
c -= 43;
if (isPositiveAndBelow (c, numElementsInArray (base64DecodingTable)))
{
setBitRange ((size_t) pos, 6, base64DecodingTable [c]);
pos += 6;
}
}
}
|
aneeshvartakavi/birdID
|
birdID/JuceLibraryCode/modules/juce_core/memory/juce_MemoryBlock.cpp
|
C++
|
gpl-2.0
| 11,524 |
/*
Wireless charger IDT P9023 Implementation
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/gpio.h>
#include <linux/workqueue.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/asus_bat.h>
#include <linux/asus_chg.h>
#include <linux/i2c.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/module.h>
#include "axc_IDTP9023Charger.h"
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low +++
extern void ASUS_Wireless_set_VDDMAX(void);
extern void IDTP9023_handler_judgeWireless(void);
extern bool g_ASUS_WC_set_low_VDDMAX;
extern bool g_PastTime_set_WC_low_VDD;
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low ---
//ASUS_BSP Eason_Chang:add WirelessChg soft start+++
extern bool g_ASUS_WC_CHG_DONE_set_DCIN300;
extern bool g_PastTime_set_WC_DCIN300;
extern void set_DCIN_300mA(void);
//ASUS_BSP Eason_Chang:add WirelessChg soft start---
extern void msleep(unsigned int msecs);
static u32 g_IDTP9023_slave_addr=0;
static int g_IDTP9023_reg_value=0;
static int g_IDTP9023_reg_address=0;
//Eason: read RxID +++
static int IDTP9023_value_since_reg0xA854_shift[6];
//Eason: read RxID ---
static struct IDTP9023_info *g_IDTP9023_info=NULL;
struct IDTP9023_platform_data{
int intr_gpio;
};
struct IDTP9023_info {
struct i2c_client *i2c_client;
struct IDTP9023_platform_data *pdata;
};
struct IDTP9023_command{
char *name;;
u8 addr;
u8 len;
enum readwrite{
E_READ=0,
E_WRITE=1,
E_READWRITE=2,
E_NOUSE=3,
}rw;
};
enum IDTP9023_CMD_ID {
IDTP9023_CNTL,
};
struct IDTP9023_command IDTP9023_CMD_Table[]={
{"EOP", 0x00, 2, E_READWRITE}, //EOP
};
static int IDTP9023_i2c_read(__u8 *buf_addr, int len, void *data)
{
int i=0;
int retries=6;
int status=0;
struct i2c_msg msg[] = {
{
.addr = g_IDTP9023_slave_addr,
.flags = 0,
.len = 2, // register address len+1:u8 , len+2:u16
.buf = buf_addr,
},
{
.addr = g_IDTP9023_slave_addr,
.flags = I2C_M_RD,
.len = len,
.buf = data,
},
};
pr_debug("[BAT][WC][I2c]IDTP9023_i2c_read+++\n");
if(g_IDTP9023_info){
do{
pr_debug("[BAT][WC][I2c]IDTP9023_i2c_transfer\n");
status = i2c_transfer(g_IDTP9023_info->i2c_client->adapter,
msg, ARRAY_SIZE(msg));
if ((status < 0) && (i < retries)){
msleep(5);
printk("[BAT][WC][I2c]%s retry %d\r\n", __FUNCTION__, i);
i++;
}
} while ((status < 0) && (i < retries));
}
if(status < 0)
{
printk("[BAT][WC][I2c]IDTP9023: i2c read error %d \n", status);
}
pr_debug("[BAT][WC][I2c]IDTP9023_i2c_read---\n");
return status;
}
static int IDTP9023_read_reg(int cmd, void *data)
{
int status=0;
#if 0
if(cmd>=0 && cmd < ARRAY_SIZE(IDTP9023_CMD_Table))
{
if(E_WRITE==IDTP9023_CMD_Table[cmd].rw || E_NOUSE==IDTP9023_CMD_Table[cmd].rw)
{ // skip read for these command
printk("[BAT][WC][I2c]IDTP9023: read ignore cmd\r\n");
}
else
{
pr_debug("[BAT][WC][I2c]IDTP9023_read_reg\n");
status=IDTP9023_i2c_read(IDTP9023_CMD_Table[cmd].addr, IDTP9023_CMD_Table[cmd].len, data);
}
}
else
printk("[BAT][WC][I2c]IDTP9023: unknown read cmd\r\n");
#endif
__u8 buf_addr[3];
buf_addr[0] = 0x88;
buf_addr[1] = 0x00;
//Eason: read RxID +++
if( (4 <= g_IDTP9023_reg_address) && (9 >= g_IDTP9023_reg_address) )
{
buf_addr[0] = 0x88;
buf_addr[1] = 0x04;
}
//Eason: read RxID ---
status=IDTP9023_i2c_read(buf_addr, 1, data);
return status;
}
static void IDTP9023_proc_read(void)
{
int status;
int16_t reg_value=0;//for 2 byte I2c date should use int16_t instead int, let negative value can show correctly. ex:current
printk("[BAT][WC][Proc]%s \r\n", __FUNCTION__);
status=IDTP9023_read_reg(g_IDTP9023_reg_address,®_value);
g_IDTP9023_reg_value = reg_value;
if(status > 0 && reg_value >= 0){
printk("[BAT][WC][Proc] found! IDTP9023=%d\r\n",reg_value);
}
}
//ASUS BSP Eason_Chang IDTP9023 +++
static int IDTP9023_i2c_write(u16 addr, int len, void *data)
{
int i=0;
int status=0;
u8 buf[len + 2]; // register address len+1:u8 , len+2:u16
static struct i2c_msg msg;
int retries = 6;
msg.addr = g_IDTP9023_slave_addr;
msg.flags = 0; //write
msg.len = len + 2, // register address len+1:u8 , len+2:u16
msg.buf = buf;
/*
struct i2c_msg msg[] = {
{
.addr = g_IDTP9023_slave_addr,
.flags = 0,
.len = len + 2, // register address len+1:u8 , len+2:u16
.buf = buf,
},
};
*/
if(3== g_IDTP9023_reg_address)
{
memset(buf, 0, len+2);
buf[0] = 0x88;
buf[1] = 0x00;
memcpy(buf + 2, data, len);//register address buf+1:u8 , buf+2:u16
}
//Eason: read RxID +++
if( (4 <= g_IDTP9023_reg_address) && (9 >= g_IDTP9023_reg_address) )
{
memset(buf, 0, len+2);
buf[0] = 0x88;
buf[1] = 0x01;
memcpy(buf + 2, data, len);//register address buf+1:u8 , buf+2:u16
}
//Eason: read RxID ---
do {
status = i2c_transfer(g_IDTP9023_info->i2c_client->adapter,
&msg, 1);
if ((status < 0) && (i < retries)){
msleep(5);
printk("[BAT][WC][I2c]%s retry %d\r\n", __FUNCTION__, i);
i++;
}
} while ((status < 0) && (i < retries));
if (status < 0)
{
printk("[BAT][WC][I2c]IDTP9023: i2c write error %d \n", status);
}
return status;
}
static int IDTP9023_write_reg(int cmd, void *data)
{
int status=0;
#if 0
if(cmd>=0 && cmd < ARRAY_SIZE(IDTP9023_CMD_Table))
{
if(E_READ==IDTP9023_CMD_Table[cmd].rw || E_NOUSE==IDTP9023_CMD_Table[cmd].rw)
{ // skip read for these command
}
else
status=IDTP9023_i2c_write(IDTP9023_CMD_Table[cmd].addr, IDTP9023_CMD_Table[cmd].len, data);
}
else
printk("[BAT][WC][I2c]IDTP9023: unknown write cmd\r\n");
#endif
uint16_t addr = 0x8800;
if(3== g_IDTP9023_reg_address)
IDTP9023_i2c_write(addr,4,data);
//Eason: read RxID +++
else if( (4 <= g_IDTP9023_reg_address) && (9 >= g_IDTP9023_reg_address) )
{
IDTP9023_i2c_write(addr,3,data);
}
//Eason: read RxID ---
return status;
}
static void IDTP9023_proc_write(void)
{
int status;
uint8_t i2cdata[32]={0};
i2cdata[0] = g_IDTP9023_reg_value;
printk("[BAT][WC][Proc]%s:%d \r\n", __FUNCTION__,g_IDTP9023_reg_value);
if(3 == g_IDTP9023_reg_address)
{
i2cdata[0]=0xAA;
i2cdata[1]=0x00;
i2cdata[2]=0xEF;
i2cdata[3]=0x01;
}
//Eason: read RxID +++
else if( (4 <= g_IDTP9023_reg_address) && (9 >= g_IDTP9023_reg_address) )
{
i2cdata[0]=0xA8;
i2cdata[1]=(0x50 + g_IDTP9023_reg_address);
i2cdata[2]=0x02;
}
//Eason: read RxID ---
status=IDTP9023_write_reg(g_IDTP9023_reg_address,i2cdata);
if(status > 0 ){
printk("[BAT][WC][Proc] proc write\r\n");
}
}
static ssize_t IDTP9023_read_proc(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
IDTP9023_proc_read();
return sprintf(page, "0x%02X\n", g_IDTP9023_reg_value);
}
static ssize_t IDTP9023_write_proc(struct file *filp, const char __user *buff,
unsigned long len, void *data)
{
int val;
char messages[256];
if (len > 256) {
len = 256;
}
if (copy_from_user(messages, buff, len)) {
return -EFAULT;
}
val = (int)simple_strtol(messages, NULL, 10);
g_IDTP9023_reg_value = val;
IDTP9023_proc_write();
printk("[BAT][WC][Proc]mode:%d\n",g_IDTP9023_reg_value);
return len;
}
void static create_IDTP9023_proc_file(void)
{
struct proc_dir_entry *IDTP9023_proc_file = create_proc_entry("driver/IDTP9023", 0644, NULL);
if (IDTP9023_proc_file) {
IDTP9023_proc_file->read_proc = IDTP9023_read_proc;
IDTP9023_proc_file->write_proc = IDTP9023_write_proc;
}
else {
printk("[BAT][WC][Proc]proc file create failed!\n");
}
return;
}
static ssize_t IDTP9023Address_read_proc(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
return sprintf(page, "%d\n", g_IDTP9023_reg_address);
}
static ssize_t IDTP9023Address_write_proc(struct file *filp, const char __user *buff,
unsigned long len, void *data)
{
int val;
char messages[256];
if (len > 256) {
len = 256;
}
if (copy_from_user(messages, buff, len)) {
return -EFAULT;
}
val = (int)simple_strtol(messages, NULL, 10);
g_IDTP9023_reg_address = val;
printk("[BAT][WC][Proc]IDTP9023Address:%d\n",val);
return len;
}
void static create_IDTP9023Address_proc_file(void)
{
struct proc_dir_entry *IDTP9023Address_proc_file = create_proc_entry("driver/IDTP9023Addr", 0644, NULL);
if (IDTP9023Address_proc_file) {
IDTP9023Address_proc_file->read_proc = IDTP9023Address_read_proc;
IDTP9023Address_proc_file->write_proc = IDTP9023Address_write_proc;
}
else {
printk("[BAT][WC][Proc]Addr proc file create failed!\n");
}
return;
}
//Eason: read RxID +++
static void Read_IDTP9023RxID(void)
{
int i;
for(i=0;i<=5;i++)
{
g_IDTP9023_reg_address = i + 4;
IDTP9023_proc_write();
g_IDTP9023_reg_address = 0;
IDTP9023_proc_read();
IDTP9023_value_since_reg0xA854_shift[i] = g_IDTP9023_reg_value;
}
}
static ssize_t IDTP9023RxID_read_proc(char *page, char **start, off_t off, int count,
int *eof, void *data)
{
Read_IDTP9023RxID();
return sprintf(page, "%02X%02X%02X%02X%02X%02X\n", IDTP9023_value_since_reg0xA854_shift[0]
,IDTP9023_value_since_reg0xA854_shift[1]
,IDTP9023_value_since_reg0xA854_shift[2]
,IDTP9023_value_since_reg0xA854_shift[3]
,IDTP9023_value_since_reg0xA854_shift[4]
,IDTP9023_value_since_reg0xA854_shift[5]);
}
static ssize_t IDTP9023RxID_write_proc(struct file *filp, const char __user *buff,
unsigned long len, void *data)
{
int val;
char messages[256];
if (len > 256) {
len = 256;
}
if (copy_from_user(messages, buff, len)) {
return -EFAULT;
}
val = (int)simple_strtol(messages, NULL, 10);
printk("[BAT][WC][Proc]IDTP9023RxID:%d\n",val);
return len;
}
void static create_IDTP9023RxID_proc_file(void)
{
struct proc_dir_entry *IDTP9023RxID_proc_file = create_proc_entry("driver/IDTP9023_RxID", 0644, NULL);
if (IDTP9023RxID_proc_file) {
IDTP9023RxID_proc_file->read_proc = IDTP9023RxID_read_proc;
IDTP9023RxID_proc_file->write_proc = IDTP9023RxID_write_proc;
}
else {
printk("[BAT][WC][Proc][RxID]Addr proc file create failed!\n");
}
return;
}
//Eason: read RxID ---
void IDTP9023_RxTurnOffTx(void)
{
g_IDTP9023_reg_address = 3;
IDTP9023_proc_write();
printk("[BAT][WC]%s\n",__FUNCTION__);
}
extern void asus_chg_set_chg_mode(enum asus_chg_src chg_src);
#define GPIO_WC_PD_DET 20
struct workqueue_struct *wc_intr_wq = NULL;
struct delayed_work wc_worker;
static irqreturn_t wc_pd_det_handler(int irq, void *dev_id)
{
queue_delayed_work(wc_intr_wq, &wc_worker, 0);
printk("[BAT][WC]%s\n",__FUNCTION__);
return IRQ_HANDLED;
}
static IDTP9023_PIN wc_gGpio_pin[]=
{
{//WC_RESET
.gpio = 85,
.name = "WC_RESET",
.in_out_flag = 1,
.init_value = 0,
},
{//WC_PD_DET
.gpio = 20,
.name = "WC_PD_DET",
.in_out_flag = 0,
.handler = wc_pd_det_handler,
.trigger_flag= IRQF_TRIGGER_FALLING|IRQF_TRIGGER_RISING,
},
};
bool Is_WC_connect(void)
{
int connect;
//Eason_Chang: PF500KL WC_PD_DET reverse. default high, with wireless low+++
if(g_ASUS_hwID >= PF500KL_PR){
connect = !gpio_get_value(GPIO_WC_PD_DET);
}else{
connect = gpio_get_value(GPIO_WC_PD_DET);
}
//Eason_Chang: PF500KL WC_PD_DET reverse. default high, with wireless low---
if(connect)
return true;
else
return false;
}
static void wc_work(struct work_struct *dat)
{
//Eason_Chang: PF500KL WC_PD_DET reverse. default high, with wireless low+++
if(g_ASUS_hwID >= PF500KL_PR){
if(1 == !gpio_get_value(GPIO_WC_PD_DET))
{
asus_chg_set_chg_mode(ASUS_CHG_SRC_WC);
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low +++
IDTP9023_handler_judgeWireless();
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low ---
}
else
{
//Eason: read RxID +++
g_IDTP9023_reg_address = 0;//set default
//Eason: read RxID ---
asus_chg_set_chg_mode(ASUS_CHG_SRC_NONE);
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low +++
g_ASUS_WC_set_low_VDDMAX = false;
g_PastTime_set_WC_low_VDD = false;
ASUS_Wireless_set_VDDMAX();
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low ---
//ASUS_BSP Eason_Chang:add WirelessChg soft start+++
g_ASUS_WC_CHG_DONE_set_DCIN300 = false;
g_PastTime_set_WC_DCIN300 = false;
set_DCIN_300mA();
//ASUS_BSP Eason_Chang:add WirelessChg soft start---
}
}else{
//Eason_Chang: PF500KL WC_PD_DET reverse. default high, with wireless low---
if(1 == gpio_get_value(GPIO_WC_PD_DET))
{
asus_chg_set_chg_mode(ASUS_CHG_SRC_WC);
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low +++
IDTP9023_handler_judgeWireless();
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low ---
}
else
{
//Eason: read RxID +++
g_IDTP9023_reg_address = 0;//set default
//Eason: read RxID ---
asus_chg_set_chg_mode(ASUS_CHG_SRC_NONE);
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low +++
g_ASUS_WC_set_low_VDDMAX = false;
g_PastTime_set_WC_low_VDD = false;
ASUS_Wireless_set_VDDMAX();
//ASUS_BSP Eason_Chang: wireless mode (1)Cap>=80% &(2)Temp>45degC set VDD_MAX(0x1040) low ---
//ASUS_BSP Eason_Chang:add WirelessChg soft start+++
g_ASUS_WC_CHG_DONE_set_DCIN300 = false;
g_PastTime_set_WC_DCIN300 = false;
set_DCIN_300mA();
//ASUS_BSP Eason_Chang:add WirelessChg soft start---
}
}
}
static int AXC_IDTP9023_GPIO_setting(void)
{
IDTP9023_PIN_DEF i;
int err = 0;
printk("%s+++\n",__FUNCTION__);
for(i = 0; i< IDTP9023_PIN_COUNT;i++){
//rquest
err = gpio_request(wc_gGpio_pin[i].gpio, wc_gGpio_pin[i].name);
if (err < 0) {
printk("[BAT][WC]gpio_request %s failed,err = %d\n", wc_gGpio_pin[i].name, err);
goto err_exit;
}
//input
if(wc_gGpio_pin[i].in_out_flag == 0){
err = gpio_direction_input(wc_gGpio_pin[i].gpio);
if (err < 0) {
printk( "[BAT][WC]gpio_direction_input %s failed, err = %d\n", wc_gGpio_pin[i].name, err);
goto err_exit;
}
if(wc_gGpio_pin[i].handler != NULL){
wc_gGpio_pin[i].irq = gpio_to_irq(wc_gGpio_pin[i].gpio);
printk("[BAT][WC]:GPIO:%d,IRQ:%d\n",wc_gGpio_pin[i].gpio, wc_gGpio_pin[i].irq);
if(true == wc_gGpio_pin[i].irq_enabled){
enable_irq_wake(wc_gGpio_pin[i].irq);
}
err = request_irq(wc_gGpio_pin[i].irq ,
wc_gGpio_pin[i].handler,
wc_gGpio_pin[i].trigger_flag,
wc_gGpio_pin[i].name,
NULL);
if (err < 0) {
printk( "[BAT][CHG][SMB]request_irq %s failed, err = %d\n",wc_gGpio_pin[i].name,err);
goto err_exit;
}
}
//output
}else{
gpio_direction_output(wc_gGpio_pin[i].gpio, wc_gGpio_pin[i].init_value);
}
}
printk("%s---\n",__FUNCTION__);
return 0;
err_exit:
for(i = 0; i<IDTP9023_PIN_COUNT;i++){
gpio_free(wc_gGpio_pin[i].gpio);
}
printk("[BAT][WC]IDTP9023_Charger_InitGPIO_err_exit\n");
return err;
}
static int IDT_P9023_i2c_probe(struct i2c_client *client, const struct i2c_device_id *devid)
{
struct IDTP9023_info *info;
wc_intr_wq = create_singlethread_workqueue("wirelessChg_intr_wq");
INIT_DELAYED_WORK(&wc_worker,wc_work);
//Eason when device boot on wireless Tx, set wireless charging status +++
queue_delayed_work(wc_intr_wq, &wc_worker, 10 * HZ);
//Eason when device boot on wireless Tx, set wireless charging status ---
printk("%s+++\n",__FUNCTION__);
g_IDTP9023_info=info = kzalloc(sizeof(struct IDTP9023_info), GFP_KERNEL);
g_IDTP9023_slave_addr=client->addr;
info->i2c_client = client;
i2c_set_clientdata(client, info);
create_IDTP9023_proc_file();
create_IDTP9023Address_proc_file();
//Eason: read RxID +++
create_IDTP9023RxID_proc_file();
//Eason: read RxID ---
if (0 != AXC_IDTP9023_GPIO_setting())
{
printk( "[BAT][WC]Charger gpio can't init\n");
}
printk("%s---\n",__FUNCTION__);
return 0;
}
static int IDT_P9023_i2c_remove(struct i2c_client *client)
{
return 0;
}
const struct i2c_device_id IDTP9023_i2c_id[] = {
{"IDT_P9023_i2c", 0},
{}
};
MODULE_DEVICE_TABLE(i2c, IDTP9023_i2c_id);
static struct of_device_id IDTP9023_match_table[] = {
{ .compatible = "IDT,P9023",},
{ },
};
static struct i2c_driver IDTP9023_i2c_driver = {
.driver = {
.name = "IDT_P9023_i2c",
.owner = THIS_MODULE,
.of_match_table = IDTP9023_match_table,
},
.probe = IDT_P9023_i2c_probe,
.remove = IDT_P9023_i2c_remove,
.id_table = IDTP9023_i2c_id,
};
static int __init IDTP9023_init(void)
{
printk("[BAT][IDTP9023]init\n");
//Eason_Chang:A90FF dont do wireless charger+++
if(g_ASUS_hwID == A90_EVB0)
{
printk("[BAT]%s FAIL\n",__FUNCTION__);
return -EINVAL;
}
//Eason_Chang:A90FF dont do wireless charger---
return i2c_add_driver(&IDTP9023_i2c_driver);
}
static void __exit IDTP9023_exit(void)
{
printk("[BAT][IDTP9023]exit\n");
i2c_del_driver(&IDTP9023_i2c_driver);
}
module_init(IDTP9023_init);
module_exit(IDTP9023_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("ASUS Wireless charger IDTP9023 driver");
MODULE_VERSION("1.0");
MODULE_AUTHOR("Eason Chang <[email protected]>");
|
shakalaca/ASUS_PadFone_PF500KL
|
kernel/drivers/power/charger/axc_IDTP9023Charger.c
|
C
|
gpl-2.0
| 18,545 |
/* 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.
*
* 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.
*
* $URL: https://scummvm.svn.sourceforge.net/svnroot/scummvm/scummvm/tags/release-1-1-1/engines/groovie/music.cpp $
* $Id: music.cpp 47333 2010-01-16 21:34:36Z fingolfin $
*
*/
#include "groovie/music.h"
#include "groovie/resource.h"
#include "common/config-manager.h"
#include "sound/audiocd.h"
namespace Groovie {
// MusicPlayer
MusicPlayer::MusicPlayer(GroovieEngine *vm) :
_vm(vm), _isPlaying(false), _backgroundFileRef(0), _gameVolume(100),
_prevCDtrack(0), _backgroundDelay(0) {
}
MusicPlayer::~MusicPlayer() {
AudioCD.stop();
}
void MusicPlayer::playSong(uint32 fileref) {
Common::StackLock lock(_mutex);
// Set the volumes
_fadingEndVolume = 100;
_gameVolume = 100;
// Play the referenced file once
play(fileref, false);
}
void MusicPlayer::setBackgroundSong(uint32 fileref) {
Common::StackLock lock(_mutex);
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Changing the background song: %04X", fileref);
_backgroundFileRef = fileref;
}
void MusicPlayer::frameTick() {
if (_backgroundDelay > 0) {
_backgroundDelay--;
if (_backgroundDelay == 0)
playSong(_backgroundFileRef);
}
}
void MusicPlayer::setBackgroundDelay(uint16 delay) {
_backgroundDelay = delay;
}
void MusicPlayer::playCD(uint8 track) {
int startms = 0;
// Stop the MIDI playback
unload();
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Playing CD track %d", track);
if (track == 3) {
// This is the credits song, start at 23:20
startms = 1400000;
// TODO: If we want to play it directly from the CD, we should decrement
// the song number (it's track 2 on the 2nd CD)
} else if ((track == 98) && (_prevCDtrack == 3)) {
// Track 98 is used as a hack to stop the credits song
AudioCD.stop();
return;
}
// Save the playing track in order to be able to stop the credits song
_prevCDtrack = track;
// Wait until the CD stops playing the current song
// It was in the original interpreter, but it introduces a big delay
// in the middle of the introduction, so it's disabled right now
/*
AudioCD.updateCD();
while (AudioCD.isPlaying()) {
// Wait a bit and try again
_vm->_system->delayMillis(100);
AudioCD.updateCD();
}
*/
// Play the track starting at the requested offset (1000ms = 75 frames)
AudioCD.play(track - 1, 1, startms * 75 / 1000, 0);
}
void MusicPlayer::startBackground() {
debugC(3, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: startBackground()");
if (!_isPlaying && _backgroundFileRef) {
debugC(3, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Starting the background song (0x%4X)", _backgroundFileRef);
play(_backgroundFileRef, true);
}
}
void MusicPlayer::setUserVolume(uint16 volume) {
Common::StackLock lock(_mutex);
// Save the new user volume
_userVolume = volume;
if (_userVolume > 0x100)
_userVolume = 0x100;
// Apply it
updateVolume();
}
void MusicPlayer::setGameVolume(uint16 volume, uint16 time) {
Common::StackLock lock(_mutex);
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Setting game volume from %d to %d in %dms", _gameVolume, volume, time);
// Save the start parameters of the fade
_fadingStartTime = _vm->_system->getMillis();
_fadingStartVolume = _gameVolume;
_fadingDuration = time;
// Save the new game volume
_fadingEndVolume = volume;
if (_fadingEndVolume > 100)
_fadingEndVolume = 100;
}
bool MusicPlayer::play(uint32 fileref, bool loop) {
// Unload the previous song
unload();
// Set the new state
_isPlaying = true;
// Load the new file
return load(fileref, loop);
}
void MusicPlayer::applyFading() {
debugC(6, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: applyFading() _fadingStartTime = %d, _fadingDuration = %d, _fadingStartVolume = %d, _fadingEndVolume = %d", _fadingStartTime, _fadingDuration, _fadingStartVolume, _fadingEndVolume);
Common::StackLock lock(_mutex);
// Calculate the passed time
uint32 time = _vm->_system->getMillis() - _fadingStartTime;
debugC(6, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: time = %d, _gameVolume = %d", time, _gameVolume);
if (time >= _fadingDuration) {
// Set the end volume
_gameVolume = _fadingEndVolume;
} else {
// Calculate the interpolated volume for the current time
_gameVolume = (_fadingStartVolume * (_fadingDuration - time) +
_fadingEndVolume * time) / _fadingDuration;
}
if (_gameVolume == _fadingEndVolume) {
// If we were fading to 0, stop the playback and restore the volume
if (_fadingEndVolume == 0) {
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Faded to zero: end of song. _fadingEndVolume set to 100");
unload();
}
}
// Apply it
updateVolume();
}
void MusicPlayer::onTimer(void *refCon) {
debugC(9, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: onTimer()");
MusicPlayer *music = (MusicPlayer *)refCon;
Common::StackLock lock(music->_mutex);
// Apply the game volume fading
if (music->_gameVolume != music->_fadingEndVolume) {
// Apply the next step of the fading
music->applyFading();
}
// Handle internal timed events
music->onTimerInternal();
}
void MusicPlayer::unload() {
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Stopping the playback");
// Set the new state
_isPlaying = false;
}
// MusicPlayerMidi
MusicPlayerMidi::MusicPlayerMidi(GroovieEngine *vm) :
MusicPlayer(vm), _midiParser(NULL), _data(NULL), _driver(NULL) {
// Initialize the channel volumes
for (int i = 0; i < 0x10; i++) {
_chanVolumes[i] = 0x7F;
}
}
MusicPlayerMidi::~MusicPlayerMidi() {
// Stop the callback
if (_driver)
_driver->setTimerCallback(NULL, NULL);
Common::StackLock lock(_mutex);
// Unload the parser
unload();
delete _midiParser;
// Unload the MIDI Driver
if (_driver)
_driver->close();
delete _driver;
}
int MusicPlayerMidi::open() {
// Don't ever call open without first setting the output driver!
if (!_driver)
return 255;
int ret = _driver->open();
if (ret)
return ret;
return 0;
}
void MusicPlayerMidi::close() {}
void MusicPlayerMidi::send(uint32 b) {
if ((b & 0xFFF0) == 0x07B0) { // Volume change
// Save the specific channel volume
byte chan = b & 0xF;
_chanVolumes[chan] = (b >> 16) & 0x7F;
// Send the updated value
updateChanVolume(chan);
return;
}
if (_driver)
_driver->send(b);
}
void MusicPlayerMidi::metaEvent(byte type, byte *data, uint16 length) {
switch (type) {
case 0x2F:
// End of Track, play the background song
endTrack();
break;
default:
if (_driver)
_driver->metaEvent(type, data, length);
break;
}
}
void MusicPlayerMidi::setTimerCallback(void *timer_param, Common::TimerManager::TimerProc timer_proc) {
if (_driver)
_driver->setTimerCallback(timer_param, timer_proc);
}
uint32 MusicPlayerMidi::getBaseTempo() {
if (_driver)
return _driver->getBaseTempo();
else
return 0;
}
MidiChannel *MusicPlayerMidi::allocateChannel() {
if (_driver)
return _driver->allocateChannel();
else
return 0;
}
MidiChannel *MusicPlayerMidi::getPercussionChannel() {
if (_driver)
return _driver->getPercussionChannel();
else
return 0;
}
void MusicPlayerMidi::updateChanVolume(byte channel) {
// Generate a MIDI Control change message for the volume
uint32 b = 0x7B0;
// Specify the channel
b |= (channel & 0xF);
// Scale by the user and game volumes
uint32 val = (_chanVolumes[channel] * _userVolume * _gameVolume) / 0x100 / 100;
val &= 0x7F;
// Send it to the driver
if (_driver)
_driver->send(b | (val << 16));
}
void MusicPlayerMidi::endTrack() {
debugC(3, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: endTrack()");
unload();
}
void MusicPlayerMidi::onTimerInternal() {
// TODO: We really only need to call this while music is playing.
if (_midiParser)
_midiParser->onTimer();
}
void MusicPlayerMidi::updateVolume() {
// Apply it to all the channels
for (int i = 0; i < 0x10; i++) {
updateChanVolume(i);
}
}
void MusicPlayerMidi::unload() {
MusicPlayer::unload();
// Unload the parser data
if (_midiParser)
_midiParser->unloadMusic();
// Unload the data
delete[] _data;
_data = NULL;
}
bool MusicPlayerMidi::loadParser(Common::SeekableReadStream *stream, bool loop) {
if (!_midiParser)
return false;
// Read the whole file to memory
int length = stream->size();
_data = new byte[length];
stream->read(_data, length);
delete stream;
// Set the looping option
_midiParser->property(MidiParser::mpAutoLoop, loop);
// Start parsing the data
if (!_midiParser->loadMusic(_data, length)) {
error("Groovie::Music: Couldn't parse the data");
return false;
}
// Activate the timer source
if (_driver)
_driver->setTimerCallback(this, &onTimer);
return true;
}
// MusicPlayerXMI
MusicPlayerXMI::MusicPlayerXMI(GroovieEngine *vm, const Common::String >lName) :
MusicPlayerMidi(vm) {
// Create the parser
_midiParser = MidiParser::createParser_XMIDI();
// Create the driver
MidiDriverType driver = detectMusicDriver(MDT_MIDI | MDT_ADLIB | MDT_PREFER_MIDI);
_driver = createMidi(driver);
this->open();
// Set the parser's driver
_midiParser->setMidiDriver(this);
// Set the timer rate
_midiParser->setTimerRate(_driver->getBaseTempo());
// Initialize the channel banks
for (int i = 0; i < 0x10; i++) {
_chanBanks[i] = 0;
}
// Load the Global Timbre Library
if (driver == MD_ADLIB) {
// MIDI through AdLib
_musicType = MD_ADLIB;
loadTimbres(gtlName + ".ad");
// Setup the percussion channel
for (uint i = 0; i < _timbres.size(); i++) {
if (_timbres[i].bank == 0x7F)
setTimbreAD(9, _timbres[i]);
}
} else if ((driver == MD_MT32) || ConfMan.getBool("native_mt32")) {
// MT-32
_musicType = MD_MT32;
loadTimbres(gtlName + ".mt");
} else {
// GM
_musicType = 0;
}
}
MusicPlayerXMI::~MusicPlayerXMI() {
//~MusicPlayer();
// Unload the timbres
clearTimbres();
}
void MusicPlayerXMI::send(uint32 b) {
if ((b & 0xFFF0) == 0x72B0) { // XMIDI Patch Bank Select 114
// From AIL2's documentation: XMIDI Patch Bank Select controller (114)
// selects a bank to be used when searching the next patches
byte chan = b & 0xF;
byte bank = (b >> 16) & 0xFF;
debugC(5, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Selecting bank %X for channel %X", bank, chan);
_chanBanks[chan] = bank;
return;
} else if ((b & 0xF0) == 0xC0) { // Program change
// We intercept the program change when using AdLib or MT32 drivers,
// since we have custom timbres for them. The command is sent
// unchanged to GM drivers.
if (_musicType != 0) {
byte chan = b & 0xF;
byte patch = (b >> 8) & 0xFF;
debugC(5, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Setting custom patch %X from bank %X to channel %X", patch, _chanBanks[chan], chan);
// Try to find the requested patch from the previously
// specified bank
int numTimbres = _timbres.size();
for (int i = 0; i < numTimbres; i++) {
if ((_timbres[i].bank == _chanBanks[chan]) &&
(_timbres[i].patch == patch)) {
if (_musicType == MD_ADLIB) {
setTimbreAD(chan, _timbres[i]);
} else if (_musicType == MD_MT32) {
setTimbreMT(chan, _timbres[i]);
}
return;
}
}
// If we got here we couldn't find the patch, and the
// received message will be sent unchanged.
}
}
MusicPlayerMidi::send(b);
}
bool MusicPlayerXMI::load(uint32 fileref, bool loop) {
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Starting the playback of song: %04X", fileref);
// Open the song resource
Common::SeekableReadStream *file = _vm->_resMan->open(fileref);
if (!file) {
error("Groovie::Music: Couldn't find resource 0x%04X", fileref);
return false;
}
return loadParser(file, loop);
}
void MusicPlayerXMI::loadTimbres(const Common::String &filename) {
// Load the Global Timbre Library format as documented in AIL2
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Loading the GTL file %s", filename.c_str());
// Does it exist?
if (!Common::File::exists(filename)) {
error("Groovie::Music: %s not found", filename.c_str());
return;
}
// Open the GTL
Common::File *gtl = new Common::File();
if (!gtl->open(filename.c_str())) {
delete gtl;
error("Groovie::Music: Couldn't open %s", filename.c_str());
return;
}
// Clear the old timbres before loading the new ones
clearTimbres();
// Get the list of timbres
while (true) {
Timbre t;
t.patch = gtl->readByte();
t.bank = gtl->readByte();
if ((t.patch == 0xFF) && (t.bank == 0xFF)) {
// End of list
break;
}
// We temporarily use the size field to store the offset
t.size = gtl->readUint32LE();
// Add it to the list
_timbres.push_back(t);
}
// Read the timbres
for (unsigned int i = 0; i < _timbres.size(); i++) {
// Seek to the start of the timbre
gtl->seek(_timbres[i].size);
// Read the size
_timbres[i].size = gtl->readUint16LE() - 2;
// Allocate memory for the timbre data
_timbres[i].data = new byte[_timbres[i].size];
// Read the timbre data
gtl->read(_timbres[i].data, _timbres[i].size);
debugC(5, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Loaded patch %x in bank %x with size %d",
_timbres[i].patch, _timbres[i].bank, _timbres[i].size);
}
// Close the file
delete gtl;
}
void MusicPlayerXMI::clearTimbres() {
// Delete the allocated data
int num = _timbres.size();
for (int i = 0; i < num; i++) {
delete[] _timbres[i].data;
}
// Erase the array entries
_timbres.clear();
}
void MusicPlayerXMI::setTimbreAD(byte channel, const Timbre &timbre) {
// Verify the timbre size
if (timbre.size != 12) {
error("Groovie::Music: Invalid size for an AdLib timbre: %d", timbre.size);
}
// Prepare the AdLib Instrument array from the GTL entry
//
// struct AdLibInstrument used by our AdLib MIDI synth is 30 bytes.
// Since we pass data + 2 for non percussion instruments we need to
// have a buffer of size 32, so there are no invalid memory reads,
// when setting up an AdLib instrument.
byte data[32];
memset(data, 0, sizeof(data));
data[2] = timbre.data[1]; // mod_characteristic
data[3] = timbre.data[2] ^ 0x3F; // mod_scalingOutputLevel
data[4] = ~timbre.data[3]; // mod_attackDecay
data[5] = ~timbre.data[4]; // mod_sustainRelease
data[6] = timbre.data[5]; // mod_waveformSelect
data[7] = timbre.data[7]; // car_characteristic
data[8] = timbre.data[8] ^ 0x3F; // car_scalingOutputLevel
data[9] = ~timbre.data[9]; // car_attackDecay
data[10] = ~timbre.data[10]; // car_sustainRelease
data[11] = timbre.data[11]; // car_waveformSelect
data[12] = timbre.data[6]; // feedback
// Send the instrument to the driver
if (timbre.bank == 0x7F) {
// This is a Percussion instrument, this will always be set on the same note
data[0] = timbre.patch;
// From AIL2's documentation: If the instrument is to be played in MIDI
// channel 10, num specifies its desired absolute MIDI note number.
data[1] = timbre.data[0];
_driver->getPercussionChannel()->sysEx_customInstrument('ADLP', data);
} else {
// Some tweaks for non-percussion instruments
byte mult1 = timbre.data[1] & 0xF;
if (mult1 < 4)
mult1 = 1 << mult1;
data[2] = (timbre.data[1] & 0xF0) + (mult1 & 0xF);
byte mult2 = timbre.data[7] & 0xF;
if (mult2 < 4)
mult2 = 1 << mult2;
data[7] = (timbre.data[7] & 0xF0) + (mult2 & 0xF);
// TODO: Fix CHARACTERISTIC: 0xF0: pitch_vib, amp_vib, sustain_sound, env_scaling 0xF: freq_mult
// TODO: Fix KSL_TL: 0xC: key_scale_lvl 0x3F: out_lvl
// From AIL2's documentation: num specifies the number of semitones
// by which to transpose notes played with the instrument.
if (timbre.data[0] != 0)
warning("Groovie::Music: AdLib instrument's transposing not supported");
_driver->sysEx_customInstrument(channel, 'ADL ', data + 2);
}
}
void MusicPlayerXMI::setTimbreMT(byte channel, const Timbre &timbre) {
// Verify the timbre size
if (timbre.size != 0xF6) {
error("Groovie::Music: Invalid size for an MT-32 timbre: %d", timbre.size);
}
// Show the timbre name as extra debug information
Common::String name((char*)timbre.data, 10);
debugC(5, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Using MT32 timbre: %s", name.c_str());
// TODO: Support MT-32 custom instruments
warning("Groovie::Music: Setting MT32 custom instruments isn't supported yet");
}
// MusicPlayerMac
MusicPlayerMac::MusicPlayerMac(GroovieEngine *vm) :
MusicPlayerMidi(vm) {
}
bool MusicPlayerMac::load(uint32 fileref, bool loop) {
debugC(1, kGroovieDebugMIDI | kGroovieDebugAll, "Groovie::Music: Starting the playback of song: %04X", fileref);
debug("Groovie::Music: Starting the playback of song: %04X %d", fileref, fileref);
// Open the song resource
/*
Common::SeekableReadStream *file = _vm->_resMan->open(fileref);
if (!file) {
error("Groovie::Music: Couldn't find resource 0x%04X", fileref);
return false;
}
*/
//return loadParser(file, loop);
return false;
}
} // End of Groovie namespace
|
DerKnob/scummvm-for-sally
|
engines/groovie/music.cpp
|
C++
|
gpl-2.0
| 18,641 |
/*
* Copyright (c) 1997, 2019, 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.
*
*/
#ifndef SHARE_OOPS_INSTANCEOOP_HPP
#define SHARE_OOPS_INSTANCEOOP_HPP
#include "oops/oop.hpp"
// An instanceOop is an instance of a Java Class
// Evaluating "new HashTable()" will create an instanceOop.
class instanceOopDesc : public oopDesc {
public:
// aligned header size.
static int header_size() { return sizeof(instanceOopDesc)/HeapWordSize; }
// If compressed, the offset of the fields of the instance may not be aligned.
static int base_offset_in_bytes() {
// offset computation code breaks if UseCompressedClassPointers
// only is true
return (UseCompressedOops && UseCompressedClassPointers) ?
klass_gap_offset_in_bytes() :
sizeof(instanceOopDesc);
}
static bool contains_field_offset(int offset, int nonstatic_field_size) {
int base_in_bytes = base_offset_in_bytes();
return (offset >= base_in_bytes &&
(offset-base_in_bytes) < nonstatic_field_size * heapOopSize);
}
};
#endif // SHARE_OOPS_INSTANCEOOP_HPP
|
md-5/jdk10
|
src/hotspot/share/oops/instanceOop.hpp
|
C++
|
gpl-2.0
| 2,058 |
DROP TABLE `#__{COMPONENT_NAME}_{CONTROLLER_NAMES}`
|
asikatw/ref-legacy
|
cli/akbuilder/tmpl/component/subsystem.site/sql/uninstall.sql
|
SQL
|
gpl-2.0
| 52 |
using System;
using System.Collections.Generic;
using Server;
using Server.Mobiles;
using Server.Items;
using Server.Gumps;
using Server.Engines.PartySystem;
using System.Linq;
namespace Server.Engines.Shadowguard
{
[PropertyObject]
public abstract class ShadowguardEncounter
{
[CommandProperty(AccessLevel.GameMaster)]
public ShadowguardController Controller { get { return ShadowguardController.Instance; } }
public Rectangle2D[] Bounds { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public ShadowguardRegion Region { get { return Instance.Region; } }
[CommandProperty(AccessLevel.GameMaster)]
public Point3D StartLoc { get { return Def.StartLoc; } }
public Point3D[] SpawnPoints { get { return Def.SpawnPoints; } }
public Rectangle2D[] SpawnRecs { get { return Def.SpawnRecs; } }
[CommandProperty(AccessLevel.GameMaster)]
public EncounterType Encounter { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public bool HasBegun { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public bool DoneWarning { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public DateTime StartTime { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public Mobile PartyLeader { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public ShadowguardInstance Instance { get; set; }
[CommandProperty(AccessLevel.GameMaster)]
public bool ForceExpire
{
get { return false; }
set
{
if (value)
Expire();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool ForceComplete
{
get { return false; }
set
{
if (value)
CompleteEncounter();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public BaseAddon Addon { get; set; }
public abstract Type AddonType { get; }
public EncounterDef Def { get { return Defs[Encounter]; } }
public virtual TimeSpan EncounterDuration { get { return TimeSpan.FromMinutes(30); } }
public virtual TimeSpan ResetDuration { get { return TimeSpan.FromSeconds(60); } }
[CommandProperty(AccessLevel.GameMaster)]
public bool Active { get { return Controller != null && Controller.Encounters.Contains(this); } }
public List<PlayerMobile> Participants { get; private set; } = new List<PlayerMobile>();
public ShadowguardEncounter(EncounterType encounter, ShadowguardInstance instance = null)
{
Encounter = encounter;
Instance = instance;
if(instance != null)
instance.Encounter = this;
}
public override string ToString()
{
return Encounter.ToString();
}
public int PartySize()
{
if (PartyLeader == null || this.Region == null)
return 0;
int inRegion = this.Region.GetPlayerCount();
if (inRegion > 0)
return inRegion;
Party p = Party.Get(PartyLeader);
if (p == null)
return 1;
return p.Members.Count;
}
public void OnBeforeBegin(Mobile m)
{
PartyLeader = m;
StartTime = DateTime.UtcNow;
DoneWarning = false;
Setup();
SendPartyMessage(1156185);
/*Please wait while your Shadowguard encounter is prepared.
Do no leave the area or logoff during this time. You will
teleported when the encounter is ready and if you leave
there is no way to enter once the encounter begins.*/
CheckAddon();
Timer.DelayCall(ShadowguardController.ReadyDuration, OnBeginEncounter);
}
public void CheckAddon()
{
Type addon = AddonType;
if (addon == null)
return;
BaseAddon ad = Controller.Addons.FirstOrDefault(a => a.GetType() == addon && a.Map == Map.Internal);
if (ad == null)
{
ad = Activator.CreateInstance(addon) as BaseAddon;
Controller.Addons.Add(ad);
}
ad.MoveToWorld(new Point3D(Instance.Center.X - 1, Instance.Center.Y - 1, Instance.Center.Z), Map.TerMur);
Addon = ad;
}
public void OnBeginEncounter()
{
AddPlayers(PartyLeader);
HasBegun = true;
SendPartyMessage(1156251, 0x20);
//There is a 30 minute time limit for each encounter. You will receive a time limit warning at 5 minutes.
}
public void AddPlayers(Mobile m)
{
if(m == null || !m.Alive || !m.InRange(Controller.Location, 25) || m.NetState == null)
{
Reset(true);
}
else
{
Party p = Party.Get(m);
if(p != null)
{
foreach (var pm in p.Members.Select(x => x.Mobile))
{
AddPlayer(pm);
}
}
AddPlayer(m);
}
}
protected void SendPartyMessage(int cliloc, int hue = 0x3B2)
{
if (HasBegun)
{
foreach (var pm in Region.GetEnumeratedMobiles().OfType<PlayerMobile>())
{
pm.SendLocalizedMessage(cliloc, null, hue);
}
}
else
{
if (PartyLeader == null)
return;
Party p = Party.Get(PartyLeader);
if (p != null)
p.Members.ForEach(info => info.Mobile.SendLocalizedMessage(cliloc, null, hue));
else
PartyLeader.SendLocalizedMessage(cliloc, null, hue);
}
}
protected void SendPartyMessage(string message, int hue = 0x3B2)
{
if (HasBegun)
{
foreach (var pm in Region.GetEnumeratedMobiles().OfType<PlayerMobile>())
{
pm.SendMessage(hue, message);
}
}
else
{
if (PartyLeader == null)
return;
Party p = Party.Get(PartyLeader);
if (p != null)
p.Members.ForEach(info => info.Mobile.SendMessage(hue, message));
else
PartyLeader.SendMessage(hue, message);
}
}
public void AddPlayer(Mobile m)
{
Point3D p = StartLoc;
ConvertOffset(ref p);
MovePlayer(m, p);
m.CloseGump(typeof(ShadowguardGump));
if (m is PlayerMobile)
{
Participants.Add((PlayerMobile)m);
}
}
public void DoWarning()
{
ColUtility.ForEach(this.Region.GetEnumeratedMobiles().Where(m => m is PlayerMobile), m =>
{
m.SendLocalizedMessage(1156252); // You have 5 minutes remaining in the encounter!
});
DoneWarning = true;
}
public virtual void Expire(bool message = true)
{
if(message)
{
ColUtility.ForEach(this.Region.GetEnumeratedMobiles().Where(m => m is PlayerMobile), m =>
{
m.SendLocalizedMessage(1156253, "", 0x32); // The encounter timer has expired!
});
}
Timer.DelayCall(TimeSpan.FromSeconds(5), () =>
{
Reset(true);
});
}
public virtual void CompleteEncounter()
{
if (Completed)
return;
Timer.DelayCall(ResetDuration, () =>
{
Reset();
});
if (this is RoofEncounter)
SendPartyMessage(1156250); // Congratulations! You have bested Shadowguard and prevented Minax from exploiting the Time Gate! You will be teleported out in a few minutes.
else
SendPartyMessage(1156244); //You have bested this tower of Shadowguard! You will be teleported out of the tower in 60 seconds!
Completed = true;
}
public virtual void Reset(bool expired = false)
{
if (!Active)
return;
Controller.OnEncounterComplete(this, expired);
RemovePlayers();
PartyLeader = null;
HasBegun = false;
ClearItems();
if (Addon != null)
{
Addon.Internalize();
Addon = null;
}
Instance.ClearRegion();
Instance.CompleteEncounter();
}
private void RemovePlayers()
{
ColUtility.ForEach(Region.GetEnumeratedMobiles().Where(
m => m is PlayerMobile ||
(m is BaseCreature &&
((BaseCreature)m).GetMaster() is PlayerMobile)),
m =>
{
MovePlayer(m, Controller.KickLocation, false);
if (m is PlayerMobile && Participants.Contains((PlayerMobile)m))
{
Participants.Remove((PlayerMobile)m);
}
});
}
public static void MovePlayer(Mobile m, Point3D p, bool pets = true)
{
if (pets)
BaseCreature.TeleportPets(m, p, m.Map);
m.MoveToWorld(p, m.Map);
Effects.SendLocationParticles(EffectItem.Create(m.Location, m.Map, EffectItem.DefaultDuration), 0x3728, 10, 10, 5023);
m.PlaySound(0x1FE);
}
public virtual void OnTick()
{
}
public virtual void ClearItems()
{
}
public virtual void Setup()
{
}
public virtual void CheckEncounter()
{
}
public virtual void OnCreatureKilled(BaseCreature bc)
{
}
public void CheckPlayerStatus(Mobile m)
{
if (m is PlayerMobile)
{
foreach (var pm in Region.GetEnumeratedMobiles().OfType<PlayerMobile>())
{
if (pm.Alive && pm.NetState != null)
{
return;
}
}
Expire(false);
SendPartyMessage(1156267); // All members of your party are dead, have logged off, or have chosen to exit Shadowguard. You will be removed from the encounter shortly.
}
}
public void ConvertOffset(ref Point3D p)
{
p = new Point3D(Instance.Center.X + p.X, Instance.Center.Y + p.Y, Instance.Center.Z + p.Z);
}
public void ConvertOffset(ref Rectangle2D rec)
{
rec = new Rectangle2D(Instance.Center.X + rec.X, Instance.Center.Y + rec.Y, rec.Width, rec.Height);
}
public virtual void Serialize(GenericWriter writer)
{
writer.Write(2);
writer.WriteMobileList<PlayerMobile>(Participants);
writer.WriteDeltaTime(StartTime);
writer.Write(Completed);
writer.Write(HasBegun);
writer.Write(Instance.Index);
writer.Write(PartyLeader);
writer.Write(Addon);
}
public virtual void Deserialize(GenericReader reader)
{
int version = reader.ReadInt();
switch (version)
{
case 2:
Participants = reader.ReadStrongMobileList<PlayerMobile>();
goto case 1;
case 1:
StartTime = reader.ReadDeltaTime();
Completed = reader.ReadBool();
HasBegun = reader.ReadBool();
goto case 0;
case 0:
Instance = Controller.Instances[reader.ReadInt()];
PartyLeader = reader.ReadMobile();
Addon = reader.ReadItem() as BaseAddon;
break;
}
if (Instance != null)
{
Instance.Encounter = this;
}
if (Completed)
{
Timer.DelayCall(ResetDuration, () =>
{
Reset();
});
}
}
public static Dictionary<EncounterType, EncounterDef> Defs { get; set; }
public static void Configure()
{
Defs = new Dictionary<EncounterType, EncounterDef>();
Defs[EncounterType.Bar] = new EncounterDef(
new Point3D(0, 0, 0),
new Point3D[] { new Point3D(-16, 8, 0), new Point3D(-16, 4, 0), new Point3D(-16, -6, 0), new Point3D(-16, -10, 0) },
new Rectangle2D[] { new Rectangle2D(-15, -12, 1, 8), new Rectangle2D(-15, 2, 1, 8) });
Defs[EncounterType.Orchard] = new EncounterDef(
new Point3D(0, 0, 0),
new Point3D[] { new Point3D(-10, -11, 0), new Point3D(-18, -15, 0), new Point3D(-11, -19, 0), new Point3D(-17, -10, 0),
new Point3D(-21, 10, 0), new Point3D(-17, 16, 0), new Point3D(-13, 12, 0), new Point3D(-11, 18, 0),
new Point3D(10, -20, 0), new Point3D(10, -11, 0), new Point3D(14, -15, 0), new Point3D(17, -10, 0),
new Point3D(10, 10, 0), new Point3D(9, 16, 0), new Point3D(13, 16, 0), new Point3D(15, 10, 0)},
new Rectangle2D[] { });
Defs[EncounterType.Armory] = new EncounterDef(
new Point3D(0, 0, 0),
new Point3D[] { new Point3D(5, -7, 0), new Point3D(5, -9, 0), new Point3D(5, -11, 0), new Point3D(5, -13, 0),
new Point3D(5, -17, 0), new Point3D(5, -19, 0), new Point3D(5, -21, 0), new Point3D(5, 16, 0),
new Point3D(5, 18, 0), new Point3D(5, 11, 0), new Point3D(5, 9, 0),
new Point3D(-23, -10, 0), new Point3D(-20, -15, 0), new Point3D(-16, -19, 0),
new Point3D(9, 5, 0), new Point3D(11, 5, 0), new Point3D(16, 5, 0), new Point3D(18, 5, 0),
new Point3D(-21, 5, 0), new Point3D(-19, 5, 0), new Point3D(-17, 5, 0), new Point3D(-12, 5, 0),
new Point3D(-10, 5, 0), new Point3D(-8, 5, 0), new Point3D(-23, 5, 0),
new Point3D(-18, -17, 0), new Point3D(-10, -23, 0), new Point3D(-13, -21, 0)},
new Rectangle2D[] { new Rectangle2D(-25, -24, 18, 18), new Rectangle2D(-25, 4, 18, 18), new Rectangle2D(4, 20, 18, 18), new Rectangle2D(4, -6, 18, 18), });
Defs[EncounterType.Fountain] = new EncounterDef(
new Point3D(11, 11, 0),
new Point3D[] { new Point3D(-6, 7, 0), new Point3D(5, 7, 0), new Point3D(7, 5, 0), new Point3D(7, -6, 0) },
new Rectangle2D[] { new Rectangle2D(-24, 8, 45, 17), new Rectangle2D(-24, -25, 45, 16), new Rectangle2D(-25, -8, 16, 15), new Rectangle2D(8, -8, 16, 15 ),
new Rectangle2D(12, -4, 2, 6), new Rectangle2D(-4, 12, 6, 2)});
Defs[EncounterType.Belfry] = new EncounterDef(
new Point3D(15, 1, 0),
new Point3D[] { new Point3D(0, 0, 22), new Point3D(-5, -5, 22) },
new Rectangle2D[] { new Rectangle2D(8, -9, 15, 15), new Rectangle2D(-24, -9, 15, 18) });
Defs[EncounterType.Roof] = new EncounterDef(
new Point3D(-8, -8, 0),
new Point3D[] { new Point3D(0, 0, 30) },
new Rectangle2D[] { });
}
public static ShadowguardEncounter ConstructEncounter(EncounterType type)
{
switch (type)
{
default:
case EncounterType.Bar: return new BarEncounter();
case EncounterType.Orchard: return new OrchardEncounter();
case EncounterType.Armory: return new ArmoryEncounter();
case EncounterType.Fountain: return new FountainEncounter();
case EncounterType.Belfry: return new BelfryEncounter();
case EncounterType.Roof: return new RoofEncounter();
}
}
}
public class EncounterDef
{
public Point3D StartLoc { get; private set; }
public Point3D[] SpawnPoints { get; private set; }
public Rectangle2D[] SpawnRecs { get; private set; }
public EncounterDef(Point3D start, Point3D[] points, Rectangle2D[] recs)
{
StartLoc = start;
SpawnPoints = points;
SpawnRecs = recs;
}
}
}
|
A2152225/ServUO
|
Scripts/Services/Expansions/Time Of Legends/Shadowguard/ShadowguardEncounter.cs
|
C#
|
gpl-2.0
| 17,173 |
<div class="noarticletext">There is currently no text in this page, you can <a href="http://docs.jquery.com/Special:Search/UI/API/1.8/Menu" title="Special:Search/UI/API/1.8/Menu">search for this page title</a> in other pages or <a href="http://docs.jquery.com/action/edit/UI/API/1.8/Menu" class="external text" title="http://docs.jquery.com/action/edit/UI/API/1.8/Menu">edit this page</a>.</div>
|
mikeusry/Mister-Sparky
|
sites/all/modules/jquery_ui/jquery.ui/docs/menu.html
|
HTML
|
gpl-2.0
| 396 |
# SubaccountRequest
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**keyid** | **string** | Clé API |
**sub_account_edit** | **string** | action à réaliser soit setPrice pour définir un prix ou addCredit pour ajouter du credit ou setRestriction modifier la restriction stop / |
**sub_account_key_id** | **string** | keyid du sous-compte | [optional]
**sub_account_add_credit** | **string** | montant du crédit à ajouter | [optional]
**sub_account_restriction_stop** | **string** | | [optional]
**sub_account_restriction_time** | **string** | | [optional]
**sub_account_price** | **string** | | [optional]
**sub_account_country_code** | **string** | | [optional]
[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)
|
MAN-IN-WAN/Kob-Eye
|
Class/Lib/Isendpro/docs/Model/SubaccountRequest.md
|
Markdown
|
gpl-2.0
| 908 |
/*
* Copyright (c) 1999, 2013, 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.
*
*/
#ifndef SHARE_VM_C1_C1_COMPILATION_HPP
#define SHARE_VM_C1_C1_COMPILATION_HPP
#include "ci/ciEnv.hpp"
#include "ci/ciMethodData.hpp"
#include "code/exceptionHandlerTable.hpp"
#include "memory/resourceArea.hpp"
#include "runtime/deoptimization.hpp"
class CompilationResourceObj;
class XHandlers;
class ExceptionInfo;
class DebugInformationRecorder;
class FrameMap;
class IR;
class IRScope;
class Instruction;
class LinearScan;
class OopMap;
class LIR_Emitter;
class LIR_Assembler;
class CodeEmitInfo;
class ciEnv;
class ciMethod;
class ValueStack;
class LIR_OprDesc;
class C1_MacroAssembler;
class CFGPrinter;
typedef LIR_OprDesc* LIR_Opr;
define_array(BasicTypeArray, BasicType)
define_stack(BasicTypeList, BasicTypeArray)
define_array(ExceptionInfoArray, ExceptionInfo*)
define_stack(ExceptionInfoList, ExceptionInfoArray)
class Compilation: public StackObj {
friend class CompilationResourceObj;
private:
// compilation specifics
Arena* _arena;
int _next_id;
int _next_block_id;
AbstractCompiler* _compiler;
ciEnv* _env;
CompileLog* _log;
ciMethod* _method;
int _osr_bci;
IR* _hir;
int _max_spills;
FrameMap* _frame_map;
C1_MacroAssembler* _masm;
bool _has_exception_handlers;
bool _has_fpu_code;
bool _has_unsafe_access;
bool _would_profile;
bool _has_method_handle_invokes; // True if this method has MethodHandle invokes.
const char* _bailout_msg;
ExceptionInfoList* _exception_info_list;
ExceptionHandlerTable _exception_handler_table;
ImplicitExceptionTable _implicit_exception_table;
LinearScan* _allocator;
CodeOffsets _offsets;
CodeBuffer _code;
bool _has_access_indexed;
// compilation helpers
void initialize();
void build_hir();
void emit_lir();
void emit_code_epilog(LIR_Assembler* assembler);
int emit_code_body();
int compile_java_method();
void install_code(int frame_size);
void compile_method();
void generate_exception_handler_table();
ExceptionInfoList* exception_info_list() const { return _exception_info_list; }
ExceptionHandlerTable* exception_handler_table() { return &_exception_handler_table; }
LinearScan* allocator() { return _allocator; }
void set_allocator(LinearScan* allocator) { _allocator = allocator; }
Instruction* _current_instruction; // the instruction currently being processed
#ifndef PRODUCT
Instruction* _last_instruction_printed; // the last instruction printed during traversal
#endif // PRODUCT
public:
// creation
Compilation(AbstractCompiler* compiler, ciEnv* env, ciMethod* method,
int osr_bci, BufferBlob* buffer_blob);
~Compilation();
static Compilation* current() {
return (Compilation*) ciEnv::current()->compiler_data();
}
// accessors
ciEnv* env() const { return _env; }
CompileLog* log() const { return _log; }
AbstractCompiler* compiler() const { return _compiler; }
bool has_exception_handlers() const { return _has_exception_handlers; }
bool has_fpu_code() const { return _has_fpu_code; }
bool has_unsafe_access() const { return _has_unsafe_access; }
int max_vector_size() const { return 0; }
ciMethod* method() const { return _method; }
int osr_bci() const { return _osr_bci; }
bool is_osr_compile() const { return osr_bci() >= 0; }
IR* hir() const { return _hir; }
int max_spills() const { return _max_spills; }
FrameMap* frame_map() const { return _frame_map; }
CodeBuffer* code() { return &_code; }
C1_MacroAssembler* masm() const { return _masm; }
CodeOffsets* offsets() { return &_offsets; }
Arena* arena() { return _arena; }
bool has_access_indexed() { return _has_access_indexed; }
// Instruction ids
int get_next_id() { return _next_id++; }
int number_of_instructions() const { return _next_id; }
// BlockBegin ids
int get_next_block_id() { return _next_block_id++; }
int number_of_blocks() const { return _next_block_id; }
// setters
void set_has_exception_handlers(bool f) { _has_exception_handlers = f; }
void set_has_fpu_code(bool f) { _has_fpu_code = f; }
void set_has_unsafe_access(bool f) { _has_unsafe_access = f; }
void set_would_profile(bool f) { _would_profile = f; }
void set_has_access_indexed(bool f) { _has_access_indexed = f; }
// Add a set of exception handlers covering the given PC offset
void add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers);
// Statistics gathering
void notice_inlined_method(ciMethod* method);
// JSR 292
bool has_method_handle_invokes() const { return _has_method_handle_invokes; }
void set_has_method_handle_invokes(bool z) { _has_method_handle_invokes = z; }
DebugInformationRecorder* debug_info_recorder() const; // = _env->debug_info();
Dependencies* dependency_recorder() const; // = _env->dependencies()
ImplicitExceptionTable* implicit_exception_table() { return &_implicit_exception_table; }
Instruction* current_instruction() const { return _current_instruction; }
Instruction* set_current_instruction(Instruction* instr) {
Instruction* previous = _current_instruction;
_current_instruction = instr;
return previous;
}
#ifndef PRODUCT
void maybe_print_current_instruction();
#endif // PRODUCT
// error handling
void bailout(const char* msg);
bool bailed_out() const { return _bailout_msg != NULL; }
const char* bailout_msg() const { return _bailout_msg; }
static int desired_max_code_buffer_size() {
#ifndef PPC
return (int) NMethodSizeLimit; // default 256K or 512K
#else
// conditional branches on PPC are restricted to 16 bit signed
return MIN2((unsigned int)NMethodSizeLimit,32*K);
#endif
}
static int desired_max_constant_size() {
return desired_max_code_buffer_size() / 10;
}
static bool setup_code_buffer(CodeBuffer* cb, int call_stub_estimate);
// timers
static void print_timers();
#ifndef PRODUCT
// debugging support.
// produces a file named c1compileonly in the current directory with
// directives to compile only the current method and it's inlines.
// The file can be passed to the command line option -XX:Flags=<filename>
void compile_only_this_method();
void compile_only_this_scope(outputStream* st, IRScope* scope);
void exclude_this_method();
#endif // PRODUCT
bool is_profiling() {
return env()->comp_level() == CompLevel_full_profile ||
env()->comp_level() == CompLevel_limited_profile;
}
bool count_invocations() { return is_profiling(); }
bool count_backedges() { return is_profiling(); }
// Helpers for generation of profile information
bool profile_branches() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && C1ProfileBranches;
}
bool profile_calls() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && C1ProfileCalls;
}
bool profile_inlined_calls() {
return profile_calls() && C1ProfileInlinedCalls;
}
bool profile_checkcasts() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && C1ProfileCheckcasts;
}
bool profile_parameters() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && MethodData::profile_parameters();
}
bool profile_arguments() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && MethodData::profile_arguments();
}
bool profile_return() {
return env()->comp_level() == CompLevel_full_profile &&
C1UpdateMethodData && MethodData::profile_return();
}
// will compilation make optimistic assumptions that might lead to
// deoptimization and that the runtime will account for?
bool is_optimistic() const {
return !TieredCompilation &&
(RangeCheckElimination || UseLoopInvariantCodeMotion) &&
method()->method_data()->trap_count(Deoptimization::Reason_none) == 0;
}
ciKlass* cha_exact_type(ciType* type);
// Dump inlining replay data to the stream.
void dump_inline_data(outputStream* out) { /* do nothing now */ }
};
// Macro definitions for unified bailout-support
// The methods bailout() and bailed_out() are present in all classes
// that might bailout, but forward all calls to Compilation
#define BAILOUT(msg) { bailout(msg); return; }
#define BAILOUT_(msg, res) { bailout(msg); return res; }
#define CHECK_BAILOUT() { if (bailed_out()) return; }
#define CHECK_BAILOUT_(res) { if (bailed_out()) return res; }
class InstructionMark: public StackObj {
private:
Compilation* _compilation;
Instruction* _previous;
public:
InstructionMark(Compilation* compilation, Instruction* instr) {
_compilation = compilation;
_previous = _compilation->set_current_instruction(instr);
}
~InstructionMark() {
_compilation->set_current_instruction(_previous);
}
};
//----------------------------------------------------------------------
// Base class for objects allocated by the compiler in the compilation arena
class CompilationResourceObj ALLOCATION_SUPER_CLASS_SPEC {
public:
void* operator new(size_t size) throw() { return Compilation::current()->arena()->Amalloc(size); }
void* operator new(size_t size, Arena* arena) throw() {
return arena->Amalloc(size);
}
void operator delete(void* p) {} // nothing to do
};
//----------------------------------------------------------------------
// Class for aggregating exception handler information.
// Effectively extends XHandlers class with PC offset of
// potentially exception-throwing instruction.
// This class is used at the end of the compilation to build the
// ExceptionHandlerTable.
class ExceptionInfo: public CompilationResourceObj {
private:
int _pco; // PC of potentially exception-throwing instruction
XHandlers* _exception_handlers; // flat list of exception handlers covering this PC
public:
ExceptionInfo(int pco, XHandlers* exception_handlers)
: _pco(pco)
, _exception_handlers(exception_handlers)
{ }
int pco() { return _pco; }
XHandlers* exception_handlers() { return _exception_handlers; }
};
#endif // SHARE_VM_C1_C1_COMPILATION_HPP
|
mur47x111/JDK8-concurrent-tagging
|
src/share/vm/c1/c1_Compilation.hpp
|
C++
|
gpl-2.0
| 12,152 |
/*
* Glide64 - Glide video plugin for Nintendo 64 emulators.
* Copyright (c) 2002 Dave2001
*
* 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., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA
*/
//****************************************************************
//
// Glide64 - Glide Plugin for Nintendo 64 emulators (tested mostly with Project64)
// Project started on December 29th, 2001
//
// To modify Glide64:
// * Write your name and (optional)email, commented by your work, so I know who did it, and so that you can find which parts you modified when it comes time to send it to me.
// * Do NOT send me the whole project or file that you modified. Take out your modified code sections, and tell me where to put them. If people sent the whole thing, I would have many different versions, but no idea how to combine them all.
//
// Official Glide64 development channel: #Glide64 on EFnet
//
// Original author: Dave2001 ([email protected])
// Other authors: Gonetz, Gugaman
//
//****************************************************************
#ifndef Util_H
#define Util_H
#include <stdint.h>
#include "winlnxdefs.h"
#include "rdp.h"
#define NOT_TMU0 0x00
#define NOT_TMU1 0x01
#define NOT_TMU2 0x02
void util_init ();
void clip_z ();
void clip_tri (WORD linew = 0);
BOOL cull_tri (VERTEX **v);
void DrawTri (VERTEX **v, WORD linew = 0);
void do_triangle_stuff (WORD linew = 0);
void do_triangle_stuff_2 (WORD linew = 0);
void add_tri (VERTEX *v, int n, int type);
void apply_shade_mods (VERTEX *v);
void update ();
void update_scissor ();
void set_message_combiner ();
void fix_tex_coord (VERTEX **v);
// positional and texel coordinate clipping
#define CCLIP(ux,lx,ut,lt,uc,lc) \
if (ux > lx || lx < uc || ux > lc) { rdp.tri_n += 2; return; } \
if (ux < uc) { \
float p = (uc-ux)/(lx-ux); \
ut = p*(lt-ut)+ut; \
ux = uc; \
} \
if (lx > lc) { \
float p = (lc-ux)/(lx-ux); \
lt = p*(lt-ut)+ut; \
lx = lc; \
}
#define CCLIP2(ux,lx,ut,lt,un,ln,uc,lc) \
if (ux > lx || lx < uc || ux > lc) { rdp.tri_n += 2; return; } \
if (ux < uc) { \
float p = (uc-ux)/(lx-ux); \
ut = p*(lt-ut)+ut; \
un = p*(ln-un)+un; \
ux = uc; \
} \
if (lx > lc) { \
float p = (lc-ux)/(lx-ux); \
lt = p*(lt-ut)+ut; \
ln = p*(ln-un)+un; \
lx = lc; \
}
#if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))
#include <stdlib.h>
#define bswap32(x) _byteswap_ulong(x)
#else
static inline uint32_t bswap32(uint32_t val)
{
return (((val & 0xff000000) >> 24) |
((val & 0x00ff0000) >> 8) |
((val & 0x0000ff00) << 8) |
((val & 0x000000ff) << 24));
}
#endif
#define ALOWORD(x) (*((uint16_t*)&(x))) // low word
template<class T> static inline T __ROR__(T value, unsigned int count)
{
const unsigned int nbits = sizeof(T) * 8;
count %= nbits;
T low = value << (nbits - count);
value >>= count;
value |= low;
return value;
}
// rotate left
template<class T> static T __ROL__(T value, unsigned int count)
{
const unsigned int nbits = sizeof(T) * 8;
count %= nbits;
T high = value >> (nbits - count);
value <<= count;
value |= high;
return value;
}
#endif // ifndef Util_H
|
bentley/mupen64plus-video-glide64
|
src/Util.h
|
C
|
gpl-2.0
| 3,986 |
<?php
/*
Template Name: Guest Portal
*/
?>
<?php get_header(); ?>
<div class="band" id="main">
<div class="container">
<div class="four columns" id="sidebar">
<?php if(get_field('menu')) : ?><div id="subnav-sidebar"><?php the_field('menu'); ?></div><?php else: ?><?php endif; ?>
</div>
<div class="twelve columns" id="content">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post" id="post-<?php the_ID(); ?>">
<div>
<?php $welcome_photo = get_post_meta($post->ID, 'welcome_photo', true); if ($welcome_photo) { ?><div class="welcome-photo"><img src="<?php echo wp_get_attachment_url($welcome_photo); ?>" alt="<?php the_title(); ?>" /></div><?php } else { ?><?php } ?></div>
<div class="clear"></div>
<?php if(get_field('callouts')): ?>
<ul class="callouts">
<?php while(the_repeater_field('callouts')): ?>
<li class="three columns">
<?php if(get_sub_field('photo')) : ?><?php if(get_sub_field('link_url')) : ?><a href="<?php the_sub_field('link_url'); ?>"><?php else: ?><?php endif; ?><img src="<?php the_sub_field('photo'); ?>" class="callout-photo" /><?php if(get_sub_field('link_url')) : ?></a><?php else: ?><?php endif; ?><?php else: ?><?php endif; ?>
</li>
<?php endwhile; ?>
</ul>
<?php endif; ?>
<div class="entry">
<?php the_content(''); ?>
</div>
</div>
<?php endwhile; ?>
<?php else : ?>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer(); ?>
|
Dovedesign/WoodsDev
|
wp-content/themes/woodlandswtn/page-portal.php
|
PHP
|
gpl-2.0
| 1,498 |
<?php
global $default_img;
$image = 'http://' . $_SERVER['HTTP_HOST'] . $default_img;
if (isset($node->field_image['und'])) {
$image = file_create_url($node->field_image['und'][0]['uri']);
}
$filter_string = "";
foreach ($node->field_category['und'] as $category) {
$filter_string .= ' ' . str_replace(' ', '_', strtolower($category['taxonomy_term']->name));
}
?>
<figure class="portfolio_item<?php echo $filter_string; ?>">
<!--image & description-->
<div class="popup_wrap relative r_corners wrapper db_xs_centered">
<img src="<?php echo $image; ?>" alt="" class="">
<div class="project_description vc_child t_align_c tr_all_long">
<div class="d_inline_m">
<h4 class="lh_inherit"><a href="<?php echo $node_url; ?>" class="color_light tr_all not_hover"><?php echo $title; ?></a></h4>
<!--project's info-->
<ul class="dotted_list m_bottom_5 color_light custom-dotted-list">
<li class="m_right_15 relative d_inline_m">
<a href="#" class="color_light not_hover fs_small">
<?php if (isset($node->field_video['und']) && strip_tags($node->field_video['und'][0]['value']) != "") : ?>
<i class="icon-video"></i>
<?php else: ?>
<i class="icon-picture"></i>
<?php endif; ?>
</a>
</li>
<li class="m_right_15 relative d_inline_m category wtext-pro-links"><?php print illusion_format_comma_field('field_category', $node); ?></li>
</ul>
<div class="d_inline_b clearfix">
<?php if (isset($node->field_video['und']) && strip_tags($node->field_video['und'][0]['value']) != "") : ?>
<a href="<?php echo strip_tags($node->field_video['und'][0]['value']); ?>" data-group="portfolio" data-title="<?php echo $title; ?>" class="jackbox icon_wrap_size_3 color_light n_sc_hover d_block circle f_left">
<i class="icon-play"></i>
</a>
<?php else: ?>
<a href="<?php echo $image; ?>" data-group="portfolio" data-title="<?php echo $title; ?>" class="jackbox icon_wrap_size_3 color_light n_sc_hover d_block circle f_left m_right_10">
<i class="icon-plus"></i>
</a>
<a href="<?php echo $node_url; ?>" class="icon_wrap_size_3 color_light n_sc_hover d_block circle f_left">
<i class="icon-link"></i>
</a>
<?php endif; ?>
</div>
</div>
</div>
</div>
</figure>
|
xstatic/jaxfoodie
|
sites/all/themes/illusion/templates/node/reviews/node--view--reviews-block--block-wtext2.tpl.php
|
PHP
|
gpl-2.0
| 2,881 |
INCLUDE("/Users/chris/Code/Gargoyle/linphone-iphone/submodules/build/iphone-toolchain.cmake")
SET(CMAKE_SYSTEM "Generic")
SET(CMAKE_SYSTEM_NAME "Generic")
SET(CMAKE_SYSTEM_VERSION "")
SET(CMAKE_SYSTEM_PROCESSOR "armv6")
SET(CMAKE_HOST_SYSTEM "Darwin-11.3.0")
SET(CMAKE_HOST_SYSTEM_NAME "Darwin")
SET(CMAKE_HOST_SYSTEM_VERSION "11.3.0")
SET(CMAKE_HOST_SYSTEM_PROCESSOR "i386")
SET(CMAKE_CROSSCOMPILING "TRUE")
SET(CMAKE_SYSTEM_LOADED 1)
|
GargoyleSoftware/voip-client-ios
|
submodules/build-armv6-apple-darwin/externals/zrtpcpp/CMakeFiles/CMakeSystem.cmake
|
CMake
|
gpl-2.0
| 440 |
#!/usr/bin/python
#Pyxis and Original Sipie: Sirius Command Line Player
#Copyright (C) Corey Ling, Eli Criffield
#
#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.
import cookielib
import urllib2
import urllib
import os
import sys
import re
import time
from Config import Config, toBool
from ProviderUSA import ProviderUSA
from ProviderCanada import ProviderCanada
from Exceptions import AuthError, LoginError, InvalidStream
from Debug import log, logfile
from xml.dom.minidom import parse
import htmlfixes
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
print 'Missing dependency: BeautifulSoup'
print ' to install run `easy_install BeautifulSoup`'
print ' or if you have apt try '
print ' apt-get install python-beautifulsoup'
print ''
print 'or download the beautifulsoup.py module and put it in the current directory.'
print 'http://www.crummy.com/software/BeautifulSoup/'
sys.exit(300)
if 'find' not in dir(BeautifulSoup):
print 'Pyxis requires a newer version of Beautiful soup:'
print 'Get the latest version from: http://www.crummy.com/software/BeautifulSoup/'
sys.exit(301)
class Sirius(object):
"""Handles all access to the SIRIUS website"""
def __init__(self):
#Get settings
config = Config()
self.account = config.account
self.settings = config.settings
self.host = 'www.sirius.com'
self.__headers = {'User-agent': 'Mozilla/5.0 (X11; U; %s i686; en-US; rv:1.8.0.7) github.com/kasuko/pyxis Firefox/1.5.0.7' % \
sys.platform}
self.token = ''
self.__stream = None
self.asxURL = None
self.allstreams = []
self.playing = None
self.__cookie_jar = None
if self.account.login_type not in ['subscriber', 'guest']:
print 'invalid login_type in config file'
sys.exit(101)
if toBool(self.account.canada):
self.provider = ProviderCanada(self)
else:
self.provider = ProviderUSA(self)
self.cookiefile = os.path.join(config.confpath, 'cookies.txt')
self.playlist = os.path.join(config.confpath, 'playlist')
self.__setupOpener()
def __setupOpener(self):
"""Initialize proper cookies and parameters for website retrival"""
self.__cookie_jar = cookielib.MozillaCookieJar(self.cookiefile)
cookie_handler = urllib2.HTTPCookieProcessor(self.__cookie_jar)
if os.path.isfile(self.cookiefile):
self.__cookie_jar.load()
# this way its all one big session, even on exit and restart
self.__cookie_jar.load(ignore_discard=True, ignore_expires=
True)
http_proxy = os.environ.get('http_proxy')
if http_proxy is not None:
proxy_handler = urllib2.ProxyHandler({'http': http_proxy})
opener = urllib2.build_opener(cookie_handler, proxy_handler)
else:
opener = urllib2.build_opener(cookie_handler)
urllib2.install_opener(opener)
def sanitize(self, data):
""" Sanitizes Data against specific errors in the Sirus HTML that
Beautiful soup can not handle.
"""
for sub in htmlfixes.subs:
data = re.sub(sub[0], sub[1], data)
logfile('sanitize.html', data) #DEBUG
return data
def findSessionID(self):
""" finds the session ID cookie and returns the value """
for (index, cookie) in enumerate(self.__cookie_jar):
if 'JSESSIONID' in cookie.name:
return cookie.value
return False
def getURL(self, url, postdict=None, poststring=None):
""" get a url, the second arg could be dictionary of
options for a post
If there is no second option use get
This will use the cookies and tokens for this instance
of Sirius
returns a file handle
"""
if postdict:
postdata = urllib.urlencode(postdict)
else:
postdata = None
if poststring:
postdata = poststring
log("url=%s" % url) #DEBUG
log("POST=%s" % postdata)#DEBUG
req = urllib2.Request(url, postdata, self.__headers)
handle = None
while handle is None:
try:
handle = urllib2.urlopen(req)
except urllib2.URLError:
print("Error while fetching %s\nTrying again in 30 seconds..." % url);
time.sleep(30);
handle = None
self.__cookie_jar.save(ignore_discard=True, ignore_expires=True)
return handle
def getAsxURL(self):
''' Returns an the url of the asx for the self.__stream,
Diffrent from tryGetAsxURL it will try to authticate insted of
fail if its needs to
'''
try:
url = self.provider.tryGetAsxURL(self.__stream)
except AuthError:
self.provider.auth()
url = self.provider.tryGetAsxURL(self.__stream)
return url
def getStreams(self):
''' Returns an the list of streams
Diffrent from tryGeStreams it will try to authticate insted of
fail if its needs to
'''
try:
streams = self.provider.tryGetStreams()
except AuthError:
self.provider.auth()
streams = self.provider.tryGetStreams()
return streams
def validateStream(self, stream=None):
'''checks if stream is valid if theres no agument then it checks
self.__stream'''
if stream is None:
stream = self.__stream
log('Validationg stream %s' % stream)
if len(self.allstreams) < 5:
self.allstreams = self.getStreams()
if stream not in self.allstreams:
log('stream %s invalid' % stream)
raise InvalidStream
def setStreamByLongName(self, longName):
'''Sets the currently playing stream to the stream refered to by
longname'''
log('Setting Stream to %s' % longName)
#print 'setStreamByLongName:',longName #DEBUG
if len(self.allstreams) < 5:
self.allstreams = self.getStreams()
for stream in self.allstreams:
if stream['longName'].lower().strip() == longName.lower():
#print 'setStreamByLongName, stream:',stream #DEBUG
self.__stream = stream
log('Stream set to %s' % stream)
return
raise InvalidStream
def getNowPlaying(self):
'''return a dictionary for current song/artist per channel'''
nowplaying = {}
url = 'http://www.siriusxm.com/padData/pad_provider.jsp?all_channels=y'
try:
sirius_xml = parse(urllib.urlopen(url))
except Exception:
log("ERROR getting now-playing list: %s" % url)
return "FAILURE"
for channels in sirius_xml.getElementsByTagName('event'):
channel = channels.getElementsByTagName('channelname')[0].firstChild.data
song = channels.getElementsByTagName('songtitle')[0].firstChild.data
artist = channels.getElementsByTagName('artist')[0].firstChild.data
nowplaying[str(channel).strip().lower()] = {'artist': artist, 'song': song}
sirius_xml.unlink()
return nowplaying
def nowPlaying(self):
'''return a dictionary of info about whats currently playing'''
nowplaying = {}
channel = None
stream = self.__stream['longName'].lower()
nowPlayingInfo = self.getNowPlaying()
if stream in nowPlayingInfo:
channel = stream
else:
for info in nowPlayingInfo:
#Remove all non letter characters then compare
cleanInfo = re.sub("[\W]", "", info)
cleanStream = re.sub("[\W]", "", stream)
if cleanStream == cleanInfo or cleanStream in cleanInfo:
channel = info
break
if channel:
channel = channel.strip()
song = nowPlayingInfo[channel]['song']
artist = nowPlayingInfo[channel]['artist']
nowplaying['playing'] = song + ', ' + artist
nowplaying['longName'] = channel.title()
else:
nowplaying['playing'] = 'No channel information for stream ' + stream
nowplaying['longName'] = 'ERROR'
nowplaying['logfmt'] = '%s %s: %s' % (time.strftime('%y %m|%d %H:%M'),
nowplaying['longName'], nowplaying['playing'])
if nowplaying['playing'] != self.playing:
nowplaying['new'] = True
self.playing = nowplaying['playing']
logfd = open(self.playlist,'a')
nowplayinglog = nowplaying['logfmt'].encode("utf-8")
logfd.write("%s\n" % nowplayinglog)
logfd.close()
else:
nowplaying['new'] = False
return nowplaying
|
Kasuko/pyxis
|
pyxis/Sirius.py
|
Python
|
gpl-2.0
| 9,660 |
/*
* CINELERRA
* Copyright (C) 2008 Adam Williams <broadcast at earthling dot 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
*
*/
#include "mwindow.h"
#include "mwindowgui.h"
#include "recconfirmdelete.h"
#include <libintl.h>
#define _(String) gettext(String)
#define gettext_noop(String) String
#define N_(String) gettext_noop (String)
RecConfirmDelete::RecConfirmDelete(MWindow *mwindow)
: BC_Window(PROGRAM_NAME ": Confirm",
mwindow->gui->get_abs_cursor_x(1),
mwindow->gui->get_abs_cursor_y(1),
320, 100)
{
}
RecConfirmDelete::~RecConfirmDelete()
{
}
int RecConfirmDelete::create_objects(char *string)
{
char string2[256];
int x = 10, y = 10;
sprintf(string2, _("Delete this file and %s?"), string);
add_subwindow(new BC_Title(x, y, string2));
y += 30;
add_subwindow(new BC_OKButton(x, y));
x = get_w() - 100;
add_subwindow(new BC_CancelButton(x, y));
return 0;
}
|
petterreinholdtsen/cinelerra-cv
|
cinelerra/recconfirmdelete.C
|
C++
|
gpl-2.0
| 1,584 |
/*
* Copyright (C) 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#pragma once
#include "MediaPlayerEnums.h"
namespace WebCore {
class HTMLMediaElementEnums : public MediaPlayerEnums {
public:
using MediaPlayerEnums::VideoFullscreenMode;
enum DelayedActionType {
LoadMediaResource = 1 << 0,
ConfigureTextTracks = 1 << 1,
TextTrackChangesNotification = 1 << 2,
ConfigureTextTrackDisplay = 1 << 3,
CheckPlaybackTargetCompatablity = 1 << 4,
CheckMediaState = 1 << 5,
MediaEngineUpdated = 1 << 6,
UpdatePlayState = 1 << 7,
EveryDelayedAction = LoadMediaResource | ConfigureTextTracks | TextTrackChangesNotification | ConfigureTextTrackDisplay | CheckPlaybackTargetCompatablity | CheckMediaState | UpdatePlayState,
};
enum ReadyState { HAVE_NOTHING, HAVE_METADATA, HAVE_CURRENT_DATA, HAVE_FUTURE_DATA, HAVE_ENOUGH_DATA };
enum NetworkState { NETWORK_EMPTY, NETWORK_IDLE, NETWORK_LOADING, NETWORK_NO_SOURCE };
enum TextTrackVisibilityCheckType { CheckTextTrackVisibility, AssumeTextTrackVisibilityChanged };
enum InvalidURLAction { DoNothing, Complain };
typedef enum {
NoSeek,
Fast,
Precise
} SeekType;
};
} // namespace WebCore
|
Debian/openjfx
|
modules/web/src/main/native/Source/WebCore/html/HTMLMediaElementEnums.h
|
C
|
gpl-2.0
| 2,550 |
#! /bin/sh
#
echo
echo -----------------------------------------------------------------------------------------------
echo BEGIN AUTOMATED TEST - 1 2 and 4 PMs S0 100GB and 1TB and S1_7 100GB with 2 Arrays 1 Pass
echo -----------------------------------------------------------------------------------------------
echo
#
echo
echo ------------------------------------------------------------------
echo BEGINNING OF 1 2 and 4 PM 2 Array S0 100GB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------
echo starting 1PM 2Array stream0 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 1 2
/home/pf/auto/common/exeStreamTest.sh 0 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 2PM 2Array stream0 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 2 2
/home/pf/auto/common/exeStreamTest.sh 0 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 4PM 2Array stream0 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 4 2
/home/pf/auto/common/exeStreamTest.sh 0 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo END OF 1 2 and 4 PM 2 Array S0 100GB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------
echo BEGINNING 1 2 and 4 PM 2 Array S0 1TB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------
echo starting 1PM 2Array stream0 1TB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 1 2
/home/pf/auto/common/exeStreamTest.sh 0 1t 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 2PM 2Array stream0 1TB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 2 2
/home/pf/auto/common/exeStreamTest.sh 0 1t 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 4PM 2Array stream0 1TB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 4 2
/home/pf/auto/common/exeStreamTest.sh 0 1t 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo END OF 1 2 and 4 PM 2 Array S0 1TB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------
echo executing setLowMem100 script to prep for following stream1_7 tests
echo ------------------------------------------------------------------
echo
#
/usr/local/Calpont/bin/setLowMem100.sh
#
echo
echo ------------------------------------------------------------------
echo BEGINNING OF 1 2 and 4 PM 2 Array S1_7 100GB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------
echo starting 1PM 2Array stream1_7 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 1 2
/home/pf/auto/common/exeStreamTest.sh 1_7 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 2PM 2Array stream1_7 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 2 2
/home/pf/auto/common/exeStreamTest.sh 1_7 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo starting 4PM 2Array stream1_7 100GB i16 1x w/restart
echo ------------------------------------------------------------------
echo
#
/home/pf/auto/common/setTestEnv.sh 1 4 2
/home/pf/auto/common/exeStreamTest.sh 1_7 100 16 1 Y
#
echo
echo ------------------------------------------------------------------
echo END OF 1 2 and 4 PM 2 Array S1_7 100GB TESTS!
echo ------------------------------------------------------------------
echo
echo ------------------------------------------------------------------------------------------------
echo END OF AUTOMATED TEST - 1 2 and 4 PMs S0 100GB and 1TB and S1_7 100GB with 2 Arrays 1 Pass
echo ------------------------------------------------------------------------------------------------
echo
# End of script
|
infinidb/infinidb
|
utils/scenarios/perf/source/pf/scripts/2a_100g_1t_s0_s17.sh
|
Shell
|
gpl-2.0
| 4,954 |
package org.zhouer.vt;
import java.awt.Cursor;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class User implements KeyListener, MouseListener, MouseMotionListener {
private final Config config;
private boolean isDefaultCursor;
private final Application parent;
private int pressX, pressY, dragX, dragY;
private final VT100 vt;
public User(final Application p, final VT100 v, final Config c) {
this.parent = p;
this.vt = v;
this.config = c;
this.isDefaultCursor = true;
}
public void keyPressed(final KeyEvent e) {
int len;
final byte[] buf = new byte[4];
/*
* System.out.println( "key presses: " + e ); System.out.println( "key
* modifier: " + e.getModifiers() );
*/
if (e.isAltDown() || e.isMetaDown()) {
if (e.getKeyCode() == KeyEvent.VK_A) {
vt.setSelectedAll();
vt.repaint();
}
return;
}
// 其他功能鍵
switch (e.getKeyCode()) {
case KeyEvent.VK_UP:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = 'A';
len = 3;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'A';
len = 3;
}
break;
case KeyEvent.VK_DOWN:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = 'B';
len = 3;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'B';
len = 3;
}
break;
case KeyEvent.VK_RIGHT:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = 'C';
len = 3;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'C';
len = 3;
}
break;
case KeyEvent.VK_LEFT:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = 'D';
len = 3;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'D';
len = 3;
}
break;
case KeyEvent.VK_INSERT:
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '2';
buf[3] = '~';
len = 4;
break;
case KeyEvent.VK_HOME:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '1';
buf[3] = '~';
len = 4;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'H';
len = 3;
}
break;
case KeyEvent.VK_PAGE_UP:
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '5';
buf[3] = '~';
len = 4;
break;
case KeyEvent.VK_DELETE:
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '3';
buf[3] = '~';
len = 4;
break;
case KeyEvent.VK_END:
if (this.vt.getKeypadMode() == VT100.NUMERIC_KEYPAD) {
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '4';
buf[3] = '~';
len = 4;
} else {
buf[0] = 0x1b;
buf[1] = 0x4f;
buf[2] = 'F';
len = 3;
}
break;
case KeyEvent.VK_PAGE_DOWN:
buf[0] = 0x1b;
buf[1] = 0x5b;
buf[2] = '6';
buf[3] = '~';
len = 4;
break;
default:
len = 0;
}
if (len != 0) {
this.parent.writeBytes(buf, 0, len);
return;
}
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
// 在 Mac 上 keyTyped 似乎收不到 esc
this.parent.writeByte((byte) 0x1b);
return;
}
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
// ptt 只吃 0x0d, 只送 0x0a 沒用
this.parent.writeByte((byte) 0x0d);
return;
}
}
public void keyReleased(final KeyEvent e) {
}
public void keyTyped(final KeyEvent e) {
// System.out.println( "key typed: " + e );
// 功能鍵
if (e.isAltDown() || e.isMetaDown()) {
return;
}
// delete, enter, esc 會在 keyPressed 被處理
if ((e.getKeyChar() == KeyEvent.VK_DELETE)
|| (e.getKeyChar() == KeyEvent.VK_ENTER)
|| (e.getKeyChar() == KeyEvent.VK_ESCAPE)) {
return;
}
// 一般按鍵,直接送出
this.parent.writeChar(e.getKeyChar());
}
public void mouseClicked(final MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1) {
// 左鍵
if (this.vt.isOverURL(e.getX(), e.getY())) {
// click
// 開啟瀏覽器
final String url = this.vt.getURL(e.getX(), e.getY());
if (url.length() != 0) {
this.parent.openExternalBrowser(url);
}
return;
} else if (e.getClickCount() == 2) {
// double click
// 選取連續字元
this.vt.selectConsequtive(e.getX(), e.getY());
this.vt.repaint();
return;
} else if (e.getClickCount() == 3) {
// triple click
// 選取整行
this.vt.selectEntireLine(e.getX(), e.getY());
this.vt.repaint();
return;
}
} else if (e.getButton() == MouseEvent.BUTTON2) {
// 中鍵
// 貼上
if (e.isControlDown()) {
// 按下 ctrl 則彩色貼上
this.parent.colorPaste();
} else {
this.parent.paste();
}
return;
} else if (e.getButton() == MouseEvent.BUTTON3) {
// 右鍵
// 跳出 popup menu
this.parent.showPopup(e.getX(), e.getY());
return;
}
this.vt.requestFocusInWindow();
this.vt.resetSelected();
this.vt.repaint();
}
public void mouseDragged(final MouseEvent e) {
this.dragX = e.getX();
this.dragY = e.getY();
this.vt.setSelected(this.pressX, this.pressY, this.dragX, this.dragY);
this.vt.repaint();
}
public void mouseEntered(final MouseEvent e) {
}
public void mouseExited(final MouseEvent e) {
}
public void mouseMoved(final MouseEvent e) {
final boolean cover = this.vt.isOverURL(e.getX(), e.getY());
// 只有滑鼠游標需改變時才 setCursor
if (this.isDefaultCursor && cover) {
this.vt.setCursor(new Cursor(Cursor.HAND_CURSOR));
this.isDefaultCursor = false;
} else if (!this.isDefaultCursor && !cover) {
this.vt.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
this.isDefaultCursor = true;
}
}
public void mousePressed(final MouseEvent e) {
this.pressX = e.getX();
this.pressY = e.getY();
}
public void mouseReleased(final MouseEvent e) {
boolean meta, ctrl;
// 只處理左鍵
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
meta = e.isAltDown() || e.isMetaDown();
ctrl = e.isControlDown();
// select 時按住 meta 表反向,即:
// 若有 copy on select 則按住 meta 代表不複製,若沒有 copy on select 則按住 meta 代表要複製。
if (this.config.getBooleanValue(Config.COPY_ON_SELECT) == meta) {
return;
}
// ctrl 代表複製時包含色彩。
if (ctrl) {
this.parent.colorCopy();
} else {
this.parent.copy();
}
}
}
|
TheProjecter/ztermapplet
|
src/org/zhouer/vt/User.java
|
Java
|
gpl-2.0
| 6,830 |
#include "sa_tools.h"
//--------------------------------------------------------------------------------------
#define PROGRESS 100000000
size_t PREFIX_TABLE_K_VALUE = 16;
size_t PREFIX_TABLE_NT_VALUE[256];
char *global_sa_genome;
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
int ncmp_by_id(void const *a, void const *b) {
return (strncmp(&global_sa_genome[(*(uint *)a)], &global_sa_genome[(*(uint *)b)], 1000));
}
void compute_sa(uint *sa, uint num_sufixes) {
qsort(sa, num_sufixes, sizeof(uint), ncmp_by_id);
}
//--------------------------------------------------------------------------------------
void compute_lcp(char *s, uint *sa, uint *lcp, uint num_sufixes) {
uint count = 0;
char *curr, *prev;
int h = 0;
lcp[0] = 0;
uint progress = 0;
for (int i = 1; i < num_sufixes; i++) {
progress++;
if (progress % PROGRESS == 0) printf("\tlcp processing %0.2f %c (max. 255 = %u)...\n",
100.0f * progress / num_sufixes, '%', count);
prev = s + sa[i - 1];
curr = s + sa[i];
h = 0;
while (*prev == *curr) {
h++;
prev++;
curr++;
}
lcp[i] = h;
if (h >= 255) count++;
}
printf("\t, num lcp >= 255 -> %u\n", count);
}
//--------------------------------------------------------------------------------------
void compute_child(uint *lcp, int *child, uint num_sufixes) {
const int no_value = -1; //len + 10;
for (uint i = 0; i < num_sufixes; i++){
child[i] = no_value;
}
int last_index = no_value;
int stack_size = num_sufixes / 2;
int *stack = (int *) malloc(stack_size * sizeof(int));
int index = 0;
printf("\tcomputing up and down values...(%u)\n", num_sufixes);
// compute up and down values
stack[index] = 0;
for (uint i = 1; i < num_sufixes; i++) {
// printf("i = %i -> lcp[i] = %i, lcp[stack[index]] = %i, index = %i\n", i, lcp[i], lcp[stack[index]], index);
// if (i == 322) exit(-1);
while (lcp[i] < lcp[stack[index]]) {
last_index = stack[index];
if (--index < 0) index = 0;
if (lcp[i] <= lcp[stack[index]] && lcp[stack[index]] != lcp[last_index]) {
child[stack[index]] = last_index;
//if (i - 1 == 20603) { printf("000\n"); exit(-1); }
}
}
//now LCP[i] >= LCP[top] holds
if (last_index != no_value){
//if (i - 1 == 20603) { printf("111\n"); exit(-1); }
child[i-1] = last_index;
last_index = no_value;
}
if (index + 1 >= stack_size) { printf("Overflow (%i)\n", index); exit(-1); }
stack[++index] = i;
}
//last row (fix for last character of sequence not being unique
// while (0 == lcp[stack[index]] || no_value == lcp[stack[index]] ){
while (0 < lcp[stack[index]] ){
last_index = stack[index];
if (--index < 0) index = 0;
if (0 <= lcp[stack[index]] && lcp[stack[index]] != lcp[last_index]) {
child[stack[index]] = last_index;
}
}
printf("\tcomputing up and down values...Done\n");
printf("\tcompuing next l-index values...\n");
// compute next l-index values
index = 0;
stack[index] = 0;
for (uint i = 1; i < num_sufixes; i++) {
//printf("i = %i -> lcp[i] = %i, lcp[stack[index]] = %i, index = %i\n", i, lcp[i], lcp[stack[index]], index);
while (lcp[i] < lcp[stack[index]]) {
if (--index < 0) index = 0;
}
last_index = stack[index];
if (lcp[i] == lcp[last_index]) {
if (--index < 0) index = 0;
child[last_index] = i;
}
if (index + 1 >= stack_size) { printf("Overflow (%i)\n", index); exit(-1); }
stack[++index] = i;
}
printf("\tcompuing next l-index values...Done\n");
free(stack);
}
//--------------------------------------------------------------------------------------
inline size_t compute_prefix_value(char *prefix, int len) {
size_t value = 0;
for (int i = len - 1, j = 0; i >= 0; i--, j += 2) {
value += ((1LL * PREFIX_TABLE_NT_VALUE[(unsigned char)prefix[i]]) << j);
}
return value;
}
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
|
fw1121/hpg-aligner
|
src/sa/sa_tools.c
|
C
|
gpl-2.0
| 4,244 |
/****************************************************************************\
* srun_job.c - job data structure creation functions
*****************************************************************************
* Copyright (C) 2002-2007 The Regents of the University of California.
* Copyright (C) 2008 Lawrence Livermore National Security.
* Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
* Written by Mark Grondona <[email protected]>.
* CODE-OCEC-09-009. All rights reserved.
*
* This file is part of SLURM, a resource management program.
* For details, see <http://www.schedmd.com/slurmdocs/>.
* Please also read the included file: DISCLAIMER.
*
* SLURM 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.
*
* In addition, as a special exception, the copyright holders give permission
* to link the code of portions of this program with the OpenSSL library under
* certain conditions as described in each individual source file, and
* distribute linked combinations including the two. You must obey the GNU
* General Public License in all respects for all of the code used other than
* OpenSSL. If you modify file(s) with this exception, you may extend this
* exception to your version of the file(s), but you are not obligated to do
* so. If you do not wish to do so, delete this exception statement from your
* version. If you delete this exception statement from all source files in
* the program, then also delete it here.
*
* SLURM 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 SLURM; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
\*****************************************************************************/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include "src/common/bitstring.h"
#include "src/common/cbuf.h"
#include "src/common/hostlist.h"
#include "src/common/log.h"
#include "src/common/read_config.h"
#include "src/common/slurm_protocol_api.h"
#include "src/common/xmalloc.h"
#include "src/common/xstring.h"
#include "src/common/io_hdr.h"
#include "src/common/forward.h"
#include "src/common/fd.h"
#include "src/srun/srun_job.h"
#include "src/srun/opt.h"
#include "src/srun/fname.h"
#include "src/srun/debugger.h"
/*
* allocation information structure used to store general information
* about node allocation to be passed to _job_create_structure()
*/
typedef struct allocation_info {
uint32_t jobid;
uint32_t stepid;
char *nodelist;
uint32_t nnodes;
uint32_t num_cpu_groups;
uint16_t *cpus_per_node;
uint32_t *cpu_count_reps;
dynamic_plugin_data_t *select_jobinfo;
} allocation_info_t;
/*
* Prototypes:
*/
static inline int _estimate_nports(int nclients, int cli_per_port);
static int _compute_task_count(allocation_info_t *info);
static void _set_ntasks(allocation_info_t *info);
static srun_job_t *_job_create_structure(allocation_info_t *info);
static char * _normalize_hostlist(const char *hostlist);
/*
* Create an srun job structure w/out an allocation response msg.
* (i.e. use the command line options)
*/
srun_job_t *
job_create_noalloc(void)
{
srun_job_t *job = NULL;
allocation_info_t *ai = xmalloc(sizeof(*ai));
uint16_t cpn = 1;
hostlist_t hl = hostlist_create(opt.nodelist);
if (!hl) {
error("Invalid node list `%s' specified", opt.nodelist);
goto error;
}
srand48(getpid());
ai->jobid = MIN_NOALLOC_JOBID +
((uint32_t) lrand48() %
(MAX_NOALLOC_JOBID - MIN_NOALLOC_JOBID + 1));
ai->stepid = (uint32_t) (lrand48());
ai->nodelist = opt.nodelist;
ai->nnodes = hostlist_count(hl);
hostlist_destroy(hl);
cpn = (opt.ntasks + ai->nnodes - 1) / ai->nnodes;
ai->cpus_per_node = &cpn;
ai->cpu_count_reps = &ai->nnodes;
/*
* Create job, then fill in host addresses
*/
job = _job_create_structure(ai);
job_update_io_fnames(job);
error:
xfree(ai);
return (job);
}
/*
* Create an srun job structure for a step w/out an allocation response msg.
* (i.e. inside an allocation)
*/
srun_job_t *
job_step_create_allocation(resource_allocation_response_msg_t *resp)
{
uint32_t job_id = resp->job_id;
srun_job_t *job = NULL;
allocation_info_t *ai = xmalloc(sizeof(*ai));
hostlist_t hl = NULL;
char *buf = NULL;
int count = 0;
uint32_t alloc_count = 0;
ai->jobid = job_id;
ai->stepid = NO_VAL;
ai->nodelist = opt.alloc_nodelist;
hl = hostlist_create(ai->nodelist);
hostlist_uniq(hl);
alloc_count = hostlist_count(hl);
ai->nnodes = alloc_count;
hostlist_destroy(hl);
if (opt.exc_nodes) {
hostlist_t exc_hl = hostlist_create(opt.exc_nodes);
hostlist_t inc_hl = NULL;
char *node_name = NULL;
hl = hostlist_create(ai->nodelist);
if(opt.nodelist) {
inc_hl = hostlist_create(opt.nodelist);
}
hostlist_uniq(hl);
//info("using %s or %s", opt.nodelist, ai->nodelist);
while ((node_name = hostlist_shift(exc_hl))) {
int inx = hostlist_find(hl, node_name);
if (inx >= 0) {
debug("excluding node %s", node_name);
hostlist_delete_nth(hl, inx);
ai->nnodes--; /* decrement node count */
}
if(inc_hl) {
inx = hostlist_find(inc_hl, node_name);
if (inx >= 0) {
error("Requested node %s is also "
"in the excluded list.",
node_name);
error("Job not submitted.");
hostlist_destroy(exc_hl);
hostlist_destroy(inc_hl);
goto error;
}
}
free(node_name);
}
hostlist_destroy(exc_hl);
/* we need to set this here so if there are more nodes
* available than we requested we can set it
* straight. If there is no exclude list then we set
* the vars then.
*/
if (!opt.nodes_set) {
/* we don't want to set the number of nodes =
* to the number of requested processes unless we
* know it is less than the number of nodes
* in the allocation
*/
if(opt.ntasks_set && (opt.ntasks < ai->nnodes))
opt.min_nodes = opt.ntasks;
else
opt.min_nodes = ai->nnodes;
opt.nodes_set = true;
}
if(!opt.max_nodes)
opt.max_nodes = opt.min_nodes;
if((opt.max_nodes > 0) && (opt.max_nodes < ai->nnodes))
ai->nnodes = opt.max_nodes;
count = hostlist_count(hl);
if(!count) {
error("Hostlist is now nothing! Can't run job.");
hostlist_destroy(hl);
goto error;
}
if(inc_hl) {
count = hostlist_count(inc_hl);
if(count < ai->nnodes) {
/* add more nodes to get correct number for
allocation */
hostlist_t tmp_hl = hostlist_copy(hl);
int i=0;
int diff = ai->nnodes - count;
buf = hostlist_ranged_string_xmalloc(inc_hl);
hostlist_delete(tmp_hl, buf);
xfree(buf);
while ((node_name = hostlist_shift(tmp_hl)) &&
(i < diff)) {
hostlist_push(inc_hl, node_name);
i++;
}
hostlist_destroy(tmp_hl);
}
buf = hostlist_ranged_string_xmalloc(inc_hl);
hostlist_destroy(inc_hl);
xfree(opt.nodelist);
opt.nodelist = buf;
} else {
if (count > ai->nnodes) {
/* remove more nodes than needed for
allocation */
int i=0;
for (i=count; i>ai->nnodes; i--)
hostlist_delete_nth(hl, i);
}
xfree(opt.nodelist);
opt.nodelist = hostlist_ranged_string_xmalloc(hl);
}
hostlist_destroy(hl);
} else {
if (!opt.nodes_set) {
/* we don't want to set the number of nodes =
* to the number of requested processes unless we
* know it is less than the number of nodes
* in the allocation
*/
if(opt.ntasks_set && (opt.ntasks < ai->nnodes))
opt.min_nodes = opt.ntasks;
else
opt.min_nodes = ai->nnodes;
opt.nodes_set = true;
}
if(!opt.max_nodes)
opt.max_nodes = opt.min_nodes;
if((opt.max_nodes > 0) && (opt.max_nodes < ai->nnodes))
ai->nnodes = opt.max_nodes;
/* Don't reset the ai->nodelist because that is the
* nodelist we want to say the allocation is under
* opt.nodelist is what is used for the allocation.
*/
/* xfree(ai->nodelist); */
/* ai->nodelist = xstrdup(buf); */
}
/* get the correct number of hosts to run tasks on */
if (opt.nodelist) {
hl = hostlist_create(opt.nodelist);
if (opt.distribution != SLURM_DIST_ARBITRARY)
hostlist_uniq(hl);
if (!hostlist_count(hl)) {
error("Hostlist is now nothing! Can not run job.");
hostlist_destroy(hl);
goto error;
}
buf = hostlist_ranged_string_xmalloc(hl);
count = hostlist_count(hl);
hostlist_destroy(hl);
/* Don't reset the ai->nodelist because that is the
* nodelist we want to say the allocation is under
* opt.nodelist is what is used for the allocation.
*/
/* xfree(ai->nodelist); */
/* ai->nodelist = xstrdup(buf); */
xfree(opt.nodelist);
opt.nodelist = buf;
}
if (opt.distribution == SLURM_DIST_ARBITRARY) {
if (count != opt.ntasks) {
error("You asked for %d tasks but specified %d nodes",
opt.ntasks, count);
goto error;
}
}
if (ai->nnodes == 0) {
error("No nodes in allocation, can't run job");
goto error;
}
ai->num_cpu_groups = resp->num_cpu_groups;
ai->cpus_per_node = resp->cpus_per_node;
ai->cpu_count_reps = resp->cpu_count_reps;
/* info("looking for %d nodes out of %s with a must list of %s", */
/* ai->nnodes, ai->nodelist, opt.nodelist); */
/*
* Create job
*/
job = _job_create_structure(ai);
error:
xfree(ai);
return (job);
}
/*
* Create an srun job structure from a resource allocation response msg
*/
extern srun_job_t *
job_create_allocation(resource_allocation_response_msg_t *resp)
{
srun_job_t *job;
allocation_info_t *i = xmalloc(sizeof(*i));
i->nodelist = _normalize_hostlist(resp->node_list);
i->nnodes = resp->node_cnt;
i->jobid = resp->job_id;
i->stepid = NO_VAL;
i->num_cpu_groups = resp->num_cpu_groups;
i->cpus_per_node = resp->cpus_per_node;
i->cpu_count_reps = resp->cpu_count_reps;
i->select_jobinfo = select_g_select_jobinfo_copy(resp->select_jobinfo);
job = _job_create_structure(i);
xfree(i->nodelist);
xfree(i);
return (job);
}
void
update_job_state(srun_job_t *job, srun_job_state_t state)
{
pthread_mutex_lock(&job->state_mutex);
if (job->state < state) {
job->state = state;
pthread_cond_signal(&job->state_cond);
}
pthread_mutex_unlock(&job->state_mutex);
return;
}
srun_job_state_t
job_state(srun_job_t *job)
{
srun_job_state_t state;
slurm_mutex_lock(&job->state_mutex);
state = job->state;
slurm_mutex_unlock(&job->state_mutex);
return state;
}
void
job_force_termination(srun_job_t *job)
{
static int kill_sent = 0;
static time_t last_msg = 0;
if (kill_sent == 0) {
info("forcing job termination");
/* Sends SIGKILL to tasks directly */
update_job_state(job, SRUN_JOB_FORCETERM);
} else {
time_t now = time(NULL);
if (last_msg != now) {
info("job abort in progress");
last_msg = now;
}
if (kill_sent == 1) {
/* Try sending SIGKILL through slurmctld */
slurm_kill_job_step(job->jobid, job->stepid, SIGKILL);
}
}
kill_sent++;
}
static inline int
_estimate_nports(int nclients, int cli_per_port)
{
div_t d;
d = div(nclients, cli_per_port);
return d.rem > 0 ? d.quot + 1 : d.quot;
}
static int
_compute_task_count(allocation_info_t *ainfo)
{
int i, cnt = 0;
#if defined HAVE_BGQ
//#if defined HAVE_BGQ && HAVE_BG_FILES
/* always return the ntasks here for Q */
info("returning %d", opt.ntasks);
return opt.ntasks;
#endif
if (opt.cpus_set) {
for (i = 0; i < ainfo->num_cpu_groups; i++)
cnt += ( ainfo->cpu_count_reps[i] *
(ainfo->cpus_per_node[i]/opt.cpus_per_task));
}
return (cnt < ainfo->nnodes) ? ainfo->nnodes : cnt;
}
static void
_set_ntasks(allocation_info_t *ai)
{
if (!opt.ntasks_set) {
opt.ntasks = _compute_task_count(ai);
if (opt.cpus_set)
opt.ntasks_set = true; /* implicit */
}
}
/*
* Create an srun job structure from a resource allocation response msg
*/
static srun_job_t *
_job_create_structure(allocation_info_t *ainfo)
{
srun_job_t *job = xmalloc(sizeof(srun_job_t));
int i;
_set_ntasks(ainfo);
debug2("creating job with %d tasks", opt.ntasks);
slurm_mutex_init(&job->state_mutex);
pthread_cond_init(&job->state_cond, NULL);
job->state = SRUN_JOB_INIT;
job->nodelist = xstrdup(ainfo->nodelist);
job->stepid = ainfo->stepid;
#if defined HAVE_BGQ
//#if defined HAVE_BGQ && defined HAVE_BG_FILES
job->nhosts = ainfo->nnodes;
select_g_alter_node_cnt(SELECT_APPLY_NODE_MAX_OFFSET, &job->nhosts);
#elif defined HAVE_FRONT_END /* Limited job step support */
opt.overcommit = true;
job->nhosts = 1;
#else
job->nhosts = ainfo->nnodes;
#endif
#if !defined HAVE_FRONT_END || (defined HAVE_BGQ)
//#if !defined HAVE_FRONT_END || (defined HAVE_BGQ && defined HAVE_BG_FILES)
if(opt.min_nodes > job->nhosts) {
error("Only allocated %d nodes asked for %d",
job->nhosts, opt.min_nodes);
if (opt.exc_nodes) {
/* When resources are pre-allocated and some nodes
* are explicitly excluded, this error can occur. */
error("Are required nodes explicitly excluded?");
}
return NULL;
}
if ((ainfo->cpus_per_node == NULL) ||
(ainfo->cpu_count_reps == NULL)) {
error("cpus_per_node array is not set");
return NULL;
}
#endif
job->select_jobinfo = ainfo->select_jobinfo;
job->jobid = ainfo->jobid;
job->ntasks = opt.ntasks;
for (i=0; i<ainfo->num_cpu_groups; i++) {
job->cpu_count += ainfo->cpus_per_node[i] *
ainfo->cpu_count_reps[i];
}
job->rc = -1;
job_update_io_fnames(job);
return (job);
}
void
job_update_io_fnames(srun_job_t *job)
{
job->ifname = fname_create(job, opt.ifname);
job->ofname = fname_create(job, opt.ofname);
job->efname = opt.efname ? fname_create(job, opt.efname) : job->ofname;
}
static char *
_normalize_hostlist(const char *hostlist)
{
char *buf = NULL;
hostlist_t hl = hostlist_create(hostlist);
if (hl)
buf = hostlist_ranged_string_xmalloc(hl);
if (!hl || !buf)
return xstrdup(hostlist);
return buf;
}
|
chaos/slurm
|
src/srun/srun_job.c
|
C
|
gpl-2.0
| 14,643 |
###
### I think it's not worth to make such a small project
### modular. So this is a simple gnu Makefile...
###
fbgrab: fbgrab.c
splint +posixlib fbgrab.c
gcc -g -Wall fbgrab.c -lpng -lz -o fbgrab
install:
strip fbgrab
install fbgrab /usr/bin/fbgrab
install fbgrab.1.man /usr/man/man1/fbgrab.1
clean:
rm -f fbgrab *~ \#*\#
|
MikeMayer/FBGrab
|
Makefile
|
Makefile
|
gpl-2.0
| 333 |
/**
* 客户端异常演示
*
* @author XiongChun
* @since 2012-08-20
*/
Ext.onReady(function() {
var firstForm = new Ext.form.FormPanel({
id : 'firstForm',
name : 'firstForm',
labelWidth : 40, // 标签宽度
// frame : true, // 是否渲染表单面板背景色
defaultType : 'textfield', // 表单元素默认类型
labelAlign : 'right', // 标签对齐方式
bodyStyle : 'padding:5 5 5 5', // 表单元素和表单面板的边距
items : [{
fieldLabel : '文本1', // 标签
name : 'text1', // name:后台根据此name属性取值
allowBlank : true,
anchor : '100%' // 宽度百分比
}]
});
var firstWindow = new Ext.Window({
title : '<span class="commoncss">演示客户端请求异常处理</span>', // 窗口标题
layout : 'fit', // 设置窗口布局模式
width : 580, // 窗口宽度
height : 120, // 窗口高度
closable : false, // 是否可关闭
collapsible : true, // 是否可收缩
maximizable : true, // 设置是否可以最大化
border : false, // 边框线设置
constrain : true, // 设置窗口是否可以溢出父容器
pageY : 20, // 页面定位X坐标
pageX : document.body.clientWidth / 2 - 580 / 2, // 页面定位Y坐标
items : [firstForm], // 嵌入的表单面板
buttons : [{ // 窗口底部按钮配置
text : '请求1(form.submit)', // 按钮文本
iconCls : 'acceptIcon', // 按钮图标
handler : function() { // 按钮响应函数
submitTheForm();
}
}, { // 窗口底部按钮配置
text : '请求2(ajax.request)', // 按钮文本
iconCls : 'acceptIcon', // 按钮图标
handler : function() { // 按钮响应函数
submitTheFormBasedAjaxRequest();
}
}, { // 窗口底部按钮配置
text : '请求3(form.load)', // 按钮文本
iconCls : 'acceptIcon', // 按钮图标
handler : function() { // 按钮响应函数
loadCallBack();
}
}, { // 窗口底部按钮配置
text : '请求4(data.store.load)', // 按钮文本
iconCls : 'acceptIcon', // 按钮图标
handler : function() { // 按钮响应函数
loadCallBack();
}
}]
});
firstWindow.show(); // 显示窗口
/**
* 表单提交(表单自带Ajax提交)
*/
function submitTheForm() {
if (!firstForm.form.isValid())
return;
firstForm.form.submit({
url : 'otherDemo.do?reqCode=doError',
waitTitle : '提示',
method : 'POST',
waitMsg : '正在处理数据,请稍候...',
success : function(form, action) {
Ext.MessageBox.alert('提示', action.result.msg);
}
});
}
/**
* 表单提交(Ext.Ajax提交)
*/
function submitTheFormBasedAjaxRequest() {
if (!firstForm.form.isValid())
return;
var params = firstForm.getForm().getValues();
params.text4 = '文本4附加参数';
Ext.Ajax.request({
url : 'otherDemo.do?reqCode=doError',
success : function(response, opts) {
var resultArray = Ext.util.JSON
.decode(response.responseText);
Ext.Msg.alert('提示', resultArray.msg);
},
params : params
});
}
// 表单加载数据的回调函数
function loadCallBack() {
firstForm.form.load({
waitMsg : '正在读取信息',// 提示信息
waitTitle : '提示',// 标题
url : 'otherDemo.do?reqCode=doError',// 请求的url地址
// method : 'GET',// 请求方式
success : function(form, action) {// 加载成功的处理函数
Ext.Msg.alert('提示', '数据读取成功');
}
});
}
// 表格数据查询
function storeLoad() {
var store = new Ext.data.Store({
// 获取数据的方式
proxy : new Ext.data.HttpProxy({
url : 'otherDemo.do?reqCode=doError'
}),
// 数据读取器
reader : new Ext.data.JsonReader({
totalProperty : 'TOTALCOUNT', // 记录总数
root : 'ROOT' // Json中的列表数据根节点
}, [{
name : 'xmid' // Json中的属性Key值
}])
});
store.load();
}
});
|
jreadstone/zsyproject
|
WebRoot/demo/other/js/exception.js
|
JavaScript
|
gpl-2.0
| 4,475 |
<?php
/**
* Plugin Name: Timeline Twitter Feed
* Plugin URI: http://wordpress.org/plugins/timeline-twitter-feed/
* Description: Timeline Twitter Feed let's you output your timeline feed and multiple hashtags into your WordPress site as flat HTML.
* Version: 1.2
* Author: Ezra Verheijen
* Author URI: http://profiles.wordpress.org/ezraverheijen/
* License: GPL v3
* Text Domain: timeline-twitter-feed
*
* Copyright (c) 2014, Ezra Verheijen
*
* Forked from jTwits by Floris P. Lof which was forked from Twitter Feed Pro by Alex Moss.
*
* @uses weDevs Settings API from Tareq Hasan <https://github.com/tareq1988/wordpress-settings-api-class>
* @uses TwitterWP from Justin Sternberg <https://github.com/jtsternberg/TwitterWP>
*
* Timeline Twitter Feed 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.
*
* Timeline Twitter Feed 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 recieved a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit; // exit if accessed directly
}
if ( ! class_exists( 'Timeline_Twitter_Feed' ) ) {
foreach ( glob( dirname( __FILE__ ) . '/includes/*.php' ) as $file ) {
require_once( $file );
}
class Timeline_Twitter_Feed {
const PLUGIN_NAME = 'Timeline Twitter Feed';
const PLUGIN_VERSION = '1.2';
const TEXTDOMAIN = 'timeline-twitter-feed';
private $other_options = array();
function __construct() {
$this->other_options = get_option( Timeline_Twitter_Feed_Options::OTHER_OPTIONS );
add_action( 'widgets_init', array( $this, 'register_twitter_feed_widget' ) );
add_action( 'plugins_loaded', array( $this, 'load_plugin_translation' ) );
new Timeline_Twitter_Feed_Backend();
new Timeline_Twitter_Feed_Frontend();
new Timeline_Twitter_Feed_Shortcode();
if ( 'on' === $this->other_options[Timeline_Twitter_Feed_Options::APPROVAL_FIRST] ) {
new Timeline_Twitter_Feed_Dashboard_Widget();
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), array( $this, 'add_plugin_settings_link' ) );
register_activation_hook( __FILE__, array( $this, 'add_default_options_to_database' ) );
register_deactivation_hook( __FILE__, array( $this, 'add_plugin_delete_helper' ) );
}
public function register_twitter_feed_widget() {
register_widget( 'Timeline_Twitter_Feed_Widget' );
}
public function load_plugin_translation() {
load_plugin_textdomain(
self::TEXTDOMAIN,
false,
dirname( plugin_basename( __FILE__ ) ) . '/languages/'
);
}
public function add_default_options_to_database() {
add_option( Timeline_Twitter_Feed_Options::BASIC_OPTIONS, array(
Timeline_Twitter_Feed_Options::CONSUMER_KEY => '',
Timeline_Twitter_Feed_Options::CONSUMER_SECRET => '',
Timeline_Twitter_Feed_Options::ACCESS_TOKEN => '',
Timeline_Twitter_Feed_Options::ACCESS_SECRET => '',
Timeline_Twitter_Feed_Options::USERNAME => '',
Timeline_Twitter_Feed_Options::NUM_TWEETS => '3',
) );
add_option( Timeline_Twitter_Feed_Options::ADVANCED_OPTIONS, array(
Timeline_Twitter_Feed_Options::NUM_HASHTAG_TWEETS => '3',
Timeline_Twitter_Feed_Options::ONLY_HASHTAGS => 'off',
Timeline_Twitter_Feed_Options::TWITTER_JS => 'on',
Timeline_Twitter_Feed_Options::PROFILE_IMG => 'off',
Timeline_Twitter_Feed_Options::HTTPS_IMG => 'off',
Timeline_Twitter_Feed_Options::FOLLOW_BUTTON => 'on',
Timeline_Twitter_Feed_Options::LANGUAGE => 'en',
Timeline_Twitter_Feed_Options::LARGE_BUTTON => 'off',
Timeline_Twitter_Feed_Options::FOLLOWER_COUNT => 'on',
Timeline_Twitter_Feed_Options::USER_LINKS => 'on',
Timeline_Twitter_Feed_Options::HASH_LINKS => 'on',
Timeline_Twitter_Feed_Options::TIMESTAMP => 'on',
Timeline_Twitter_Feed_Options::LINK_TO_TWEET => 'on',
Timeline_Twitter_Feed_Options::USE_CSS => 'on',
Timeline_Twitter_Feed_Options::AUTH => 'on',
Timeline_Twitter_Feed_Options::ERROR_MESSAGE => 'Unable to show tweets right now...',
) );
add_option( Timeline_Twitter_Feed_Options::OTHER_OPTIONS, array(
Timeline_Twitter_Feed_Options::CACHE_EXPIRE => '300',
Timeline_Twitter_Feed_Options::DO_AJAX_UPDATES => 'off',
Timeline_Twitter_Feed_Options::KEYWORD_FILTER => '',
Timeline_Twitter_Feed_Options::APPROVAL_FIRST => 'off',
Timeline_Twitter_Feed_Options::CUSTOM_CSS => '',
Timeline_Twitter_Feed_Options::PREFIX => '(about',
Timeline_Twitter_Feed_Options::SECONDS => 'seconds',
Timeline_Twitter_Feed_Options::MINUTES => 'minutes',
Timeline_Twitter_Feed_Options::HOUR => 'hour',
Timeline_Twitter_Feed_Options::HOURS => 'hours',
Timeline_Twitter_Feed_Options::DAY => 'day',
Timeline_Twitter_Feed_Options::DAYS => 'days',
Timeline_Twitter_Feed_Options::SUFFIX => 'ago)',
) );
add_option( Timeline_Twitter_Feed_Options::APPROVED, array() );
add_option( Timeline_Twitter_Feed_Options::HASH_KEYS, array() );
}
public function add_plugin_settings_link( $links ) {
array_unshift( $links, sprintf(
'<a href="options-general.php?page=%s">%s</a>',
self::TEXTDOMAIN,
__( 'Settings' ) // translated by WordPress
) );
return $links;
}
/**
* Add an entry to the database which holds the current database entries of this plugin.
*
* @see uninstall.php
*/
public function add_plugin_delete_helper() {
add_option( 'ttf_delete_helper', array(
Timeline_Twitter_Feed_Options::BASIC_OPTIONS,
Timeline_Twitter_Feed_Options::ADVANCED_OPTIONS,
Timeline_Twitter_Feed_Options::OTHER_OPTIONS,
Timeline_Twitter_Feed_Options::HELP,
Timeline_Twitter_Feed_Options::APPROVED,
Timeline_Twitter_Feed_Options::OUTPUT,
Timeline_Twitter_Feed_Options::HASH_KEYS,
) );
}
}
new Timeline_Twitter_Feed();
}
|
xicaborrero/la-tribune
|
wp-content/plugins/timeline-twitter-feed/timeline-twitter-feed.php
|
PHP
|
gpl-2.0
| 6,613 |
var Login = {
data : function () {
return {
account : {
username : 'admin',
password : '123'
}
}
},
methods : {
submit : function () {
var _this = this;
$('#loginForm').validate({
errorElement: 'span',
errorClass: 'help-block',
rules : {
username : {
required : true
},
password : {
required : true
}
},
message : {
username : {
required : 'username required'
},
password : {
required : 'password required'
}
},
highlight: function (element) {
$(element).addClass('validateColor');
},
success: function (error,element) {
$(element).closest('.validateColor').removeClass('validateColor');
},
errorPlacement: function (error, element) {
},
invalidHandler: function (event, validator) {
var errorMap = validator.errorMap;
var uls = $('<ul>');
for (var name in errorMap) {
uls.append($('<li>').text(errorMap[name]));
}
if ($(uls).children('li').length > 0) {
toastr.clear();
toastr.error($(uls)[0], '失败');
return;
}
},
submitHandler : function (form) {
$.ajax({
url: basePath + 'doLogin',
type: "POST",
data: {
username : _this.account.username,
password : _this.account.password
},
success: function (data) {
if (data.success) {
window.location.href = '/home';
}
}
});
}
});
}
}
}
var bindLogin = Vue.extend(Login);
new bindLogin().$mount('#loginForm');
|
ISKonst88/winebosom
|
target/com.bosomwine-1.0-SNAPSHOT/resource/js/app/login/login.js
|
JavaScript
|
gpl-2.0
| 2,490 |
<?php
function connect() {
$server = "localhost";
$username = "username";
$password = "passwd";
$db = "database_name";
$pdo = new PDO("mysql:host=$server;dbname=$db",$username,$password);
// mysql_connect($server, $username, $password);
// mysql_select_db($db);
return $pdo;
}
?>
|
aaronshifman/Cascade_RNAseq_viewer
|
connection.php
|
PHP
|
gpl-2.0
| 316 |
<div class="modal-header">
<button type="button" class="close" ng-click="cancel()" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" translate="help.add_item_min_max"></h4>
</div>
<div class="modal-body">
<div class="col-md-10 col-md-offset-1" style="margin-bottom: 15px">
<button class="btn btn-group col-md-4 {{ active11 }}" ng-click="changeFormula(1)">Manual</button>
<!--<button disabled class="btn btn-group col-md-4 {{ active12 }}" ng-click="changeFormula(2)">Option One</button>-->
<!--<button disabled class="btn btn-group col-md-4 {{ active13 }}" ng-click="changeFormula(3)">Option two</button>-->
</div>
<form class="col-md-12" novalidate name="myForm" ng-if="useFormular1">
<!--item_id-->
<div class="form-group">
<label class="required" for="item_id" translate="labels.product"></label>
<select required="" id="item_id" class="form-control" ng-model="newItem.item_id" ng-options="obj.id as obj.name for obj in vaccines | filter:{status:'active'}:true">
<option value="" translate="labels.select"></option>
</select>
</div>
<!--min_value-->
<div class="form-group">
<label class="required" for="min_value" translate="labels.min_value"></label>
<input required="" type="number" min="0" ng-model="newItem.min_value" class="form-control" id="min_value" placeholder="{{ 'labels.min_value' | translate }}">
</div>
<!--max_value-->
<div class="form-group">
<label class="required" for="max_value" translate="labels.max_value"></label>
<input required="" type="number" min="0" ng-model="newItem.max_value" class="form-control" id="max_value" placeholder="{{ 'labels.max_value' | translate }}">
</div>
<button type="submit" ng-disabled="myForm.$invalid" class="btn btn-default" translate="labels.submit" ng-click="save(newItem,'items_min_max',items_min_max)"></button>
<button class="btn btn-warning" type="button" ng-click="cancel()" translate="labels.cancel"></button>
<br>
<span ng-if="currentSaving"><i class='fa fa-cog fa-2x fa-spin '></i> <span translate="labels.saving">Saving....</span> </span>
</form>
<!--formula two-->
<form class="col-md-12" novalidate name="myForm" ng-if="useFormular2">
<!--item_id-->
<div class="form-group">
<div class="col-md-12" style="margin-bottom: 15px">
<label class="required" for="item_id" translate="labels.product"></label>
<select required="" id="item_id" class="form-control" ng-model="newItem.item_id" ng-options="obj.id as obj.name for obj in vaccines | filter:{status:'active'}:true">
<option value="" translate="labels.select"></option>
</select>
</div>
</div>
<!--item_id-->
<div class="form-group" >
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="annual_need" translate="labels.annual_need"></label>
<input required="" type="text" ng-model="newItem.annual_need" class="form-control" id="annual_need" placeholder="{{ 'labels.annual_need' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="shipments_per_year" translate="labels.shipments_per_year"></label>
<input required="" type="text" ng-model="newItem.shipments_per_year" class="form-control" id="shipments_per_year" placeholder="{{ 'labels.shipments_per_year' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="exampleInputPassword1" translate="labels.annual_need_safety"></label>
<input required="" type="text" ng-model="newItem.annual_need_safety" class="form-control" id="annual_need_safety" placeholder="{{ 'labels.annual_need_safety' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="lead_time" translate="labels.lead_time"></label>
<input required="" type="text" ng-model="newItem.lead_time" class="form-control" id="lead_time" placeholder="{{ 'labels.lead_time' | translate }}">
</div>
</div>
<div class="col-md-12" style="margin-top: 10px">
<button type="submit" ng-disabled="myForm.$invalid" class="btn btn-default" translate="labels.submit" ng-click="saveFromFormula1(newItem,'items_min_max',items_min_max)"></button>
<button class="btn btn-warning" type="button" ng-click="cancel()" translate="labels.cancel"></button>
<br>
<span ng-if="currentSaving"><i class='fa fa-cog fa-2x fa-spin '></i> <span translate="labels.saving">Saving....</span> </span>
</div>
</form>
<!--formula three-->
<form class="col-md-12" novalidate name="myForm" ng-if="useFormular3">
<!--item_id-->
<div class="form-group" >
<div class="col-md-12" style="margin-bottom: 15px">
<label class="required" for="item_id" translate="labels.product"></label>
<select required="" id="item_id" class="form-control" ng-model="newItem.item_id" ng-options="obj.id as obj.name for obj in vaccines | filter:{status:'active'}:true">
<option value="" translate="labels.select"></option>
</select>
</div>
</div>
<!--item_id-->
<div class="form-group" >
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="total_population" translate="labels.total_population"></label>
<input required="" type="text" ng-model="newItem.annual_need" class="form-control" id="total_population" placeholder="{{ 'labels.total_population' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="under_one" translate="labels.under_one"></label>
<input required="" type="text" ng-model="newItem.under_one" class="form-control" id="under_one" placeholder="{{ 'labels.under_one' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="no_doses" translate="labels.no_doses"></label>
<input required="" type="text" ng-model="newItem.no_doses" class="form-control" id="no_doses" placeholder="{{ 'labels.no_doses' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="lead_time" translate="labels.wastage_factor"></label>
<input required="" type="text" ng-model="newItem.wastage_factor" class="form-control" id="wastage_factor" placeholder="{{ 'labels.wastage_factor' | translate }}">
</div>
</div>
<div class="form-group">
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="annual_need" translate="labels.coverage"></label>
<input required="" type="text" ng-model="newItem.coverage" class="form-control" id="coverage" placeholder="{{ 'labels.coverage' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="shipments_per_year1" translate="labels.shipments_per_year"></label>
<input required="" type="text" ng-model="newItem.shipments_per_year" class="form-control" id="shipments_per_year1" placeholder="{{ 'labels.shipments_per_year' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="annual_need_safety1" translate="labels.annual_need_safety"></label>
<input required="" type="text" ng-model="newItem.annual_need_safety" class="form-control" id="annual_need_safety1" placeholder="{{ 'labels.annual_need_safety' | translate }}">
</div>
<div class="col-md-3" style="margin-bottom: 15px">
<label class="required" for="lead_time1" translate="labels.lead_time"></label>
<input required="" type="text" ng-model="newItem.lead_time" class="form-control" id="lead_time1" placeholder="{{ 'labels.lead_time' | translate }}">
</div>
</div>
<div class="col-md-12" style="margin-top: 10px">
<button type="submit" ng-disabled="myForm.$invalid" class="btn btn-default" translate="labels.submit" ng-click="saveFromFormula1(newItem,'items_min_max',items_min_max)"></button>
<button class="btn btn-warning" type="button" ng-click="cancel()" translate="labels.cancel"></button>
<br>
<span ng-if="currentSaving"><i class='fa fa-cog fa-2x fa-spin '></i> <span translate="labels.saving">Saving....</span> </span>
</div>
</form>
</div>
<div class="modal-footer">
</div>
|
kelvinmbwilo/VVS
|
public/views/basicdata/addItemMaxMin.html
|
HTML
|
gpl-2.0
| 9,252 |
<?php
if (!$this->CheckPermission($this->_GetModuleAlias() . '_modify_category')) return;
$categories = array();
if(isset($params['category_id'])) {
$categories = array((int)$params['category_id']);
}
if(isset($params['categories']) && is_array($params['categories'])) {
$categories = $params['categories'];
}
foreach($categories as $category_id) {
$this->DeleteCategoryById($category_id);
}
$handlers = ob_list_handlers();
for ($cnt = 0; $cnt < sizeof($handlers); $cnt++) { ob_end_clean(); }
echo $this->ModLang('deleted');
exit();
?>
|
CmsMadeSimpleTierModules/EasyList
|
framework/action.admin_deletecategory.php
|
PHP
|
gpl-2.0
| 545 |
/*=============================================================================
*
* (C) Copyright 2011, Michael Carlisle ([email protected])
*
* http://www.TheCodeKing.co.uk
*
* All rights reserved.
* The code and information is provided "as-is" without waranty of any kind,
* either expresed or implied.
*
*-----------------------------------------------------------------------------
* History:
* 01/09/2007 Michael Carlisle Version 1.0
*=============================================================================
*/
using System.Windows.Forms;
namespace TheCodeKing.ActiveButtons.Controls
{
/// <summary>
/// The ActiveMenu class used to create concrete instances of the
/// <see cref = "T:IActiveMenu"></see> instance.
/// </summary>
/// <example>
/// This sample shows how to get an instance of the IActiveMenu and
/// render an instance of a button in the title bar.
/// <code>
/// // get an instance of the menu for the current form
/// IActiveMenu menu = ActiveMenu.GetInstance(this);
///
/// // create a new instance of ActiveButton
/// ActiveButton button = new ActiveButton();
/// button.Text = "One";
/// button.BackColor = Color.Blue;
/// button.Click += new EventHandler(button_Click);
///
/// // add the button to the title bar menu
/// menu.Items.Add(button);
/// </code>
/// </example>
public static class ActiveMenu
{
/// <summary>
/// Creates or returns the menu instance for a given form.
/// </summary>
public static IActiveMenu GetInstance(Form form)
{
return ActiveMenuImpl.GetInstance(form);
}
}
}
|
bkbartk/dRemote
|
ActiveButtons.Net-master/Source/Controls/ActiveMenu.cs
|
C#
|
gpl-2.0
| 1,730 |
<?php
/**
* @copyright Copyright 2003-2016 Zen Cart Development Team
* @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0
* @version GIT: $Id: $
*/
namespace ZenCart\AdminNotifications;
/**
* Class AdminNotifications
* @package ZenCart\AdminNotifications
*/
class AdminNotifications extends \base
{
public function __construct($session, $db)
{
$this->session = $session;
$this->db = $db;
$this->notificationList = array();
$this->initNotificationsList();
}
public function getNotificationList()
{
return $this->notificationList;
}
private function initNotificationsList()
{
}
public function addNotification($notification)
{
$entryHash = md5($notification['text']);
if ($this->notificationExists($notification)) {
return;
}
$link = '#';
if (isset($notification['link'])) {
$link = $notification['link'];
}
$class = 'fa fa-user text-red';
if (isset($notification['class'])) {
$class = $notification['class'];
}
$pageKey = '';
if (isset($notification['pageKey'])) {
$pageKey = $notification['pageKey'];
}
$this->notificationList[$notification['type']][$entryHash] = array(
'text' => $notification['text'],
'link' => $link,
'class' => $class,
'pageKey' => $pageKey
);
}
private function notificationExists($notification)
{
if (!isset($this->notificationList[$notification['type']])) {
return false;
}
$entryHash = md5($notification['text']);
if ($this->notificationList[$notification['type']]['entry'] != $entryHash) {
return false;
}
return true;
}
}
|
drbyte/zc-v1-series
|
includes/library/zencart/AdminNotifications/src/AdminNotifications.php
|
PHP
|
gpl-2.0
| 1,867 |
// Javascript For the types
jQuery(function($){
// ------------------------- GENERICS ------------------------
/**
* Simple select
*/
$('.wpdreamsSelect .wpdreamsselect').change(function () {
_self.hidden = $(this).next();
var selhidden = $(this).next().next();
var val = $(_self.hidden).val().match(/(.*[\S\s]*?)\|\|(.*)/);
var options = val[1];
var selected = val[2];
$(_self.hidden).val(options + "||" + $(this).val());
selhidden.val($(this).val());
});
$('.wpdreamsSelect .triggerer').bind('click', function () {
var parent = $(this).parent();
var select = $('select', parent);
var hidden = select.next();
var selhidden = hidden.next();
var val = $(hidden).val().replace(/(\r\n|\n|\r)/gm, "").match(/(.*[\S\s]*?)\|\|(.*)/);
var selected = $.trim(val[2]);
select.val(selected);
selhidden.val(selected);
});
/**
* Textarea as parameter
*/
$('.wpdreamsTextareaIsParam .triggerer').bind('click', function () {
$('textarea', $(this).parent()).change();
});
/**
* OnOff button
*/
$('.wpdreamsOnOff .wpdreamsOnOffInner').on('click', function () {
var hidden = $(this).prev();
var val = $(hidden).val();
if (val == 1) {
val = 0;
$(this).parent().removeClass("active");
} else {
val = 1;
$(this).parent().addClass("active");
}
$(hidden).val(val);
$(hidden).change();
});
$('.wpdreamsOnOff .triggerer').on('click', function () {
var hidden = $('input[type=hidden]', $(this).parent());
var div = $(this).parent();
var val = $(hidden).val();
if (val == 0) {
div.removeClass("active");
} else {
div.addClass("active");
}
});
/**
* YesNo button
*/
$('.wpdreamsYesNo .wpdreamsYesNoInner').on('click', function () {
var hidden = $(this).prev();
var val = $(hidden).val();
if (val == 1) {
val = 0;
$(this).parent().removeClass("active");
} else {
val = 1;
$(this).parent().addClass("active");
}
$(hidden).val(val);
$(hidden).change();
});
$('.wpdreamsYesNo .triggerer').on('click', function () {
var hidden = $('input[type=hidden]', $(this).parent());
var div = $(this).parent();
var val = $(hidden).val();
if (val == 0) {
div.removeClass("active");
} else {
div.addClass("active");
}
$(hidden).change();
});
/**
* Up-down arrow
*/
$('.wpdreams-updown .wpdreams-uparrow').click(function () {
var prev = $(this).parent().prev();
while (!prev.is('input')) {
prev = prev.prev();
}
prev.val(parseFloat($(prev).val()) + 1);
prev.change();
});
$('.wpdreams-updown .wpdreams-downarrow').click(function () {
var prev = $(this).parent().prev();
while (!prev.is('input')) {
prev = prev.prev();
}
prev.val(parseFloat($(prev).val()) - 1);
prev.change();
});
/**
* 4 value storage (padding, margin etc..)
*/
$('.wpdreamsFour input[type=text]').change(function () {
var value = "";
$('input[type=text]', $(this).parent()).each(function () {
value += $(this).val() + "||";
});
$('input[isparam=1]', $(this).parent()).val("||" + value);
$('input[isparam=1]', $(this).parent()).change();
});
$('.wpdreamsFour>fieldset>.triggerer').bind('click', function () {
var hidden = $("input[isparam=1]", $(this).parent());
var values = hidden.val().match(/\|\|(.*?)\|\|(.*?)\|\|(.*?)\|\|(.*?)\|\|/);
var i = 1;
$('input[type=text]', $(this).parent()).each(function () {
if ($(this).attr('name') != null) {
$(this).val(values[i]);
i++;
}
});
hidden.change();
});
// --------------------- COMPLEX TYPES -----------------------
/**
* Array-chained select
*/
$('.wpdreamsCustomArraySelect select').change(function () {
var $hidden = $('input[isparam=1]', $(this).parent());
var valArr = [];
$('select', $(this).parent()).each(function(index){
valArr.push( $(this).val() );
});
$hidden.val( valArr.join('||') );
});
/**
* Category selector
*/
$('div.wpdreamsCategories').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCategories-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsCategories')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).attr('bid');
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id + " li:not(.hiddend)")
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Draggable selector
*/
$('div.wpdreamsDraggable').each(function(){
var id = $(this).attr('id').match(/^wpdreamsDraggable-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsDraggable')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).attr('key');
});
val = val.substring(1);
hidden.val(val);
});
});
/**
* User role select
*/
$('div.wpdreamsUserRoleSelect').each(function(){
var id = $(this).attr('id').match(/^wpdreamsUserRoleSelect-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsUserRoleSelect')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' +name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).html();
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id)
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Custom Post types
*/
$('div.wpdreamsCustomPostTypes').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCustomPostTypes-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsCustomPostTypes')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).html();
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id)
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Custom Post types, built in version
*/
$('div.wpdreamsCustomPostTypesAll').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCustomPostTypesAll-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsCustomPostTypesAll')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).html();
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id)
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Custom post types, editable version
*/
$('div.wpdreamsCustomPostTypesEditable').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCustomPostTypesEditable-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).keyup(function () {
parent = $(this).parent();
while (!parent.hasClass('wpdreamsCustomPostTypesEditable')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $('label', this).html() + ";" + $('input', this).val();
});
val = val.substring(1);
hidden.val(val);
});
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
$("#sortable_conn" + id + " li input").keyup(function () {
parent = $(this).parent();
while (!parent.hasClass('wpdreamsCustomPostTypesEditable')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
//console.log(val);
items.each(function () {
val += "|" + $('label', this).html() + ";" + $('input', this).val();
});
val = val.substring(1);
hidden.val(val);
});
if ($("#sortable_conn" + id + " li input").length != 0) {
$("#sortable_conn" + id + " li input").keyup();
} else {
$("#sortable_conn" + id).each(function () {
parent = $(this).parent();
while (!parent.hasClass('wpdreamsCustomPostTypesEditable')) {
parent = $(parent).parent();
}
var hidden = $('input[name=' + name + ']', parent);
hidden.val("");
});
}
}
});
});
/**
* Custom field selectors
*/
$('div.wpdreamsCustomFields').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCustomFields-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsCustomFields')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).html();
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id)
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Page parent selector
*/
$('div.wpdreamsPageParents').each(function(){
var id = $(this).attr('id').match(/^wpdreamsPageParents-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsPageParents')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).attr('bid');
});
val = val.substring(1);
hidden.val(val);
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id)
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
/**
* Taxonomy term selector
*/
$('div.wpdreamsCustomTaxonomyTerm').each(function(){
var id = $(this).attr('id').match(/^wpdreamsCustomTaxonomyTerm-(.*)/)[1];
var selector = "#sortable" + id +", #sortable_conn" + id;
var name = $('input[isparam=1]', this).attr('name');
$(selector).sortable({
connectWith: ".connectedSortable"
}, {
update: function (event, ui) {
}
}).disableSelection();
$("#taxonomy_selector_" + id).change(function () {
var taxonomy = $(this).val();
$("li", "#sortable" + id).css('display', 'none').addClass('hiddend');
$("li[taxonomy='" + taxonomy + "']", "#sortable" + id).css('display', 'block').removeClass('hiddend');
});
$("#taxonomy_selector_" + id).change();
$(selector).on('sortupdate', function(event, ui) {
if (typeof(ui)!='undefined')
parent = $(ui.item).parent();
else
parent = $(event.target);
while (!parent.hasClass('wpdreamsCustomTaxonomyTerm')) {
parent = $(parent).parent();
}
var items = $('ul[id*=sortable_conn] li', parent);
var hidden = $('input[name=' + name + ']', parent);
var val = "";
items.each(function () {
val += "|" + $(this).attr('term_id') + "-" + $(this).attr('taxonomy');
});
val = val.substring(1);
hidden.val(val);
});
$("#wpdreamsCustomTaxonomyTerm-" + id + " .hide-children").change(function(){
if ($(this).get(0).checked)
$("#sortablecontainer" + id + " li").filter(':not(.termlevel-0)').css('display', 'none');
else
$("#sortablecontainer" + id + " li").filter(':not(.termlevel-0)').css('display', 'block');
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-left").click(function(){
$("#sortable_conn" + id + " li")
.detach().appendTo("#sortable" + id + "");
$(selector).trigger("sortupdate");
});
$("#sortablecontainer" + id + " .arrow-all-right").click(function(){
$("#sortable" + id + " li:not(.hiddend)")
.detach().appendTo("#sortable_conn" + id);
$(selector).trigger("sortupdate");
});
});
// ----------------------- THEME RELATED ---------------------
/**
* Theme Chooser
*
* Since 4.5.4 better load balancing and loading bar implemented.
*/
$('.wpdreamsThemeChooser select').bind('change', function () {
var c = confirm('Do you really want to load this template?');
if (!c) return;
var parent = $(this);
while (parent.is('form') != true) {
parent = parent.parent();
}
var themeDiv = $('div[name="' + $(this).val() + '"]');
var items = JSON.parse( themeDiv.text() );
var itemsCount = $.map(items, function(n, i) { return i; }).length;
// Loader start here
$("#wpd_body_loader").css("display", "block");
$("#wpd_loading_msg").html("Loading " + "0/" + itemsCount);
var count = 0;
var t = null;
// Delay the start by 1 second for the browser to finish all pending operations
setTimeout(function() {
$.each( items, function (key, value) {
param = $('input[name="' + key + '"]', parent);
if (param.length == 0)
param = $('select[name="' + key + '"]', parent);
if (param.length == 0)
param = $('textarea[name="' + key + '"]', parent);
param.val(value);
// Delay execution by 60ms for each item
setTimeout(function(tc) {
$("#wpd_loading_msg").html("Loading " + tc + "/" + itemsCount);
// Abort the execution of the loading removal
clearTimeout(t);
$('>.triggerer', param.parent()).trigger('click');
// Give 800 milliseconds to render, until the last one reached
// then remove the loader. The last timeout is not aborted,
// it is executed after 800 ms, finally removing the loading bar.
t = setTimeout(function() {
$("#wpd_body_loader").css("display", "none");
$("#preview .refresh").click();
}, (800));
}, (count * 60), (count +1) );
count++;
});
}, 1000);
});
/**
* Animation selector
*/
$('.wpdreamsAnimations .wpdreamsanimationselect').change(function () {
var parent = $(this).parent();
$('span', parent).removeClass();
$('span', parent).addClass("asp_an_" + $(this).val());
});
$('.wpdreamsAnimations .triggerer').bind('click', function () {
var parent = $(this).parent();
var select = $('select', parent);
return;
});
/**
* Image Settings
* The name of the separate params determinates the value outputted in the hidden field.
*/
$('.wpdreamsImageSettings input, .wpdreamsImageSettings select').change(function () {
parent = $(this).parent();
while (parent.hasClass('item') != true) {
parent = parent.parent();
}
var elements = $('input[param!=1], select', parent);
var hidden = $('input[param=1]', parent);
var ret = "";
elements.each(function () {
ret += $(this).attr("name") + ":" + $(this).val() + ";";
});
hidden.val(ret);
});
$('.wpdreamsImageSettings>fieldset>.triggerer').bind("click", function () {
var elements = $('input[param!=1], select', parent);
var hidden = $('input[param=1]', parent);
elements.each(function () {
var name = $(this).attr("name");
var regex = new RegExp(".*" + name + ":(.*?);.*");
val = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(regex);
$(this).val(val[1]);
if ($(this).next().hasClass('triggerer')) $(this).next().click();
});
});
//Image Settings End
/**
* Numeric unit related
*/
$('.wpdreamsNumericUnit select, .wpdreamsNumericUnit input[name=numeric]').change(function () {
var value = "";
var parent = $(this).parent();
while (parent.hasClass('wpdreamsNumericUnit') != true) {
parent = $(parent).parent();
}
var value = $('input[name=numeric]', parent).val() + $('select', parent).val();
$('input[type=hidden]', parent).val(value);
});
$('.wpdreamsNumericUnit .triggerer').bind('click', function () {
var value = "";
var parent = $(this).parent();
while (parent.hasClass('wpdreamsNumericUnit') != true) {
parent = $(parent).parent();
}
var hiddenval = $('input[type=hidden]', parent).val();
var value = hiddenval.match(/([0-9]+)(.*)/)
$('input[name=numeric]', parent).val(value[1]);
$('select', parent).val(value[2]);
});
/**
* Image chooser (radio image)
*/
$('.wpdreamsImageRadio img.radioimage').click(function () {
var $parent = $(this).parent();
var $hidden = $("input[class=realvalue]", $parent);
$('img.selected', $parent).removeClass('selected');
$(this).addClass('selected');
var value = $(this).attr('sel').substring(1);
$hidden.val(value);
$hidden.change();
});
$('.wpdreamsImageRadio .triggerer').bind('click', function () {
var $parent = $(this).parent();
var $hidden = $("input[class=realvalue]", $parent);
$('img.selected', $parent).removeClass('selected');
$('img[src*="' + $hidden.val() + '"]', $parent).addClass('selected');
$hidden.change();
});
/**
* Loader chooser
*/
$('.wpdreamsLoaderSelect .asp-select-loader, .wpdreamsLoaderSelect .asp-select-loader-selected').click(function () {
var $parent = $(this).parent();
var $hidden = $("input[class=realvalue]", $parent);
$('div.asp-select-loader-selected', $parent)
.addClass('asp-select-loader')
.removeClass('asp-select-loader-selected');
$(this).addClass('asp-select-loader-selected').removeClass('asp-select-loader');
var value = $(this).attr('sel');
$hidden.val(value);
$hidden.change();
});
$('.wpdreamsLoaderSelect .triggerer').bind('click', function () {
var $parent = $(this).parent();
var $hidden = $("input[class=realvalue]", $parent);
$('div.asp-select-loader-selected', $parent)
.addClass('asp-select-loader')
.removeClass('asp-select-loader-selected');
$('div[sel*="' + $hidden.val() + '"]', $parent)
.addClass('asp-select-loader-selected')
.removeClass('asp-select-loader');
$hidden.change();
});
/**
* Spectrum: color chooser
*/
$(".wpdreamsColorPicker .color").spectrum({
showInput: true,
showAlpha: true,
showPalette: true,
showSelectionPalette: true
});
$('.wpdreamsColorPicker .triggerer').bind('click', function () {
function hex2rgb(hex, opacity) {
var rgb = hex.replace('#', '').match(/(.{2})/g);
var i = 3;
while (i--) {
rgb[i] = parseInt(rgb[i], 16);
}
if (typeof opacity == 'undefined') {
return 'rgb(' + rgb.join(', ') + ')';
}
return 'rgba(' + rgb.join(', ') + ', ' + opacity + ')';
}
var parent = $(this).parent();
var input = $('input.color', parent);
var val = input.val();
if (val.length <= 7) val = hex2rgb(val, 1);
input.spectrum("set", val);
});
/**
* Gradient chooser
*/
$(".wpdreamsGradient .color, .wpdreamsGradient .grad_type, .wpdreamsGradient .dslider").change(function () {
var $parent = $(this);
while (!$parent.hasClass('wpdreamsGradient')) {
$parent = $parent.parent();
}
var $hidden = $('input.gradient', $parent);
var $colors = $('input.color', $parent);
var $type = $('select.grad_type', $parent);
var $dslider = $('div.dslider', $parent);
var $grad_ex = $('div.grad_ex', $parent);
var $dbg = $('div.dbg', $parent);
var $dtxt = $('div.dtxt', $parent);
$dbg.css({
"-webkit-transform": "rotate(" + $dslider.slider('value') + "deg)",
"-moz-transform": "rotate(" + $dslider.slider('value') + "deg)",
"transform": "rotate(" + $dslider.slider('value') + "deg)"
});
$dtxt.html($dslider.slider('value'));
grad($grad_ex, $($colors[0]).val(), $($colors[1]).val(), $type.val(), $dslider.slider('value'));
$hidden.val(
$type.val() + '-' +
$dslider.slider('value') + '-' +
$($colors[0]).val() + '-' +
$($colors[1]).val()
);
$hidden.change();
});
$(".wpdreamsGradient>.triggerer").click(function () {
var $parent = $(this).parent();
var $hidden = $('input.gradient', $parent);
var $colors = $('input.color', $parent);
var $dslider = $('div.dslider', $parent);
var $type = $('select.grad_type', $parent);
var colors = $hidden.val().match(/(.*?)-(.*?)-(.*?)-(.*)/);
if (colors == null || colors[1] == null) {
//Fallback to older 1 color
$type.val(0);
$dslider.slider('value', 0);
$($colors[0]).spectrum('set', $hidden.val());
$($colors[1]).spectrum('set', $hidden.val());
} else {
$type.val(colors[1]);
$dslider.slider('value', colors[2]);
$($colors[0]).val(colors[3]);
$($colors[1]).val(colors[4]);
$($colors[0]).spectrum('set', colors[3]);
$($colors[1]).spectrum('set', colors[4]);
}
});
function grad(el, c1, c2, t, d) {
if (t != 0) {
$(el).css('background-image', '-webkit-linear-gradient(' + d + 'deg, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-moz-linear-gradient(' + d + 'deg, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-ms-linear-gradient(' + d + 'deg, ' + c1 + ', ' + c2 + ')')
.css('background-image', 'linear-gradient(' + d + 'deg, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-o-linear-gradient(' + d + 'deg, ' + c1 + ', ' + c2 + ')');
} else {
$(el).css('background-image', '-webkit-radial-gradient(center, ellipse cover, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-moz-radial-gradient(center, ellipse cover, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-ms-radial-gradient(center, ellipse cover, ' + c1 + ', ' + c2 + ')')
.css('background-image', 'radial-gradient(ellipse at center, ' + c1 + ', ' + c2 + ')')
.css('background-image', '-o-radial-gradient(center, ellipse cover, ' + c1 + ', ' + c2 + ')');
}
}
/**
* TextShadow chooser
*/
$('.wpdreamsTextShadow input[type=text]').change(function () {
var value = "";
var parent = $(this).parent();
while (parent.hasClass('wpdreamsTextShadow') != true) {
parent = $(parent).parent();
}
var hlength = $.trim($('input[name*="_xx_hlength_xx_"]', parent).val()) + "px ";
var vlength = $.trim($('input[name*="_xx_vlength_xx_"]', parent).val()) + "px ";
var blurradius = $.trim($('input[name*="_xx_blurradius_xx_"]', parent).val()) + "px ";
var color = $.trim($('input[name*="_xx_color_xx_"]', parent).val()) + " ";
var boxshadow = "text-shadow:" + hlength + vlength + blurradius + color;
$('input[type=hidden]', parent).val(boxshadow);
$('input[type=hidden]', parent).change();
});
$('.wpdreamsTextShadow>fieldset>.triggerer').bind('click', function () {
var parent = $(this).parent();
var hidden = $("input[type=hidden]", parent);
var boxshadow = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(/box-shadow:(.*?)px (.*?)px (.*?)px (.*?);/);
$('input[name*="_xx_hlength_xx_"]', parent).val(boxshadow[1]) + "px ";
$('input[name*="_xx_vlength_xx_"]', parent).val(boxshadow[2]) + "px ";
$('input[name*="_xx_blurradius_xx_"]', parent).val(boxshadow[3]) + "px ";
$('input[name*="_xx_color_xx_"]', parent).val(boxshadow[4]) + " ";
$('input[name*="_xx_color_xx_"]', parent).keyup();
});
/**
* BoxShadow chooser
*/
$('.wpdreamsBoxShadow input[type=text], .wpdreamsBoxShadow select').change(function () {
var value = "";
var parent = $(this).parent();
while (parent.hasClass('wpdreamsBoxShadow') != true) {
parent = $(parent).parent();
}
var hlength = $.trim($('input[name*="_xx_hlength_xx_"]', parent).val()) + "px ";
var vlength = $.trim($('input[name*="_xx_vlength_xx_"]', parent).val()) + "px ";
var blurradius = $.trim($('input[name*="_xx_blurradius_xx_"]', parent).val()) + "px ";
var spread = $.trim($('input[name*="_xx_spread_xx_"]', parent).val()) + "px ";
var color = $.trim($('input[name*="_xx_color_xx_"]', parent).val()) + " ";
var inset = $.trim($('select[name*="_xx_inset_xx_"]', parent).val()) + ";";
var boxshadow = "box-shadow:" + hlength + vlength + blurradius + spread + color + inset;
$('input[type=hidden]', parent).val(boxshadow);
$('input[type=hidden]', parent).change();
});
$('.wpdreamsBoxShadow>fieldset>.triggerer').bind('click', function () {
var parent = $(this).parent();
var hidden = $("input[type=hidden]", parent);
var boxshadow = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(/box-shadow:(.*?)px (.*?)px (.*?)px (.*?)px (.*?)\) (.*?);/);
var plus = ")";
if (boxshadow == null) {
boxshadow = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(/box-shadow:(.*?)px (.*?)px (.*?)px (.*?)px (.*?) (.*?);/);
plus = '';
}
$('input[name*="_xx_hlength_xx_"]', parent).val(boxshadow[1]);
$('input[name*="_xx_vlength_xx_"]', parent).val(boxshadow[2]);
$('input[name*="_xx_blurradius_xx_"]', parent).val(boxshadow[3]);
$('input[name*="_xx_spread_xx_"]', parent).val(boxshadow[4]);
$('input[name*="_xx_color_xx_"]', parent).val(boxshadow[5] + plus);
$('select[name*="_xx_inset_xx_"]', parent).val(boxshadow[6]);
$('input[name*="_xx_color_xx_"]', parent).spectrum('set', boxshadow[5] + plus);
});
/**
* Border chooser
*/
$('.wpdreamsBorder input[type=text], .wpdreamsBorder select').bind("change", function () {
var value = "";
var parent = $(this).parent();
while (parent.hasClass('wpdreamsBorder') != true) {
parent = $(parent).parent();
}
var width = $('input[name*="_xx_width_xx_"]', parent).val() + "px ";
var style = $('select[name*="_xx_style_xx_"]', parent).val() + " ";
var color = $('input[name*="_xx_color_xx_"]', parent).val() + ";";
var border = "border:" + width + style + color;
var topleft = $.trim($('input[name*="_xx_topleft_xx_"]', parent).val()) + "px ";
var topright = $.trim($('input[name*="_xx_topright_xx_"]', parent).val()) + "px ";
var bottomright = $.trim($('input[name*="_xx_bottomright_xx_"]', parent).val()) + "px ";
var bottomleft = $.trim($('input[name*="_xx_bottomleft_xx_"]', parent).val()) + "px;";
var borderradius = "border-radius:" + topleft + topright + bottomright + bottomleft;
var value = border + borderradius;
$('input[type=hidden]', parent).val(value);
$('input[type=hidden]', parent).change();
});
$('.wpdreamsBorder>fieldset>.triggerer').bind('click', function () {
var parent = $(this).parent();
var hidden = $("input[type=hidden]", parent);
var border = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(/border:(.*?)px (.*?) (.*?);/);
$('input[name*="_xx_width_xx_"]', parent).val(border[1]) + "px ";
$('select[name*="_xx_style_xx_"]', parent).val(border[2]) + " ";
$('input[name*="_xx_color_xx_"]', parent).val(border[3]) + ";";
var borderradius = hidden.val().replace(/(\r\n|\n|\r)/gm, "").match(/border-radius:(.*?)px(.*?)px(.*?)px(.*?)px;/);
$('input[name*="_xx_topleft_xx_"]', parent).val(borderradius[1]) + "px ";
$('input[name*="_xx_topright_xx_"]', parent).val(borderradius[2]) + "px ";
$('input[name*="_xx_bottomright_xx_"]', parent).val(borderradius[3]) + "px ";
$('input[name*="_xx_bottomleft_xx_"]', parent).val(borderradius[4]) + "px;";
$('input[name*="_xx_color_xx_"]', parent).spectrum('set', border[3]);
});
/**
* Border Radius chooser
*/
$('.wpdreamsBorderRadius input[type=text]').change(function () {
var value = "";
$('input[type=text]', $(this).parent()).each(function () {
value += " " + $(this).val() + "px";
});
$('input[type=hidden]', $(this).parent()).val("border-radius:" + value + ";");
$('input[type=hidden]', $(this).parent()).change();
});
$('.wpdreamsBorderRadius>fieldset>.triggerer').bind('click', function () {
var hidden = $("input[type=hidden]", $(this).parent());
var values = hidden.val().match(/(.*?)px(.*?)px(.*?)px(.*?)px;/);
var i = 1;
$('input[type=text]', $(this).parent()).each(function () {
if ($(this).attr('name') != null) {
$(this).val(values[i]);
i++;
}
});
});
// ----------------------- ETC.. ---------------------
$('.successMsg').each(function () {
$(this).delay(4000).fadeOut();
});
$('img.delete').click(function () {
var del = confirm("Do yo really want to delete this item?");
if (del) {
$(this).next().submit();
}
});
});
|
hikaram/wee
|
wp-content/plugins/ajax-search-pro/backend/settings/assets/types_1.js
|
JavaScript
|
gpl-2.0
| 38,480 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Search_Lucene
* @subpackage Search
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Search_Lucene_Search_Similarity_Default */
//require_once 'Zend/Search/Lucene/Search/Similarity/Default.php';
/**
* @category Zend
* @package Zend_Search_Lucene
* @subpackage Search
* @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
abstract class Zend_Search_Lucene_Search_Similarity
{
/**
* The Similarity implementation used by default.
*
* @var Zend_Search_Lucene_Search_Similarity
*/
private static $_defaultImpl;
/**
* Cache of decoded bytes.
* Array of floats
*
* @var array
*/
private static $_normTable = array( 0 => 0.0,
1 => 5.820766E-10,
2 => 6.9849193E-10,
3 => 8.1490725E-10,
4 => 9.313226E-10,
5 => 1.1641532E-9,
6 => 1.3969839E-9,
7 => 1.6298145E-9,
8 => 1.8626451E-9,
9 => 2.3283064E-9,
10 => 2.7939677E-9,
11 => 3.259629E-9,
12 => 3.7252903E-9,
13 => 4.656613E-9,
14 => 5.5879354E-9,
15 => 6.519258E-9,
16 => 7.4505806E-9,
17 => 9.313226E-9,
18 => 1.1175871E-8,
19 => 1.3038516E-8,
20 => 1.4901161E-8,
21 => 1.8626451E-8,
22 => 2.2351742E-8,
23 => 2.6077032E-8,
24 => 2.9802322E-8,
25 => 3.7252903E-8,
26 => 4.4703484E-8,
27 => 5.2154064E-8,
28 => 5.9604645E-8,
29 => 7.4505806E-8,
30 => 8.940697E-8,
31 => 1.0430813E-7,
32 => 1.1920929E-7,
33 => 1.4901161E-7,
34 => 1.7881393E-7,
35 => 2.0861626E-7,
36 => 2.3841858E-7,
37 => 2.9802322E-7,
38 => 3.5762787E-7,
39 => 4.172325E-7,
40 => 4.7683716E-7,
41 => 5.9604645E-7,
42 => 7.1525574E-7,
43 => 8.34465E-7,
44 => 9.536743E-7,
45 => 1.1920929E-6,
46 => 1.4305115E-6,
47 => 1.66893E-6,
48 => 1.9073486E-6,
49 => 2.3841858E-6,
50 => 2.861023E-6,
51 => 3.33786E-6,
52 => 3.8146973E-6,
53 => 4.7683716E-6,
54 => 5.722046E-6,
55 => 6.67572E-6,
56 => 7.6293945E-6,
57 => 9.536743E-6,
58 => 1.1444092E-5,
59 => 1.335144E-5,
60 => 1.5258789E-5,
61 => 1.9073486E-5,
62 => 2.2888184E-5,
63 => 2.670288E-5,
64 => 3.0517578E-5,
65 => 3.8146973E-5,
66 => 4.5776367E-5,
67 => 5.340576E-5,
68 => 6.1035156E-5,
69 => 7.6293945E-5,
70 => 9.1552734E-5,
71 => 1.0681152E-4,
72 => 1.2207031E-4,
73 => 1.5258789E-4,
74 => 1.8310547E-4,
75 => 2.1362305E-4,
76 => 2.4414062E-4,
77 => 3.0517578E-4,
78 => 3.6621094E-4,
79 => 4.272461E-4,
80 => 4.8828125E-4,
81 => 6.1035156E-4,
82 => 7.324219E-4,
83 => 8.544922E-4,
84 => 9.765625E-4,
85 => 0.0012207031,
86 => 0.0014648438,
87 => 0.0017089844,
88 => 0.001953125,
89 => 0.0024414062,
90 => 0.0029296875,
91 => 0.0034179688,
92 => 0.00390625,
93 => 0.0048828125,
94 => 0.005859375,
95 => 0.0068359375,
96 => 0.0078125,
97 => 0.009765625,
98 => 0.01171875,
99 => 0.013671875,
100 => 0.015625,
101 => 0.01953125,
102 => 0.0234375,
103 => 0.02734375,
104 => 0.03125,
105 => 0.0390625,
106 => 0.046875,
107 => 0.0546875,
108 => 0.0625,
109 => 0.078125,
110 => 0.09375,
111 => 0.109375,
112 => 0.125,
113 => 0.15625,
114 => 0.1875,
115 => 0.21875,
116 => 0.25,
117 => 0.3125,
118 => 0.375,
119 => 0.4375,
120 => 0.5,
121 => 0.625,
122 => 0.75,
123 => 0.875,
124 => 1.0,
125 => 1.25,
126 => 1.5,
127 => 1.75,
128 => 2.0,
129 => 2.5,
130 => 3.0,
131 => 3.5,
132 => 4.0,
133 => 5.0,
134 => 6.0,
135 => 7.0,
136 => 8.0,
137 => 10.0,
138 => 12.0,
139 => 14.0,
140 => 16.0,
141 => 20.0,
142 => 24.0,
143 => 28.0,
144 => 32.0,
145 => 40.0,
146 => 48.0,
147 => 56.0,
148 => 64.0,
149 => 80.0,
150 => 96.0,
151 => 112.0,
152 => 128.0,
153 => 160.0,
154 => 192.0,
155 => 224.0,
156 => 256.0,
157 => 320.0,
158 => 384.0,
159 => 448.0,
160 => 512.0,
161 => 640.0,
162 => 768.0,
163 => 896.0,
164 => 1024.0,
165 => 1280.0,
166 => 1536.0,
167 => 1792.0,
168 => 2048.0,
169 => 2560.0,
170 => 3072.0,
171 => 3584.0,
172 => 4096.0,
173 => 5120.0,
174 => 6144.0,
175 => 7168.0,
176 => 8192.0,
177 => 10240.0,
178 => 12288.0,
179 => 14336.0,
180 => 16384.0,
181 => 20480.0,
182 => 24576.0,
183 => 28672.0,
184 => 32768.0,
185 => 40960.0,
186 => 49152.0,
187 => 57344.0,
188 => 65536.0,
189 => 81920.0,
190 => 98304.0,
191 => 114688.0,
192 => 131072.0,
193 => 163840.0,
194 => 196608.0,
195 => 229376.0,
196 => 262144.0,
197 => 327680.0,
198 => 393216.0,
199 => 458752.0,
200 => 524288.0,
201 => 655360.0,
202 => 786432.0,
203 => 917504.0,
204 => 1048576.0,
205 => 1310720.0,
206 => 1572864.0,
207 => 1835008.0,
208 => 2097152.0,
209 => 2621440.0,
210 => 3145728.0,
211 => 3670016.0,
212 => 4194304.0,
213 => 5242880.0,
214 => 6291456.0,
215 => 7340032.0,
216 => 8388608.0,
217 => 1.048576E7,
218 => 1.2582912E7,
219 => 1.4680064E7,
220 => 1.6777216E7,
221 => 2.097152E7,
222 => 2.5165824E7,
223 => 2.9360128E7,
224 => 3.3554432E7,
225 => 4.194304E7,
226 => 5.0331648E7,
227 => 5.8720256E7,
228 => 6.7108864E7,
229 => 8.388608E7,
230 => 1.00663296E8,
231 => 1.17440512E8,
232 => 1.34217728E8,
233 => 1.6777216E8,
234 => 2.01326592E8,
235 => 2.34881024E8,
236 => 2.68435456E8,
237 => 3.3554432E8,
238 => 4.02653184E8,
239 => 4.69762048E8,
240 => 5.3687091E8,
241 => 6.7108864E8,
242 => 8.0530637E8,
243 => 9.395241E8,
244 => 1.07374182E9,
245 => 1.34217728E9,
246 => 1.61061274E9,
247 => 1.87904819E9,
248 => 2.14748365E9,
249 => 2.68435456E9,
250 => 3.22122547E9,
251 => 3.75809638E9,
252 => 4.2949673E9,
253 => 5.3687091E9,
254 => 6.4424509E9,
255 => 7.5161928E9 );
/**
* Set the default Similarity implementation used by indexing and search
* code.
*
* @param Zend_Search_Lucene_Search_Similarity $similarity
*/
public static function setDefault(Zend_Search_Lucene_Search_Similarity $similarity)
{
self::$_defaultImpl = $similarity;
}
/**
* Return the default Similarity implementation used by indexing and search
* code.
*
* @return Zend_Search_Lucene_Search_Similarity
*/
public static function getDefault()
{
if (!self::$_defaultImpl instanceof Zend_Search_Lucene_Search_Similarity) {
self::$_defaultImpl = new Zend_Search_Lucene_Search_Similarity_Default();
}
return self::$_defaultImpl;
}
/**
* Computes the normalization value for a field given the total number of
* terms contained in a field. These values, together with field boosts, are
* stored in an index and multipled into scores for hits on each field by the
* search code.
*
* Matches in longer fields are less precise, so implemenations of this
* method usually return smaller values when 'numTokens' is large,
* and larger values when 'numTokens' is small.
*
* That these values are computed under
* IndexWriter::addDocument(Document) and stored then using
* encodeNorm(float). Thus they have limited precision, and documents
* must be re-indexed if this method is altered.
*
* fieldName - name of field
* numTokens - the total number of tokens contained in fields named
* 'fieldName' of 'doc'.
* Returns a normalization factor for hits on this field of this document
*
* @param string $fieldName
* @param integer $numTokens
* @return float
*/
abstract public function lengthNorm($fieldName, $numTokens);
/**
* Computes the normalization value for a query given the sum of the squared
* weights of each of the query terms. This value is then multipled into the
* weight of each query term.
*
* This does not affect ranking, but rather just attempts to make scores
* from different queries comparable.
*
* sumOfSquaredWeights - the sum of the squares of query term weights
* Returns a normalization factor for query weights
*
* @param float $sumOfSquaredWeights
* @return float
*/
abstract public function queryNorm($sumOfSquaredWeights);
/**
* Decodes a normalization factor stored in an index.
*
* @param integer $byte
* @return float
*/
public static function decodeNorm($byte)
{
return self::$_normTable[$byte & 0xFF];
}
/**
* Encodes a normalization factor for storage in an index.
*
* The encoding uses a five-bit exponent and three-bit mantissa, thus
* representing values from around 7x10^9 to 2x10^-9 with about one
* significant decimal digit of accuracy. Zero is also represented.
* Negative numbers are rounded up to zero. Values too large to represent
* are rounded down to the largest representable value. Positive values too
* small to represent are rounded up to the smallest positive representable
* value.
*
* @param float $f
* @return integer
*/
static function encodeNorm($f)
{
return self::_floatToByte($f);
}
/**
* Float to byte conversion
*
* @param integer $b
* @return float
*/
private static function _floatToByte($f)
{
// round negatives up to zero
if ($f <= 0.0) {
return 0;
}
// search for appropriate value
$lowIndex = 0;
$highIndex = 255;
while ($highIndex >= $lowIndex) {
// $mid = ($highIndex - $lowIndex)/2;
$mid = ($highIndex + $lowIndex) >> 1;
$delta = $f - self::$_normTable[$mid];
if ($delta < 0) {
$highIndex = $mid-1;
} elseif ($delta > 0) {
$lowIndex = $mid+1;
} else {
return $mid; // We got it!
}
}
// round to closest value
if ($highIndex != 255 &&
$f - self::$_normTable[$highIndex] > self::$_normTable[$highIndex+1] - $f ) {
return $highIndex + 1;
} else {
return $highIndex;
}
}
/**
* Computes a score factor based on a term or phrase's frequency in a
* document. This value is multiplied by the idf(Term, Searcher)
* factor for each term in the query and these products are then summed to
* form the initial score for a document.
*
* Terms and phrases repeated in a document indicate the topic of the
* document, so implementations of this method usually return larger values
* when 'freq' is large, and smaller values when 'freq'
* is small.
*
* freq - the frequency of a term within a document
* Returns a score factor based on a term's within-document frequency
*
* @param float $freq
* @return float
*/
abstract public function tf($freq);
/**
* Computes the amount of a sloppy phrase match, based on an edit distance.
* This value is summed for each sloppy phrase match in a document to form
* the frequency that is passed to tf(float).
*
* A phrase match with a small edit distance to a document passage more
* closely matches the document, so implementations of this method usually
* return larger values when the edit distance is small and smaller values
* when it is large.
*
* distance - the edit distance of this sloppy phrase match
* Returns the frequency increment for this match
*
* @param integer $distance
* @return float
*/
abstract public function sloppyFreq($distance);
/**
* Computes a score factor for a simple term or a phrase.
*
* The default implementation is:
* return idfFreq(searcher.docFreq(term), searcher.maxDoc());
*
* input - the term in question or array of terms
* reader - reader the document collection being searched
* Returns a score factor for the term
*
* @param mixed $input
* @param Zend_Search_Lucene_Interface $reader
* @return a score factor for the term
*/
public function idf($input, Zend_Search_Lucene_Interface $reader)
{
if (!is_array($input)) {
return $this->idfFreq($reader->docFreq($input), $reader->count());
} else {
$idf = 0.0;
foreach ($input as $term) {
$idf += $this->idfFreq($reader->docFreq($term), $reader->count());
}
return $idf;
}
}
/**
* Computes a score factor based on a term's document frequency (the number
* of documents which contain the term). This value is multiplied by the
* tf(int) factor for each term in the query and these products are
* then summed to form the initial score for a document.
*
* Terms that occur in fewer documents are better indicators of topic, so
* implemenations of this method usually return larger values for rare terms,
* and smaller values for common terms.
*
* docFreq - the number of documents which contain the term
* numDocs - the total number of documents in the collection
* Returns a score factor based on the term's document frequency
*
* @param integer $docFreq
* @param integer $numDocs
* @return float
*/
abstract public function idfFreq($docFreq, $numDocs);
/**
* Computes a score factor based on the fraction of all query terms that a
* document contains. This value is multiplied into scores.
*
* The presence of a large portion of the query terms indicates a better
* match with the query, so implemenations of this method usually return
* larger values when the ratio between these parameters is large and smaller
* values when the ratio between them is small.
*
* overlap - the number of query terms matched in the document
* maxOverlap - the total number of terms in the query
* Returns a score factor based on term overlap with the query
*
* @param integer $overlap
* @param integer $maxOverlap
* @return float
*/
abstract public function coord($overlap, $maxOverlap);
}
|
chisimba/chisimba
|
app/core_modules/search/resources/1.7.3/Search/Lucene/Search/Similarity.php
|
PHP
|
gpl-2.0
| 24,755 |
<?php
/**
* @package Joomla.Administrator
* @subpackage com_plugins
*
* @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Plugins\Administrator\Model;
defined('_JEXEC') or die;
use Joomla\CMS\Mvc\Factory\MvcFactoryInterface;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Model\ListModel;
use Joomla\Utilities\ArrayHelper;
/**
* Methods supporting a list of plugin records.
*
* @since 1.6
*/
class Plugins extends ListModel
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
* @param MvcFactoryInterface $factory The factory.
*
* @see \Joomla\CMS\Model\Model
* @since 3.2
*/
public function __construct($config = array(), MvcFactoryInterface $factory = null)
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'extension_id', 'a.extension_id',
'name', 'a.name',
'folder', 'a.folder',
'element', 'a.element',
'checked_out', 'a.checked_out',
'checked_out_time', 'a.checked_out_time',
'state', 'a.state',
'enabled', 'a.enabled',
'access', 'a.access', 'access_level',
'ordering', 'a.ordering',
'client_id', 'a.client_id',
);
}
parent::__construct($config, $factory);
}
/**
* Method to auto-populate the model state.
*
* Note. Calling getState in this method will result in recursion.
*
* @param string $ordering An optional ordering field.
* @param string $direction An optional direction (asc|desc).
*
* @return void
*
* @since 1.6
*/
protected function populateState($ordering = 'folder', $direction = 'asc')
{
// Load the parameters.
$params = ComponentHelper::getParams('com_plugins');
$this->setState('params', $params);
// List state information.
parent::populateState($ordering, $direction);
}
/**
* Method to get a store id based on model configuration state.
*
* This is necessary because the model is used by the component and
* different modules that might need different sets of data or different
* ordering requirements.
*
* @param string $id A prefix for the store id.
*
* @return string A store id.
*/
protected function getStoreId($id = '')
{
// Compile the store id.
$id .= ':' . $this->getState('filter.search');
$id .= ':' . $this->getState('filter.access');
$id .= ':' . $this->getState('filter.enabled');
$id .= ':' . $this->getState('filter.folder');
return parent::getStoreId($id);
}
/**
* Returns an object list.
*
* @param \JDatabaseQuery $query A database query object.
* @param integer $limitstart Offset.
* @param integer $limit The number of records.
*
* @return array
*/
protected function _getList($query, $limitstart = 0, $limit = 0)
{
$search = $this->getState('filter.search');
$ordering = $this->getState('list.ordering', 'ordering');
// If "Sort Table By:" is not set, set ordering to name
if ($ordering == '')
{
$ordering = 'name';
}
if ($ordering == 'name' || (!empty($search) && stripos($search, 'id:') !== 0))
{
$this->_db->setQuery($query);
$result = $this->_db->loadObjectList();
$this->translate($result);
if (!empty($search))
{
$escapedSearchString = $this->refineSearchStringToRegex($search, '/');
foreach ($result as $i => $item)
{
if (!preg_match("/$escapedSearchString/i", $item->name))
{
unset($result[$i]);
}
}
}
$orderingDirection = strtolower($this->getState('list.direction'));
$direction = ($orderingDirection == 'desc') ? -1 : 1;
$result = ArrayHelper::sortObjects($result, $ordering, $direction, true, true);
$total = count($result);
$this->cache[$this->getStoreId('getTotal')] = $total;
if ($total < $limitstart)
{
$limitstart = 0;
$this->setState('list.start', 0);
}
return array_slice($result, $limitstart, $limit ?: null);
}
else
{
if ($ordering == 'ordering')
{
$query->order('a.folder ASC');
$ordering = 'a.ordering';
}
$query->order($this->_db->quoteName($ordering) . ' ' . $this->getState('list.direction'));
if ($ordering == 'folder')
{
$query->order('a.ordering ASC');
}
$result = parent::_getList($query, $limitstart, $limit);
$this->translate($result);
return $result;
}
}
/**
* Translate a list of objects.
*
* @param array &$items The array of objects.
*
* @return array The array of translated objects.
*/
protected function translate(&$items)
{
$lang = \JFactory::getLanguage();
foreach ($items as &$item)
{
$source = JPATH_PLUGINS . '/' . $item->folder . '/' . $item->element;
$extension = 'plg_' . $item->folder . '_' . $item->element;
$lang->load($extension . '.sys', JPATH_ADMINISTRATOR, null, false, true)
|| $lang->load($extension . '.sys', $source, null, false, true);
$item->name = \JText::_($item->name);
}
}
/**
* Build an SQL query to load the list data.
*
* @return \JDatabaseQuery
*/
protected function getListQuery()
{
// Create a new query object.
$db = $this->getDbo();
$query = $db->getQuery(true);
// Select the required fields from the table.
$query->select(
$this->getState(
'list.select',
'a.extension_id , a.name, a.element, a.folder, a.checked_out, a.checked_out_time,' .
' a.enabled, a.access, a.ordering'
)
)
->from($db->quoteName('#__extensions') . ' AS a')
->where($db->quoteName('type') . ' = ' . $db->quote('plugin'));
// Join over the users for the checked out user.
$query->select('uc.name AS editor')
->join('LEFT', '#__users AS uc ON uc.id=a.checked_out');
// Join over the asset groups.
$query->select('ag.title AS access_level')
->join('LEFT', '#__viewlevels AS ag ON ag.id = a.access');
// Filter by access level.
if ($access = $this->getState('filter.access'))
{
$query->where('a.access = ' . (int) $access);
}
// Filter by published state.
$published = (string) $this->getState('filter.enabled');
if (is_numeric($published))
{
$query->where('a.enabled = ' . (int) $published);
}
elseif ($published === '')
{
$query->where('(a.enabled IN (0, 1))');
}
// Filter by state.
$query->where('a.state >= 0');
// Filter by folder.
if ($folder = $this->getState('filter.folder'))
{
$query->where('a.folder = ' . $db->quote($folder));
}
// Filter by search in name or id.
$search = $this->getState('filter.search');
if (!empty($search))
{
if (stripos($search, 'id:') === 0)
{
$query->where('a.extension_id = ' . (int) substr($search, 3));
}
}
return $query;
}
/**
* Method to get the data that should be injected in the form.
*
* @return mixed The data for the form.
*
* @since 3.5
*/
protected function loadFormData()
{
$data = parent::loadFormData();
// Set the selected filter values for pages that use the \JLayouts for filtering
$data->list['sortTable'] = $this->state->get('list.ordering');
$data->list['directionTable'] = $this->state->get('list.direction');
return $data;
}
}
|
NunoLopes96/gsoc17_expand_extension_manager
|
administrator/components/com_plugins/Model/Plugins.php
|
PHP
|
gpl-2.0
| 7,299 |
// -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _GTKMM_SELECTIONDATA_P_H
#define _GTKMM_SELECTIONDATA_P_H
#endif /* _GTKMM_SELECTIONDATA_P_H */
|
agomusic/ardour3
|
libs/gtkmm2/gtk/gtkmm/private/selectiondata_p.h
|
C
|
gpl-2.0
| 166 |
/****************************************************************************
* MeshLab o o *
* A versatile mesh processing toolbox o o *
* _ O _ *
* Copyright(C) 2008 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* 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 (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
/****************************************************************************
History
$Log: editmeasure.h,v $
****************************************************************************/
#ifndef EditMeasurePLUGIN_H
#define EditMeasurePLUGIN_H
#include <QObject>
#include <QStringList>
#include <QList>
#include <common/interfaces.h>
#include <wrap/gui/rubberband.h>
class EditMeasurePlugin : public QObject, public MeshEditInterface
{
Q_OBJECT
Q_INTERFACES(MeshEditInterface)
public:
EditMeasurePlugin();
virtual ~EditMeasurePlugin() {}
static const QString Info();
virtual bool StartEdit(MeshModel &, GLArea *);
virtual void EndEdit(MeshModel &, GLArea *);
virtual void Decorate(MeshModel &, GLArea *,QPainter*);
virtual void mousePressEvent(QMouseEvent *, MeshModel &, GLArea * );
virtual void mouseMoveEvent(QMouseEvent *, MeshModel &, GLArea * );
virtual void mouseReleaseEvent(QMouseEvent *event, MeshModel &, GLArea * );
private:
QFont qFont;
vcg::Rubberband rubberband;
bool was_ready;
signals:
void suspendEditToggle();
};
#endif
|
guerrerocarlos/meshlab
|
src/plugins/edit_measure/edit_measure.h
|
C
|
gpl-2.0
| 2,818 |
/*
* linux/mm/nommu.c
*
* Replacement code for mm functions to support CPU's that don't
* have any form of memory management unit (thus no virtual memory).
*
* See Documentation/nommu-mmap.txt
*
* Copyright (c) 2004-2008 David Howells <[email protected]>
* Copyright (c) 2000-2003 David McCullough <[email protected]>
* Copyright (c) 2000-2001 D Jeff Dionne <[email protected]>
* Copyright (c) 2002 Greg Ungerer <[email protected]>
* Copyright (c) 2007-2010 Paul Mundt <[email protected]>
*/
#include <linux/export.h>
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/swap.h>
#include <linux/file.h>
#include <linux/highmem.h>
#include <linux/pagemap.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/mount.h>
#include <linux/personality.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/audit.h>
#include <asm/uaccess.h>
#include <asm/tlb.h>
#include <asm/tlbflush.h>
#include <asm/mmu_context.h>
#include "internal.h"
#if 0
#define kenter(FMT, ...) \
printk(KERN_DEBUG "==> %s("FMT")\n", __func__, ##__VA_ARGS__)
#define kleave(FMT, ...) \
printk(KERN_DEBUG "<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
#define kdebug(FMT, ...) \
printk(KERN_DEBUG "xxx" FMT"yyy\n", ##__VA_ARGS__)
#else
#define kenter(FMT, ...) \
no_printk(KERN_DEBUG "==> %s("FMT")\n", __func__, ##__VA_ARGS__)
#define kleave(FMT, ...) \
no_printk(KERN_DEBUG "<== %s()"FMT"\n", __func__, ##__VA_ARGS__)
#define kdebug(FMT, ...) \
no_printk(KERN_DEBUG FMT"\n", ##__VA_ARGS__)
#endif
void *high_memory;
struct page *mem_map;
unsigned long max_mapnr;
unsigned long num_physpages;
unsigned long highest_memmap_pfn;
struct percpu_counter vm_committed_as;
int sysctl_overcommit_memory = OVERCOMMIT_GUESS; /* heuristic overcommit */
int sysctl_overcommit_ratio = 50; /* default is 50% */
int sysctl_max_map_count = DEFAULT_MAX_MAP_COUNT;
int sysctl_nr_trim_pages = CONFIG_NOMMU_INITIAL_TRIM_EXCESS;
int heap_stack_gap = 0;
atomic_long_t mmap_pages_allocated;
EXPORT_SYMBOL(mem_map);
EXPORT_SYMBOL(num_physpages);
/* list of mapped, potentially shareable regions */
static struct kmem_cache *vm_region_jar;
struct rb_root nommu_region_tree = RB_ROOT;
DECLARE_RWSEM(nommu_region_sem);
const struct vm_operations_struct generic_file_vm_ops = {
};
/*
* Return the total memory allocated for this pointer, not
* just what the caller asked for.
*
* Doesn't have to be accurate, i.e. may have races.
*/
unsigned int kobjsize(const void *objp)
{
struct page *page;
/*
* If the object we have should not have ksize performed on it,
* return size of 0
*/
if (!objp || !virt_addr_valid(objp))
return 0;
page = virt_to_head_page(objp);
/*
* If the allocator sets PageSlab, we know the pointer came from
* kmalloc().
*/
if (PageSlab(page))
return ksize(objp);
/*
* If it's not a compound page, see if we have a matching VMA
* region. This test is intentionally done in reverse order,
* so if there's no VMA, we still fall through and hand back
* PAGE_SIZE for 0-order pages.
*/
if (!PageCompound(page)) {
struct vm_area_struct *vma;
vma = find_vma(current->mm, (unsigned long)objp);
if (vma)
return vma->vm_end - vma->vm_start;
}
/*
* The ksize() function is only guaranteed to work for pointers
* returned by kmalloc(). So handle arbitrary pointers here.
*/
return PAGE_SIZE << compound_order(page);
}
int __get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int nr_pages, unsigned int foll_flags,
struct page **pages, struct vm_area_struct **vmas,
int *retry)
{
struct vm_area_struct *vma;
unsigned long vm_flags;
int i;
/* calculate required read or write permissions.
* If FOLL_FORCE is set, we only require the "MAY" flags.
*/
vm_flags = (foll_flags & FOLL_WRITE) ?
(VM_WRITE | VM_MAYWRITE) : (VM_READ | VM_MAYREAD);
vm_flags &= (foll_flags & FOLL_FORCE) ?
(VM_MAYREAD | VM_MAYWRITE) : (VM_READ | VM_WRITE);
for (i = 0; i < nr_pages; i++) {
vma = find_vma(mm, start);
if (!vma)
goto finish_or_fault;
/* protect what we can, including chardevs */
if ((vma->vm_flags & (VM_IO | VM_PFNMAP)) ||
!(vm_flags & vma->vm_flags))
goto finish_or_fault;
if (pages) {
pages[i] = virt_to_page(start);
if (pages[i])
page_cache_get(pages[i]);
}
if (vmas)
vmas[i] = vma;
start = (start + PAGE_SIZE) & PAGE_MASK;
}
return i;
finish_or_fault:
return i ? : -EFAULT;
}
/*
* get a list of pages in an address range belonging to the specified process
* and indicate the VMA that covers each page
* - this is potentially dodgy as we may end incrementing the page count of a
* slab page or a secondary page from a compound page
* - don't permit access to VMAs that don't support it, such as I/O mappings
*/
int get_user_pages(struct task_struct *tsk, struct mm_struct *mm,
unsigned long start, int nr_pages, int write, int force,
struct page **pages, struct vm_area_struct **vmas)
{
int flags = 0;
if (write)
flags |= FOLL_WRITE;
if (force)
flags |= FOLL_FORCE;
return __get_user_pages(tsk, mm, start, nr_pages, flags, pages, vmas,
NULL);
}
EXPORT_SYMBOL(get_user_pages);
/**
* follow_pfn - look up PFN at a user virtual address
* @vma: memory mapping
* @address: user virtual address
* @pfn: location to store found PFN
*
* Only IO mappings and raw PFN mappings are allowed.
*
* Returns zero and the pfn at @pfn on success, -ve otherwise.
*/
int follow_pfn(struct vm_area_struct *vma, unsigned long address,
unsigned long *pfn)
{
if (!(vma->vm_flags & (VM_IO | VM_PFNMAP)))
return -EINVAL;
*pfn = address >> PAGE_SHIFT;
return 0;
}
EXPORT_SYMBOL(follow_pfn);
DEFINE_RWLOCK(vmlist_lock);
struct vm_struct *vmlist;
void vfree(const void *addr)
{
kfree(addr);
}
EXPORT_SYMBOL(vfree);
void *__vmalloc(unsigned long size, gfp_t gfp_mask, pgprot_t prot)
{
/*
* You can't specify __GFP_HIGHMEM with kmalloc() since kmalloc()
* returns only a logical address.
*/
return kmalloc(size, (gfp_mask | __GFP_COMP) & ~__GFP_HIGHMEM);
}
EXPORT_SYMBOL(__vmalloc);
void *vmalloc_user(unsigned long size)
{
void *ret;
ret = __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO,
PAGE_KERNEL);
if (ret) {
struct vm_area_struct *vma;
down_write(¤t->mm->mmap_sem);
vma = find_vma(current->mm, (unsigned long)ret);
if (vma)
vma->vm_flags |= VM_USERMAP;
up_write(¤t->mm->mmap_sem);
}
return ret;
}
EXPORT_SYMBOL(vmalloc_user);
struct page *vmalloc_to_page(const void *addr)
{
return virt_to_page(addr);
}
EXPORT_SYMBOL(vmalloc_to_page);
unsigned long vmalloc_to_pfn(const void *addr)
{
return page_to_pfn(virt_to_page(addr));
}
EXPORT_SYMBOL(vmalloc_to_pfn);
long vread(char *buf, char *addr, unsigned long count)
{
memcpy(buf, addr, count);
return count;
}
long vwrite(char *buf, char *addr, unsigned long count)
{
/* Don't allow overflow */
if ((unsigned long) addr + count < count)
count = -(unsigned long) addr;
memcpy(addr, buf, count);
return(count);
}
/*
* vmalloc - allocate virtually continguos memory
*
* @size: allocation size
*
* Allocate enough pages to cover @size from the page level
* allocator and map them into continguos kernel virtual space.
*
* For tight control over page level allocator and protection flags
* use __vmalloc() instead.
*/
void *vmalloc(unsigned long size)
{
return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL);
}
EXPORT_SYMBOL(vmalloc);
/*
* vzalloc - allocate virtually continguos memory with zero fill
*
* @size: allocation size
*
* Allocate enough pages to cover @size from the page level
* allocator and map them into continguos kernel virtual space.
* The memory allocated is set to zero.
*
* For tight control over page level allocator and protection flags
* use __vmalloc() instead.
*/
void *vzalloc(unsigned long size)
{
return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO,
PAGE_KERNEL);
}
EXPORT_SYMBOL(vzalloc);
/**
* vmalloc_node - allocate memory on a specific node
* @size: allocation size
* @node: numa node
*
* Allocate enough pages to cover @size from the page level
* allocator and map them into contiguous kernel virtual space.
*
* For tight control over page level allocator and protection flags
* use __vmalloc() instead.
*/
void *vmalloc_node(unsigned long size, int node)
{
return vmalloc(size);
}
EXPORT_SYMBOL(vmalloc_node);
/**
* vzalloc_node - allocate memory on a specific node with zero fill
* @size: allocation size
* @node: numa node
*
* Allocate enough pages to cover @size from the page level
* allocator and map them into contiguous kernel virtual space.
* The memory allocated is set to zero.
*
* For tight control over page level allocator and protection flags
* use __vmalloc() instead.
*/
void *vzalloc_node(unsigned long size, int node)
{
return vzalloc(size);
}
EXPORT_SYMBOL(vzalloc_node);
#ifndef PAGE_KERNEL_EXEC
# define PAGE_KERNEL_EXEC PAGE_KERNEL
#endif
/**
* vmalloc_exec - allocate virtually contiguous, executable memory
* @size: allocation size
*
* Kernel-internal function to allocate enough pages to cover @size
* the page level allocator and map them into contiguous and
* executable kernel virtual space.
*
* For tight control over page level allocator and protection flags
* use __vmalloc() instead.
*/
void *vmalloc_exec(unsigned long size)
{
return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM, PAGE_KERNEL_EXEC);
}
/**
* vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
* @size: allocation size
*
* Allocate enough 32bit PA addressable pages to cover @size from the
* page level allocator and map them into continguos kernel virtual space.
*/
void *vmalloc_32(unsigned long size)
{
return __vmalloc(size, GFP_KERNEL, PAGE_KERNEL);
}
EXPORT_SYMBOL(vmalloc_32);
/**
* vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
* @size: allocation size
*
* The resulting memory area is 32bit addressable and zeroed so it can be
* mapped to userspace without leaking data.
*
* VM_USERMAP is set on the corresponding VMA so that subsequent calls to
* remap_vmalloc_range() are permissible.
*/
void *vmalloc_32_user(unsigned long size)
{
/*
* We'll have to sort out the ZONE_DMA bits for 64-bit,
* but for now this can simply use vmalloc_user() directly.
*/
return vmalloc_user(size);
}
EXPORT_SYMBOL(vmalloc_32_user);
void *vmap(struct page **pages, unsigned int count, unsigned long flags, pgprot_t prot)
{
BUG();
return NULL;
}
EXPORT_SYMBOL(vmap);
void vunmap(const void *addr)
{
BUG();
}
EXPORT_SYMBOL(vunmap);
void *vm_map_ram(struct page **pages, unsigned int count, int node, pgprot_t prot)
{
BUG();
return NULL;
}
EXPORT_SYMBOL(vm_map_ram);
void vm_unmap_ram(const void *mem, unsigned int count)
{
BUG();
}
EXPORT_SYMBOL(vm_unmap_ram);
void vm_unmap_aliases(void)
{
}
EXPORT_SYMBOL_GPL(vm_unmap_aliases);
/*
* Implement a stub for vmalloc_sync_all() if the architecture chose not to
* have one.
*/
void __attribute__((weak)) vmalloc_sync_all(void)
{
}
/**
* alloc_vm_area - allocate a range of kernel address space
* @size: size of the area
*
* Returns: NULL on failure, vm_struct on success
*
* This function reserves a range of kernel address space, and
* allocates pagetables to map that range. No actual mappings
* are created. If the kernel address space is not shared
* between processes, it syncs the pagetable across all
* processes.
*/
struct vm_struct *alloc_vm_area(size_t size, pte_t **ptes)
{
BUG();
return NULL;
}
EXPORT_SYMBOL_GPL(alloc_vm_area);
void free_vm_area(struct vm_struct *area)
{
BUG();
}
EXPORT_SYMBOL_GPL(free_vm_area);
int vm_insert_page(struct vm_area_struct *vma, unsigned long addr,
struct page *page)
{
return -EINVAL;
}
EXPORT_SYMBOL(vm_insert_page);
/*
* sys_brk() for the most part doesn't need the global kernel
* lock, except when an application is doing something nasty
* like trying to un-brk an area that has already been mapped
* to a regular file. in this case, the unmapping will need
* to invoke file system routines that need the global lock.
*/
SYSCALL_DEFINE1(brk, unsigned long, brk)
{
struct mm_struct *mm = current->mm;
if (brk < mm->start_brk || brk > mm->context.end_brk)
return mm->brk;
if (mm->brk == brk)
return mm->brk;
/*
* Always allow shrinking brk
*/
if (brk <= mm->brk) {
mm->brk = brk;
return brk;
}
/*
* Ok, looks good - let it rip.
*/
flush_icache_range(mm->brk, brk);
return mm->brk = brk;
}
/*
* initialise the VMA and region record slabs
*/
void __init mmap_init(void)
{
int ret;
ret = percpu_counter_init(&vm_committed_as, 0);
VM_BUG_ON(ret);
vm_region_jar = KMEM_CACHE(vm_region, SLAB_PANIC);
}
/*
* validate the region tree
* - the caller must hold the region lock
*/
#ifdef CONFIG_DEBUG_NOMMU_REGIONS
static noinline void validate_nommu_regions(void)
{
struct vm_region *region, *last;
struct rb_node *p, *lastp;
lastp = rb_first(&nommu_region_tree);
if (!lastp)
return;
last = rb_entry(lastp, struct vm_region, vm_rb);
BUG_ON(unlikely(last->vm_end <= last->vm_start));
BUG_ON(unlikely(last->vm_top < last->vm_end));
while ((p = rb_next(lastp))) {
region = rb_entry(p, struct vm_region, vm_rb);
last = rb_entry(lastp, struct vm_region, vm_rb);
BUG_ON(unlikely(region->vm_end <= region->vm_start));
BUG_ON(unlikely(region->vm_top < region->vm_end));
BUG_ON(unlikely(region->vm_start < last->vm_top));
lastp = p;
}
}
#else
static void validate_nommu_regions(void)
{
}
#endif
/*
* add a region into the global tree
*/
static void add_nommu_region(struct vm_region *region)
{
struct vm_region *pregion;
struct rb_node **p, *parent;
validate_nommu_regions();
parent = NULL;
p = &nommu_region_tree.rb_node;
while (*p) {
parent = *p;
pregion = rb_entry(parent, struct vm_region, vm_rb);
if (region->vm_start < pregion->vm_start)
p = &(*p)->rb_left;
else if (region->vm_start > pregion->vm_start)
p = &(*p)->rb_right;
else if (pregion == region)
return;
else
BUG();
}
rb_link_node(®ion->vm_rb, parent, p);
rb_insert_color(®ion->vm_rb, &nommu_region_tree);
validate_nommu_regions();
}
/*
* delete a region from the global tree
*/
static void delete_nommu_region(struct vm_region *region)
{
BUG_ON(!nommu_region_tree.rb_node);
validate_nommu_regions();
rb_erase(®ion->vm_rb, &nommu_region_tree);
validate_nommu_regions();
}
/*
* free a contiguous series of pages
*/
static void free_page_series(unsigned long from, unsigned long to)
{
for (; from < to; from += PAGE_SIZE) {
struct page *page = virt_to_page(from);
kdebug("- free %lx", from);
atomic_long_dec(&mmap_pages_allocated);
if (page_count(page) != 1)
kdebug("free page %p: refcount not one: %d",
page, page_count(page));
put_page(page);
}
}
/*
* release a reference to a region
* - the caller must hold the region semaphore for writing, which this releases
* - the region may not have been added to the tree yet, in which case vm_top
* will equal vm_start
*/
static void __put_nommu_region(struct vm_region *region)
__releases(nommu_region_sem)
{
kenter("%p{%d}", region, region->vm_usage);
BUG_ON(!nommu_region_tree.rb_node);
if (--region->vm_usage == 0) {
if (region->vm_top > region->vm_start)
delete_nommu_region(region);
up_write(&nommu_region_sem);
if (region->vm_file)
fput(region->vm_file);
/* IO memory and memory shared directly out of the pagecache
* from ramfs/tmpfs mustn't be released here */
if (region->vm_flags & VM_MAPPED_COPY) {
kdebug("free series");
free_page_series(region->vm_start, region->vm_top);
}
kmem_cache_free(vm_region_jar, region);
} else {
up_write(&nommu_region_sem);
}
}
/*
* release a reference to a region
*/
static void put_nommu_region(struct vm_region *region)
{
down_write(&nommu_region_sem);
__put_nommu_region(region);
}
/*
* update protection on a vma
*/
static void protect_vma(struct vm_area_struct *vma, unsigned long flags)
{
#ifdef CONFIG_MPU
struct mm_struct *mm = vma->vm_mm;
long start = vma->vm_start & PAGE_MASK;
while (start < vma->vm_end) {
protect_page(mm, start, flags);
start += PAGE_SIZE;
}
update_protections(mm);
#endif
}
/*
* add a VMA into a process's mm_struct in the appropriate place in the list
* and tree and add to the address space's page tree also if not an anonymous
* page
* - should be called with mm->mmap_sem held writelocked
*/
static void add_vma_to_mm(struct mm_struct *mm, struct vm_area_struct *vma)
{
struct vm_area_struct *pvma, *prev;
struct address_space *mapping;
struct rb_node **p, *parent, *rb_prev;
kenter(",%p", vma);
BUG_ON(!vma->vm_region);
mm->map_count++;
vma->vm_mm = mm;
protect_vma(vma, vma->vm_flags);
/* add the VMA to the mapping */
if (vma->vm_file) {
mapping = vma->vm_file->f_mapping;
mutex_lock(&mapping->i_mmap_mutex);
flush_dcache_mmap_lock(mapping);
vma_prio_tree_insert(vma, &mapping->i_mmap);
flush_dcache_mmap_unlock(mapping);
mutex_unlock(&mapping->i_mmap_mutex);
}
/* add the VMA to the tree */
parent = rb_prev = NULL;
p = &mm->mm_rb.rb_node;
while (*p) {
parent = *p;
pvma = rb_entry(parent, struct vm_area_struct, vm_rb);
/* sort by: start addr, end addr, VMA struct addr in that order
* (the latter is necessary as we may get identical VMAs) */
if (vma->vm_start < pvma->vm_start)
p = &(*p)->rb_left;
else if (vma->vm_start > pvma->vm_start) {
rb_prev = parent;
p = &(*p)->rb_right;
} else if (vma->vm_end < pvma->vm_end)
p = &(*p)->rb_left;
else if (vma->vm_end > pvma->vm_end) {
rb_prev = parent;
p = &(*p)->rb_right;
} else if (vma < pvma)
p = &(*p)->rb_left;
else if (vma > pvma) {
rb_prev = parent;
p = &(*p)->rb_right;
} else
BUG();
}
rb_link_node(&vma->vm_rb, parent, p);
rb_insert_color(&vma->vm_rb, &mm->mm_rb);
/* add VMA to the VMA list also */
prev = NULL;
if (rb_prev)
prev = rb_entry(rb_prev, struct vm_area_struct, vm_rb);
__vma_link_list(mm, vma, prev, parent);
}
/*
* delete a VMA from its owning mm_struct and address space
*/
static void delete_vma_from_mm(struct vm_area_struct *vma)
{
struct address_space *mapping;
struct mm_struct *mm = vma->vm_mm;
kenter("%p", vma);
protect_vma(vma, 0);
mm->map_count--;
if (mm->mmap_cache == vma)
mm->mmap_cache = NULL;
/* remove the VMA from the mapping */
if (vma->vm_file) {
mapping = vma->vm_file->f_mapping;
mutex_lock(&mapping->i_mmap_mutex);
flush_dcache_mmap_lock(mapping);
vma_prio_tree_remove(vma, &mapping->i_mmap);
flush_dcache_mmap_unlock(mapping);
mutex_unlock(&mapping->i_mmap_mutex);
}
/* remove from the MM's tree and list */
rb_erase(&vma->vm_rb, &mm->mm_rb);
if (vma->vm_prev)
vma->vm_prev->vm_next = vma->vm_next;
else
mm->mmap = vma->vm_next;
if (vma->vm_next)
vma->vm_next->vm_prev = vma->vm_prev;
}
/*
* destroy a VMA record
*/
static void delete_vma(struct mm_struct *mm, struct vm_area_struct *vma)
{
kenter("%p", vma);
if (vma->vm_ops && vma->vm_ops->close)
vma->vm_ops->close(vma);
if (vma->vm_file) {
fput(vma->vm_file);
if (vma->vm_flags & VM_EXECUTABLE)
removed_exe_file_vma(mm);
}
put_nommu_region(vma->vm_region);
kmem_cache_free(vm_area_cachep, vma);
}
/*
* look up the first VMA in which addr resides, NULL if none
* - should be called with mm->mmap_sem at least held readlocked
*/
struct vm_area_struct *find_vma(struct mm_struct *mm, unsigned long addr)
{
struct vm_area_struct *vma;
/* check the cache first */
vma = ACCESS_ONCE(mm->mmap_cache);
if (vma && vma->vm_start <= addr && vma->vm_end > addr)
return vma;
/* trawl the list (there may be multiple mappings in which addr
* resides) */
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (vma->vm_start > addr)
return NULL;
if (vma->vm_end > addr) {
mm->mmap_cache = vma;
return vma;
}
}
return NULL;
}
EXPORT_SYMBOL(find_vma);
/*
* find a VMA
* - we don't extend stack VMAs under NOMMU conditions
*/
struct vm_area_struct *find_extend_vma(struct mm_struct *mm, unsigned long addr)
{
return find_vma(mm, addr);
}
/*
* expand a stack to a given address
* - not supported under NOMMU conditions
*/
int expand_stack(struct vm_area_struct *vma, unsigned long address)
{
return -ENOMEM;
}
/*
* look up the first VMA exactly that exactly matches addr
* - should be called with mm->mmap_sem at least held readlocked
*/
static struct vm_area_struct *find_vma_exact(struct mm_struct *mm,
unsigned long addr,
unsigned long len)
{
struct vm_area_struct *vma;
unsigned long end = addr + len;
/* check the cache first */
vma = mm->mmap_cache;
if (vma && vma->vm_start == addr && vma->vm_end == end)
return vma;
/* trawl the list (there may be multiple mappings in which addr
* resides) */
for (vma = mm->mmap; vma; vma = vma->vm_next) {
if (vma->vm_start < addr)
continue;
if (vma->vm_start > addr)
return NULL;
if (vma->vm_end == end) {
mm->mmap_cache = vma;
return vma;
}
}
return NULL;
}
/*
* determine whether a mapping should be permitted and, if so, what sort of
* mapping we're capable of supporting
*/
static int validate_mmap_request(struct file *file,
unsigned long addr,
unsigned long len,
unsigned long prot,
unsigned long flags,
unsigned long pgoff,
unsigned long *_capabilities)
{
unsigned long capabilities, rlen;
int ret;
/* do the simple checks first */
if (flags & MAP_FIXED) {
printk(KERN_DEBUG
"%d: Can't do fixed-address/overlay mmap of RAM\n",
current->pid);
return -EINVAL;
}
if ((flags & MAP_TYPE) != MAP_PRIVATE &&
(flags & MAP_TYPE) != MAP_SHARED)
return -EINVAL;
if (!len)
return -EINVAL;
/* Careful about overflows.. */
rlen = PAGE_ALIGN(len);
if (!rlen || rlen > TASK_SIZE)
return -ENOMEM;
/* offset overflow? */
if ((pgoff + (rlen >> PAGE_SHIFT)) < pgoff)
return -EOVERFLOW;
if (file) {
/* validate file mapping requests */
struct address_space *mapping;
/* files must support mmap */
if (!file->f_op || !file->f_op->mmap)
return -ENODEV;
/* work out if what we've got could possibly be shared
* - we support chardevs that provide their own "memory"
* - we support files/blockdevs that are memory backed
*/
mapping = file->f_mapping;
if (!mapping)
mapping = file->f_path.dentry->d_inode->i_mapping;
capabilities = 0;
if (mapping && mapping->backing_dev_info)
capabilities = mapping->backing_dev_info->capabilities;
if (!capabilities) {
/* no explicit capabilities set, so assume some
* defaults */
switch (file->f_path.dentry->d_inode->i_mode & S_IFMT) {
case S_IFREG:
case S_IFBLK:
capabilities = BDI_CAP_MAP_COPY;
break;
case S_IFCHR:
capabilities =
BDI_CAP_MAP_DIRECT |
BDI_CAP_READ_MAP |
BDI_CAP_WRITE_MAP;
break;
default:
return -EINVAL;
}
}
/* eliminate any capabilities that we can't support on this
* device */
if (!file->f_op->get_unmapped_area)
capabilities &= ~BDI_CAP_MAP_DIRECT;
if (!file->f_op->read)
capabilities &= ~BDI_CAP_MAP_COPY;
/* The file shall have been opened with read permission. */
if (!(file->f_mode & FMODE_READ))
return -EACCES;
if (flags & MAP_SHARED) {
/* do checks for writing, appending and locking */
if ((prot & PROT_WRITE) &&
!(file->f_mode & FMODE_WRITE))
return -EACCES;
if (IS_APPEND(file->f_path.dentry->d_inode) &&
(file->f_mode & FMODE_WRITE))
return -EACCES;
if (locks_verify_locked(file->f_path.dentry->d_inode))
return -EAGAIN;
if (!(capabilities & BDI_CAP_MAP_DIRECT))
return -ENODEV;
/* we mustn't privatise shared mappings */
capabilities &= ~BDI_CAP_MAP_COPY;
}
else {
/* we're going to read the file into private memory we
* allocate */
if (!(capabilities & BDI_CAP_MAP_COPY))
return -ENODEV;
/* we don't permit a private writable mapping to be
* shared with the backing device */
if (prot & PROT_WRITE)
capabilities &= ~BDI_CAP_MAP_DIRECT;
}
if (capabilities & BDI_CAP_MAP_DIRECT) {
if (((prot & PROT_READ) && !(capabilities & BDI_CAP_READ_MAP)) ||
((prot & PROT_WRITE) && !(capabilities & BDI_CAP_WRITE_MAP)) ||
((prot & PROT_EXEC) && !(capabilities & BDI_CAP_EXEC_MAP))
) {
capabilities &= ~BDI_CAP_MAP_DIRECT;
if (flags & MAP_SHARED) {
printk(KERN_WARNING
"MAP_SHARED not completely supported on !MMU\n");
return -EINVAL;
}
}
}
/* handle executable mappings and implied executable
* mappings */
if (file->f_path.mnt->mnt_flags & MNT_NOEXEC) {
if (prot & PROT_EXEC)
return -EPERM;
}
else if ((prot & PROT_READ) && !(prot & PROT_EXEC)) {
/* handle implication of PROT_EXEC by PROT_READ */
if (current->personality & READ_IMPLIES_EXEC) {
if (capabilities & BDI_CAP_EXEC_MAP)
prot |= PROT_EXEC;
}
}
else if ((prot & PROT_READ) &&
(prot & PROT_EXEC) &&
!(capabilities & BDI_CAP_EXEC_MAP)
) {
/* backing file is not executable, try to copy */
capabilities &= ~BDI_CAP_MAP_DIRECT;
}
}
else {
/* anonymous mappings are always memory backed and can be
* privately mapped
*/
capabilities = BDI_CAP_MAP_COPY;
/* handle PROT_EXEC implication by PROT_READ */
if ((prot & PROT_READ) &&
(current->personality & READ_IMPLIES_EXEC))
prot |= PROT_EXEC;
}
/* allow the security API to have its say */
ret = security_mmap_addr(addr);
if (ret < 0)
return ret;
/* looks okay */
*_capabilities = capabilities;
return 0;
}
/*
* we've determined that we can make the mapping, now translate what we
* now know into VMA flags
*/
static unsigned long determine_vm_flags(struct file *file,
unsigned long prot,
unsigned long flags,
unsigned long capabilities)
{
unsigned long vm_flags;
vm_flags = calc_vm_prot_bits(prot) | calc_vm_flag_bits(flags);
/* vm_flags |= mm->def_flags; */
if (!(capabilities & BDI_CAP_MAP_DIRECT)) {
/* attempt to share read-only copies of mapped file chunks */
vm_flags |= VM_MAYREAD | VM_MAYWRITE | VM_MAYEXEC;
if (file && !(prot & PROT_WRITE))
vm_flags |= VM_MAYSHARE;
} else {
/* overlay a shareable mapping on the backing device or inode
* if possible - used for chardevs, ramfs/tmpfs/shmfs and
* romfs/cramfs */
vm_flags |= VM_MAYSHARE | (capabilities & BDI_CAP_VMFLAGS);
if (flags & MAP_SHARED)
vm_flags |= VM_SHARED;
}
/* refuse to let anyone share private mappings with this process if
* it's being traced - otherwise breakpoints set in it may interfere
* with another untraced process
*/
if ((flags & MAP_PRIVATE) && current->ptrace)
vm_flags &= ~VM_MAYSHARE;
return vm_flags;
}
/*
* set up a shared mapping on a file (the driver or filesystem provides and
* pins the storage)
*/
static int do_mmap_shared_file(struct vm_area_struct *vma)
{
int ret;
ret = vma->vm_file->f_op->mmap(vma->vm_file, vma);
if (ret == 0) {
vma->vm_region->vm_top = vma->vm_region->vm_end;
return 0;
}
if (ret != -ENOSYS)
return ret;
/* getting -ENOSYS indicates that direct mmap isn't possible (as
* opposed to tried but failed) so we can only give a suitable error as
* it's not possible to make a private copy if MAP_SHARED was given */
return -ENODEV;
}
/*
* set up a private mapping or an anonymous shared mapping
*/
static int do_mmap_private(struct vm_area_struct *vma,
struct vm_region *region,
unsigned long len,
unsigned long capabilities)
{
struct page *pages;
unsigned long total, point, n;
void *base;
int ret, order;
/* invoke the file's mapping function so that it can keep track of
* shared mappings on devices or memory
* - VM_MAYSHARE will be set if it may attempt to share
*/
if (capabilities & BDI_CAP_MAP_DIRECT) {
ret = vma->vm_file->f_op->mmap(vma->vm_file, vma);
if (ret == 0) {
/* shouldn't return success if we're not sharing */
BUG_ON(!(vma->vm_flags & VM_MAYSHARE));
vma->vm_region->vm_top = vma->vm_region->vm_end;
return 0;
}
if (ret != -ENOSYS)
return ret;
/* getting an ENOSYS error indicates that direct mmap isn't
* possible (as opposed to tried but failed) so we'll try to
* make a private copy of the data and map that instead */
}
/* allocate some memory to hold the mapping
* - note that this may not return a page-aligned address if the object
* we're allocating is smaller than a page
*/
order = get_order(len);
kdebug("alloc order %d for %lx", order, len);
pages = alloc_pages(GFP_KERNEL, order);
if (!pages)
goto enomem;
total = 1 << order;
atomic_long_add(total, &mmap_pages_allocated);
point = len >> PAGE_SHIFT;
/* we allocated a power-of-2 sized page set, so we may want to trim off
* the excess */
if (sysctl_nr_trim_pages && total - point >= sysctl_nr_trim_pages) {
while (total > point) {
order = ilog2(total - point);
n = 1 << order;
kdebug("shave %lu/%lu @%lu", n, total - point, total);
atomic_long_sub(n, &mmap_pages_allocated);
total -= n;
set_page_refcounted(pages + total);
__free_pages(pages + total, order);
}
}
for (point = 1; point < total; point++)
set_page_refcounted(&pages[point]);
base = page_address(pages);
region->vm_flags = vma->vm_flags |= VM_MAPPED_COPY;
region->vm_start = (unsigned long) base;
region->vm_end = region->vm_start + len;
region->vm_top = region->vm_start + (total << PAGE_SHIFT);
vma->vm_start = region->vm_start;
vma->vm_end = region->vm_start + len;
if (vma->vm_file) {
/* read the contents of a file into the copy */
mm_segment_t old_fs;
loff_t fpos;
fpos = vma->vm_pgoff;
fpos <<= PAGE_SHIFT;
old_fs = get_fs();
set_fs(KERNEL_DS);
ret = vma->vm_file->f_op->read(vma->vm_file, base, len, &fpos);
set_fs(old_fs);
if (ret < 0)
goto error_free;
/* clear the last little bit */
if (ret < len)
memset(base + ret, 0, len - ret);
}
return 0;
error_free:
free_page_series(region->vm_start, region->vm_top);
region->vm_start = vma->vm_start = 0;
region->vm_end = vma->vm_end = 0;
region->vm_top = 0;
return ret;
enomem:
printk("Allocation of length %lu from process %d (%s) failed\n",
len, current->pid, current->comm);
show_free_areas(0);
return -ENOMEM;
}
/*
* handle mapping creation for uClinux
*/
unsigned long do_mmap_pgoff(struct file *file,
unsigned long addr,
unsigned long len,
unsigned long prot,
unsigned long flags,
unsigned long pgoff)
{
struct vm_area_struct *vma;
struct vm_region *region;
struct rb_node *rb;
unsigned long capabilities, vm_flags, result;
int ret;
kenter(",%lx,%lx,%lx,%lx,%lx", addr, len, prot, flags, pgoff);
/* decide whether we should attempt the mapping, and if so what sort of
* mapping */
ret = validate_mmap_request(file, addr, len, prot, flags, pgoff,
&capabilities);
if (ret < 0) {
kleave(" = %d [val]", ret);
return ret;
}
/* we ignore the address hint */
addr = 0;
len = PAGE_ALIGN(len);
/* we've determined that we can make the mapping, now translate what we
* now know into VMA flags */
vm_flags = determine_vm_flags(file, prot, flags, capabilities);
/* we're going to need to record the mapping */
region = kmem_cache_zalloc(vm_region_jar, GFP_KERNEL);
if (!region)
goto error_getting_region;
vma = kmem_cache_zalloc(vm_area_cachep, GFP_KERNEL);
if (!vma)
goto error_getting_vma;
region->vm_usage = 1;
region->vm_flags = vm_flags;
region->vm_pgoff = pgoff;
INIT_LIST_HEAD(&vma->anon_vma_chain);
vma->vm_flags = vm_flags;
vma->vm_pgoff = pgoff;
if (file) {
region->vm_file = file;
get_file(file);
vma->vm_file = file;
get_file(file);
if (vm_flags & VM_EXECUTABLE) {
added_exe_file_vma(current->mm);
vma->vm_mm = current->mm;
}
}
down_write(&nommu_region_sem);
/* if we want to share, we need to check for regions created by other
* mmap() calls that overlap with our proposed mapping
* - we can only share with a superset match on most regular files
* - shared mappings on character devices and memory backed files are
* permitted to overlap inexactly as far as we are concerned for in
* these cases, sharing is handled in the driver or filesystem rather
* than here
*/
if (vm_flags & VM_MAYSHARE) {
struct vm_region *pregion;
unsigned long pglen, rpglen, pgend, rpgend, start;
pglen = (len + PAGE_SIZE - 1) >> PAGE_SHIFT;
pgend = pgoff + pglen;
for (rb = rb_first(&nommu_region_tree); rb; rb = rb_next(rb)) {
pregion = rb_entry(rb, struct vm_region, vm_rb);
if (!(pregion->vm_flags & VM_MAYSHARE))
continue;
/* search for overlapping mappings on the same file */
if (pregion->vm_file->f_path.dentry->d_inode !=
file->f_path.dentry->d_inode)
continue;
if (pregion->vm_pgoff >= pgend)
continue;
rpglen = pregion->vm_end - pregion->vm_start;
rpglen = (rpglen + PAGE_SIZE - 1) >> PAGE_SHIFT;
rpgend = pregion->vm_pgoff + rpglen;
if (pgoff >= rpgend)
continue;
/* handle inexactly overlapping matches between
* mappings */
if ((pregion->vm_pgoff != pgoff || rpglen != pglen) &&
!(pgoff >= pregion->vm_pgoff && pgend <= rpgend)) {
/* new mapping is not a subset of the region */
if (!(capabilities & BDI_CAP_MAP_DIRECT))
goto sharing_violation;
continue;
}
/* we've found a region we can share */
pregion->vm_usage++;
vma->vm_region = pregion;
start = pregion->vm_start;
start += (pgoff - pregion->vm_pgoff) << PAGE_SHIFT;
vma->vm_start = start;
vma->vm_end = start + len;
if (pregion->vm_flags & VM_MAPPED_COPY) {
kdebug("share copy");
vma->vm_flags |= VM_MAPPED_COPY;
} else {
kdebug("share mmap");
ret = do_mmap_shared_file(vma);
if (ret < 0) {
vma->vm_region = NULL;
vma->vm_start = 0;
vma->vm_end = 0;
pregion->vm_usage--;
pregion = NULL;
goto error_just_free;
}
}
fput(region->vm_file);
kmem_cache_free(vm_region_jar, region);
region = pregion;
result = start;
goto share;
}
/* obtain the address at which to make a shared mapping
* - this is the hook for quasi-memory character devices to
* tell us the location of a shared mapping
*/
if (capabilities & BDI_CAP_MAP_DIRECT) {
addr = file->f_op->get_unmapped_area(file, addr, len,
pgoff, flags);
if (IS_ERR_VALUE(addr)) {
ret = addr;
if (ret != -ENOSYS)
goto error_just_free;
/* the driver refused to tell us where to site
* the mapping so we'll have to attempt to copy
* it */
ret = -ENODEV;
if (!(capabilities & BDI_CAP_MAP_COPY))
goto error_just_free;
capabilities &= ~BDI_CAP_MAP_DIRECT;
} else {
vma->vm_start = region->vm_start = addr;
vma->vm_end = region->vm_end = addr + len;
}
}
}
vma->vm_region = region;
/* set up the mapping
* - the region is filled in if BDI_CAP_MAP_DIRECT is still set
*/
if (file && vma->vm_flags & VM_SHARED)
ret = do_mmap_shared_file(vma);
else
ret = do_mmap_private(vma, region, len, capabilities);
if (ret < 0)
goto error_just_free;
add_nommu_region(region);
/* clear anonymous mappings that don't ask for uninitialized data */
if (!vma->vm_file && !(flags & MAP_UNINITIALIZED))
memset((void *)region->vm_start, 0,
region->vm_end - region->vm_start);
/* okay... we have a mapping; now we have to register it */
result = vma->vm_start;
current->mm->total_vm += len >> PAGE_SHIFT;
share:
add_vma_to_mm(current->mm, vma);
/* we flush the region from the icache only when the first executable
* mapping of it is made */
if (vma->vm_flags & VM_EXEC && !region->vm_icache_flushed) {
flush_icache_range(region->vm_start, region->vm_end);
region->vm_icache_flushed = true;
}
up_write(&nommu_region_sem);
kleave(" = %lx", result);
return result;
error_just_free:
up_write(&nommu_region_sem);
error:
if (region->vm_file)
fput(region->vm_file);
kmem_cache_free(vm_region_jar, region);
if (vma->vm_file)
fput(vma->vm_file);
if (vma->vm_flags & VM_EXECUTABLE)
removed_exe_file_vma(vma->vm_mm);
kmem_cache_free(vm_area_cachep, vma);
kleave(" = %d", ret);
return ret;
sharing_violation:
up_write(&nommu_region_sem);
printk(KERN_WARNING "Attempt to share mismatched mappings\n");
ret = -EINVAL;
goto error;
error_getting_vma:
kmem_cache_free(vm_region_jar, region);
printk(KERN_WARNING "Allocation of vma for %lu byte allocation"
" from process %d failed\n",
len, current->pid);
show_free_areas(0);
return -ENOMEM;
error_getting_region:
printk(KERN_WARNING "Allocation of vm region for %lu byte allocation"
" from process %d failed\n",
len, current->pid);
show_free_areas(0);
return -ENOMEM;
}
SYSCALL_DEFINE6(mmap_pgoff, unsigned long, addr, unsigned long, len,
unsigned long, prot, unsigned long, flags,
unsigned long, fd, unsigned long, pgoff)
{
struct file *file = NULL;
unsigned long retval = -EBADF;
audit_mmap_fd(fd, flags);
if (!(flags & MAP_ANONYMOUS)) {
file = fget(fd);
if (!file)
goto out;
}
flags &= ~(MAP_EXECUTABLE | MAP_DENYWRITE);
retval = vm_mmap_pgoff(file, addr, len, prot, flags, pgoff);
if (file)
fput(file);
out:
return retval;
}
#ifdef __ARCH_WANT_SYS_OLD_MMAP
struct mmap_arg_struct {
unsigned long addr;
unsigned long len;
unsigned long prot;
unsigned long flags;
unsigned long fd;
unsigned long offset;
};
SYSCALL_DEFINE1(old_mmap, struct mmap_arg_struct __user *, arg)
{
struct mmap_arg_struct a;
if (copy_from_user(&a, arg, sizeof(a)))
return -EFAULT;
if (a.offset & ~PAGE_MASK)
return -EINVAL;
return sys_mmap_pgoff(a.addr, a.len, a.prot, a.flags, a.fd,
a.offset >> PAGE_SHIFT);
}
#endif /* __ARCH_WANT_SYS_OLD_MMAP */
/*
* split a vma into two pieces at address 'addr', a new vma is allocated either
* for the first part or the tail.
*/
int split_vma(struct mm_struct *mm, struct vm_area_struct *vma,
unsigned long addr, int new_below)
{
struct vm_area_struct *new;
struct vm_region *region;
unsigned long npages;
kenter("");
/* we're only permitted to split anonymous regions (these should have
* only a single usage on the region) */
if (vma->vm_file)
return -ENOMEM;
if (mm->map_count >= sysctl_max_map_count)
return -ENOMEM;
region = kmem_cache_alloc(vm_region_jar, GFP_KERNEL);
if (!region)
return -ENOMEM;
new = kmem_cache_alloc(vm_area_cachep, GFP_KERNEL);
if (!new) {
kmem_cache_free(vm_region_jar, region);
return -ENOMEM;
}
/* most fields are the same, copy all, and then fixup */
*new = *vma;
*region = *vma->vm_region;
new->vm_region = region;
npages = (addr - vma->vm_start) >> PAGE_SHIFT;
if (new_below) {
region->vm_top = region->vm_end = new->vm_end = addr;
} else {
region->vm_start = new->vm_start = addr;
region->vm_pgoff = new->vm_pgoff += npages;
}
if (new->vm_ops && new->vm_ops->open)
new->vm_ops->open(new);
delete_vma_from_mm(vma);
down_write(&nommu_region_sem);
delete_nommu_region(vma->vm_region);
if (new_below) {
vma->vm_region->vm_start = vma->vm_start = addr;
vma->vm_region->vm_pgoff = vma->vm_pgoff += npages;
} else {
vma->vm_region->vm_end = vma->vm_end = addr;
vma->vm_region->vm_top = addr;
}
add_nommu_region(vma->vm_region);
add_nommu_region(new->vm_region);
up_write(&nommu_region_sem);
add_vma_to_mm(mm, vma);
add_vma_to_mm(mm, new);
return 0;
}
/*
* shrink a VMA by removing the specified chunk from either the beginning or
* the end
*/
static int shrink_vma(struct mm_struct *mm,
struct vm_area_struct *vma,
unsigned long from, unsigned long to)
{
struct vm_region *region;
kenter("");
/* adjust the VMA's pointers, which may reposition it in the MM's tree
* and list */
delete_vma_from_mm(vma);
if (from > vma->vm_start)
vma->vm_end = from;
else
vma->vm_start = to;
add_vma_to_mm(mm, vma);
/* cut the backing region down to size */
region = vma->vm_region;
BUG_ON(region->vm_usage != 1);
down_write(&nommu_region_sem);
delete_nommu_region(region);
if (from > region->vm_start) {
to = region->vm_top;
region->vm_top = region->vm_end = from;
} else {
region->vm_start = to;
}
add_nommu_region(region);
up_write(&nommu_region_sem);
free_page_series(from, to);
return 0;
}
/*
* release a mapping
* - under NOMMU conditions the chunk to be unmapped must be backed by a single
* VMA, though it need not cover the whole VMA
*/
int do_munmap(struct mm_struct *mm, unsigned long start, size_t len)
{
struct vm_area_struct *vma;
unsigned long end;
int ret;
kenter(",%lx,%zx", start, len);
len = PAGE_ALIGN(len);
if (len == 0)
return -EINVAL;
end = start + len;
/* find the first potentially overlapping VMA */
vma = find_vma(mm, start);
if (!vma) {
static int limit = 0;
if (limit < 5) {
printk(KERN_WARNING
"munmap of memory not mmapped by process %d"
" (%s): 0x%lx-0x%lx\n",
current->pid, current->comm,
start, start + len - 1);
limit++;
}
return -EINVAL;
}
/* we're allowed to split an anonymous VMA but not a file-backed one */
if (vma->vm_file) {
do {
if (start > vma->vm_start) {
kleave(" = -EINVAL [miss]");
return -EINVAL;
}
if (end == vma->vm_end)
goto erase_whole_vma;
vma = vma->vm_next;
} while (vma);
kleave(" = -EINVAL [split file]");
return -EINVAL;
} else {
/* the chunk must be a subset of the VMA found */
if (start == vma->vm_start && end == vma->vm_end)
goto erase_whole_vma;
if (start < vma->vm_start || end > vma->vm_end) {
kleave(" = -EINVAL [superset]");
return -EINVAL;
}
if (start & ~PAGE_MASK) {
kleave(" = -EINVAL [unaligned start]");
return -EINVAL;
}
if (end != vma->vm_end && end & ~PAGE_MASK) {
kleave(" = -EINVAL [unaligned split]");
return -EINVAL;
}
if (start != vma->vm_start && end != vma->vm_end) {
ret = split_vma(mm, vma, start, 1);
if (ret < 0) {
kleave(" = %d [split]", ret);
return ret;
}
}
return shrink_vma(mm, vma, start, end);
}
erase_whole_vma:
delete_vma_from_mm(vma);
delete_vma(mm, vma);
kleave(" = 0");
return 0;
}
EXPORT_SYMBOL(do_munmap);
int vm_munmap(unsigned long addr, size_t len)
{
struct mm_struct *mm = current->mm;
int ret;
down_write(&mm->mmap_sem);
ret = do_munmap(mm, addr, len);
up_write(&mm->mmap_sem);
return ret;
}
EXPORT_SYMBOL(vm_munmap);
SYSCALL_DEFINE2(munmap, unsigned long, addr, size_t, len)
{
return vm_munmap(addr, len);
}
/*
* release all the mappings made in a process's VM space
*/
void exit_mmap(struct mm_struct *mm)
{
struct vm_area_struct *vma;
if (!mm)
return;
kenter("");
mm->total_vm = 0;
while ((vma = mm->mmap)) {
mm->mmap = vma->vm_next;
delete_vma_from_mm(vma);
delete_vma(mm, vma);
cond_resched();
}
kleave("");
}
unsigned long vm_brk(unsigned long addr, unsigned long len)
{
return -ENOMEM;
}
/*
* expand (or shrink) an existing mapping, potentially moving it at the same
* time (controlled by the MREMAP_MAYMOVE flag and available VM space)
*
* under NOMMU conditions, we only permit changing a mapping's size, and only
* as long as it stays within the region allocated by do_mmap_private() and the
* block is not shareable
*
* MREMAP_FIXED is not supported under NOMMU conditions
*/
unsigned long do_mremap(unsigned long addr,
unsigned long old_len, unsigned long new_len,
unsigned long flags, unsigned long new_addr)
{
struct vm_area_struct *vma;
/* insanity checks first */
old_len = PAGE_ALIGN(old_len);
new_len = PAGE_ALIGN(new_len);
if (old_len == 0 || new_len == 0)
return (unsigned long) -EINVAL;
if (addr & ~PAGE_MASK)
return -EINVAL;
if (flags & MREMAP_FIXED && new_addr != addr)
return (unsigned long) -EINVAL;
vma = find_vma_exact(current->mm, addr, old_len);
if (!vma)
return (unsigned long) -EINVAL;
if (vma->vm_end != vma->vm_start + old_len)
return (unsigned long) -EFAULT;
if (vma->vm_flags & VM_MAYSHARE)
return (unsigned long) -EPERM;
if (new_len > vma->vm_region->vm_end - vma->vm_region->vm_start)
return (unsigned long) -ENOMEM;
/* all checks complete - do it */
vma->vm_end = vma->vm_start + new_len;
return vma->vm_start;
}
EXPORT_SYMBOL(do_mremap);
SYSCALL_DEFINE5(mremap, unsigned long, addr, unsigned long, old_len,
unsigned long, new_len, unsigned long, flags,
unsigned long, new_addr)
{
unsigned long ret;
down_write(¤t->mm->mmap_sem);
ret = do_mremap(addr, old_len, new_len, flags, new_addr);
up_write(¤t->mm->mmap_sem);
return ret;
}
struct page *follow_page(struct vm_area_struct *vma, unsigned long address,
unsigned int foll_flags)
{
return NULL;
}
int remap_pfn_range(struct vm_area_struct *vma, unsigned long addr,
unsigned long pfn, unsigned long size, pgprot_t prot)
{
if (addr != (pfn << PAGE_SHIFT))
return -EINVAL;
vma->vm_flags |= VM_IO | VM_RESERVED | VM_PFNMAP;
return 0;
}
EXPORT_SYMBOL(remap_pfn_range);
int vm_iomap_memory(struct vm_area_struct *vma, phys_addr_t start, unsigned long len)
{
unsigned long pfn = start >> PAGE_SHIFT;
unsigned long vm_len = vma->vm_end - vma->vm_start;
pfn += vma->vm_pgoff;
return io_remap_pfn_range(vma, vma->vm_start, pfn, vm_len, vma->vm_page_prot);
}
EXPORT_SYMBOL(vm_iomap_memory);
int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
unsigned long pgoff)
{
unsigned int size = vma->vm_end - vma->vm_start;
if (!(vma->vm_flags & VM_USERMAP))
return -EINVAL;
vma->vm_start = (unsigned long)(addr + (pgoff << PAGE_SHIFT));
vma->vm_end = vma->vm_start + size;
return 0;
}
EXPORT_SYMBOL(remap_vmalloc_range);
unsigned long arch_get_unmapped_area(struct file *file, unsigned long addr,
unsigned long len, unsigned long pgoff, unsigned long flags)
{
return -ENOMEM;
}
void arch_unmap_area(struct mm_struct *mm, unsigned long addr)
{
}
void unmap_mapping_range(struct address_space *mapping,
loff_t const holebegin, loff_t const holelen,
int even_cows)
{
}
EXPORT_SYMBOL(unmap_mapping_range);
/*
* 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.
*
* We currently support three overcommit policies, which are set via the
* vm.overcommit_memory sysctl. See Documentation/vm/overcommit-accounting
*
* Strict overcommit modes added 2002 Feb 26 by Alan Cox.
* Additional code 2002 Jul 20 by Robert Love.
*
* cap_sys_admin is 1 if the process has admin privileges, 0 otherwise.
*
* Note this is a helper function intended to be used by LSMs which
* wish to use this logic.
*/
int __vm_enough_memory(struct mm_struct *mm, long pages, int cap_sys_admin)
{
long free, allowed;
vm_acct_memory(pages);
/*
* Sometimes we want to use more memory than we have
*/
if (sysctl_overcommit_memory == OVERCOMMIT_ALWAYS)
return 0;
if (sysctl_overcommit_memory == OVERCOMMIT_GUESS) {
free = global_page_state(NR_FREE_PAGES);
free += global_page_state(NR_FILE_PAGES);
/*
* shmem pages shouldn't be counted as free in this
* case, they can't be purged, only swapped out, and
* that won't affect the overall amount of available
* memory in the system.
*/
free -= global_page_state(NR_SHMEM);
free += nr_swap_pages;
/*
* Any slabs which are created with the
* SLAB_RECLAIM_ACCOUNT flag claim to have contents
* which are reclaimable, under pressure. The dentry
* cache and most inode caches should fall into this
*/
free += global_page_state(NR_SLAB_RECLAIMABLE);
/*
* Leave reserved pages. The pages are not for anonymous pages.
*/
if (free <= totalreserve_pages)
goto error;
else
free -= totalreserve_pages;
/*
* Leave the last 3% for root
*/
if (!cap_sys_admin)
free -= free / 32;
if (free > pages)
return 0;
goto error;
}
allowed = totalram_pages * sysctl_overcommit_ratio / 100;
/*
* Leave the last 3% for root
*/
if (!cap_sys_admin)
allowed -= allowed / 32;
allowed += total_swap_pages;
/* Don't let a single process grow too big:
leave 3% of the size of this process for other processes */
if (mm)
allowed -= mm->total_vm / 32;
if (percpu_counter_read_positive(&vm_committed_as) < allowed)
return 0;
error:
vm_unacct_memory(pages);
return -ENOMEM;
}
int in_gate_area_no_mm(unsigned long addr)
{
return 0;
}
int filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
BUG();
return 0;
}
EXPORT_SYMBOL(filemap_fault);
static int __access_remote_vm(struct task_struct *tsk, struct mm_struct *mm,
unsigned long addr, void *buf, int len, int write)
{
struct vm_area_struct *vma;
down_read(&mm->mmap_sem);
/* the access must start within one of the target process's mappings */
vma = find_vma(mm, addr);
if (vma) {
/* don't overrun this mapping */
if (addr + len >= vma->vm_end)
len = vma->vm_end - addr;
/* only read or write mappings where it is permitted */
if (write && vma->vm_flags & VM_MAYWRITE)
copy_to_user_page(vma, NULL, addr,
(void *) addr, buf, len);
else if (!write && vma->vm_flags & VM_MAYREAD)
copy_from_user_page(vma, NULL, addr,
buf, (void *) addr, len);
else
len = 0;
} else {
len = 0;
}
up_read(&mm->mmap_sem);
return len;
}
/**
* @access_remote_vm - access another process' address space
* @mm: the mm_struct of the target address space
* @addr: start address to access
* @buf: source or destination buffer
* @len: number of bytes to transfer
* @write: whether the access is a write
*
* The caller must hold a reference on @mm.
*/
int access_remote_vm(struct mm_struct *mm, unsigned long addr,
void *buf, int len, int write)
{
return __access_remote_vm(NULL, mm, addr, buf, len, write);
}
/*
* Access another process' address space.
* - source/target buffer must be kernel space
*/
int access_process_vm(struct task_struct *tsk, unsigned long addr, void *buf, int len, int write)
{
struct mm_struct *mm;
if (addr + len < addr)
return 0;
mm = get_task_mm(tsk);
if (!mm)
return 0;
len = __access_remote_vm(tsk, mm, addr, buf, len, write);
mmput(mm);
return len;
}
/**
* nommu_shrink_inode_mappings - Shrink the shared mappings on an inode
* @inode: The inode to check
* @size: The current filesize of the inode
* @newsize: The proposed filesize of the inode
*
* Check the shared mappings on an inode on behalf of a shrinking truncate to
* make sure that that any outstanding VMAs aren't broken and then shrink the
* vm_regions that extend that beyond so that do_mmap_pgoff() doesn't
* automatically grant mappings that are too large.
*/
int nommu_shrink_inode_mappings(struct inode *inode, size_t size,
size_t newsize)
{
struct vm_area_struct *vma;
struct prio_tree_iter iter;
struct vm_region *region;
pgoff_t low, high;
size_t r_size, r_top;
low = newsize >> PAGE_SHIFT;
high = (size + PAGE_SIZE - 1) >> PAGE_SHIFT;
down_write(&nommu_region_sem);
mutex_lock(&inode->i_mapping->i_mmap_mutex);
/* search for VMAs that fall within the dead zone */
vma_prio_tree_foreach(vma, &iter, &inode->i_mapping->i_mmap,
low, high) {
/* found one - only interested if it's shared out of the page
* cache */
if (vma->vm_flags & VM_SHARED) {
mutex_unlock(&inode->i_mapping->i_mmap_mutex);
up_write(&nommu_region_sem);
return -ETXTBSY; /* not quite true, but near enough */
}
}
/* reduce any regions that overlap the dead zone - if in existence,
* these will be pointed to by VMAs that don't overlap the dead zone
*
* we don't check for any regions that start beyond the EOF as there
* shouldn't be any
*/
vma_prio_tree_foreach(vma, &iter, &inode->i_mapping->i_mmap,
0, ULONG_MAX) {
if (!(vma->vm_flags & VM_SHARED))
continue;
region = vma->vm_region;
r_size = region->vm_top - region->vm_start;
r_top = (region->vm_pgoff << PAGE_SHIFT) + r_size;
if (r_top > newsize) {
region->vm_top -= r_top - newsize;
if (region->vm_end > region->vm_top)
region->vm_end = region->vm_top;
}
}
mutex_unlock(&inode->i_mapping->i_mmap_mutex);
up_write(&nommu_region_sem);
return 0;
}
|
lollipop-og/android_kernel_geehrc
|
mm/nommu.c
|
C
|
gpl-2.0
| 52,460 |
VERSION = 2
PATCHLEVEL = 6
SUBLEVEL = 38
EXTRAVERSION = .6
NAME = Flesh-Eating Bats with Fangs
# *DOCUMENTATION*
# To see a list of typical targets execute "make help"
# More info can be located in ./README
# Comments in this file are targeted only to the developer, do not
# expect to learn how to build the kernel reading this file.
# Do not:
# o use make's built-in rules and variables
# (this increases performance and avoids hard-to-debug behaviour);
# o print "Entering directory ...";
MAKEFLAGS += -rR --no-print-directory
# Avoid funny character set dependencies
unexport LC_ALL
LC_COLLATE=C
LC_NUMERIC=C
export LC_COLLATE LC_NUMERIC
# We are using a recursive build, so we need to do a little thinking
# to get the ordering right.
#
# Most importantly: sub-Makefiles should only ever modify files in
# their own directory. If in some directory we have a dependency on
# a file in another dir (which doesn't happen often, but it's often
# unavoidable when linking the built-in.o targets which finally
# turn into vmlinux), we will call a sub make in that other dir, and
# after that we are sure that everything which is in that other dir
# is now up to date.
#
# The only cases where we need to modify files which have global
# effects are thus separated out and done before the recursive
# descending is started. They are now explicitly listed as the
# prepare rule.
# To put more focus on warnings, be less verbose as default
# Use 'make V=1' to see the full commands
ifeq ("$(origin V)", "command line")
KBUILD_VERBOSE = $(V)
endif
ifndef KBUILD_VERBOSE
KBUILD_VERBOSE = 0
endif
# Call a source code checker (by default, "sparse") as part of the
# C compilation.
#
# Use 'make C=1' to enable checking of only re-compiled files.
# Use 'make C=2' to enable checking of *all* source files, regardless
# of whether they are re-compiled or not.
#
# See the file "Documentation/sparse.txt" for more details, including
# where to get the "sparse" utility.
ifeq ("$(origin C)", "command line")
KBUILD_CHECKSRC = $(C)
endif
ifndef KBUILD_CHECKSRC
KBUILD_CHECKSRC = 0
endif
# Use make M=dir to specify directory of external module to build
# Old syntax make ... SUBDIRS=$PWD is still supported
# Setting the environment variable KBUILD_EXTMOD take precedence
ifdef SUBDIRS
KBUILD_EXTMOD ?= $(SUBDIRS)
endif
ifeq ("$(origin M)", "command line")
KBUILD_EXTMOD := $(M)
endif
# kbuild supports saving output files in a separate directory.
# To locate output files in a separate directory two syntaxes are supported.
# In both cases the working directory must be the root of the kernel src.
# 1) O=
# Use "make O=dir/to/store/output/files/"
#
# 2) Set KBUILD_OUTPUT
# Set the environment variable KBUILD_OUTPUT to point to the directory
# where the output files shall be placed.
# export KBUILD_OUTPUT=dir/to/store/output/files/
# make
#
# The O= assignment takes precedence over the KBUILD_OUTPUT environment
# variable.
# KBUILD_SRC is set on invocation of make in OBJ directory
# KBUILD_SRC is not intended to be used by the regular user (for now)
ifeq ($(KBUILD_SRC),)
# OK, Make called in directory where kernel src resides
# Do we want to locate output files in a separate directory?
ifeq ("$(origin O)", "command line")
KBUILD_OUTPUT := $(O)
endif
# That's our default target when none is given on the command line
PHONY := _all
_all:
# Cancel implicit rules on top Makefile
$(CURDIR)/Makefile Makefile: ;
ifneq ($(KBUILD_OUTPUT),)
# Invoke a second make in the output directory, passing relevant variables
# check that the output directory actually exists
saved-output := $(KBUILD_OUTPUT)
KBUILD_OUTPUT := $(shell cd $(KBUILD_OUTPUT) && /bin/pwd)
$(if $(KBUILD_OUTPUT),, \
$(error output directory "$(saved-output)" does not exist))
PHONY += $(MAKECMDGOALS) sub-make
$(filter-out _all sub-make $(CURDIR)/Makefile, $(MAKECMDGOALS)) _all: sub-make
$(Q)@:
sub-make: FORCE
$(if $(KBUILD_VERBOSE:1=),@)$(MAKE) -C $(KBUILD_OUTPUT) \
KBUILD_SRC=$(CURDIR) \
KBUILD_EXTMOD="$(KBUILD_EXTMOD)" -f $(CURDIR)/Makefile \
$(filter-out _all sub-make,$(MAKECMDGOALS))
# Leave processing to above invocation of make
skip-makefile := 1
endif # ifneq ($(KBUILD_OUTPUT),)
endif # ifeq ($(KBUILD_SRC),)
# We process the rest of the Makefile if this is the final invocation of make
ifeq ($(skip-makefile),)
# If building an external module we do not care about the all: rule
# but instead _all depend on modules
PHONY += all
ifeq ($(KBUILD_EXTMOD),)
_all: all
else
_all: modules
endif
srctree := $(if $(KBUILD_SRC),$(KBUILD_SRC),$(CURDIR))
objtree := $(CURDIR)
src := $(srctree)
obj := $(objtree)
VPATH := $(srctree)$(if $(KBUILD_EXTMOD),:$(KBUILD_EXTMOD))
export srctree objtree VPATH
# SUBARCH tells the usermode build what the underlying arch is. That is set
# first, and if a usermode build is happening, the "ARCH=um" on the command
# line overrides the setting of ARCH below. If a native build is happening,
# then ARCH is assigned, getting whatever value it gets normally, and
# SUBARCH is subsequently ignored.
SUBARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ \
-e s/sh[234].*/sh/ )
# Cross compiling and selecting different set of gcc/bin-utils
# ---------------------------------------------------------------------------
#
# When performing cross compilation for other architectures ARCH shall be set
# to the target architecture. (See arch/* for the possibilities).
# ARCH can be set during invocation of make:
# make ARCH=ia64
# Another way is to have ARCH set in the environment.
# The default ARCH is the host where make is executed.
# CROSS_COMPILE specify the prefix used for all executables used
# during compilation. Only gcc and related bin-utils executables
# are prefixed with $(CROSS_COMPILE).
# CROSS_COMPILE can be set on the command line
# make CROSS_COMPILE=ia64-linux-
# Alternatively CROSS_COMPILE can be set in the environment.
# A third alternative is to store a setting in .config so that plain
# "make" in the configured kernel build directory always uses that.
# Default value for CROSS_COMPILE is not to prefix executables
# Note: Some architectures assign CROSS_COMPILE in their arch/*/Makefile
SUBARCH := arm
export KBUILD_BUILDHOST := $(SUBARCH)
ARCH ?= $(SUBARCH)
CROSS_COMPILE ?= /home/infamous/Toolchains/arm-eabi-4.4.3/bin/arm-eabi-
# Architecture as present in compile.h
UTS_MACHINE := $(ARCH)
SRCARCH := $(ARCH)
# Additional ARCH settings for x86
ifeq ($(ARCH),i386)
SRCARCH := x86
endif
ifeq ($(ARCH),x86_64)
SRCARCH := x86
endif
# Additional ARCH settings for sparc
ifeq ($(ARCH),sparc32)
SRCARCH := sparc
endif
ifeq ($(ARCH),sparc64)
SRCARCH := sparc
endif
# Additional ARCH settings for sh
ifeq ($(ARCH),sh64)
SRCARCH := sh
endif
# Where to locate arch specific headers
hdr-arch := $(SRCARCH)
ifeq ($(ARCH),m68knommu)
hdr-arch := m68k
endif
KCONFIG_CONFIG ?= .config
export KCONFIG_CONFIG
# SHELL used by kbuild
CONFIG_SHELL := $(shell if [ -x "$$BASH" ]; then echo $$BASH; \
else if [ -x /bin/bash ]; then echo /bin/bash; \
else echo sh; fi ; fi)
HOSTCC = gcc
HOSTCXX = g++
HOSTCFLAGS = -Wall -Wmissing-prototypes -Wstrict-prototypes -O2 -fomit-frame-pointer
HOSTCXXFLAGS = -O2
# Decide whether to build built-in, modular, or both.
# Normally, just do built-in.
KBUILD_MODULES :=
KBUILD_BUILTIN := 1
# If we have only "make modules", don't compile built-in objects.
# When we're building modules with modversions, we need to consider
# the built-in objects during the descend as well, in order to
# make sure the checksums are up to date before we record them.
ifeq ($(MAKECMDGOALS),modules)
KBUILD_BUILTIN := $(if $(CONFIG_MODVERSIONS),1)
endif
# If we have "make <whatever> modules", compile modules
# in addition to whatever we do anyway.
# Just "make" or "make all" shall build modules as well
ifneq ($(filter all _all modules,$(MAKECMDGOALS)),)
KBUILD_MODULES := 1
endif
ifeq ($(MAKECMDGOALS),)
KBUILD_MODULES := 1
endif
export KBUILD_MODULES KBUILD_BUILTIN
export KBUILD_CHECKSRC KBUILD_SRC KBUILD_EXTMOD
# Beautify output
# ---------------------------------------------------------------------------
#
# Normally, we echo the whole command before executing it. By making
# that echo $($(quiet)$(cmd)), we now have the possibility to set
# $(quiet) to choose other forms of output instead, e.g.
#
# quiet_cmd_cc_o_c = Compiling $(RELDIR)/$@
# cmd_cc_o_c = $(CC) $(c_flags) -c -o $@ $<
#
# If $(quiet) is empty, the whole command will be printed.
# If it is set to "quiet_", only the short version will be printed.
# If it is set to "silent_", nothing will be printed at all, since
# the variable $(silent_cmd_cc_o_c) doesn't exist.
#
# A simple variant is to prefix commands with $(Q) - that's useful
# for commands that shall be hidden in non-verbose mode.
#
# $(Q)ln $@ :<
#
# If KBUILD_VERBOSE equals 0 then the above command will be hidden.
# If KBUILD_VERBOSE equals 1 then the above command is displayed.
ifeq ($(KBUILD_VERBOSE),1)
quiet =
Q =
else
quiet=quiet_
Q = @
endif
# If the user is running make -s (silent mode), suppress echoing of
# commands
ifneq ($(findstring s,$(MAKEFLAGS)),)
quiet=silent_
endif
export quiet Q KBUILD_VERBOSE
# Look for make include files relative to root of kernel src
MAKEFLAGS += --include-dir=$(srctree)
# We need some generic definitions (do not try to remake the file).
$(srctree)/scripts/Kbuild.include: ;
include $(srctree)/scripts/Kbuild.include
# Make variables (CC, etc...)
AS = $(CROSS_COMPILE)as
LD = $(CROSS_COMPILE)ld
REAL_CC = $(CROSS_COMPILE)gcc
CPP = $(CC) -E
AR = $(CROSS_COMPILE)ar
NM = $(CROSS_COMPILE)nm
STRIP = $(CROSS_COMPILE)strip
OBJCOPY = $(CROSS_COMPILE)objcopy
OBJDUMP = $(CROSS_COMPILE)objdump
AWK = awk
GENKSYMS = scripts/genksyms/genksyms
INSTALLKERNEL := installkernel
DEPMOD = /sbin/depmod
KALLSYMS = scripts/kallsyms
PERL = perl
CHECK = sparse
# Use the wrapper for the compiler. This wrapper scans for new
# warnings and causes the build to stop upon encountering them.
CC = $(srctree)/scripts/gcc-wrapper.py $(REAL_CC)
CHECKFLAGS := -D__linux__ -Dlinux -D__STDC__ -Dunix -D__unix__ \
-Wbitwise -Wno-return-void $(CF)
CFLAGS_MODULE =
AFLAGS_MODULE =
LDFLAGS_MODULE =
CFLAGS_KERNEL =
AFLAGS_KERNEL =
CFLAGS_GCOV = -fprofile-arcs -ftest-coverage
# Use LINUXINCLUDE when you must reference the include/ directory.
# Needed to be compatible with the O= option
LINUXINCLUDE := -I$(srctree)/arch/$(hdr-arch)/include -Iinclude \
$(if $(KBUILD_SRC), -I$(srctree)/include) \
-include include/generated/autoconf.h
KBUILD_CPPFLAGS := -D__KERNEL__
KBUILD_CFLAGS := -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs \
-fno-strict-aliasing -fno-common \
-Werror-implicit-function-declaration \
-Wno-format-security \
-fno-delete-null-pointer-checks
KBUILD_AFLAGS_KERNEL :=
KBUILD_CFLAGS_KERNEL :=
KBUILD_AFLAGS := -D__ASSEMBLY__
KBUILD_AFLAGS_MODULE := -DMODULE
KBUILD_CFLAGS_MODULE := -DMODULE
KBUILD_LDFLAGS_MODULE := -T $(srctree)/scripts/module-common.lds
# Read KERNELRELEASE from include/config/kernel.release (if it exists)
KERNELRELEASE = $(shell cat include/config/kernel.release 2> /dev/null)
KERNELVERSION = $(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)
export VERSION PATCHLEVEL SUBLEVEL KERNELRELEASE KERNELVERSION
export ARCH SRCARCH CONFIG_SHELL HOSTCC HOSTCFLAGS CROSS_COMPILE AS LD CC
export CPP AR NM STRIP OBJCOPY OBJDUMP
export MAKE AWK GENKSYMS INSTALLKERNEL PERL UTS_MACHINE
export HOSTCXX HOSTCXXFLAGS LDFLAGS_MODULE CHECK CHECKFLAGS
export KBUILD_CPPFLAGS NOSTDINC_FLAGS LINUXINCLUDE OBJCOPYFLAGS LDFLAGS
export KBUILD_CFLAGS CFLAGS_KERNEL CFLAGS_MODULE CFLAGS_GCOV
export KBUILD_AFLAGS AFLAGS_KERNEL AFLAGS_MODULE
export KBUILD_AFLAGS_MODULE KBUILD_CFLAGS_MODULE KBUILD_LDFLAGS_MODULE
export KBUILD_AFLAGS_KERNEL KBUILD_CFLAGS_KERNEL
# When compiling out-of-tree modules, put MODVERDIR in the module
# tree rather than in the kernel tree. The kernel tree might
# even be read-only.
export MODVERDIR := $(if $(KBUILD_EXTMOD),$(firstword $(KBUILD_EXTMOD))/).tmp_versions
# Files to ignore in find ... statements
RCS_FIND_IGNORE := \( -name SCCS -o -name BitKeeper -o -name .svn -o -name CVS -o -name .pc -o -name .hg -o -name .git \) -prune -o
export RCS_TAR_IGNORE := --exclude SCCS --exclude BitKeeper --exclude .svn --exclude CVS --exclude .pc --exclude .hg --exclude .git
# ===========================================================================
# Rules shared between *config targets and build targets
# Basic helpers built in scripts/
PHONY += scripts_basic
scripts_basic:
$(Q)$(MAKE) $(build)=scripts/basic
$(Q)rm -f .tmp_quiet_recordmcount
# To avoid any implicit rule to kick in, define an empty command.
scripts/basic/%: scripts_basic ;
PHONY += outputmakefile
# outputmakefile generates a Makefile in the output directory, if using a
# separate output directory. This allows convenient use of make in the
# output directory.
outputmakefile:
ifneq ($(KBUILD_SRC),)
$(Q)ln -fsn $(srctree) source
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/mkmakefile \
$(srctree) $(objtree) $(VERSION) $(PATCHLEVEL)
endif
# To make sure we do not include .config for any of the *config targets
# catch them early, and hand them over to scripts/kconfig/Makefile
# It is allowed to specify more targets when calling make, including
# mixing *config targets and build targets.
# For example 'make oldconfig all'.
# Detect when mixed targets is specified, and make a second invocation
# of make so .config is not included in this case either (for *config).
no-dot-config-targets := clean mrproper distclean \
cscope TAGS tags help %docs check% coccicheck \
include/linux/version.h headers_% \
kernelversion %src-pkg
config-targets := 0
mixed-targets := 0
dot-config := 1
ifneq ($(filter $(no-dot-config-targets), $(MAKECMDGOALS)),)
ifeq ($(filter-out $(no-dot-config-targets), $(MAKECMDGOALS)),)
dot-config := 0
endif
endif
ifeq ($(KBUILD_EXTMOD),)
ifneq ($(filter config %config,$(MAKECMDGOALS)),)
config-targets := 1
ifneq ($(filter-out config %config,$(MAKECMDGOALS)),)
mixed-targets := 1
endif
endif
endif
ifeq ($(mixed-targets),1)
# ===========================================================================
# We're called with mixed targets (*config and build targets).
# Handle them one by one.
%:: FORCE
$(Q)$(MAKE) -C $(srctree) KBUILD_SRC= $@
else
ifeq ($(config-targets),1)
# ===========================================================================
# *config targets only - make sure prerequisites are updated, and descend
# in scripts/kconfig to make the *config target
# Read arch specific Makefile to set KBUILD_DEFCONFIG as needed.
# KBUILD_DEFCONFIG may point out an alternative default configuration
# used for 'make defconfig'
include $(srctree)/arch/$(SRCARCH)/Makefile
export KBUILD_DEFCONFIG KBUILD_KCONFIG
config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
%config: scripts_basic outputmakefile FORCE
$(Q)mkdir -p include/linux include/config
$(Q)$(MAKE) $(build)=scripts/kconfig $@
else
# ===========================================================================
# Build targets only - this includes vmlinux, arch specific targets, clean
# targets and others. In general all targets except *config targets.
ifeq ($(KBUILD_EXTMOD),)
# Additional helpers built in scripts/
# Carefully list dependencies so we do not try to build scripts twice
# in parallel
PHONY += scripts
scripts: scripts_basic include/config/auto.conf include/config/tristate.conf
$(Q)$(MAKE) $(build)=$(@)
# Objects we will link into vmlinux / subdirs we need to visit
init-y := init/
drivers-y := drivers/ sound/ firmware/
net-y := net/
libs-y := lib/
core-y := usr/
endif # KBUILD_EXTMOD
ifeq ($(dot-config),1)
# Read in config
-include include/config/auto.conf
ifeq ($(KBUILD_EXTMOD),)
# Read in dependencies to all Kconfig* files, make sure to run
# oldconfig if changes are detected.
-include include/config/auto.conf.cmd
# To avoid any implicit rule to kick in, define an empty command
$(KCONFIG_CONFIG) include/config/auto.conf.cmd: ;
# If .config is newer than include/config/auto.conf, someone tinkered
# with it and forgot to run make oldconfig.
# if auto.conf.cmd is missing then we are probably in a cleaned tree so
# we execute the config step to be sure to catch updated Kconfig files
include/config/%.conf: $(KCONFIG_CONFIG) include/config/auto.conf.cmd
$(Q)$(MAKE) -f $(srctree)/Makefile silentoldconfig
else
# external modules needs include/generated/autoconf.h and include/config/auto.conf
# but do not care if they are up-to-date. Use auto.conf to trigger the test
PHONY += include/config/auto.conf
include/config/auto.conf:
$(Q)test -e include/generated/autoconf.h -a -e $@ || ( \
echo; \
echo " ERROR: Kernel configuration is invalid."; \
echo " include/generated/autoconf.h or $@ are missing.";\
echo " Run 'make oldconfig && make prepare' on kernel src to fix it."; \
echo; \
/bin/false)
endif # KBUILD_EXTMOD
else
# Dummy target needed, because used as prerequisite
include/config/auto.conf: ;
endif # $(dot-config)
# The all: target is the default when no target is given on the
# command line.
# This allow a user to issue only 'make' to build a kernel including modules
# Defaults to vmlinux, but the arch makefile usually adds further targets
all: vmlinux
ifdef CONFIG_CC_OPTIMIZE_FOR_SIZE
KBUILD_CFLAGS += -Os
else
KBUILD_CFLAGS += -O2
endif
include $(srctree)/arch/$(SRCARCH)/Makefile
ifneq ($(CONFIG_FRAME_WARN),0)
KBUILD_CFLAGS += $(call cc-option,-Wframe-larger-than=${CONFIG_FRAME_WARN})
endif
# Force gcc to behave correct even for buggy distributions
ifndef CONFIG_CC_STACKPROTECTOR
KBUILD_CFLAGS += $(call cc-option, -fno-stack-protector)
endif
ifdef CONFIG_FRAME_POINTER
KBUILD_CFLAGS += -fno-omit-frame-pointer -fno-optimize-sibling-calls
else
# Some targets (ARM with Thumb2, for example), can't be built with frame
# pointers. For those, we don't have FUNCTION_TRACER automatically
# select FRAME_POINTER. However, FUNCTION_TRACER adds -pg, and this is
# incompatible with -fomit-frame-pointer with current GCC, so we don't use
# -fomit-frame-pointer with FUNCTION_TRACER.
ifndef CONFIG_FUNCTION_TRACER
KBUILD_CFLAGS += -fomit-frame-pointer
endif
endif
ifdef CONFIG_DEBUG_INFO
KBUILD_CFLAGS += -g
KBUILD_AFLAGS += -gdwarf-2
endif
ifdef CONFIG_DEBUG_INFO_REDUCED
KBUILD_CFLAGS += $(call cc-option, -femit-struct-debug-baseonly)
endif
ifdef CONFIG_FUNCTION_TRACER
KBUILD_CFLAGS += -pg
ifdef CONFIG_DYNAMIC_FTRACE
ifdef CONFIG_HAVE_C_RECORDMCOUNT
BUILD_C_RECORDMCOUNT := y
export BUILD_C_RECORDMCOUNT
endif
endif
endif
# We trigger additional mismatches with less inlining
ifdef CONFIG_DEBUG_SECTION_MISMATCH
KBUILD_CFLAGS += $(call cc-option, -fno-inline-functions-called-once)
endif
# arch Makefile may override CC so keep this after arch Makefile is included
NOSTDINC_FLAGS += -nostdinc -isystem $(shell $(CC) -print-file-name=include)
CHECKFLAGS += $(NOSTDINC_FLAGS)
# warn about C99 declaration after statement
KBUILD_CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# disable pointer signed / unsigned warnings in gcc 4.0
KBUILD_CFLAGS += $(call cc-option,-Wno-pointer-sign,)
# disable invalid "can't wrap" optimizations for signed / pointers
KBUILD_CFLAGS += $(call cc-option,-fno-strict-overflow)
# conserve stack if available
KBUILD_CFLAGS += $(call cc-option,-fconserve-stack)
# check for 'asm goto'
ifeq ($(shell $(CONFIG_SHELL) $(srctree)/scripts/gcc-goto.sh $(CC)), y)
KBUILD_CFLAGS += -DCC_HAVE_ASM_GOTO
endif
# Add user supplied CPPFLAGS, AFLAGS and CFLAGS as the last assignments
# But warn user when we do so
warn-assign = \
$(warning "WARNING: Appending $$K$(1) ($(K$(1))) from $(origin K$(1)) to kernel $$$(1)")
ifneq ($(KCPPFLAGS),)
$(call warn-assign,CPPFLAGS)
KBUILD_CPPFLAGS += $(KCPPFLAGS)
endif
ifneq ($(KAFLAGS),)
$(call warn-assign,AFLAGS)
KBUILD_AFLAGS += $(KAFLAGS)
endif
ifneq ($(KCFLAGS),)
$(call warn-assign,CFLAGS)
KBUILD_CFLAGS += $(KCFLAGS)
endif
# Use --build-id when available.
LDFLAGS_BUILD_ID = $(patsubst -Wl$(comma)%,%,\
$(call cc-ldoption, -Wl$(comma)--build-id,))
KBUILD_LDFLAGS_MODULE += $(LDFLAGS_BUILD_ID)
LDFLAGS_vmlinux += $(LDFLAGS_BUILD_ID)
ifeq ($(CONFIG_STRIP_ASM_SYMS),y)
LDFLAGS_vmlinux += $(call ld-option, -X,)
endif
# Default kernel image to build when no specific target is given.
# KBUILD_IMAGE may be overruled on the command line or
# set in the environment
# Also any assignments in arch/$(ARCH)/Makefile take precedence over
# this default value
export KBUILD_IMAGE ?= vmlinux
#
# INSTALL_PATH specifies where to place the updated kernel and system map
# images. Default is /boot, but you can set it to other values
export INSTALL_PATH ?= /boot
#
# INSTALL_MOD_PATH specifies a prefix to MODLIB for module directory
# relocations required by build roots. This is not defined in the
# makefile but the argument can be passed to make if needed.
#
MODLIB = $(INSTALL_MOD_PATH)/lib/modules/$(KERNELRELEASE)
export MODLIB
#
# INSTALL_MOD_STRIP, if defined, will cause modules to be
# stripped after they are installed. If INSTALL_MOD_STRIP is '1', then
# the default option --strip-debug will be used. Otherwise,
# INSTALL_MOD_STRIP will used as the options to the strip command.
ifdef INSTALL_MOD_STRIP
ifeq ($(INSTALL_MOD_STRIP),1)
mod_strip_cmd = $(STRIP) --strip-debug
else
mod_strip_cmd = $(STRIP) $(INSTALL_MOD_STRIP)
endif # INSTALL_MOD_STRIP=1
else
mod_strip_cmd = true
endif # INSTALL_MOD_STRIP
export mod_strip_cmd
ifeq ($(KBUILD_EXTMOD),)
core-y += kernel/ mm/ fs/ ipc/ security/ crypto/ block/
vmlinux-dirs := $(patsubst %/,%,$(filter %/, $(init-y) $(init-m) \
$(core-y) $(core-m) $(drivers-y) $(drivers-m) \
$(net-y) $(net-m) $(libs-y) $(libs-m)))
vmlinux-alldirs := $(sort $(vmlinux-dirs) $(patsubst %/,%,$(filter %/, \
$(init-n) $(init-) \
$(core-n) $(core-) $(drivers-n) $(drivers-) \
$(net-n) $(net-) $(libs-n) $(libs-))))
init-y := $(patsubst %/, %/built-in.o, $(init-y))
core-y := $(patsubst %/, %/built-in.o, $(core-y))
drivers-y := $(patsubst %/, %/built-in.o, $(drivers-y))
net-y := $(patsubst %/, %/built-in.o, $(net-y))
libs-y1 := $(patsubst %/, %/lib.a, $(libs-y))
libs-y2 := $(patsubst %/, %/built-in.o, $(libs-y))
libs-y := $(libs-y1) $(libs-y2)
# Build vmlinux
# ---------------------------------------------------------------------------
# vmlinux is built from the objects selected by $(vmlinux-init) and
# $(vmlinux-main). Most are built-in.o files from top-level directories
# in the kernel tree, others are specified in arch/$(ARCH)/Makefile.
# Ordering when linking is important, and $(vmlinux-init) must be first.
#
# vmlinux
# ^
# |
# +-< $(vmlinux-init)
# | +--< init/version.o + more
# |
# +--< $(vmlinux-main)
# | +--< driver/built-in.o mm/built-in.o + more
# |
# +-< kallsyms.o (see description in CONFIG_KALLSYMS section)
#
# vmlinux version (uname -v) cannot be updated during normal
# descending-into-subdirs phase since we do not yet know if we need to
# update vmlinux.
# Therefore this step is delayed until just before final link of vmlinux -
# except in the kallsyms case where it is done just before adding the
# symbols to the kernel.
#
# System.map is generated to document addresses of all kernel symbols
vmlinux-init := $(head-y) $(init-y)
vmlinux-main := $(core-y) $(libs-y) $(drivers-y) $(net-y)
vmlinux-all := $(vmlinux-init) $(vmlinux-main)
vmlinux-lds := arch/$(SRCARCH)/kernel/vmlinux.lds
export KBUILD_VMLINUX_OBJS := $(vmlinux-all)
# Rule to link vmlinux - also used during CONFIG_KALLSYMS
# May be overridden by arch/$(ARCH)/Makefile
quiet_cmd_vmlinux__ ?= LD $@
cmd_vmlinux__ ?= $(LD) $(LDFLAGS) $(LDFLAGS_vmlinux) -o $@ \
-T $(vmlinux-lds) $(vmlinux-init) \
--start-group $(vmlinux-main) --end-group \
$(filter-out $(vmlinux-lds) $(vmlinux-init) $(vmlinux-main) vmlinux.o FORCE ,$^)
# Generate new vmlinux version
quiet_cmd_vmlinux_version = GEN .version
cmd_vmlinux_version = set -e; \
if [ ! -r .version ]; then \
rm -f .version; \
echo 1 >.version; \
else \
mv .version .old_version; \
expr 0$$(cat .old_version) + 1 >.version; \
fi; \
$(MAKE) $(build)=init
# Generate System.map
quiet_cmd_sysmap = SYSMAP
cmd_sysmap = $(CONFIG_SHELL) $(srctree)/scripts/mksysmap
# Link of vmlinux
# If CONFIG_KALLSYMS is set .version is already updated
# Generate System.map and verify that the content is consistent
# Use + in front of the vmlinux_version rule to silent warning with make -j2
# First command is ':' to allow us to use + in front of the rule
define rule_vmlinux__
:
$(if $(CONFIG_KALLSYMS),,+$(call cmd,vmlinux_version))
$(call cmd,vmlinux__)
$(Q)echo 'cmd_$@ := $(cmd_vmlinux__)' > $(@D)/.$(@F).cmd
$(Q)$(if $($(quiet)cmd_sysmap), \
echo ' $($(quiet)cmd_sysmap) System.map' &&) \
$(cmd_sysmap) $@ System.map; \
if [ $$? -ne 0 ]; then \
rm -f $@; \
/bin/false; \
fi;
$(verify_kallsyms)
endef
ifdef CONFIG_KALLSYMS
# Generate section listing all symbols and add it into vmlinux $(kallsyms.o)
# It's a three stage process:
# o .tmp_vmlinux1 has all symbols and sections, but __kallsyms is
# empty
# Running kallsyms on that gives us .tmp_kallsyms1.o with
# the right size - vmlinux version (uname -v) is updated during this step
# o .tmp_vmlinux2 now has a __kallsyms section of the right size,
# but due to the added section, some addresses have shifted.
# From here, we generate a correct .tmp_kallsyms2.o
# o The correct .tmp_kallsyms2.o is linked into the final vmlinux.
# o Verify that the System.map from vmlinux matches the map from
# .tmp_vmlinux2, just in case we did not generate kallsyms correctly.
# o If CONFIG_KALLSYMS_EXTRA_PASS is set, do an extra pass using
# .tmp_vmlinux3 and .tmp_kallsyms3.o. This is only meant as a
# temporary bypass to allow the kernel to be built while the
# maintainers work out what went wrong with kallsyms.
ifdef CONFIG_KALLSYMS_EXTRA_PASS
last_kallsyms := 3
else
last_kallsyms := 2
endif
kallsyms.o := .tmp_kallsyms$(last_kallsyms).o
define verify_kallsyms
$(Q)$(if $($(quiet)cmd_sysmap), \
echo ' $($(quiet)cmd_sysmap) .tmp_System.map' &&) \
$(cmd_sysmap) .tmp_vmlinux$(last_kallsyms) .tmp_System.map
$(Q)cmp -s System.map .tmp_System.map || \
(echo Inconsistent kallsyms data; \
echo Try setting CONFIG_KALLSYMS_EXTRA_PASS; \
rm .tmp_kallsyms* ; /bin/false )
endef
# Update vmlinux version before link
# Use + in front of this rule to silent warning about make -j1
# First command is ':' to allow us to use + in front of this rule
cmd_ksym_ld = $(cmd_vmlinux__)
define rule_ksym_ld
:
+$(call cmd,vmlinux_version)
$(call cmd,vmlinux__)
$(Q)echo 'cmd_$@ := $(cmd_vmlinux__)' > $(@D)/.$(@F).cmd
endef
# Generate .S file with all kernel symbols
quiet_cmd_kallsyms = KSYM $@
cmd_kallsyms = $(NM) -n $< | $(KALLSYMS) \
$(if $(CONFIG_KALLSYMS_ALL),--all-symbols) > $@
.tmp_kallsyms1.o .tmp_kallsyms2.o .tmp_kallsyms3.o: %.o: %.S scripts FORCE
$(call if_changed_dep,as_o_S)
.tmp_kallsyms%.S: .tmp_vmlinux% $(KALLSYMS)
$(call cmd,kallsyms)
# .tmp_vmlinux1 must be complete except kallsyms, so update vmlinux version
.tmp_vmlinux1: $(vmlinux-lds) $(vmlinux-all) FORCE
$(call if_changed_rule,ksym_ld)
.tmp_vmlinux2: $(vmlinux-lds) $(vmlinux-all) .tmp_kallsyms1.o FORCE
$(call if_changed,vmlinux__)
.tmp_vmlinux3: $(vmlinux-lds) $(vmlinux-all) .tmp_kallsyms2.o FORCE
$(call if_changed,vmlinux__)
# Needs to visit scripts/ before $(KALLSYMS) can be used.
$(KALLSYMS): scripts ;
# Generate some data for debugging strange kallsyms problems
debug_kallsyms: .tmp_map$(last_kallsyms)
.tmp_map%: .tmp_vmlinux% FORCE
($(OBJDUMP) -h $< | $(AWK) '/^ +[0-9]/{print $$4 " 0 " $$2}'; $(NM) $<) | sort > $@
.tmp_map3: .tmp_map2
.tmp_map2: .tmp_map1
endif # ifdef CONFIG_KALLSYMS
# Do modpost on a prelinked vmlinux. The finally linked vmlinux has
# relevant sections renamed as per the linker script.
quiet_cmd_vmlinux-modpost = LD $@
cmd_vmlinux-modpost = $(LD) $(LDFLAGS) -r -o $@ \
$(vmlinux-init) --start-group $(vmlinux-main) --end-group \
$(filter-out $(vmlinux-init) $(vmlinux-main) FORCE ,$^)
define rule_vmlinux-modpost
:
+$(call cmd,vmlinux-modpost)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost $@
$(Q)echo 'cmd_$@ := $(cmd_vmlinux-modpost)' > $(dot-target).cmd
endef
# vmlinux image - including updated kernel symbols
vmlinux: $(vmlinux-lds) $(vmlinux-init) $(vmlinux-main) vmlinux.o $(kallsyms.o) FORCE
ifdef CONFIG_HEADERS_CHECK
$(Q)$(MAKE) -f $(srctree)/Makefile headers_check
endif
ifdef CONFIG_SAMPLES
$(Q)$(MAKE) $(build)=samples
endif
ifdef CONFIG_BUILD_DOCSRC
$(Q)$(MAKE) $(build)=Documentation
endif
$(call vmlinux-modpost)
$(call if_changed_rule,vmlinux__)
$(Q)rm -f .old_version
# build vmlinux.o first to catch section mismatch errors early
ifdef CONFIG_KALLSYMS
.tmp_vmlinux1: vmlinux.o
endif
modpost-init := $(filter-out init/built-in.o, $(vmlinux-init))
vmlinux.o: $(modpost-init) $(vmlinux-main) FORCE
$(call if_changed_rule,vmlinux-modpost)
# The actual objects are generated when descending,
# make sure no implicit rule kicks in
$(sort $(vmlinux-init) $(vmlinux-main)) $(vmlinux-lds): $(vmlinux-dirs) ;
# Handle descending into subdirectories listed in $(vmlinux-dirs)
# Preset locale variables to speed up the build process. Limit locale
# tweaks to this spot to avoid wrong language settings when running
# make menuconfig etc.
# Error messages still appears in the original language
PHONY += $(vmlinux-dirs)
$(vmlinux-dirs): prepare scripts
$(Q)$(MAKE) $(build)=$@
# Store (new) KERNELRELASE string in include/config/kernel.release
include/config/kernel.release: include/config/auto.conf FORCE
$(Q)rm -f $@
$(Q)echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))" > $@
# Things we need to do before we recursively start building the kernel
# or the modules are listed in "prepare".
# A multi level approach is used. prepareN is processed before prepareN-1.
# archprepare is used in arch Makefiles and when processed asm symlink,
# version.h and scripts_basic is processed / created.
# Listed in dependency order
PHONY += prepare archprepare prepare0 prepare1 prepare2 prepare3
# prepare3 is used to check if we are building in a separate output directory,
# and if so do:
# 1) Check that make has not been executed in the kernel src $(srctree)
prepare3: include/config/kernel.release
ifneq ($(KBUILD_SRC),)
@$(kecho) ' Using $(srctree) as source for kernel'
$(Q)if [ -f $(srctree)/.config -o -d $(srctree)/include/config ]; then \
echo " $(srctree) is not clean, please run 'make mrproper'";\
echo " in the '$(srctree)' directory.";\
/bin/false; \
fi;
endif
# prepare2 creates a makefile if using a separate output directory
prepare2: prepare3 outputmakefile
prepare1: prepare2 include/linux/version.h include/generated/utsrelease.h \
include/config/auto.conf
$(cmd_crmodverdir)
archprepare: prepare1 scripts_basic
prepare0: archprepare FORCE
$(Q)$(MAKE) $(build)=.
$(Q)$(MAKE) $(build)=. missing-syscalls
# All the preparing..
prepare: prepare0
# Generate some files
# ---------------------------------------------------------------------------
# KERNELRELEASE can change from a few different places, meaning version.h
# needs to be updated, so this check is forced on all builds
uts_len := 64
define filechk_utsrelease.h
if [ `echo -n "$(KERNELRELEASE)" | wc -c ` -gt $(uts_len) ]; then \
echo '"$(KERNELRELEASE)" exceeds $(uts_len) characters' >&2; \
exit 1; \
fi; \
(echo \#define UTS_RELEASE \"$(KERNELRELEASE)\";)
endef
define filechk_version.h
(echo \#define LINUX_VERSION_CODE $(shell \
expr $(VERSION) \* 65536 + $(PATCHLEVEL) \* 256 + $(SUBLEVEL)); \
echo '#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))';)
endef
include/linux/version.h: $(srctree)/Makefile FORCE
$(call filechk,version.h)
include/generated/utsrelease.h: include/config/kernel.release FORCE
$(call filechk,utsrelease.h)
PHONY += headerdep
headerdep:
$(Q)find include/ -name '*.h' | xargs --max-args 1 scripts/headerdep.pl
# ---------------------------------------------------------------------------
PHONY += depend dep
depend dep:
@echo '*** Warning: make $@ is unnecessary now.'
# ---------------------------------------------------------------------------
# Firmware install
INSTALL_FW_PATH=$(INSTALL_MOD_PATH)/lib/firmware
export INSTALL_FW_PATH
PHONY += firmware_install
firmware_install: FORCE
@mkdir -p $(objtree)/firmware
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_install
# ---------------------------------------------------------------------------
# Kernel headers
#Default location for installed headers
export INSTALL_HDR_PATH = $(objtree)/usr
hdr-inst := -rR -f $(srctree)/scripts/Makefile.headersinst obj
# If we do an all arch process set dst to asm-$(hdr-arch)
hdr-dst = $(if $(KBUILD_HEADERS), dst=include/asm-$(hdr-arch), dst=include/asm)
PHONY += __headers
__headers: include/linux/version.h scripts_basic FORCE
$(Q)$(MAKE) $(build)=scripts scripts/unifdef
PHONY += headers_install_all
headers_install_all:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh install
PHONY += headers_install
headers_install: __headers
$(if $(wildcard $(srctree)/arch/$(hdr-arch)/include/asm/Kbuild),, \
$(error Headers not exportable for the $(SRCARCH) architecture))
$(Q)$(MAKE) $(hdr-inst)=include
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/asm $(hdr-dst)
PHONY += headers_check_all
headers_check_all: headers_install_all
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/headers.sh check
PHONY += headers_check
headers_check: headers_install
$(Q)$(MAKE) $(hdr-inst)=include HDRCHECK=1
$(Q)$(MAKE) $(hdr-inst)=arch/$(hdr-arch)/include/asm $(hdr-dst) HDRCHECK=1
# ---------------------------------------------------------------------------
# Modules
ifdef CONFIG_MODULES
# By default, build modules as well
all: modules
# Build modules
#
# A module can be listed more than once in obj-m resulting in
# duplicate lines in modules.order files. Those are removed
# using awk while concatenating to the final file.
PHONY += modules
modules: $(vmlinux-dirs) $(if $(KBUILD_BUILTIN),vmlinux) modules.builtin
$(Q)$(AWK) '!x[$$0]++' $(vmlinux-dirs:%=$(objtree)/%/modules.order) > $(objtree)/modules.order
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modbuild
modules.builtin: $(vmlinux-dirs:%=%/modules.builtin)
$(Q)$(AWK) '!x[$$0]++' $^ > $(objtree)/modules.builtin
%/modules.builtin: include/config/auto.conf
$(Q)$(MAKE) $(modbuiltin)=$*
# Target to prepare building external modules
PHONY += modules_prepare
modules_prepare: prepare scripts
# Target to install modules
PHONY += modules_install
modules_install: _modinst_ _modinst_post
PHONY += _modinst_
_modinst_:
@if [ -z "`$(DEPMOD) -V 2>/dev/null | grep module-init-tools`" ]; then \
echo "Warning: you may need to install module-init-tools"; \
echo "See http://www.codemonkey.org.uk/docs/post-halloween-2.6.txt";\
sleep 1; \
fi
@rm -rf $(MODLIB)/kernel
@rm -f $(MODLIB)/source
@mkdir -p $(MODLIB)/kernel
@ln -s $(srctree) $(MODLIB)/source
@if [ ! $(objtree) -ef $(MODLIB)/build ]; then \
rm -f $(MODLIB)/build ; \
ln -s $(objtree) $(MODLIB)/build ; \
fi
@cp -f $(objtree)/modules.order $(MODLIB)/
@cp -f $(objtree)/modules.builtin $(MODLIB)/
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
# This depmod is only for convenience to give the initial
# boot a modules.dep even before / is mounted read-write. However the
# boot script depmod is the master version.
PHONY += _modinst_post
_modinst_post: _modinst_
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.fwinst obj=firmware __fw_modinst
$(call cmd,depmod)
else # CONFIG_MODULES
# Modules not configured
# ---------------------------------------------------------------------------
modules modules_install: FORCE
@echo
@echo "The present kernel configuration has modules disabled."
@echo "Type 'make config' and enable loadable module support."
@echo "Then build a kernel with module support enabled."
@echo
@exit 1
endif # CONFIG_MODULES
###
# Cleaning is done on three levels.
# make clean Delete most generated files
# Leave enough to build external modules
# make mrproper Delete the current configuration, and all generated files
# make distclean Remove editor backup files, patch leftover files and the like
# Directories & files removed with 'make clean'
CLEAN_DIRS += $(MODVERDIR)
CLEAN_FILES += vmlinux System.map \
.tmp_kallsyms* .tmp_version .tmp_vmlinux* .tmp_System.map
# Directories & files removed with 'make mrproper'
MRPROPER_DIRS += include/config usr/include include/generated
MRPROPER_FILES += .config .config.old .version .old_version \
include/linux/version.h \
Module.symvers tags TAGS cscope*
# clean - Delete most, but leave enough to build external modules
#
clean: rm-dirs := $(CLEAN_DIRS)
clean: rm-files := $(CLEAN_FILES)
clean-dirs := $(addprefix _clean_, . $(vmlinux-alldirs) Documentation)
PHONY += $(clean-dirs) clean archclean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
clean: archclean
# mrproper - Delete all generated files, including .config
#
mrproper: rm-dirs := $(wildcard $(MRPROPER_DIRS))
mrproper: rm-files := $(wildcard $(MRPROPER_FILES))
mrproper-dirs := $(addprefix _mrproper_,Documentation/DocBook scripts)
PHONY += $(mrproper-dirs) mrproper archmrproper
$(mrproper-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _mrproper_%,%,$@)
mrproper: clean archmrproper $(mrproper-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
# distclean
#
PHONY += distclean
distclean: mrproper
@find $(srctree) $(RCS_FIND_IGNORE) \
\( -name '*.orig' -o -name '*.rej' -o -name '*~' \
-o -name '*.bak' -o -name '#*#' -o -name '.*.orig' \
-o -name '.*.rej' -o -size 0 \
-o -name '*%' -o -name '.*.cmd' -o -name 'core' \) \
-type f -print | xargs rm -f
# Packaging of the kernel to various formats
# ---------------------------------------------------------------------------
# rpm target kept for backward compatibility
package-dir := $(srctree)/scripts/package
%src-pkg: FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
%pkg: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
rpm: include/config/kernel.release FORCE
$(Q)$(MAKE) $(build)=$(package-dir) $@
# Brief documentation of the typical targets used
# ---------------------------------------------------------------------------
boards := $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*_defconfig)
boards := $(notdir $(boards))
board-dirs := $(dir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/*/*_defconfig))
board-dirs := $(sort $(notdir $(board-dirs:/=)))
help:
@echo 'Cleaning targets:'
@echo ' clean - Remove most generated files but keep the config and'
@echo ' enough build support to build external modules'
@echo ' mrproper - Remove all generated files + config + various backup files'
@echo ' distclean - mrproper + remove editor backup and patch files'
@echo ''
@echo 'Configuration targets:'
@$(MAKE) -f $(srctree)/scripts/kconfig/Makefile help
@echo ''
@echo 'Other generic targets:'
@echo ' all - Build all targets marked with [*]'
@echo '* vmlinux - Build the bare kernel'
@echo '* modules - Build all modules'
@echo ' modules_install - Install all modules to INSTALL_MOD_PATH (default: /)'
@echo ' firmware_install- Install all firmware to INSTALL_FW_PATH'
@echo ' (default: $$(INSTALL_MOD_PATH)/lib/firmware)'
@echo ' dir/ - Build all files in dir and below'
@echo ' dir/file.[oisS] - Build specified target only'
@echo ' dir/file.lst - Build specified mixed source/assembly target only'
@echo ' (requires a recent binutils and recent build (System.map))'
@echo ' dir/file.ko - Build module including final link'
@echo ' modules_prepare - Set up for building external modules'
@echo ' tags/TAGS - Generate tags file for editors'
@echo ' cscope - Generate cscope index'
@echo ' kernelrelease - Output the release version string'
@echo ' kernelversion - Output the version stored in Makefile'
@echo ' headers_install - Install sanitised kernel headers to INSTALL_HDR_PATH'; \
echo ' (default: $(INSTALL_HDR_PATH))'; \
echo ''
@echo 'Static analysers'
@echo ' checkstack - Generate a list of stack hogs'
@echo ' namespacecheck - Name space analysis on compiled kernel'
@echo ' versioncheck - Sanity check on version.h usage'
@echo ' includecheck - Check for duplicate included header files'
@echo ' export_report - List the usages of all exported symbols'
@echo ' headers_check - Sanity check on exported headers'
@echo ' headerdep - Detect inclusion cycles in headers'
@$(MAKE) -f $(srctree)/scripts/Makefile.help checker-help
@echo ''
@echo 'Kernel packaging:'
@$(MAKE) $(build)=$(package-dir) help
@echo ''
@echo 'Documentation targets:'
@$(MAKE) -f $(srctree)/Documentation/DocBook/Makefile dochelp
@echo ''
@echo 'Architecture specific targets ($(SRCARCH)):'
@$(if $(archhelp),$(archhelp),\
echo ' No architecture specific help defined for $(SRCARCH)')
@echo ''
@$(if $(boards), \
$(foreach b, $(boards), \
printf " %-24s - Build for %s\\n" $(b) $(subst _defconfig,,$(b));) \
echo '')
@$(if $(board-dirs), \
$(foreach b, $(board-dirs), \
printf " %-16s - Show %s-specific targets\\n" help-$(b) $(b);) \
printf " %-16s - Show all of the above\\n" help-boards; \
echo '')
@echo ' make V=0|1 [targets] 0 => quiet build (default), 1 => verbose build'
@echo ' make V=2 [targets] 2 => give reason for rebuild of target'
@echo ' make O=dir [targets] Locate all output files in "dir", including .config'
@echo ' make C=1 [targets] Check all c source with $$CHECK (sparse by default)'
@echo ' make C=2 [targets] Force check of all c source with $$CHECK'
@echo ''
@echo 'Execute "make" or "make all" to build all targets marked with [*] '
@echo 'For further info see the ./README file'
help-board-dirs := $(addprefix help-,$(board-dirs))
help-boards: $(help-board-dirs)
boards-per-dir = $(notdir $(wildcard $(srctree)/arch/$(SRCARCH)/configs/$*/*_defconfig))
$(help-board-dirs): help-%:
@echo 'Architecture specific targets ($(SRCARCH) $*):'
@$(if $(boards-per-dir), \
$(foreach b, $(boards-per-dir), \
printf " %-24s - Build for %s\\n" $*/$(b) $(subst _defconfig,,$(b));) \
echo '')
# Documentation targets
# ---------------------------------------------------------------------------
%docs: scripts_basic FORCE
$(Q)$(MAKE) $(build)=Documentation/DocBook $@
else # KBUILD_EXTMOD
###
# External module support.
# When building external modules the kernel used as basis is considered
# read-only, and no consistency checks are made and the make
# system is not used on the basis kernel. If updates are required
# in the basis kernel ordinary make commands (without M=...) must
# be used.
#
# The following are the only valid targets when building external
# modules.
# make M=dir clean Delete all automatically generated files
# make M=dir modules Make all modules in specified dir
# make M=dir Same as 'make M=dir modules'
# make M=dir modules_install
# Install the modules built in the module directory
# Assumes install directory is already created
# We are always building modules
KBUILD_MODULES := 1
PHONY += crmodverdir
crmodverdir:
$(cmd_crmodverdir)
PHONY += $(objtree)/Module.symvers
$(objtree)/Module.symvers:
@test -e $(objtree)/Module.symvers || ( \
echo; \
echo " WARNING: Symbol version dump $(objtree)/Module.symvers"; \
echo " is missing; modules will have no dependencies and modversions."; \
echo )
module-dirs := $(addprefix _module_,$(KBUILD_EXTMOD))
PHONY += $(module-dirs) modules
$(module-dirs): crmodverdir $(objtree)/Module.symvers
$(Q)$(MAKE) $(build)=$(patsubst _module_%,%,$@)
modules: $(module-dirs)
@$(kecho) ' Building modules, stage 2.';
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
PHONY += modules_install
modules_install: _emodinst_ _emodinst_post
install-dir := $(if $(INSTALL_MOD_DIR),$(INSTALL_MOD_DIR),extra)
PHONY += _emodinst_
_emodinst_:
$(Q)mkdir -p $(MODLIB)/$(install-dir)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modinst
PHONY += _emodinst_post
_emodinst_post: _emodinst_
$(call cmd,depmod)
clean-dirs := $(addprefix _clean_,$(KBUILD_EXTMOD))
PHONY += $(clean-dirs) clean
$(clean-dirs):
$(Q)$(MAKE) $(clean)=$(patsubst _clean_%,%,$@)
clean: rm-dirs := $(MODVERDIR)
clean: rm-files := $(KBUILD_EXTMOD)/Module.symvers
help:
@echo ' Building external modules.'
@echo ' Syntax: make -C path/to/kernel/src M=$$PWD target'
@echo ''
@echo ' modules - default target, build the module(s)'
@echo ' modules_install - install the module'
@echo ' clean - remove generated files in module directory only'
@echo ''
# Dummies...
PHONY += prepare scripts
prepare: ;
scripts: ;
endif # KBUILD_EXTMOD
clean: $(clean-dirs)
$(call cmd,rmdirs)
$(call cmd,rmfiles)
@find $(or $(KBUILD_EXTMOD), .) $(RCS_FIND_IGNORE) \
\( -name '*.[oas]' -o -name '*.ko' -o -name '.*.cmd' \
-o -name '.*.d' -o -name '.*.tmp' -o -name '*.mod.c' \
-o -name '*.symtypes' -o -name 'modules.order' \
-o -name modules.builtin -o -name '.tmp_*.o.*' \
-o -name '*.gcno' \) -type f -print | xargs rm -f
# Generate tags for editors
# ---------------------------------------------------------------------------
quiet_cmd_tags = GEN $@
cmd_tags = $(CONFIG_SHELL) $(srctree)/scripts/tags.sh $@
tags TAGS cscope: FORCE
$(call cmd,tags)
# Scripts to check various things for consistency
# ---------------------------------------------------------------------------
includecheck:
find * $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkincludes.pl
versioncheck:
find * $(RCS_FIND_IGNORE) \
-name '*.[hcS]' -type f -print | sort \
| xargs $(PERL) -w $(srctree)/scripts/checkversion.pl
coccicheck:
$(Q)$(CONFIG_SHELL) $(srctree)/scripts/$@
namespacecheck:
$(PERL) $(srctree)/scripts/namespace.pl
export_report:
$(PERL) $(srctree)/scripts/export_report.pl
endif #ifeq ($(config-targets),1)
endif #ifeq ($(mixed-targets),1)
PHONY += checkstack kernelrelease kernelversion
# UML needs a little special treatment here. It wants to use the host
# toolchain, so needs $(SUBARCH) passed to checkstack.pl. Everyone
# else wants $(ARCH), including people doing cross-builds, which means
# that $(SUBARCH) doesn't work here.
ifeq ($(ARCH), um)
CHECKSTACK_ARCH := $(SUBARCH)
else
CHECKSTACK_ARCH := $(ARCH)
endif
checkstack:
$(OBJDUMP) -d vmlinux $$(find . -name '*.ko') | \
$(PERL) $(src)/scripts/checkstack.pl $(CHECKSTACK_ARCH)
kernelrelease:
@echo "$(KERNELVERSION)$$($(CONFIG_SHELL) $(srctree)/scripts/setlocalversion $(srctree))"
kernelversion:
@echo $(KERNELVERSION)
# Single targets
# ---------------------------------------------------------------------------
# Single targets are compatible with:
# - build with mixed source and output
# - build with separate output dir 'make O=...'
# - external modules
#
# target-dir => where to store outputfile
# build-dir => directory in kernel source tree to use
ifeq ($(KBUILD_EXTMOD),)
build-dir = $(patsubst %/,%,$(dir $@))
target-dir = $(dir $@)
else
zap-slash=$(filter-out .,$(patsubst %/,%,$(dir $@)))
build-dir = $(KBUILD_EXTMOD)$(if $(zap-slash),/$(zap-slash))
target-dir = $(if $(KBUILD_EXTMOD),$(dir $<),$(dir $@))
endif
%.s: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.i: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.lst: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.s: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.o: %.S prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
%.symtypes: %.c prepare scripts FORCE
$(Q)$(MAKE) $(build)=$(build-dir) $(target-dir)$(notdir $@)
# Modules
/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%/: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir)
%.ko: prepare scripts FORCE
$(cmd_crmodverdir)
$(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
$(build)=$(build-dir) $(@:.ko=.o)
$(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
# FIXME Should go into a make.lib or something
# ===========================================================================
quiet_cmd_rmdirs = $(if $(wildcard $(rm-dirs)),CLEAN $(wildcard $(rm-dirs)))
cmd_rmdirs = rm -rf $(rm-dirs)
quiet_cmd_rmfiles = $(if $(wildcard $(rm-files)),CLEAN $(wildcard $(rm-files)))
cmd_rmfiles = rm -f $(rm-files)
# Run depmod only if we have System.map and depmod is executable
quiet_cmd_depmod = DEPMOD $(KERNELRELEASE)
cmd_depmod = \
if [ -r System.map -a -x $(DEPMOD) ]; then \
$(DEPMOD) -ae -F System.map \
$(if $(strip $(INSTALL_MOD_PATH)), -b $(INSTALL_MOD_PATH) ) \
$(KERNELRELEASE); \
fi
# Create temporary dir for module support files
# clean it up only when building all modules
cmd_crmodverdir = $(Q)mkdir -p $(MODVERDIR) \
$(if $(KBUILD_MODULES),; rm -f $(MODVERDIR)/*)
a_flags = -Wp,-MD,$(depfile) $(KBUILD_AFLAGS) $(AFLAGS_KERNEL) \
$(KBUILD_AFLAGS_KERNEL) \
$(NOSTDINC_FLAGS) $(LINUXINCLUDE) $(KBUILD_CPPFLAGS) \
$(modkern_aflags) $(EXTRA_AFLAGS) $(AFLAGS_$(basetarget).o)
quiet_cmd_as_o_S = AS $@
cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $<
# read all saved command lines
targets := $(wildcard $(sort $(targets)))
cmd_files := $(wildcard .*.cmd $(foreach f,$(targets),$(dir $(f)).$(notdir $(f)).cmd))
ifneq ($(cmd_files),)
$(cmd_files): ; # Do not try to update included dependency files
include $(cmd_files)
endif
# Shorthand for $(Q)$(MAKE) -f scripts/Makefile.clean obj=dir
# Usage:
# $(Q)$(MAKE) $(clean)=dir
clean := -f $(if $(KBUILD_SRC),$(srctree)/)scripts/Makefile.clean obj
endif # skip-makefile
PHONY += FORCE
FORCE:
# Declare the contents of the .PHONY variable as phony. We keep that
# information in a variable so we can use it in if_changed and friends.
.PHONY: $(PHONY)
|
lnfamous/Kernel_Htc_Pico_Stock
|
Makefile
|
Makefile
|
gpl-2.0
| 52,351 |
import React from 'react';
import IconBase from './IconBase.js';
import './StopButtonIcon.css';
export const StopButtonIcon = () => (
<IconBase viewBox="0 0 20 20">
<path d="M3.401,13.367h0.959l1.56-1.56H4.181v-4.07h3.177c0.207,0,0.405-0.084,0.553-0.23l3.608-3.633V6.21l1.56-1.56V1.983c0-0.315-0.192-0.602-0.485-0.721c-0.29-0.122-0.624-0.055-0.85,0.171L7.032,6.178h-3.63c-0.433,0-0.78,0.349-0.78,0.78v5.629C2.621,13.018,2.968,13.367,3.401,13.367z" />
<path d="M11.519,15.674l-2.416-2.418L8,14.358l3.745,3.753c0.149,0.149,0.349,0.228,0.553,0.228c0.1,0,0.201-0.019,0.297-0.059c0.291-0.12,0.483-0.405,0.483-0.72V9.28l-1.56,1.56V15.674z" />
<path d="M19.259,0.785c-0.167-0.168-0.387-0.25-0.606-0.25s-0.438,0.082-0.606,0.25l-4.968,4.968l-1.56,1.56l-4.496,4.494l-1.56,1.56L0.83,18.001c-0.335,0.335-0.335,0.877,0,1.213c0.167,0.167,0.386,0.251,0.606,0.251c0.22,0,0.439-0.084,0.606-0.251l5.407-5.407l1.105-1.104l2.965-2.966l1.56-1.56l6.18-6.181C19.594,1.664,19.594,1.12,19.259,0.785z" />
</IconBase>
);
export default StopButtonIcon;
|
physiii/open-automation
|
src/views/icons/MuteButtonIcon.js
|
JavaScript
|
gpl-2.0
| 1,035 |
using System;
using System.Text;
namespace qGen
{
[Serializable]
public class Condition
{
protected qGen.SqlModes m_Mode = qGen.SqlModes.Ansi;
public Condition()
{
}
public qGen.SqlModes Mode
{
get
{
return m_Mode;
}
set
{
m_Mode = value;
}
}
public string ToString(qGen.SqlModes mode)
{
m_Mode = mode;
return this.ToString();
}
}
public class NestedCondition : Condition
{
public qGen.Where Where;
public NestedCondition(Where where)
{
this.Where = where;
}
public override string ToString()
{
this.Where.SqlMode = this.m_Mode;
return "(" + this.Where.ToString() + ")";
}
}
internal class SqlCondition : Condition
{
protected string Text = "";
public SqlCondition()
: base()
{
}
public SqlCondition(string text)
: this()
{
this.Text = text;
}
public override string ToString()
{
return this.Text;
}
}
public class ComparisonCondition : Condition
{
protected string LeftValue = "";
protected object m_RightValue = "", m_RightValue2 = "";
public qGen.ComparisonOperators Operator = qGen.ComparisonOperators.Equals;
public ComparisonCondition()
: base()
{
}
public ComparisonCondition(string LeftValue, object RightValue)
: this(LeftValue, qGen.ComparisonOperators.Equals, RightValue)
{
}
public ComparisonCondition(string leftValue, qGen.ComparisonOperators compOperator, object rightValue)
: this()
{
this.LeftValue = leftValue;
this.Operator = compOperator;
this.m_RightValue = rightValue;
}
public ComparisonCondition(string leftValue, object minValue, object maxValue)
: this()
{
this.LeftValue = leftValue;
this.Operator = ComparisonOperators.Between;
this.m_RightValue = minValue;
this.m_RightValue2 = maxValue;
}
public ComparisonCondition(qGen.SqlModes Mode, string LeftValue, qGen.ComparisonOperators compOperator, object RightValue)
: this(LeftValue, compOperator, RightValue)
{
m_Mode = Mode;
}
public object RightValue
{
get
{
return m_RightValue;
}
set
{
this.m_RightValue = value;
}
}
private string FormatValue(object value)
{
if (value == null || value is DBNull) {
return "NULL";
} else if (value is double || value is decimal) {
return Lfx.Types.Formatting.FormatNumberSql(System.Convert.ToDecimal(value), 8);
} else if (value is NullableDateTime && value != null) {
return "'" + Lfx.Types.Formatting.FormatDateTimeSql(((NullableDateTime)(value)).Value) + "'";
} else if (value is DateTime) {
return "'" + Lfx.Types.Formatting.FormatDateTimeSql((DateTime)value) + "'";
} else if (value is int || value is long) {
return value.ToString();
} else if (value is SqlExpression) {
return value.ToString();
} else if (value is qGen.Select) {
// Sub select
return "(" + value.ToString() + ")";
} else if (value is SqlFunctions) {
switch((SqlFunctions)value) {
case SqlFunctions.Now:
return "NOW()";
default:
return value.ToString();
}
} else if (value is int[]) {
string[] RightValStr = Array.ConvertAll<int, string>((int[])value, new Converter<int, string>(Convert.ToString));
return string.Join(",", RightValStr);
} else if (value is string[]) {
string[] EscapedStrings = ((string[])(value));
for (int i = 0; i < EscapedStrings.Length; i++) {
EscapedStrings[i] = Lfx.Data.Connection.EscapeString(EscapedStrings[i], m_Mode);
}
return "'" + string.Join("','", EscapedStrings) + "'";
} else if (value is System.Collections.IList) {
// Si es una lista, formateo cada uno de los elementos
StringBuilder Res = new StringBuilder();
System.Collections.IList Lista = (System.Collections.IList)value;
foreach (object a in Lista) {
if(Res.Length == 0)
Res.Append(FormatValue(a));
else
Res.Append("," + FormatValue(a));
}
return Res.ToString();
} else {
return "'" + Lfx.Data.Connection.EscapeString(value.ToString(), m_Mode) + "'";
}
}
public object RightValue2
{
get
{
return m_RightValue2;
}
set
{
this.m_RightValue2 = value;
}
}
public override string ToString()
{
string Result = null;
switch (Operator) {
case qGen.ComparisonOperators.NullSafeEquals:
Result = LeftValue + "<=>" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.Equals:
if (m_RightValue == null)
Result = LeftValue + " IS " + FormatValue(RightValue);
else
Result = LeftValue + "=" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.GreaterOrEqual:
Result = LeftValue + ">=" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.GreaterThan:
Result = LeftValue + ">" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.InsensitiveLike:
switch (m_Mode) {
case qGen.SqlModes.PostgreSql:
Result = LeftValue + " ILIKE " + FormatValue(RightValue);
break;
default:
Result = LeftValue + " LIKE " + FormatValue(RightValue);
break;
}
break;
case qGen.ComparisonOperators.InsensitiveNotLike:
switch (m_Mode) {
case qGen.SqlModes.PostgreSql:
Result = LeftValue + " NOT ILIKE " + FormatValue(RightValue);
break;
default:
Result = LeftValue + " NOT LIKE " + FormatValue(RightValue);
break;
}
break;
case qGen.ComparisonOperators.LessOrEqual:
Result = LeftValue + "<=" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.LessThan:
Result = LeftValue + "<" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.NotEqual:
if (m_RightValue == null)
Result = LeftValue + " IS NOT " + FormatValue(RightValue);
else
Result = LeftValue + "<>" + FormatValue(RightValue);
break;
case qGen.ComparisonOperators.SensitiveLike:
switch (m_Mode) {
case qGen.SqlModes.MySql:
Result = "BINARY " + LeftValue + " LIKE BINARY " + FormatValue(RightValue);
break;
default:
Result = LeftValue + " LIKE " + FormatValue(RightValue);
break;
}
break;
case qGen.ComparisonOperators.SensitiveNotLike:
switch (m_Mode) {
case qGen.SqlModes.MySql:
Result = "BINARY " + LeftValue + " NOT LIKE BINARY " + FormatValue(RightValue);
break;
default:
Result = LeftValue + " NOT LIKE " + FormatValue(RightValue);
break;
}
break;
case qGen.ComparisonOperators.SoundsLike:
switch (m_Mode) {
case qGen.SqlModes.MySql:
// FIXME: Parece que el SOUNDS LIKE no funciona bien en MySql
// Result = LeftValue.Replace("%", "") & " SOUNDS LIKE " & RightValue.Replace("%", "")
Result = LeftValue + " LIKE " + FormatValue(RightValue);
break;
case qGen.SqlModes.PostgreSql:
Result = LeftValue + " ILIKE " + FormatValue(RightValue);
break;
default:
Result = LeftValue + " LIKE " + FormatValue(RightValue);
break;
}
break;
case qGen.ComparisonOperators.In:
Result = LeftValue + " IN (" + FormatValue(RightValue) + ")";
break;
case qGen.ComparisonOperators.NotIn:
Result = LeftValue + " NOT IN (" + FormatValue(RightValue) + ")";
break;
case ComparisonOperators.Between:
Result = LeftValue + " BETWEEN " + FormatValue(RightValue) + " AND " + FormatValue(RightValue2);
break;
}
return Result;
}
}
}
|
EquisTango/lazaro
|
Lfx/Data/qGen/Condition.cs
|
C#
|
gpl-2.0
| 14,332 |
/*
* Copyright (c) 2012-2013 The Linux Foundation. All rights reserved.
*
* Previously licensed under the ISC license by Qualcomm Atheros, 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.
*/
/*
* This file was originally distributed by Qualcomm Atheros, Inc.
* under proprietary terms before Copyright ownership was assigned
* to the Linux Foundation.
*/
/*===========================================================================
*
* @file: wlan_defs.h
*
* @brief: This file defines the common typedefs
*
* @author: Gagan Jain
*
* Copyright (C) 2010, Qualcomm, Inc.
* All rights reserved.
*
*=========================================================================*/
#ifndef __WLAN_DEFS_H__
#define __WLAN_DEFS_H__
/*
*/
#include "wlan_qct_pal_type.h"
/*
*/
/*
*/
typedef wpt_uint32 uint32; /* */
typedef wpt_uint16 uint16; /* */
typedef wpt_uint8 uint8; /* */
typedef wpt_int32 int32; /* */
typedef wpt_int16 int16; /* */
typedef wpt_int8 int8; /* */
typedef wpt_int64 int64; /* */
typedef wpt_uint64 uint64; /* */
typedef wpt_byte byte; /* */
typedef wpt_boolean boolean; /* */
#endif //
|
curbthepain/revkernel_us990
|
drivers/staging/prima/CORE/WDI/CP/inc/qwlanfw_defs.h
|
C
|
gpl-2.0
| 2,686 |
\chapter {HAPI}
\section{Overview}
HAPI has been designed to be a fully modular haptic rendering engine,
allowing users to easily add, substitute or modify any component of the
haptics rendering process.
HAPI consists of the following parts:
\begin{itemize}
\item Device handling
\item Geometry based haptics
\begin{itemize}
\item Collision handling
\item Haptics rendering algorithm
\item Surface interaction algorithm
\end{itemize}
\item Free space haptics
\begin{itemize}
\item Force effects
\end{itemize}
\item Thread handling
\end{itemize}
\subsection{Device handling}
The device handling layer provides a device independent interface for various haptics devices. It handles device initialization, cleanup, access to device state such as position and orientation and output such as force and torque. HAPI can easily be extended for new devices by implementing abstract functions for performing those tasks. See section \ref{ssAddingHapticsSupport}.
\subsection{Geometry based haptics}
\subsubsection{Haptics rendering algorithm}
A haptics rendering algorithm is needed in order to calculate forces and
torques from the interaction of the haptics device with objects in the scene. An interface is provided to give a user the opportunity to implement their own
algorithm. There are four algorithms already implemented. They are:
\begin{itemize}
\item God object algorithm - point proxy based
\item Ruspini algorithm - sphere proxy based
\item Chai3D - use Chai3D rendering library
\item OpenHaptics - use OpenHaptics rendering library
\end{itemize}
Some of them have restrictions on what features of HAPI can be used, e.g. some does not support user defined surfaces. All these algorithms provide 3-DOF feedback only(i.e. no torque). 6-DOF algorithms are not currently available, however they can be generated by user force effects and rendering algoritms. Check out the details of each algorithm in chapter \ref{secHapticsRenderingAlgorithms} to find out what is supported.
\subsubsection{Collision handling}
HAPI contains classes for collision handling used in the
haptics rendering algorithms. A user have to create instances of these
classes and feed them to the haptics device that they are to be
rendered at. It also contains classes for building binary bound trees
such as axis-aligned and oriented bounding box trees from triangles,
that can be used in order to do faster collision detection.
\subsubsection{Surface handling}
When touching the surface of a geometry, the haptics rendering
algorithm has to know what forces to generate depending on the
penetration of the surface. This is handled by the surface classes. A
user can define an arbitrary function for the force and proxy
movement (does not work for all haptics rendering algorithms though as
mentioned earlier).
\subsection{Free space haptic effects}
\subsubsection{Force effects}
Often a user wants to generate forces that are not based on
touching geometries, but instead is only depending on the state of the haptics device, such as the position and orientation. Some exampels of such effects are force fields, gravity, springs, viscosity, etc. In these cases a force effect can be used.
\subsection{Thread handling}
HAPI manages high-priority threads running at 1000 Hz for the haptics
rendering and provides mechanisms to communicate between different
threads. The thread handling functions can also be used to create new
user defined threads.
|
cihrke/hapi-lwr
|
doc/overview.tex
|
TeX
|
gpl-2.0
| 3,443 |
<?php
class A {
public $i = 0;
function __construct($i) {
$this->i = $i;
}
function m($i) {
return $i+1;
}
}
|
liudng/examples
|
globals.php
|
PHP
|
gpl-2.0
| 120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.