answer stringlengths 15 1.25M |
|---|
!
! Copyright (C) 2002-2008 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:
!
!
!
SUBROUTINE cprmain( tau_out, fion_out, etot_out )
!
!
USE kinds, ONLY : DP
USE constants, ONLY : bohr_radius_angs, amu_au, au_gpa
USE control_flags, ONLY : iprint, isave, thdyn, tpre, iverbosity, &
tfor, remove_rigid_rot, taurdr, llondon,&
tprnfor, tsdc, lconstrain, lwf, &
ndr, ndw, nomore, tsde, textfor, &
tortho, tnosee, tnosep, trane, tranp, &
tsdp, tcp, tcap, ampre, amprp, tnoseh, &
tolp, ortho_eps, ortho_max, &
tfirst, tlast !moved here to make
!autopilot work
USE core, ONLY : rhoc
USE uspp_param, ONLY : nhm, nh
USE pseudo_base, ONLY : vkb_d
USE uspp, ONLY : nkb, vkb, becsum, deeq, okvan, nlcc_any
USE energies, ONLY : eht, epseu, exc, etot, eself, enl, &
ekin, atot, entropy, egrand, enthal, &
ekincm, print_energies
USE electrons_base, ONLY : nbspx, nbsp, ispin, f, nspin, nbsp_bgrp
USE electrons_base, ONLY : nel, iupdwn, nupdwn, nudx, nelt
USE electrons_module, ONLY : distribute_c, collect_c
USE efield_module, ONLY : efield, epol, tefield, allocate_efield, &
efield_update, ipolp, qmat, gqq, evalue,&
berry_energy, pberryel, pberryion, &
efield2, epol2, tefield2, &
allocate_efield2, efield_update2, &
ipolp2, qmat2, gqq2, evalue2, &
berry_energy2, pberryel2, pberryion2
USE ensemble_dft, ONLY : tens, z0t, gibbsfe
USE cg_module, ONLY : tcg, cg_update, c0old
USE smallbox_gvec, ONLY : ngb
USE gvecw, ONLY : ngw
USE gvect, ONLY : gstart, mill, eigts1, eigts2, eigts3
USE ions_base, ONLY : na, nat, amass, nax, nsp, rcmax
USE ions_base, ONLY : ions_cofmass, ions_kinene, &
ions_temp, ions_thermal_stress, &
if_pos, extfor
USE ions_base, ONLY : ions_vrescal, fricp, greasp, &
iforce, ndfrz, ions_shiftvar, ityp, &
atm, cdm, cdms, ions_cofmsub
USE cell_base, ONLY : at, bg, ainv, frich, &
greash, tpiba2, omega, alat, ibrav, &
celldm, h, hold, hnew, velh, &
wmass, press, iforceh, cell_force
USE local_pseudo, ONLY : <API key>
USE io_global, ONLY : stdout, ionode, ionode_id
USE dener, ONLY : detot
USE constants, ONLY : pi, k_boltzmann_au, au_ps
USE io_files, ONLY : psfile, pseudo_dir
USE wave_base, ONLY : wave_steepest, wave_verlet
USE wave_base, ONLY : wave_speed2, frice, grease
USE control_flags, ONLY : conv_elec, tconvthrs
USE check_stop, ONLY : check_stop_now
USE efcalc, ONLY : clear_nbeg, ef_force
USE ions_base, ONLY : zv, ions_vel
USE cp_electronic_mass, ONLY : emass, emass_cutoff, emass_precond
USE ions_positions, ONLY : tau0, taum, taup, taus, tausm, tausp, &
vels, velsm, velsp, ions_hmove, &
ions_move, fion, fionm
USE ions_nose, ONLY : gkbt, kbt, qnp, ndega, nhpcl, nhpdim, &
nhpbeg, nhpend, &
vnhp, xnhp0, xnhpm, xnhpp, &
atm2nhp, ions_nosevel, ions_noseupd, &
tempw, ions_nose_nrg, gkbt2nhp, &
ekin2nhp, anum2nhp
USE electrons_nose, ONLY : qne, ekincw, xnhe0, xnhep, xnhem, &
vnhe, electrons_nose_nrg, &
<API key>, &
electrons_nosevel, electrons_noseupd
USE pres_ai_mod, ONLY : P_ext, P_in, P_fin, pvar, volclu, &
surfclu, Surf_t, abivol, abisur
USE wavefunctions, ONLY : c0_bgrp, cm_bgrp, cm_d, phi, c0_d
USE wannier_module, ONLY : allocate_wannier
USE cp_interfaces, ONLY : printout_new, move_electrons, newinit
USE cell_nose, ONLY : xnhh0, xnhhm, xnhhp, vnhh, temph, &
qnh, cell_nosevel, cell_noseupd, &
cell_nose_nrg, cell_nose_shiftvar
USE cell_base, ONLY : cell_kinene, cell_gamma, &
cell_move, cell_hmove
USE gvecw, ONLY : ecutwfc
USE gvect, ONLY : ecutrho
USE time_step, ONLY : delt, tps, dt2, twodelt
USE cp_interfaces, ONLY : cp_print_rho, nlfh, prefor, dotcsc
USE cp_main_variables, ONLY : acc, lambda, lambdam, lambdap, &
ema0bg, sfac, eigr, iprint_stdout, &
irb, taub, eigrb, rhog, rhos, &
rhor, bephi, becp_bgrp, nfi, idesc, &
drhor, drhog, bec_bgrp, dbec, bec_d, iabox, nabox
#if defined (__CUDA)
USE cp_main_variables, ONLY : eigr_d
#endif
USE autopilot, ONLY : event_step, event_index, &
max_event_step, restart_p
USE cell_base, ONLY : s_to_r, r_to_s
USE wannier_subroutines, ONLY : wannier_startup, wf_closing_options, &
ef_enthalpy
USE cp_interfaces, ONLY : writefile, eigs, strucf, phfacs
USE cp_interfaces, ONLY : ortho, elec_fakekine, calbec, caldbec_bgrp
USE constraints_module, ONLY : check_constraint, remove_constr_force
USE cp_autopilot, ONLY : pilot
USE ions_nose, ONLY : ions_nose_allocate, ions_nose_shiftvar
USE orthogonalize_base, ONLY : updatc
USE control_flags, ONLY : force_pairing, tprint
USE mp, ONLY : mp_bcast, mp_sum
USE mp_global, ONLY : root_bgrp, intra_bgrp_comm, &
me_bgrp, inter_bgrp_comm, nbgrp, me_image
USE ldaU_cp, ONLY : lda_plus_u, vupsi
USE fft_base, ONLY : dfftp, dffts
USE london_module, ONLY : energy_london, force_london, stres_london
USE input_parameters, ONLY : tcpbo
USE xc_lib, ONLY : xclib_dft_is, start_exx, exx_is_active
USE device_memcpy_m, ONLY : dev_memcpy
!
IMPLICIT NONE
!
include 'laxlib.fh'
!
! ... input/output variables
!
REAL(DP), INTENT(OUT) :: tau_out(3,nat)
REAL(DP), INTENT(OUT) :: fion_out(3,nat)
REAL(DP), INTENT(OUT) :: etot_out
!
! ... control variables
!
LOGICAL :: tstop, tconv
LOGICAL :: tfile, tstdout
! logical variable used to control printout
!
! ... forces on ions
!
REAL(DP) :: maxfion, fion_tot(3)
!
! ... work variables
!
REAL(DP) :: tempp, savee, saveh, savep, epot, epre, &
enow, econs, econt, fccc, ccc, bigr, dt2bye
REAL(DP) :: ekinc0, ekinp, ekinpr, ekinc
REAL(DP) :: temps(nsp)
REAL(DP) :: ekinh, temphc
REAL(DP) :: delta_etot
REAL(DP) :: ftmp, enb, enbi
INTEGER :: is, nacc, ia, j, iter, i, isa, ipos, iat, CYCLE_NOSE
INTEGER :: k, ii, l, m, iss
REAL(DP) :: hgamma(3,3), temphh(3,3)
REAL(DP) :: fcell(3,3)
REAL(DP) :: deltaP, ekincf
REAL(DP) :: stress_gpa(3,3), thstress(3,3), stress(3,3)
!
REAL(DP), ALLOCATABLE :: usrt_tau0(:,:), usrt_taup(:,:), usrt_fion(:,:)
! temporary array used to store unsorted positions and forces for
! constrained dynamics
CHARACTER(LEN=3) :: labelw( nat )
! for force_pairing
INTEGER :: nspin_sub , i1, i2
! pmass contains masses in atomic Hartree units
REAL(DP), ALLOCATABLE :: pmass(:)
REAL(DP), ALLOCATABLE :: forceh(:,:)
!
REAL(DP) :: exx_start_thr
CALL start_clock( 'cpr_total' )
!
etot_out = 0.D0
enow = 1.D9
stress = 0.0D0
thstress = 0.0D0
! moved to control_flags.f90 (Modules)
! tfirst = .TRUE.
! tlast = .FALSE.
nacc = 5
!
if ( xclib_dft_is('meta') ) then
!HK/MCA : for SCAN0 calculation the initial SCAN has to converge better than the PBE -> PBE0 case
exx_start_thr = 1.E+1_DP
else
exx_start_thr = 1.E+2_DP
end if ! dft_is_meta
!
ALLOCATE ( pmass (nsp) )
pmass(1:nsp) = amass(1:nsp) * amu_au
nspin_sub = nspin
IF( force_pairing ) nspin_sub = 1
!
! ... Check for restart_p from Autopilot Feature Suite
!
IF ( restart_p ) THEN
!
! ... do not add past nfi
!
nomore = nomore
!
END IF
!
IF ( lda_plus_u ) ALLOCATE( forceh( 3, nat ) )
!
!
!======================================================================
!
! basic loop for molecular dynamics starts here
!
!======================================================================
!
main_loop: DO
!
CALL start_clock( 'main_loop' )
CALL start_clock( 'cpr_md' )
!
dt2bye = dt2 / emass
nfi = nfi + 1
tlast = ( nfi == nomore ) .OR. tlast
tprint = ( MOD( nfi, iprint ) == 0 ) .OR. tlast !this can be set to .true. also by cp_autopilot in 'call pilot(nfi)', to compute velocities of the wfc in the last step of CG
tfile = ( MOD( nfi, iprint ) == 0 )
tstdout = ( MOD( nfi, iprint_stdout ) == 0 ) .OR. tlast
!
IF ( abivol ) THEN
IF ( pvar ) THEN
IF ( nfi .EQ. 1 ) THEN
deltaP = (P_fin - P_in) / DBLE(nomore)
P_ext = P_in
ELSE
P_ext = P_ext + deltaP
END IF
END IF
END IF
!
IF ( ionode .AND. tstdout ) &
WRITE( stdout, '(/," * Physical Quantities at step:",I6)' ) nfi
!
IF ( tnosee ) THEN
fccc = 1.D0 / ( 1.D0 + 0.5D0 * delt * vnhe )
ELSE IF ( tsde ) THEN
fccc = 1.D0
ELSE
fccc = 1.D0 / ( 1.D0 + frice )
END IF
!
! ... calculation of velocity of nose-hoover variables
!
IF ( tnosep ) THEN
!
CALL ions_nosevel( vnhp, xnhp0, xnhpm, delt, nhpcl, nhpdim )
!
END IF
!
IF ( tnosee ) THEN
!
CALL electrons_nosevel( vnhe, xnhe0, xnhem, delt )
!
END IF
!
IF ( tnoseh ) THEN
!
CALL cell_nosevel( vnhh, xnhh0, xnhhm, delt )
!
velh(:,:) = 2.D0 * ( h(:,:) - hold(:,:) ) / delt - velh(:,:)
!
END IF
!
IF ( (okvan .or. nlcc_any ) .AND. (tfor .OR. thdyn .OR. tfirst) ) THEN
!
CALL initbox( tau0, alat, at, ainv, taub, irb, iabox, nabox )
!
CALL phbox( taub, iverbosity, eigrb )
!
END IF
!
IF ( tfor .OR. thdyn ) THEN
!
CALL phfacs( eigts1,eigts2,eigts3, eigr, mill, taus, dfftp%nr1,dfftp%nr2,dfftp%nr3, nat )
!
! ... strucf calculates the structure factor sfac
!
CALL strucf( sfac, eigts1, eigts2, eigts3, mill, dffts%ngm )
!
END IF
!
IF ( thdyn ) THEN
!
CALL formf( tfirst, eself )
!
END IF
!
IF( force_pairing ) THEN
c0_bgrp(:,iupdwn(2):nbsp) = c0_bgrp(:,1:nupdwn(2))
cm_bgrp(:,iupdwn(2):nbsp) = cm_bgrp(:,1:nupdwn(2))
!phi(:,iupdwn(2):nbsp) = phi(:,1:nupdwn(2))
CALL dev_memcpy(phi(:,iupdwn(2):), phi, [1, ubound(phi)], 1, [1, nbsp])
lambda(:,:, 2) = lambda(:,:, 1)
ENDIF
!
#if defined(__CUDA)
CALL dev_memcpy( c0_d, c0_bgrp )
#endif
!
! Autopilot (Dynamic Rules) Implimentation
!
call pilot(nfi)
!
IF ( ( tfor .OR. tfirst ) .AND. tefield ) CALL efield_update( eigr )
IF ( ( tfor .OR. tfirst ) .AND. tefield2 ) CALL efield_update2( eigr )
!
! ... pass ions information to plugins
!
CALL plugin_init_ions( tau0 )
!
IF ( lda_plus_u ) then
! forceh ! Forces on ions due to Hubbard U
forceh=0.0d0
! vupsi ! potentials on electrons due to Hubbard U
vupsi=(0.0d0,0.0d0)
CALL new_ns(c0_bgrp,eigr,vkb,vupsi,forceh)
if ( mod(nfi,iprint).eq.0 ) call write_ns
endif
!
!=======================================================================
!
! electronic degrees of freedom are updated here
!
!=======================================================================
!
! ... fake electronic kinetic energy
!
IF ( .NOT. tcg ) THEN
!
ekincf = 0.0d0
CALL elec_fakekine( ekincf, ema0bg, emass, cm_bgrp, c0_bgrp, ngw, nbsp_bgrp, 1, delt )
!
END IF
!
CALL move_electrons( nfi, tprint, tfirst, tlast, bg(:,1), bg(:,2), bg(:,3), &
fion, enthal, enb, enbi, fccc, ccc, dt2bye, stress, .false. )
!
IF (lda_plus_u) fion = fion + forceh
!
! DFT+D (Grimme) dispersion energy, forces (factor 0.5 converts to Ha/a.u.)
!
IF ( llondon ) THEN
ALLOCATE( usrt_tau0( 3, nat ))
usrt_tau0(:,:) = tau0(:,:)/alat
delta_etot = 0.5_dp*energy_london (alat, nat,ityp,at,bg, usrt_tau0)
etot = etot + delta_etot
enthal=enthal+delta_etot
IF ( tfor ) THEN
ALLOCATE( usrt_fion( 3, nat ) )
usrt_fion = 0.5_dp*force_london ( alat, nat,ityp, at,bg, usrt_tau0 )
fion(:,:) = fion(:,:) + usrt_fion(:,:)
DEALLOCATE (usrt_fion)
END IF
IF ( tpre ) stress = stress + 0.5_dp * stres_london ( alat , nat , &
ityp , at , bg , usrt_tau0 , omega )
DEALLOCATE ( usrt_tau0 )
END IF
!
IF ( tpre ) THEN
!
CALL nlfh( stress, bec_bgrp, dbec, lambda, idesc )
!
CALL ions_thermal_stress( stress, thstress, pmass, omega, h, vels, nat, ityp )
!
IF (tstdout) THEN
WRITE(stdout,'(5X,"Pressure of Nuclei (GPa)",F20.5,I7)') &
(thstress(1,1)+thstress(2,2)+thstress(3,3))/3.0_DP * au_gpa, nfi
WRITE(stdout,'(5X,"Pressure Total (GPa)",F20.5,I7)') &
(stress(1,1)+stress(2,2)+stress(3,3))/3.0_DP * au_gpa , nfi
END IF
!
END IF
!
!
!=======================================================================
!
! verlet algorithm
!
! loop which updates cell parameters and ionic degrees of freedom
! hnew=h(t+dt) is obtained from hold=h(t-dt) and h=h(t)
! tausp=pos(t+dt) from tausm=pos(t-dt) taus=pos(t) h=h(t)
!
! guessed displacement of ions
!=======================================================================
!
hgamma(:,:) = 0.D0
!
IF ( thdyn ) THEN
!
CALL cell_force( fcell, ainv, stress, omega, press, wmass )
!
CALL cell_move( hnew, h, hold, delt, iforceh, &
fcell, frich, tnoseh, vnhh, velh, tsdc )
!
velh(:,:) = ( hnew(:,:) - hold(:,:) ) / twodelt
!
CALL cell_gamma( hgamma, ainv, h, velh )
!
END IF
!
! BS : Initialization of additional cycles for the Nose thermostat ...
!
IF (tnosep) CYCLE_NOSE=0
!
444 IF ( tfor ) THEN
!
IF ( lwf ) CALL ef_force( fion, ityp, nat, zv )
!
IF( textfor ) THEN
!
FORALL( ia = 1:nat ) fion(:,ia) = fion(:,ia) + extfor(:,ia)
!
fion_tot(:) = SUM( fion(:,:), DIM = 2 ) / DBLE( nat )
!
FORALL( ia = 1:nat ) fion(:,ia) = fion(:,ia) - fion_tot(:)
!
END IF
!
IF ( remove_rigid_rot ) &
CALL remove_tot_torque( nat, tau0, pmass(ityp(:)), fion )
!
IF ( lconstrain ) THEN
!
IF ( ionode ) THEN
!
ALLOCATE( usrt_tau0( 3, nat ) )
ALLOCATE( usrt_taup( 3, nat ) )
ALLOCATE( usrt_fion( 3, nat ) )
!
usrt_tau0(:,:) = tau0(:,:)
usrt_fion(:,:) = fion(:,:)
!
! ... we first remove the component of the force along the
! ... constrain gradient (this constitutes the initial guess
! ... for the lagrange multiplier)
!
CALL remove_constr_force( nat, usrt_tau0, if_pos, ityp, 1.D0, usrt_fion )
!
fion(:,:) = usrt_fion(:,:)
!
END IF
!
CALL mp_bcast( fion, ionode_id, intra_bgrp_comm )
!
END IF
!
!
! ... call void routine for user define/ plugin patches on external forces
!
CALL plugin_ext_forces()
!
!
CALL ions_move( tausp, taus, tausm, iforce, pmass, fion, ainv, &
delt, ityp, nat, fricp, hgamma, vels, tsdp, tnosep, &
fionm, vnhp, velsp, velsm, nhpcl, nhpdim, atm2nhp )
!
IF ( lconstrain ) THEN
!
! ... constraints are imposed here
!
IF ( ionode ) THEN
!
CALL s_to_r( tausp, taup, nat, hnew )
!
usrt_taup(:,:) = taup(:,:)
!
CALL check_constraint( nat, usrt_taup, usrt_tau0, usrt_fion, &
if_pos, ityp, 1.D0, delt, amu_au )
!
taup(:,:) = usrt_taup(:,:)
fion(:,:) = usrt_fion(:,:)
!
DEALLOCATE( usrt_tau0, usrt_taup, usrt_fion )
!
END IF
!
CALL mp_bcast( taup, ionode_id, intra_bgrp_comm )
CALL mp_bcast( fion, ionode_id, intra_bgrp_comm )
!
CALL r_to_s( taup, tausp, nat, ainv )
!
END IF
!
CALL ions_cofmass( tausp, pmass, nat, ityp, cdm )
!
IF ( ndfrz == 0 ) &
CALL ions_cofmsub( tausp, iforce, nat, cdm, cdms )
!
CALL s_to_r( tausp, taup, nat, hnew )
!
END IF
!
!
! initialization with guessed positions of ions
!
!
! ... if thdyn=true g vectors and pseudopotentials are recalculated for
! ... the new cell parameters
!
!
IF ( tfor .OR. thdyn ) THEN
!
IF ( .NOT.tnosep .OR. CYCLE_NOSE.EQ.0 ) THEN
!
IF ( thdyn ) THEN
!
hold = h
h = hnew
!
IF( nbgrp > 1 ) THEN
CALL mp_bcast( h, 0, inter_bgrp_comm )
END IF
!
CALL newinit( h, iverbosity )
!
CALL newnlinit()
!
ELSE
!
hold = h
!
END IF
!
END IF
!
! ... phfac calculates eigr
!
CALL phfacs( eigts1,eigts2,eigts3, eigr, mill, tausp, dfftp%nr1,dfftp%nr2,dfftp%nr3, nat )
! ... prefor calculates vkb
!
CALL prefor( eigr, vkb )
#if defined(__CUDA)
CALL dev_memcpy( vkb_d, vkb )
#endif
!
END IF
!
!
! imposing the orthogonality
!
!
! In case of tnosep = .true., the orthonormality is done only with the most updated
! atomic coordinates coming out of the CYCLE_NOSE loop
!
IF ( .NOT.tnosep .OR. CYCLE_NOSE.EQ.2 ) THEN
!
IF ( .NOT. tcg ) THEN
!
IF ( tortho ) THEN
!
#if defined (__CUDA)
CALL ortho( vkb_d, cm_d, phi, lambda, idesc, bigr, iter, ccc, bephi, becp_bgrp )
#else
CALL ortho( vkb, cm_bgrp, phi, lambda, idesc, bigr, iter, ccc, bephi, becp_bgrp )
#endif
!
ELSE
!
CALL gram_bgrp( vkb, bec_bgrp, nkb, cm_bgrp, ngw )
!
IF ( iverbosity > 2 ) CALL dotcsc( vkb, cm_bgrp, ngw, nbsp_bgrp )
!
END IF
!
! correction to displacement of ions
!
IF ( iverbosity > 1 ) CALL laxlib_print_matrix( lambda, idesc, nbsp, 9, nudx, 1.D0, ionode, stdout )
!
IF ( tortho ) THEN
#if defined (__CUDA)
CALL updatc( ccc, lambda, phi, bephi, becp_bgrp, bec_d, cm_d, idesc )
CALL dev_memcpy( cm_bgrp, cm_d )
#else
CALL updatc( ccc, lambda, phi, bephi, becp_bgrp, bec_bgrp, cm_bgrp, idesc )
#endif
END IF
!
IF( force_pairing ) THEN
c0_bgrp(:,iupdwn(2):nbsp) = c0_bgrp(:,1:nupdwn(2))
cm_bgrp(:,iupdwn(2):nbsp) = cm_bgrp(:,1:nupdwn(2))
!phi(:,iupdwn(2):nbsp) = phi(:,1:nupdwn(2))
CALL dev_memcpy(phi(:,iupdwn(2):), phi, [1, ubound(phi)], 1, [1, nbsp])
CALL dev_memcpy(cm_d(:,iupdwn(2):), cm_d, [1, ubound(cm_d)], 1, [1, nbsp])
lambda(:,:, 2) = lambda(:,:, 1)
ENDIF
!
! the following compute only on NC pseudo components
#if defined (__CUDA)
CALL dev_memcpy( eigr_d, eigr )
!CALL dev_memcpy( cm_d, cm_bgrp )
CALL calbec( nbsp_bgrp, vkb_d, cm_d, bec_d, 1 )
!CALL dev_memcpy( vkb, vkb_d )
!CALL dev_memcpy( bec_bgrp, bec_d )
#else
CALL calbec( nbsp_bgrp, vkb, cm_bgrp, bec_bgrp, 1 )
#endif
!
IF ( tpre ) THEN
#if defined (__CUDA)
CALL caldbec_bgrp( eigr_d, cm_d, dbec, idesc )
#else
CALL caldbec_bgrp( eigr, cm_bgrp, dbec, idesc )
#endif
END IF
!
#if defined (__CUDA)
CALL dev_memcpy( vkb, vkb_d )
CALL dev_memcpy( bec_bgrp, bec_d )
#endif
!
IF ( iverbosity > 1 ) CALL dotcsc( vkb, cm_bgrp, ngw, nbsp_bgrp )
!
END IF
!
END IF !(.NOT.tnosep.OR.CYCLE_NOSE.EQ.2)
!
!
! temperature monitored and controlled
!
!
ekinp = 0.D0
ekinpr = 0.D0
tempp = 0.D0
temps = 0.D0
ekinc0 = 0.0d0
ekinc = 0.0d0
!
!
! ... ionic kinetic energy and temperature
!
IF ( tfor ) THEN
!
CALL ions_vel( vels, tausp, tausm, delt )
!
CALL ions_kinene( ekinp, vels, nat, ityp, hold, pmass )
!
CALL ions_temp( tempp, temps, ekinpr, vels, nsp, na, nat, ityp, &
hold, pmass, ndega, nhpdim, atm2nhp, ekin2nhp )
!
END IF
!
! ... fake electronic kinetic energy
!
IF ( .NOT. tcg ) THEN
!
CALL elec_fakekine( ekinc0, ema0bg, emass, c0_bgrp, cm_bgrp, ngw, nbsp_bgrp, 1, delt )
!
ekinc0 = (ekinc0 + ekincf)*0.5d0
!
ekinc = ekinc0
!
END IF
!
! ... fake cell-parameters kinetic energy
!
ekinh = 0.D0
!
IF ( thdyn ) THEN
!
CALL cell_kinene( ekinh, temphh, velh )
!
END IF
!
IF ( COUNT( iforceh == 1 ) > 0 ) THEN
!
temphc = 2.D0 / k_boltzmann_au * ekinh / DBLE( COUNT( iforceh == 1 ) )
!
ELSE
!
temphc = 0.D0
!
END IF
!
! ... udating nose-hoover friction variables
!
IF ( tnosep ) CALL ions_noseupd( xnhpp, xnhp0, xnhpm, delt, qnp, &
ekin2nhp, gkbt2nhp, vnhp, kbt, &
nhpcl, nhpdim, nhpbeg, nhpend )
!
IF ( tnosee ) CALL electrons_noseupd( xnhep, xnhe0, xnhem, &
delt, qne, ekinc, ekincw, vnhe )
!
IF ( tnoseh ) CALL cell_noseupd( xnhhp, xnhh0, xnhhm, &
delt, qnh, temphh, temph, vnhh )
!
!=================================================================
! BS : Additional cycles for the Nose thermostat ...
IF(tnosep) CYCLE_NOSE=CYCLE_NOSE+1
IF(tnosep .AND. (CYCLE_NOSE .LE. 2) ) GO TO 444
!=================================================================
!
! ... warning: thdyn and tcp/tcap are not compatible yet!!!
!
IF ( tcp .AND. tfor .AND. .NOT.thdyn ) THEN
!
IF ( tempp > (tempw+tolp) .OR. &
tempp < (tempw-tolp) .AND. tempp /= 0.D0 ) THEN
!
CALL ions_vrescal( .false., tempw, tempp, taup, &
tau0, taum, nat, ityp, fion, iforce, pmass, delt )
CALL r_to_s( taup, tausp, nat, ainv )
!
END IF
!
END IF
!
IF ( tprint ) THEN
!
IF( tortho ) THEN
!
IF( force_pairing ) THEN
lambda(:, :, 2) = lambda(:, :, 1)
lambdap(:, :, 2) = lambdap(:, :, 1)
WRITE( stdout, '("Occupations in CPR:")' )
WRITE( stdout, '(10F9.6)' ) ( f(i), i = 1, nbspx )
END IF
!
CALL eigs( nfi, lambdap, lambda, idesc )
!
ELSE
!
WRITE( stdout, '("NOTE: eigenvalues are not computed without ortho")' )
!
END IF
!
END IF
!
IF ( lwf ) CALL ef_enthalpy( enthal, tau0 )
!
IF ( tens .AND. tprint ) THEN
!
WRITE( stdout, '("Occupations :")' )
WRITE( stdout, '(10F9.6)' ) ( f(i), i = 1, nbsp )
!
END IF
!
epot = eht + epseu + exc
!
IF ( .NOT. tcg ) THEN
!
econs = ekinp + ekinh + enthal
econt = econs + ekinc
!
ELSE
!
IF ( .NOT. tens ) THEN
!
econs = ekinp + etot
atot = etot
econt = econs
!
ELSE
!
gibbsfe = atot
econs = ekinp + atot
econt = econs
!
END IF
!
END IF
!
! ... add energies of thermostats
!
IF ( tnosep ) &
econt = econt + ions_nose_nrg( xnhp0, vnhp, qnp, &
gkbt2nhp, kbt, nhpcl, nhpdim )
IF ( tnosee ) &
econt = econt + electrons_nose_nrg( xnhe0, vnhe, qne, ekincw )
IF ( tnoseh ) &
econt = econt + cell_nose_nrg( qnh, xnhh0, vnhh, temph, iforceh )
!
tps = tps + delt * au_ps
!
if (abivol) etot = etot - P_ext*volclu
if (abisur) etot = etot - Surf_t*surfclu
!
IF ( tstdout) CALL spinsq ( c0_bgrp, bec_bgrp, rhor )
!
CALL printout_new( nfi, tfirst, tfile, tprint, tps, hold, stress, &
tau0, vels, fion, ekinc, temphc, tempp, temps, etot, &
enthal, econs, econt, vnhh, xnhh0, vnhp, xnhp0, vnhe, xnhe0, atot, &
ekin, epot, tprnfor, tpre, tstdout )
!
if (abivol) etot = etot + P_ext*volclu
if (abisur) etot = etot + Surf_t*surfclu
!
IF( tfor ) THEN
!
! ... new variables for next step
!
CALL ions_shiftvar( taup, tau0, taum ) ! real positions
CALL ions_shiftvar( tausp, taus, tausm ) ! scaled positions
CALL ions_shiftvar( velsp, vels, velsm ) ! scaled velocities
!
IF ( tnosep ) CALL ions_nose_shiftvar( xnhpp, xnhp0, xnhpm )
IF ( tnosee ) CALL <API key>( xnhep, xnhe0, xnhem )
IF ( tnoseh ) CALL cell_nose_shiftvar( xnhhp, xnhh0, xnhhm )
!
IF( nbgrp > 1 ) THEN
CALL mp_bcast( tau0, 0, inter_bgrp_comm )
CALL mp_bcast( taus, 0, inter_bgrp_comm )
CALL mp_bcast( vels, 0, inter_bgrp_comm )
CALL mp_bcast( xnhp0, 0, inter_bgrp_comm )
CALL mp_bcast( xnhe0, 0, inter_bgrp_comm )
CALL mp_bcast( xnhh0, 0, inter_bgrp_comm )
END IF
!
END IF
!
ekincm = ekinc0
!
! ... cm=c(t+dt) c0=c(t)
!
IF( .NOT. tcg ) THEN
!
CALL dswap( 2*SIZE( c0_bgrp ), c0_bgrp, 1, cm_bgrp, 1 )
!
ELSE
!
CALL cg_update( tfirst, nfi, c0_bgrp )
!
IF ( tfor .AND. .NOT. tens .AND. tprint ) THEN
!
! ... in this case optimize c0 and lambda for smooth
! ... restart with CP
!
IF ( okvan .or. nlcc_any ) THEN
CALL initbox( tau0, alat, at, ainv, taub, irb, iabox, nabox )
CALL phbox( taub, iverbosity, eigrb )
END IF
CALL r_to_s( tau0, taus, nat, ainv )
CALL phfacs( eigts1,eigts2,eigts3, eigr, mill, taus, dfftp%nr1,dfftp%nr2,dfftp%nr3, nat )
CALL strucf( sfac, eigts1, eigts2, eigts3, mill, dffts%ngm )
!
IF ( thdyn ) CALL formf( tfirst, eself )
IF ( tefield ) CALL efield_update( eigr )
IF ( tefield2 ) CALL efield_update2( eigr )
!
CALL plugin_init_ions( tau0 )
!
lambdam = lambda
!
CALL move_electrons( nfi, tprint, tfirst, tlast, bg(:,1), bg(:,2), bg(:,3),&
fion, enthal, enb, enbi, fccc, ccc, dt2bye, stress,.true. )
!
END IF
!
END IF
!
! ... now: cm=c(t) c0=c(t+dt)
! ... and, if tcg == .true. :
! ... c0old=c(t),c0=c(t+dt)
!
tfirst = .FALSE.
!
CALL stop_clock( 'main_loop' )
!
! ... write on file ndw each isave
!
IF ( ( MOD( nfi, isave ) == 0 ) .AND. ( nfi < nomore ) ) THEN
!
IF ( tcg ) THEN
!
CALL writefile( h, hold ,nfi, c0_bgrp, c0old, taus, tausm, &
vels, velsm, acc, lambda, lambdam, idesc, xnhe0, xnhem, &
vnhe, xnhp0, xnhpm, vnhp, nhpcl,nhpdim,ekincm, xnhh0,&
xnhhm, vnhh, velh, fion, tps, z0t, f, rhor )
!
ELSE
!
CALL writefile( h, hold, nfi, c0_bgrp, cm_bgrp, taus, &
tausm, vels, velsm, acc, lambda, lambdam, idesc, xnhe0, &
xnhem, vnhe, xnhp0, xnhpm, vnhp, nhpcl, nhpdim, ekincm,&
xnhh0, xnhhm, vnhh, velh, fion, tps, z0t, f, rhor )
!
END IF
!
END IF
!
epre = enow
enow = etot
!
frice = frice * grease
fricp = fricp * greasp
frich = frich * greash
!
!======================================================================
!
delta_etot = ABS( epre - enow )
!
!exx_wf related
!The following criteria is used to turn on exact exchange calculation when
!GGA energy is converged up to 100 times of the input etot convergence thereshold
!
IF( .NOT.exx_is_active().AND.xclib_dft_is('hybrid').AND.tconvthrs%active ) THEN
!
IF(delta_etot.LT.tconvthrs%derho*exx_start_thr) THEN
!
WRITE(stdout,'(/,3X,"Exact Exchange is turned on ...")')
!
CALL start_exx()
!
END IF
!
END IF
!
tstop = check_stop_now() .OR. tlast
!
tconv = .FALSE.
!
IF ( tconvthrs%active ) THEN
!
! ... electrons
!
tconv = ( ekinc < tconvthrs%ekin .AND. delta_etot < tconvthrs%derho )
!
IF ( tfor ) THEN
!
! ... ions
!
maxfion = MAXVAL( ABS( fion(:,1:nat) ) )
!
tconv = tconv .AND. ( maxfion < tconvthrs%force )
!
END IF
!
END IF
!
! ... in the case cp-wf the check on convergence is done starting
! ... from the second step
!
IF ( lwf .AND. tfirst ) tconv = .FALSE.
!
IF ( tconv ) THEN
!
tlast = .TRUE.
!
IF ( ionode ) THEN
!
WRITE( stdout, &
& "(/,3X,'MAIN:',10X,'EKINC (thr)', &
& 10X,'DETOT (thr)',7X,'MAXFORCE (thr)')" )
WRITE( stdout, "(3X,'MAIN: ',3(D14.6,1X,D8.1))" ) &
ekinc, tconvthrs%ekin, delta_etot, &
tconvthrs%derho, 0.D0, tconvthrs%force
WRITE( stdout, &
"(3X,'MAIN: convergence achieved for system relaxation')" )
!
END IF
!
END IF
!
IF ( lwf ) &
CALL wf_closing_options( nfi, c0_bgrp, cm_bgrp, bec_bgrp, eigr, eigrb,&
taub, irb, ibrav, bg(:,1), bg(:,2), bg(:,3), &
taus, tausm, vels, &
velsm, acc, lambda, lambdam, idesc, xnhe0, xnhem, &
vnhe, xnhp0, xnhpm, vnhp, nhpcl, nhpdim, &
ekincm, xnhh0, xnhhm, vnhh, velh, ecutrho, &
ecutwfc,delt,celldm, fion, tps, z0t, f, rhor )
!
IF ( tstop ) EXIT main_loop
!
CALL stop_clock( 'cpr_md' )
!
END DO main_loop
!
!===================== end of main loop of molecular dynamics ===============
!
DEALLOCATE ( pmass )
! ... Here copy relevant physical quantities into the output arrays/variables
!
etot_out = etot
!
tau_out(:,:) = tau0(:,:)
fion_out(:,:) = fion(:,:)
!
conv_elec = .TRUE.
!
IF ( tcg ) cm_bgrp = c0old
!
CALL writefile( h, hold, nfi, c0_bgrp, cm_bgrp, taus, tausm, &
vels, velsm, acc, lambda, lambdam, idesc, xnhe0, xnhem, vnhe, &
xnhp0, xnhpm, vnhp, nhpcl,nhpdim,ekincm, xnhh0, xnhhm, &
vnhh, velh, fion, tps, z0t, f, rhor )
!
IF( iverbosity > 1 ) CALL laxlib_print_matrix( lambda, idesc, nbsp, nbsp, nudx, 1.D0, ionode, stdout )
!
IF (lda_plus_u) DEALLOCATE( forceh )
!
CALL stop_clock( 'cpr_total' ) ! BS
!
RETURN
!
END SUBROUTINE cprmain
!
!
SUBROUTINE terminate_run()
!
!
USE io_global, ONLY : stdout, ionode
USE control_flags, ONLY : ts_vdw, thdyn, tortho
USE cg_module, ONLY : tcg, print_clock_tcg
USE ldaU_cp, ONLY : lda_plus_u
USE mp, ONLY : mp_report
USE control_flags, ONLY : lwf, lwfpbe0nscf
USE tsvdw_module, ONLY : tsvdw_finalize
USE exx_module, ONLY : exx_finalize
USE xc_lib, ONLY : xclib_dft_is, exx_is_active
!
IMPLICIT NONE
!
! ... print statistics
!
CALL printacc()
!
!==============================================================
WRITE( stdout, '(/5x,"Called by MAIN_LOOP:")' )
CALL print_clock( 'total_time' )
CALL print_clock( 'initialize' )
CALL print_clock( 'main_loop' )
CALL print_clock( 'cpr_total' )
!==============================================================
WRITE( stdout, '(/5x,"Called by INIT_RUN:")' )
CALL print_clock( 'init_readfile' )
IF( lwf ) CALL print_clock( 'wf_start' )
!==============================================================
WRITE( stdout, '(/5x,"Called by CPR:")' )
CALL print_clock( 'cpr_md' )
CALL print_clock( 'move_electrons' )
CALL print_clock( 'move_ion' )
IF( lwf ) CALL print_clock( 'wf_close_opt' ) ! wf_close_opt = wf_1 + wf_2
!==============================================================
IF( lwf ) THEN
WRITE( stdout, '(/5x,"Called by WANNIER_MODULES:")' )
CALL print_clock( 'wf_start' )
CALL print_clock( 'wf_init' )
CALL print_clock( 'wf_close_opt' ) ! wf_close_opt = wf_1 + wf_2
CALL print_clock( 'wf_1' )
CALL print_clock( 'wf_2' )
CALL print_clock( 'ddyn_u' )
CALL print_clock( 'ortho_u' )
END IF
!==============================================================
!exx_wf related
IF ( xclib_dft_is('hybrid').AND.exx_is_active() ) THEN
!
WRITE( stdout, '(/5x,"Called by EXACT_EXCHANGE:")' )
CALL print_clock('exact_exchange') ! total time for exx
CALL print_clock('self_v') ! calculation self potential
CALL print_clock('getpairv') ! calculation pair potential
CALL print_clock('exx_gs_setup') ! calculation
CALL print_clock('exx_pairs') ! calculation
CALL print_clock('r_orbital') ! communication
CALL print_clock('totalenergy') ! communication
CALL print_clock('vl2vg') ! communication
CALL print_clock('send_psi') ! communication
CALL print_clock('sendv') ! communication
CALL print_clock('send_psi_barrier') ! communication
CALL print_clock('send_psi_wait') ! communication
!CALL print_clock('sendv_barrier') ! communication
CALL print_clock('getvofr')
CALL print_clock('getvofr_qlm')
CALL print_clock('getvofr_bound')
CALL print_clock('getvofr_geterho')
CALL print_clock('getvofr_hpotcg')
!CALL print_clock('hpotcg')
!CALL print_clock('getqlm')
!CALL print_clock('exx_bound')
!CALL print_clock('lapmv')
CALL print_clock('exx_cell_derv')
!
CALL exx_finalize() ! deallocate all arrays
!
END IF
!==============================================================
IF (thdyn) THEN
WRITE( stdout, '(/5x,"Called by CELL_DYNAMICS:")' )
CALL print_clock( 'formf' )
END IF
WRITE( stdout, '(/5x,"Called by move_electrons:")' )
CALL print_clock( 'rhoofr' )
CALL print_clock( 'vofrho' )
CALL print_clock( 'dforce' )
CALL print_clock( 'calphi' )
CALL print_clock( 'newd' )
CALL print_clock( 'nlfl' )
IF (lda_plus_u) WRITE( stdout, '(/5x,"Called by new_ns:")' )
CALL print_clock( 'new_ns:forc' )
CALL print_clock( 'projwfc_hub' )
CALL print_clock( 'dndtau' )
IF (tortho) WRITE( stdout, '(/5x,"Called by ortho:")' )
IF (tortho) THEN
CALL print_clock( 'ortho_iter' )
CALL print_clock( 'rsg' )
CALL print_clock( 'rhoset' )
CALL print_clock( 'sigset' )
CALL print_clock( 'tauset' )
CALL print_clock( 'ortho' )
CALL print_clock( 'updatc' )
ELSE
CALL print_clock( 'gram' )
END IF
WRITE( stdout, '(/5x,"Small boxes:")' )
CALL print_clock( 'rhov' )
CALL print_clock( 'fftb' )
CALL print_clock( 'set_cc' )
CALL print_clock( 'forcecc' )
WRITE( stdout, '(/5x,"Low-level routines:")' )
CALL print_clock( 'prefor' )
CALL print_clock( 'nlfq' )
CALL print_clock( 'nlsm1' )
CALL print_clock( 'nlsm2' )
CALL print_clock( 'nlsm1us' )
CALL print_clock( 'fft' )
CALL print_clock( 'ffts' )
CALL print_clock( 'fftw' )
CALL print_clock( 'fft_scatt_xy' )
CALL print_clock( 'fft_scatt_yz' )
CALL print_clock( 'fft_scatt_tg' )
CALL print_clock( 'betagx' )
CALL print_clock( 'qradx' )
CALL print_clock( 'tmp_clk1' )
CALL print_clock( 'tmp_clk2' )
CALL print_clock( 'tmp_clk3' )
CALL print_clock( 'gram' )
CALL print_clock( 'nlinit' )
CALL print_clock( 'init_dim' )
CALL print_clock( 'newnlinit' )
CALL print_clock( 'from_scratch' )
CALL print_clock( 'from_restart' )
CALL print_clock( 'new_ns' )
CALL print_clock( 'strucf' )
CALL print_clock( 'calbec' )
CALL print_clock( 'caldbec_bgrp' )
CALL print_clock( 'exch_corr' )
!==============================================================
IF (ts_vdw) THEN
WRITE( stdout, '(/5x,"Called by tsvdw:")' )
CALL print_clock( 'ts_vdw' )
CALL print_clock( 'tsvdw_pair' )
CALL print_clock( 'tsvdw_rhotot' )
CALL print_clock( 'tsvdw_screen' )
CALL print_clock( 'tsvdw_veff' )
CALL print_clock( 'tsvdw_dveff' )
CALL print_clock( 'tsvdw_energy' )
CALL print_clock( 'tsvdw_wfforce' )
!
CALL tsvdw_finalize()
END IF
!
IF (tcg) call print_clock_tcg()
!
CALL plugin_clock()
!
CALL mp_report()
!
END SUBROUTINE terminate_run |
package edu.upc.fib.ossim.memory.view;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.upc.fib.ossim.memory.MemoryPresenter;
import edu.upc.fib.ossim.template.Presenter;
import edu.upc.fib.ossim.template.view.FormTemplate;
import edu.upc.fib.ossim.utils.Functions;
import edu.upc.fib.ossim.utils.Translation;
/**
* Address translation form. Translates logical process addresses to main memory physical addresses,
* report also errors such us invalid addresses, page faults and segment faults.
*
* @author Alex Macia
*
* @see FormTemplate
*/
public class FormAddress extends FormTemplate implements ChangeListener {
private static final long serialVersionUID = 1L;
private JSpinner address; // 0 <= logical address < size
private JLabel phyAddr; // Physical Address
/**
* Construct a FormAddress
*
* @param presenter event manager
* @param title form title
* @param help help icon
* @param values Process information
*/
public FormAddress(Presenter presenter, String title, JLabel help, Vector<Object> values) {
super(presenter, title, help, values);
}
/**
* Creates and initialize form fields
*/
public void init(Vector<Object> values) {
/* program info */
grid.add(new JLabel(Translation.getInstance().getLabel("me_42")));
grid.add(new JLabel(values.get(0).toString()));
grid.add(new JLabel(Translation.getInstance().getLabel("me_83")));
SpinnerModel spmodel = new SpinnerNumberModel(0, 0, MemorySettings.MAX_MEMSIZE, 1);
address = new JSpinner(spmodel);
JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) address.getEditor();
editor.getTextField().addFocusListener(presenter);
address.addChangeListener(this);
grid.add(address);
grid.add(new JLabel(Translation.getInstance().getLabel("me_84")));
phyAddr = new JLabel(((MemoryPresenter) presenter).getAddTransPhysical(0));
grid.add(phyAddr);
Functions.getInstance().makeCompactGrid(grid, 3, 2, 10, 10, 10, 10);
pn.add(grid);
}
/**
* Returns null, no data is generated
*
*/
public Vector<Object> getSpecificData() {
return null;
}
/**
* Manage Change event from logical address spinner. Access presenter to translate
* to physical address and updates information
*/
public void stateChanged(ChangeEvent arg0) {
phyAddr.setText(((MemoryPresenter) presenter).getAddTransPhysical((Integer) address.getValue()));
}
} |
/* drivers/atm/eni.c - Efficient Networks ENI155P device driver */
/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/pci.h>
#include <linux/errno.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/sonet.h>
#include <linux/skbuff.h>
#include <linux/time.h>
#include <linux/delay.h>
#include <linux/uio.h>
#include <linux/init.h>
#include <linux/atm_eni.h>
#include <linux/bitops.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <linux/atomic.h>
#include <asm/uaccess.h>
#include <asm/string.h>
#include <asm/byteorder.h>
#include "tonga.h"
#include "midway.h"
#include "suni.h"
#include "eni.h"
#if !defined(__i386__) && !defined(__x86_64__)
#ifndef ioremap_nocache
#define ioremap_nocache(X,Y) ioremap(X,Y)
#endif
#endif
/*
* TODO:
*
* Show stoppers
* none
*
* Minor
* - OAM support
* - fix bugs listed below
*/
/*
* KNOWN BUGS:
*
* - may run into JK-JK bug and deadlock
* - should allocate UBR channel first
* - buffer space allocation algorithm is stupid
* (RX: should be maxSDU+maxdelay*rate
* TX: should be maxSDU+min(maxSDU,maxdelay*rate) )
* - doesn't support OAM cells
* - eni_put_free may hang if not putting memory fragments that _complete_
* 2^n block (never happens in real life, though)
*/
#if 0
#define DPRINTK(format,args...) printk(KERN_DEBUG format,##args)
#else
#define DPRINTK(format,args...)
#endif
#ifndef <API key>
#define <API key>
#define <API key>
#endif
#ifndef <API key>
#define NULLCHECK(x)
#define EVENT(s,a,b)
static void event_dump(void)
{
}
#else
/*
* NULL pointer checking
*/
#define NULLCHECK(x) \
if ((unsigned long) (x) < 0x30) \
printk(KERN_CRIT #x "==0x%lx\n",(unsigned long) (x))
/*
* Very extensive activity logging. Greatly improves bug detection speed but
* costs a few Mbps if enabled.
*/
#define EV 64
static const char *ev[EV];
static unsigned long ev_a[EV],ev_b[EV];
static int ec = 0;
static void EVENT(const char *s,unsigned long a,unsigned long b)
{
ev[ec] = s;
ev_a[ec] = a;
ev_b[ec] = b;
ec = (ec+1) % EV;
}
static void event_dump(void)
{
int n,i;
for (n = 0; n < EV; n++) {
i = (ec+n) % EV;
printk(KERN_NOTICE);
printk(ev[i] ? ev[i] : "(null)",ev_a[i],ev_b[i]);
}
}
#endif /* <API key> */
/*
* NExx must not be equal at end
* EExx may be equal at end
* xxPJOK verify validity of pointer jumps
* xxPMOK operating on a circular buffer of "c" words
*/
#define NEPJOK(a0,a1,b) \
((a0) < (a1) ? (b) <= (a0) || (b) > (a1) : (b) <= (a0) && (b) > (a1))
#define EEPJOK(a0,a1,b) \
((a0) < (a1) ? (b) < (a0) || (b) >= (a1) : (b) < (a0) && (b) >= (a1))
#define NEPMOK(a0,d,b,c) NEPJOK(a0,(a0+d) & (c-1),b)
#define EEPMOK(a0,d,b,c) EEPJOK(a0,(a0+d) & (c-1),b)
static int tx_complete = 0,dma_complete = 0,queued = 0,requeued = 0,
backlogged = 0,rx_enqueued = 0,rx_dequeued = 0,pushed = 0,submitted = 0,
putting = 0;
static struct atm_dev *eni_boards = NULL;
/* Read/write registers on card */
#define eni_in(r) readl(eni_dev->reg+(r)*4)
#define eni_out(v,r) writel((v),eni_dev->reg+(r)*4)
static void dump_mem(struct eni_dev *eni_dev)
{
int i;
for (i = 0; i < eni_dev->free_len; i++)
printk(KERN_DEBUG " %d: %p %d\n",i,
eni_dev->free_list[i].start,
1 << eni_dev->free_list[i].order);
}
static void dump(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
int i;
eni_dev = ENI_DEV(dev);
printk(KERN_NOTICE "Free memory\n");
dump_mem(eni_dev);
printk(KERN_NOTICE "TX buffers\n");
for (i = 0; i < NR_CHAN; i++)
if (eni_dev->tx[i].send)
printk(KERN_NOTICE " TX %d @ %p: %ld\n",i,
eni_dev->tx[i].send,eni_dev->tx[i].words*4);
printk(KERN_NOTICE "RX buffers\n");
for (i = 0; i < 1024; i++)
if (eni_dev->rx_map[i] && ENI_VCC(eni_dev->rx_map[i])->rx)
printk(KERN_NOTICE " RX %d @ %p: %ld\n",i,
ENI_VCC(eni_dev->rx_map[i])->recv,
ENI_VCC(eni_dev->rx_map[i])->words*4);
printk(KERN_NOTICE "
}
static void eni_put_free(struct eni_dev *eni_dev, void __iomem *start,
unsigned long size)
{
struct eni_free *list;
int len,order;
DPRINTK("init 0x%lx+%ld(0x%lx)\n",start,size,size);
start += eni_dev->base_diff;
list = eni_dev->free_list;
len = eni_dev->free_len;
while (size) {
if (len >= eni_dev->free_list_size) {
printk(KERN_CRIT "eni_put_free overflow (%p,%ld)\n",
start,size);
break;
}
for (order = 0; !(((unsigned long)start | size) & (1 << order)); order++);
if (MID_MIN_BUF_SIZE > (1 << order)) {
printk(KERN_CRIT "eni_put_free: order %d too small\n",
order);
break;
}
list[len].start = (void __iomem *) start;
list[len].order = order;
len++;
start += 1 << order;
size -= 1 << order;
}
eni_dev->free_len = len;
/*dump_mem(eni_dev);*/
}
static void __iomem *eni_alloc_mem(struct eni_dev *eni_dev, unsigned long *size)
{
struct eni_free *list;
void __iomem *start;
int len,i,order,best_order,index;
list = eni_dev->free_list;
len = eni_dev->free_len;
if (*size < MID_MIN_BUF_SIZE) *size = MID_MIN_BUF_SIZE;
if (*size > MID_MAX_BUF_SIZE) return NULL;
for (order = 0; (1 << order) < *size; order++);
DPRINTK("trying: %ld->%d\n",*size,order);
best_order = 65; /* we don't have more than 2^64 of anything ... */
index = 0; /* silence GCC */
for (i = 0; i < len; i++)
if (list[i].order == order) {
best_order = order;
index = i;
break;
}
else if (best_order > list[i].order && list[i].order > order) {
best_order = list[i].order;
index = i;
}
if (best_order == 65) return NULL;
start = list[index].start-eni_dev->base_diff;
list[index] = list[--len];
eni_dev->free_len = len;
*size = 1 << order;
eni_put_free(eni_dev,start+*size,(1 << best_order)-*size);
DPRINTK("%ld bytes (order %d) at 0x%lx\n",*size,order,start);
memset_io(start,0,*size); /* never leak data */
/*dump_mem(eni_dev);*/
return start;
}
static void eni_free_mem(struct eni_dev *eni_dev, void __iomem *start,
unsigned long size)
{
struct eni_free *list;
int len,i,order;
start += eni_dev->base_diff;
list = eni_dev->free_list;
len = eni_dev->free_len;
for (order = -1; size; order++) size >>= 1;
DPRINTK("eni_free_mem: %p+0x%lx (order %d)\n",start,size,order);
for (i = 0; i < len; i++)
if (((unsigned long) list[i].start) == ((unsigned long)start^(1 << order)) &&
list[i].order == order) {
DPRINTK("match[%d]: 0x%lx/0x%lx(0x%x), %d/%d\n",i,
list[i].start,start,1 << order,list[i].order,order);
list[i] = list[--len];
start = (void __iomem *) ((unsigned long) start & ~(unsigned long) (1 << order));
order++;
i = -1;
continue;
}
if (len >= eni_dev->free_list_size) {
printk(KERN_ALERT "eni_free_mem overflow (%p,%d)\n",start,
order);
return;
}
list[len].start = start;
list[len].order = order;
eni_dev->free_len = len+1;
/*dump_mem(eni_dev);*/
}
#define ENI_VCC_NOS ((struct atm_vcc *) 1)
static void rx_ident_err(struct atm_vcc *vcc)
{
struct atm_dev *dev;
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
dev = vcc->dev;
eni_dev = ENI_DEV(dev);
/* immediately halt adapter */
eni_out(eni_in(MID_MC_S) &
~(MID_DMA_ENABLE | MID_TX_ENABLE | MID_RX_ENABLE),MID_MC_S);
/* dump useful information */
eni_vcc = ENI_VCC(vcc);
printk(KERN_ALERT DEV_LABEL "(itf %d): driver error - RX ident "
"mismatch\n",dev->number);
printk(KERN_ALERT " VCI %d, rxing %d, words %ld\n",vcc->vci,
eni_vcc->rxing,eni_vcc->words);
printk(KERN_ALERT " host descr 0x%lx, rx pos 0x%lx, descr value "
"0x%x\n",eni_vcc->descr,eni_vcc->rx_pos,
(unsigned) readl(eni_vcc->recv+eni_vcc->descr*4));
printk(KERN_ALERT " last %p, servicing %d\n",eni_vcc->last,
eni_vcc->servicing);
EVENT("
printk(KERN_NOTICE "
event_dump();
ENI_DEV(dev)->fast = NULL; /* really stop it */
ENI_DEV(dev)->slow = NULL;
skb_queue_head_init(&ENI_DEV(dev)->rx_queue);
}
static int do_rx_dma(struct atm_vcc *vcc,struct sk_buff *skb,
unsigned long skip,unsigned long size,unsigned long eff)
{
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
u32 dma_rd,dma_wr;
u32 dma[RX_DMA_BUF*2];
dma_addr_t paddr;
unsigned long here;
int i,j;
eni_dev = ENI_DEV(vcc->dev);
eni_vcc = ENI_VCC(vcc);
paddr = 0; /* GCC, shut up */
if (skb) {
paddr = dma_map_single(&eni_dev->pci_dev->dev,skb->data,skb->len,
DMA_FROM_DEVICE);
if (dma_mapping_error(&eni_dev->pci_dev->dev, paddr))
goto dma_map_error;
ENI_PRV_PADDR(skb) = paddr;
if (paddr & 3)
printk(KERN_CRIT DEV_LABEL "(itf %d): VCI %d has "
"mis-aligned RX data (0x%lx)\n",vcc->dev->number,
vcc->vci,(unsigned long) paddr);
ENI_PRV_SIZE(skb) = size+skip;
/* PDU plus descriptor */
ATM_SKB(skb)->vcc = vcc;
}
j = 0;
if ((eff && skip) || 1) { /* @@@ actually, skip is always == 1 ... */
here = (eni_vcc->descr+skip) & (eni_vcc->words-1);
dma[j++] = (here << MID_DMA_COUNT_SHIFT) | (vcc->vci
<< MID_DMA_VCI_SHIFT) | MID_DT_JK;
j++;
}
here = (eni_vcc->descr+size+skip) & (eni_vcc->words-1);
if (!eff) size += skip;
else {
unsigned long words;
if (!size) {
DPRINTK("strange things happen ...\n");
EVENT("strange things happen ... (skip=%ld,eff=%ld)\n",
size,eff);
}
words = eff;
if (paddr & 15) {
unsigned long init;
init = 4-((paddr & 15) >> 2);
if (init > words) init = words;
dma[j++] = MID_DT_WORD | (init << MID_DMA_COUNT_SHIFT) |
(vcc->vci << MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
paddr += init << 2;
words -= init;
}
#ifdef <API key> /* may work with some PCI chipsets ... */
if (words & ~15) {
dma[j++] = MID_DT_16W | ((words >> 4) <<
MID_DMA_COUNT_SHIFT) | (vcc->vci <<
MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
paddr += (words & ~15) << 2;
words &= 15;
}
#endif
#ifdef <API key> /* works only with *some* PCI chipsets ... */
if (words & ~7) {
dma[j++] = MID_DT_8W | ((words >> 3) <<
MID_DMA_COUNT_SHIFT) | (vcc->vci <<
MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
paddr += (words & ~7) << 2;
words &= 7;
}
#endif
#ifdef <API key> /* recommended */
if (words & ~3) {
dma[j++] = MID_DT_4W | ((words >> 2) <<
MID_DMA_COUNT_SHIFT) | (vcc->vci <<
MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
paddr += (words & ~3) << 2;
words &= 3;
}
#endif
#ifdef <API key> /* probably useless if RX_4W, RX_8W, ... */
if (words & ~1) {
dma[j++] = MID_DT_2W | ((words >> 1) <<
MID_DMA_COUNT_SHIFT) | (vcc->vci <<
MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
paddr += (words & ~1) << 2;
words &= 1;
}
#endif
if (words) {
dma[j++] = MID_DT_WORD | (words << MID_DMA_COUNT_SHIFT)
| (vcc->vci << MID_DMA_VCI_SHIFT);
dma[j++] = paddr;
}
}
if (size != eff) {
dma[j++] = (here << MID_DMA_COUNT_SHIFT) |
(vcc->vci << MID_DMA_VCI_SHIFT) | MID_DT_JK;
j++;
}
if (!j || j > 2*RX_DMA_BUF) {
printk(KERN_CRIT DEV_LABEL "!j or j too big!!!\n");
goto trouble;
}
dma[j-2] |= MID_DMA_END;
j = j >> 1;
dma_wr = eni_in(MID_DMA_WR_RX);
dma_rd = eni_in(MID_DMA_RD_RX);
/*
* Can I move the dma_wr pointer by 2j+1 positions without overwriting
* data that hasn't been read (position of dma_rd) yet ?
*/
if (!NEPMOK(dma_wr,j+j+1,dma_rd,NR_DMA_RX)) { /* @@@ +1 is ugly */
printk(KERN_WARNING DEV_LABEL "(itf %d): RX DMA full\n",
vcc->dev->number);
goto trouble;
}
for (i = 0; i < j; i++) {
writel(dma[i*2],eni_dev->rx_dma+dma_wr*8);
writel(dma[i*2+1],eni_dev->rx_dma+dma_wr*8+4);
dma_wr = (dma_wr+1) & (NR_DMA_RX-1);
}
if (skb) {
ENI_PRV_POS(skb) = eni_vcc->descr+size+1;
skb_queue_tail(&eni_dev->rx_queue,skb);
eni_vcc->last = skb;
rx_enqueued++;
}
eni_vcc->descr = here;
eni_out(dma_wr,MID_DMA_WR_RX);
return 0;
trouble:
if (paddr)
dma_unmap_single(&eni_dev->pci_dev->dev,paddr,skb->len,
DMA_FROM_DEVICE);
dma_map_error:
if (skb) dev_kfree_skb_irq(skb);
return -1;
}
static void discard(struct atm_vcc *vcc,unsigned long size)
{
struct eni_vcc *eni_vcc;
eni_vcc = ENI_VCC(vcc);
EVENT("discard (size=%ld)\n",size,0);
while (do_rx_dma(vcc,NULL,1,size,0)) EVENT("BUSY LOOP",0,0);
/* could do a full fallback, but that might be more expensive */
if (eni_vcc->rxing) ENI_PRV_POS(eni_vcc->last) += size+1;
else eni_vcc->rx_pos = (eni_vcc->rx_pos+size+1) & (eni_vcc->words-1);
}
/*
* TODO: should check whether direct copies (without DMA setup, dequeuing on
* interrupt, etc.) aren't much faster for AAL0
*/
static int rx_aal0(struct atm_vcc *vcc)
{
struct eni_vcc *eni_vcc;
unsigned long descr;
unsigned long length;
struct sk_buff *skb;
DPRINTK(">rx_aal0\n");
eni_vcc = ENI_VCC(vcc);
descr = readl(eni_vcc->recv+eni_vcc->descr*4);
if ((descr & MID_RED_IDEN) != (MID_RED_RX_ID << MID_RED_SHIFT)) {
rx_ident_err(vcc);
return 1;
}
if (descr & MID_RED_T) {
DPRINTK(DEV_LABEL "(itf %d): trashing empty cell\n",
vcc->dev->number);
length = 0;
<API key>(&vcc->stats->rx_err);
}
else {
length = ATM_CELL_SIZE-1; /* no HEC */
}
skb = length ? atm_alloc_charge(vcc,length,GFP_ATOMIC) : NULL;
if (!skb) {
discard(vcc,length >> 2);
return 0;
}
skb_put(skb,length);
skb->tstamp = eni_vcc->timestamp;
DPRINTK("got len %ld\n",length);
if (do_rx_dma(vcc,skb,1,length >> 2,length >> 2)) return 1;
eni_vcc->rxing++;
return 0;
}
static int rx_aal5(struct atm_vcc *vcc)
{
struct eni_vcc *eni_vcc;
unsigned long descr;
unsigned long size,eff,length;
struct sk_buff *skb;
EVENT("rx_aal5\n",0,0);
DPRINTK(">rx_aal5\n");
eni_vcc = ENI_VCC(vcc);
descr = readl(eni_vcc->recv+eni_vcc->descr*4);
if ((descr & MID_RED_IDEN) != (MID_RED_RX_ID << MID_RED_SHIFT)) {
rx_ident_err(vcc);
return 1;
}
if (descr & (MID_RED_T | MID_RED_CRC_ERR)) {
if (descr & MID_RED_T) {
EVENT("empty cell (descr=0x%lx)\n",descr,0);
DPRINTK(DEV_LABEL "(itf %d): trashing empty cell\n",
vcc->dev->number);
size = 0;
}
else {
static unsigned long silence = 0;
if (time_after(jiffies, silence) || silence == 0) {
printk(KERN_WARNING DEV_LABEL "(itf %d): "
"discarding PDU(s) with CRC error\n",
vcc->dev->number);
silence = (jiffies+2*HZ)|1;
}
size = (descr & MID_RED_COUNT)*(ATM_CELL_PAYLOAD >> 2);
EVENT("CRC error (descr=0x%lx,size=%ld)\n",descr,
size);
}
eff = length = 0;
<API key>(&vcc->stats->rx_err);
}
else {
size = (descr & MID_RED_COUNT)*(ATM_CELL_PAYLOAD >> 2);
DPRINTK("size=%ld\n",size);
length = readl(eni_vcc->recv+(((eni_vcc->descr+size-1) &
(eni_vcc->words-1)))*4) & 0xffff;
/* -trailer(2)+header(1) */
if (length && length <= (size << 2)-8 && length <=
ATM_MAX_AAL5_PDU) eff = (length+3) >> 2;
else { /* ^ trailer length (8) */
EVENT("bad PDU (descr=0x08%lx,length=%ld)\n",descr,
length);
printk(KERN_ERR DEV_LABEL "(itf %d): bad AAL5 PDU "
"(VCI=%d,length=%ld,size=%ld (descr 0x%lx))\n",
vcc->dev->number,vcc->vci,length,size << 2,descr);
length = eff = 0;
<API key>(&vcc->stats->rx_err);
}
}
skb = eff ? atm_alloc_charge(vcc,eff << 2,GFP_ATOMIC) : NULL;
if (!skb) {
discard(vcc,size);
return 0;
}
skb_put(skb,length);
DPRINTK("got len %ld\n",length);
if (do_rx_dma(vcc,skb,1,size,eff)) return 1;
eni_vcc->rxing++;
return 0;
}
static inline int rx_vcc(struct atm_vcc *vcc)
{
void __iomem *vci_dsc;
unsigned long tmp;
struct eni_vcc *eni_vcc;
eni_vcc = ENI_VCC(vcc);
vci_dsc = ENI_DEV(vcc->dev)->vci+vcc->vci*16;
EVENT("rx_vcc(1)\n",0,0);
while (eni_vcc->descr != (tmp = (readl(vci_dsc+4) & MID_VCI_DESCR) >>
MID_VCI_DESCR_SHIFT)) {
EVENT("rx_vcc(2: host dsc=0x%lx, nic dsc=0x%lx)\n",
eni_vcc->descr,tmp);
DPRINTK("CB_DESCR %ld REG_DESCR %d\n",ENI_VCC(vcc)->descr,
(((unsigned) readl(vci_dsc+4) & MID_VCI_DESCR) >>
MID_VCI_DESCR_SHIFT));
if (ENI_VCC(vcc)->rx(vcc)) return 1;
}
/* clear IN_SERVICE flag */
writel(readl(vci_dsc) & ~MID_VCI_IN_SERVICE,vci_dsc);
/*
* If new data has arrived between evaluating the while condition and
* clearing IN_SERVICE, we wouldn't be notified until additional data
* follows. So we have to loop again to be sure.
*/
EVENT("rx_vcc(3)\n",0,0);
while (ENI_VCC(vcc)->descr != (tmp = (readl(vci_dsc+4) & MID_VCI_DESCR)
>> MID_VCI_DESCR_SHIFT)) {
EVENT("rx_vcc(4: host dsc=0x%lx, nic dsc=0x%lx)\n",
eni_vcc->descr,tmp);
DPRINTK("CB_DESCR %ld REG_DESCR %d\n",ENI_VCC(vcc)->descr,
(((unsigned) readl(vci_dsc+4) & MID_VCI_DESCR) >>
MID_VCI_DESCR_SHIFT));
if (ENI_VCC(vcc)->rx(vcc)) return 1;
}
return 0;
}
static void poll_rx(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
struct atm_vcc *curr;
eni_dev = ENI_DEV(dev);
while ((curr = eni_dev->fast)) {
EVENT("poll_rx.fast\n",0,0);
if (rx_vcc(curr)) return;
eni_dev->fast = ENI_VCC(curr)->next;
ENI_VCC(curr)->next = ENI_VCC_NOS;
barrier();
ENI_VCC(curr)->servicing
}
while ((curr = eni_dev->slow)) {
EVENT("poll_rx.slow\n",0,0);
if (rx_vcc(curr)) return;
eni_dev->slow = ENI_VCC(curr)->next;
ENI_VCC(curr)->next = ENI_VCC_NOS;
barrier();
ENI_VCC(curr)->servicing
}
}
static void get_service(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
struct atm_vcc *vcc;
unsigned long vci;
DPRINTK(">get_service\n");
eni_dev = ENI_DEV(dev);
while (eni_in(MID_SERV_WRITE) != eni_dev->serv_read) {
vci = readl(eni_dev->service+eni_dev->serv_read*4);
eni_dev->serv_read = (eni_dev->serv_read+1) & (NR_SERVICE-1);
vcc = eni_dev->rx_map[vci & 1023];
if (!vcc) {
printk(KERN_CRIT DEV_LABEL "(itf %d): VCI %ld not "
"found\n",dev->number,vci);
continue; /* nasty but we try to go on anyway */
/* @@@ nope, doesn't work */
}
EVENT("getting from service\n",0,0);
if (ENI_VCC(vcc)->next != ENI_VCC_NOS) {
EVENT("double service\n",0,0);
DPRINTK("Grr, servicing VCC %ld twice\n",vci);
continue;
}
ENI_VCC(vcc)->timestamp = ktime_get_real();
ENI_VCC(vcc)->next = NULL;
if (vcc->qos.rxtp.traffic_class == ATM_CBR) {
if (eni_dev->fast)
ENI_VCC(eni_dev->last_fast)->next = vcc;
else eni_dev->fast = vcc;
eni_dev->last_fast = vcc;
}
else {
if (eni_dev->slow)
ENI_VCC(eni_dev->last_slow)->next = vcc;
else eni_dev->slow = vcc;
eni_dev->last_slow = vcc;
}
putting++;
ENI_VCC(vcc)->servicing++;
}
}
static void dequeue_rx(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
struct atm_vcc *vcc;
struct sk_buff *skb;
void __iomem *vci_dsc;
int first;
eni_dev = ENI_DEV(dev);
first = 1;
while (1) {
skb = skb_dequeue(&eni_dev->rx_queue);
if (!skb) {
if (first) {
DPRINTK(DEV_LABEL "(itf %d): RX but not "
"rxing\n",dev->number);
EVENT("nothing to dequeue\n",0,0);
}
break;
}
EVENT("dequeued (size=%ld,pos=0x%lx)\n",ENI_PRV_SIZE(skb),
ENI_PRV_POS(skb));
rx_dequeued++;
vcc = ATM_SKB(skb)->vcc;
eni_vcc = ENI_VCC(vcc);
first = 0;
vci_dsc = eni_dev->vci+vcc->vci*16;
if (!EEPMOK(eni_vcc->rx_pos,ENI_PRV_SIZE(skb),
(readl(vci_dsc+4) & MID_VCI_READ) >> MID_VCI_READ_SHIFT,
eni_vcc->words)) {
EVENT("requeuing\n",0,0);
skb_queue_head(&eni_dev->rx_queue,skb);
break;
}
eni_vcc->rxing
eni_vcc->rx_pos = ENI_PRV_POS(skb) & (eni_vcc->words-1);
dma_unmap_single(&eni_dev->pci_dev->dev,ENI_PRV_PADDR(skb),skb->len,
DMA_TO_DEVICE);
if (!skb->len) dev_kfree_skb_irq(skb);
else {
EVENT("pushing (len=%ld)\n",skb->len,0);
if (vcc->qos.aal == ATM_AAL0)
*(unsigned long *) skb->data =
ntohl(*(unsigned long *) skb->data);
memset(skb->cb,0,sizeof(struct eni_skb_prv));
vcc->push(vcc,skb);
pushed++;
}
<API key>(&vcc->stats->rx);
}
wake_up(&eni_dev->rx_wait);
}
static int open_rx_first(struct atm_vcc *vcc)
{
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
unsigned long size;
DPRINTK("open_rx_first\n");
eni_dev = ENI_DEV(vcc->dev);
eni_vcc = ENI_VCC(vcc);
eni_vcc->rx = NULL;
if (vcc->qos.rxtp.traffic_class == ATM_NONE) return 0;
size = vcc->qos.rxtp.max_sdu*eni_dev->rx_mult/100;
if (size > MID_MAX_BUF_SIZE && vcc->qos.rxtp.max_sdu <=
MID_MAX_BUF_SIZE)
size = MID_MAX_BUF_SIZE;
eni_vcc->recv = eni_alloc_mem(eni_dev,&size);
DPRINTK("rx at 0x%lx\n",eni_vcc->recv);
eni_vcc->words = size >> 2;
if (!eni_vcc->recv) return -ENOBUFS;
eni_vcc->rx = vcc->qos.aal == ATM_AAL5 ? rx_aal5 : rx_aal0;
eni_vcc->descr = 0;
eni_vcc->rx_pos = 0;
eni_vcc->rxing = 0;
eni_vcc->servicing = 0;
eni_vcc->next = ENI_VCC_NOS;
return 0;
}
static int open_rx_second(struct atm_vcc *vcc)
{
void __iomem *here;
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
unsigned long size;
int order;
DPRINTK("open_rx_second\n");
eni_dev = ENI_DEV(vcc->dev);
eni_vcc = ENI_VCC(vcc);
if (!eni_vcc->rx) return 0;
/* set up VCI descriptor */
here = eni_dev->vci+vcc->vci*16;
DPRINTK("loc 0x%x\n",(unsigned) (eni_vcc->recv-eni_dev->ram)/4);
size = eni_vcc->words >> 8;
for (order = -1; size; order++) size >>= 1;
writel(0,here+4); /* descr, read = 0 */
writel(0,here+8); /* write, state, count = 0 */
if (eni_dev->rx_map[vcc->vci])
printk(KERN_CRIT DEV_LABEL "(itf %d): BUG - VCI %d already "
"in use\n",vcc->dev->number,vcc->vci);
eni_dev->rx_map[vcc->vci] = vcc; /* now it counts */
writel(((vcc->qos.aal != ATM_AAL5 ? MID_MODE_RAW : MID_MODE_AAL5) <<
MID_VCI_MODE_SHIFT) | MID_VCI_PTI_MODE |
(((eni_vcc->recv-eni_dev->ram) >> (MID_LOC_SKIP+2)) <<
<API key>) | (order << MID_VCI_SIZE_SHIFT),here);
return 0;
}
static void close_rx(struct atm_vcc *vcc)
{
DECLARE_WAITQUEUE(wait,current);
void __iomem *here;
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
eni_vcc = ENI_VCC(vcc);
if (!eni_vcc->rx) return;
eni_dev = ENI_DEV(vcc->dev);
if (vcc->vpi != ATM_VPI_UNSPEC && vcc->vci != ATM_VCI_UNSPEC) {
here = eni_dev->vci+vcc->vci*16;
/* block receiver */
writel((readl(here) & ~MID_VCI_MODE) | (MID_MODE_TRASH <<
MID_VCI_MODE_SHIFT),here);
/* wait for receiver to become idle */
udelay(27);
/* discard pending cell */
writel(readl(here) & ~MID_VCI_IN_SERVICE,here);
/* don't accept any new ones */
eni_dev->rx_map[vcc->vci] = NULL;
/* wait for RX queue to drain */
DPRINTK("eni_close: waiting for RX ...\n");
EVENT("RX closing\n",0,0);
add_wait_queue(&eni_dev->rx_wait,&wait);
set_current_state(<API key>);
barrier();
for (;;) {
/* transition service->rx: rxing++, servicing-- */
if (!eni_vcc->servicing) {
barrier();
if (!eni_vcc->rxing) break;
}
EVENT("drain PDUs (rx %ld, serv %ld)\n",eni_vcc->rxing,
eni_vcc->servicing);
printk(KERN_INFO "%d+%d RX left\n",eni_vcc->servicing,
eni_vcc->rxing);
schedule();
set_current_state(<API key>);
}
for (;;) {
int at_end;
u32 tmp;
tasklet_disable(&eni_dev->task);
tmp = readl(eni_dev->vci+vcc->vci*16+4) & MID_VCI_READ;
at_end = eni_vcc->rx_pos == tmp >> MID_VCI_READ_SHIFT;
tasklet_enable(&eni_dev->task);
if (at_end) break;
EVENT("drain discard (host 0x%lx, nic 0x%lx)\n",
eni_vcc->rx_pos,tmp);
printk(KERN_INFO "draining RX: host 0x%lx, nic 0x%x\n",
eni_vcc->rx_pos,tmp);
schedule();
set_current_state(<API key>);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&eni_dev->rx_wait,&wait);
}
eni_free_mem(eni_dev,eni_vcc->recv,eni_vcc->words << 2);
eni_vcc->rx = NULL;
}
static int start_rx(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
eni_dev = ENI_DEV(dev);
eni_dev->rx_map = (struct atm_vcc **) get_zeroed_page(GFP_KERNEL);
if (!eni_dev->rx_map) {
printk(KERN_ERR DEV_LABEL "(itf %d): couldn't get free page\n",
dev->number);
free_page((unsigned long) eni_dev->free_list);
return -ENOMEM;
}
eni_dev->rx_mult = DEFAULT_RX_MULT;
eni_dev->fast = eni_dev->last_fast = NULL;
eni_dev->slow = eni_dev->last_slow = NULL;
init_waitqueue_head(&eni_dev->rx_wait);
skb_queue_head_init(&eni_dev->rx_queue);
eni_dev->serv_read = eni_in(MID_SERV_WRITE);
eni_out(0,MID_DMA_WR_RX);
return 0;
}
enum enq_res { enq_ok,enq_next,enq_jam };
static inline void put_dma(int chan,u32 *dma,int *j,dma_addr_t paddr,
u32 size)
{
u32 init,words;
DPRINTK("put_dma: 0x%lx+0x%x\n",(unsigned long) paddr,size);
EVENT("put_dma: 0x%lx+0x%lx\n",(unsigned long) paddr,size);
#if 0 /* don't complain anymore */
if (paddr & 3)
printk(KERN_ERR "put_dma: unaligned addr (0x%lx)\n",paddr);
if (size & 3)
printk(KERN_ERR "put_dma: unaligned size (0x%lx)\n",size);
#endif
if (paddr & 3) {
init = 4-(paddr & 3);
if (init > size || size < 7) init = size;
DPRINTK("put_dma: %lx DMA: %d/%d bytes\n",
(unsigned long) paddr,init,size);
dma[(*j)++] = MID_DT_BYTE | (init << MID_DMA_COUNT_SHIFT) |
(chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += init;
size -= init;
}
words = size >> 2;
size &= 3;
if (words && (paddr & 31)) {
init = 8-((paddr & 31) >> 2);
if (init > words) init = words;
DPRINTK("put_dma: %lx DMA: %d/%d words\n",
(unsigned long) paddr,init,words);
dma[(*j)++] = MID_DT_WORD | (init << MID_DMA_COUNT_SHIFT) |
(chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += init << 2;
words -= init;
}
#ifdef <API key> /* may work with some PCI chipsets ... */
if (words & ~15) {
DPRINTK("put_dma: %lx DMA: %d*16/%d words\n",
(unsigned long) paddr,words >> 4,words);
dma[(*j)++] = MID_DT_16W | ((words >> 4) << MID_DMA_COUNT_SHIFT)
| (chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += (words & ~15) << 2;
words &= 15;
}
#endif
#ifdef <API key> /* recommended */
if (words & ~7) {
DPRINTK("put_dma: %lx DMA: %d*8/%d words\n",
(unsigned long) paddr,words >> 3,words);
dma[(*j)++] = MID_DT_8W | ((words >> 3) << MID_DMA_COUNT_SHIFT)
| (chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += (words & ~7) << 2;
words &= 7;
}
#endif
#ifdef <API key> /* probably useless if TX_8W or TX_16W */
if (words & ~3) {
DPRINTK("put_dma: %lx DMA: %d*4/%d words\n",
(unsigned long) paddr,words >> 2,words);
dma[(*j)++] = MID_DT_4W | ((words >> 2) << MID_DMA_COUNT_SHIFT)
| (chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += (words & ~3) << 2;
words &= 3;
}
#endif
#ifdef <API key> /* probably useless if TX_4W, TX_8W, ... */
if (words & ~1) {
DPRINTK("put_dma: %lx DMA: %d*2/%d words\n",
(unsigned long) paddr,words >> 1,words);
dma[(*j)++] = MID_DT_2W | ((words >> 1) << MID_DMA_COUNT_SHIFT)
| (chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += (words & ~1) << 2;
words &= 1;
}
#endif
if (words) {
DPRINTK("put_dma: %lx DMA: %d words\n",(unsigned long) paddr,
words);
dma[(*j)++] = MID_DT_WORD | (words << MID_DMA_COUNT_SHIFT) |
(chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
paddr += words << 2;
}
if (size) {
DPRINTK("put_dma: %lx DMA: %d bytes\n",(unsigned long) paddr,
size);
dma[(*j)++] = MID_DT_BYTE | (size << MID_DMA_COUNT_SHIFT) |
(chan << MID_DMA_CHAN_SHIFT);
dma[(*j)++] = paddr;
}
}
static enum enq_res do_tx(struct sk_buff *skb)
{
struct atm_vcc *vcc;
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
struct eni_tx *tx;
dma_addr_t paddr;
u32 dma_rd,dma_wr;
u32 size; /* in words */
int aal5,dma_size,i,j;
DPRINTK(">do_tx\n");
NULLCHECK(skb);
EVENT("do_tx: skb=0x%lx, %ld bytes\n",(unsigned long) skb,skb->len);
vcc = ATM_SKB(skb)->vcc;
NULLCHECK(vcc);
eni_dev = ENI_DEV(vcc->dev);
NULLCHECK(eni_dev);
eni_vcc = ENI_VCC(vcc);
tx = eni_vcc->tx;
NULLCHECK(tx);
#if 0 /* Enable this for testing with the "align" program */
{
unsigned int hack = *((char *) skb->data)-'0';
if (hack < 8) {
skb->data += hack;
skb->len -= hack;
}
}
#endif
#if 0 /* should work now */
if ((unsigned long) skb->data & 3)
printk(KERN_ERR DEV_LABEL "(itf %d): VCI %d has mis-aligned "
"TX data\n",vcc->dev->number,vcc->vci);
#endif
/*
* Potential future IP speedup: make hard_header big enough to put
* segmentation descriptor directly into PDU. Saves: 4 slave writes,
* 1 DMA xfer & 2 DMA'ed bytes (protocol layering is for wimps :-)
*/
aal5 = vcc->qos.aal == ATM_AAL5;
/* check space in buffer */
if (!aal5)
size = (ATM_CELL_PAYLOAD >> 2)+TX_DESCR_SIZE;
/* cell without HEC plus segmentation header (includes
four-byte cell header) */
else {
size = skb->len+4*AAL5_TRAILER+ATM_CELL_PAYLOAD-1;
/* add AAL5 trailer */
size = ((size-(size % ATM_CELL_PAYLOAD)) >> 2)+TX_DESCR_SIZE;
/* add segmentation header */
}
/*
* Can I move tx_pos by size bytes without getting closer than TX_GAP
* to the read pointer ? TX_GAP means to leave some space for what
* the manual calls "too close".
*/
if (!NEPMOK(tx->tx_pos,size+TX_GAP,
eni_in(MID_TX_RDPTR(tx->index)),tx->words)) {
DPRINTK(DEV_LABEL "(itf %d): TX full (size %d)\n",
vcc->dev->number,size);
return enq_next;
}
/* check DMA */
dma_wr = eni_in(MID_DMA_WR_TX);
dma_rd = eni_in(MID_DMA_RD_TX);
dma_size = 3; /* JK for descriptor and final fill, plus final size
mis-alignment fix */
DPRINTK("iovcnt = %d\n",skb_shinfo(skb)->nr_frags);
if (!skb_shinfo(skb)->nr_frags) dma_size += 5;
else dma_size += 5*(skb_shinfo(skb)->nr_frags+1);
if (dma_size > TX_DMA_BUF) {
printk(KERN_CRIT DEV_LABEL "(itf %d): needs %d DMA entries "
"(got only %d)\n",vcc->dev->number,dma_size,TX_DMA_BUF);
}
DPRINTK("dma_wr is %d, tx_pos is %ld\n",dma_wr,tx->tx_pos);
if (dma_wr != dma_rd && ((dma_rd+NR_DMA_TX-dma_wr) & (NR_DMA_TX-1)) <
dma_size) {
printk(KERN_WARNING DEV_LABEL "(itf %d): TX DMA full\n",
vcc->dev->number);
return enq_jam;
}
paddr = dma_map_single(&eni_dev->pci_dev->dev,skb->data,skb->len,
DMA_TO_DEVICE);
ENI_PRV_PADDR(skb) = paddr;
/* prepare DMA queue entries */
j = 0;
eni_dev->dma[j++] = (((tx->tx_pos+TX_DESCR_SIZE) & (tx->words-1)) <<
MID_DMA_COUNT_SHIFT) | (tx->index << MID_DMA_CHAN_SHIFT) |
MID_DT_JK;
j++;
if (!skb_shinfo(skb)->nr_frags)
if (aal5) put_dma(tx->index,eni_dev->dma,&j,paddr,skb->len);
else put_dma(tx->index,eni_dev->dma,&j,paddr+4,skb->len-4);
else {
DPRINTK("doing direct send\n"); /* @@@ well, this doesn't work anyway */
for (i = -1; i < skb_shinfo(skb)->nr_frags; i++)
if (i == -1)
put_dma(tx->index,eni_dev->dma,&j,(unsigned long)
skb->data,
skb_headlen(skb));
else
put_dma(tx->index,eni_dev->dma,&j,(unsigned long)
skb_frag_page(&skb_shinfo(skb)->frags[i]) +
skb_shinfo(skb)->frags[i].page_offset,
skb_frag_size(&skb_shinfo(skb)->frags[i]));
}
if (skb->len & 3) {
put_dma(tx->index, eni_dev->dma, &j, eni_dev->zero.dma,
4 - (skb->len & 3));
}
/* JK for AAL5 trailer - AAL0 doesn't need it, but who cares ... */
eni_dev->dma[j++] = (((tx->tx_pos+size) & (tx->words-1)) <<
MID_DMA_COUNT_SHIFT) | (tx->index << MID_DMA_CHAN_SHIFT) |
MID_DMA_END | MID_DT_JK;
j++;
DPRINTK("DMA at end: %d\n",j);
/* store frame */
writel((MID_SEG_TX_ID << MID_SEG_ID_SHIFT) |
(aal5 ? MID_SEG_AAL5 : 0) | (tx->prescaler << MID_SEG_PR_SHIFT) |
(tx->resolution << MID_SEG_RATE_SHIFT) |
(size/(ATM_CELL_PAYLOAD/4)),tx->send+tx->tx_pos*4);
/*printk("dsc = 0x%08lx\n",(unsigned long) readl(tx->send+tx->tx_pos*4));*/
writel((vcc->vci << MID_SEG_VCI_SHIFT) |
(aal5 ? 0 : (skb->data[3] & 0xf)) |
(ATM_SKB(skb)->atm_options & ATM_ATMOPT_CLP ? MID_SEG_CLP : 0),
tx->send+((tx->tx_pos+1) & (tx->words-1))*4);
DPRINTK("size: %d, len:%d\n",size,skb->len);
if (aal5)
writel(skb->len,tx->send+
((tx->tx_pos+size-AAL5_TRAILER) & (tx->words-1))*4);
j = j >> 1;
for (i = 0; i < j; i++) {
writel(eni_dev->dma[i*2],eni_dev->tx_dma+dma_wr*8);
writel(eni_dev->dma[i*2+1],eni_dev->tx_dma+dma_wr*8+4);
dma_wr = (dma_wr+1) & (NR_DMA_TX-1);
}
ENI_PRV_POS(skb) = tx->tx_pos;
ENI_PRV_SIZE(skb) = size;
ENI_VCC(vcc)->txing += size;
tx->tx_pos = (tx->tx_pos+size) & (tx->words-1);
DPRINTK("dma_wr set to %d, tx_pos is now %ld\n",dma_wr,tx->tx_pos);
eni_out(dma_wr,MID_DMA_WR_TX);
skb_queue_tail(&eni_dev->tx_queue,skb);
queued++;
return enq_ok;
}
static void poll_tx(struct atm_dev *dev)
{
struct eni_tx *tx;
struct sk_buff *skb;
enum enq_res res;
int i;
DPRINTK(">poll_tx\n");
for (i = NR_CHAN-1; i >= 0; i
tx = &ENI_DEV(dev)->tx[i];
if (tx->send)
while ((skb = skb_dequeue(&tx->backlog))) {
res = do_tx(skb);
if (res == enq_ok) continue;
DPRINTK("re-queuing TX PDU\n");
skb_queue_head(&tx->backlog,skb);
requeued++;
if (res == enq_jam) return;
break;
}
}
}
static void dequeue_tx(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
struct atm_vcc *vcc;
struct sk_buff *skb;
struct eni_tx *tx;
NULLCHECK(dev);
eni_dev = ENI_DEV(dev);
NULLCHECK(eni_dev);
while ((skb = skb_dequeue(&eni_dev->tx_queue))) {
vcc = ATM_SKB(skb)->vcc;
NULLCHECK(vcc);
tx = ENI_VCC(vcc)->tx;
NULLCHECK(ENI_VCC(vcc)->tx);
DPRINTK("dequeue_tx: next 0x%lx curr 0x%x\n",ENI_PRV_POS(skb),
(unsigned) eni_in(MID_TX_DESCRSTART(tx->index)));
if (ENI_VCC(vcc)->txing < tx->words && ENI_PRV_POS(skb) ==
eni_in(MID_TX_DESCRSTART(tx->index))) {
skb_queue_head(&eni_dev->tx_queue,skb);
break;
}
ENI_VCC(vcc)->txing -= ENI_PRV_SIZE(skb);
dma_unmap_single(&eni_dev->pci_dev->dev,ENI_PRV_PADDR(skb),skb->len,
DMA_TO_DEVICE);
if (vcc->pop) vcc->pop(vcc,skb);
else dev_kfree_skb_irq(skb);
<API key>(&vcc->stats->tx);
wake_up(&eni_dev->tx_wait);
dma_complete++;
}
}
static struct eni_tx *alloc_tx(struct eni_dev *eni_dev,int ubr)
{
int i;
for (i = !ubr; i < NR_CHAN; i++)
if (!eni_dev->tx[i].send) return eni_dev->tx+i;
return NULL;
}
static int comp_tx(struct eni_dev *eni_dev,int *pcr,int reserved,int *pre,
int *res,int unlimited)
{
static const int pre_div[] = { 4,16,128,2048 };
/* 2^(((x+2)^2-(x+2))/2+1) */
if (unlimited) *pre = *res = 0;
else {
if (*pcr > 0) {
int div;
for (*pre = 0; *pre < 3; (*pre)++)
if (TS_CLOCK/pre_div[*pre]/64 <= *pcr) break;
div = pre_div[*pre]**pcr;
DPRINTK("min div %d\n",div);
*res = TS_CLOCK/div-1;
}
else {
int div;
if (!*pcr) *pcr = eni_dev->tx_bw+reserved;
for (*pre = 3; *pre >= 0; (*pre)
if (TS_CLOCK/pre_div[*pre]/64 > -*pcr) break;
if (*pre < 3) (*pre)++; /* else fail later */
div = pre_div[*pre]*-*pcr;
DPRINTK("max div %d\n",div);
*res = DIV_ROUND_UP(TS_CLOCK, div)-1;
}
if (*res < 0) *res = 0;
if (*res > MID_SEG_MAX_RATE) *res = MID_SEG_MAX_RATE;
}
*pcr = TS_CLOCK/pre_div[*pre]/(*res+1);
DPRINTK("out pcr: %d (%d:%d)\n",*pcr,*pre,*res);
return 0;
}
static int reserve_or_set_tx(struct atm_vcc *vcc,struct atm_trafprm *txtp,
int set_rsv,int set_shp)
{
struct eni_dev *eni_dev = ENI_DEV(vcc->dev);
struct eni_vcc *eni_vcc = ENI_VCC(vcc);
struct eni_tx *tx;
unsigned long size;
void __iomem *mem;
int rate,ubr,unlimited,new_tx;
int pre,res,order;
int error;
rate = atm_pcr_goal(txtp);
ubr = txtp->traffic_class == ATM_UBR;
unlimited = ubr && (!rate || rate <= -ATM_OC3_PCR ||
rate >= ATM_OC3_PCR);
if (!unlimited) {
size = txtp->max_sdu*eni_dev->tx_mult/100;
if (size > MID_MAX_BUF_SIZE && txtp->max_sdu <=
MID_MAX_BUF_SIZE)
size = MID_MAX_BUF_SIZE;
}
else {
if (eni_dev->ubr) {
eni_vcc->tx = eni_dev->ubr;
txtp->pcr = ATM_OC3_PCR;
return 0;
}
size = UBR_BUFFER;
}
new_tx = !eni_vcc->tx;
mem = NULL; /* for gcc */
if (!new_tx) tx = eni_vcc->tx;
else {
mem = eni_alloc_mem(eni_dev,&size);
if (!mem) return -ENOBUFS;
tx = alloc_tx(eni_dev,unlimited);
if (!tx) {
eni_free_mem(eni_dev,mem,size);
return -EBUSY;
}
DPRINTK("got chan %d\n",tx->index);
tx->reserved = tx->shaping = 0;
tx->send = mem;
tx->words = size >> 2;
skb_queue_head_init(&tx->backlog);
for (order = 0; size > (1 << (order+10)); order++);
eni_out((order << MID_SIZE_SHIFT) |
((tx->send-eni_dev->ram) >> (MID_LOC_SKIP+2)),
MID_TX_PLACE(tx->index));
tx->tx_pos = eni_in(MID_TX_DESCRSTART(tx->index)) &
MID_DESCR_START;
}
error = comp_tx(eni_dev,&rate,tx->reserved,&pre,&res,unlimited);
if (!error && txtp->min_pcr > rate) error = -EINVAL;
if (!error && txtp->max_pcr && txtp->max_pcr != ATM_MAX_PCR &&
txtp->max_pcr < rate) error = -EINVAL;
if (!error && !ubr && rate > eni_dev->tx_bw+tx->reserved)
error = -EINVAL;
if (!error && set_rsv && !set_shp && rate < tx->shaping)
error = -EINVAL;
if (!error && !set_rsv && rate > tx->reserved && !ubr)
error = -EINVAL;
if (error) {
if (new_tx) {
tx->send = NULL;
eni_free_mem(eni_dev,mem,size);
}
return error;
}
txtp->pcr = rate;
if (set_rsv && !ubr) {
eni_dev->tx_bw += tx->reserved;
tx->reserved = rate;
eni_dev->tx_bw -= rate;
}
if (set_shp || (unlimited && new_tx)) {
if (unlimited && new_tx) eni_dev->ubr = tx;
tx->prescaler = pre;
tx->resolution = res;
tx->shaping = rate;
}
if (set_shp) eni_vcc->tx = tx;
DPRINTK("rsv %d shp %d\n",tx->reserved,tx->shaping);
return 0;
}
static int open_tx_first(struct atm_vcc *vcc)
{
ENI_VCC(vcc)->tx = NULL;
if (vcc->qos.txtp.traffic_class == ATM_NONE) return 0;
ENI_VCC(vcc)->txing = 0;
return reserve_or_set_tx(vcc,&vcc->qos.txtp,1,1);
}
static int open_tx_second(struct atm_vcc *vcc)
{
return 0; /* nothing to do */
}
static void close_tx(struct atm_vcc *vcc)
{
DECLARE_WAITQUEUE(wait,current);
struct eni_dev *eni_dev;
struct eni_vcc *eni_vcc;
eni_vcc = ENI_VCC(vcc);
if (!eni_vcc->tx) return;
eni_dev = ENI_DEV(vcc->dev);
/* wait for TX queue to drain */
DPRINTK("eni_close: waiting for TX ...\n");
add_wait_queue(&eni_dev->tx_wait,&wait);
set_current_state(<API key>);
for (;;) {
int txing;
tasklet_disable(&eni_dev->task);
txing = skb_peek(&eni_vcc->tx->backlog) || eni_vcc->txing;
tasklet_enable(&eni_dev->task);
if (!txing) break;
DPRINTK("%d TX left\n",eni_vcc->txing);
schedule();
set_current_state(<API key>);
}
set_current_state(TASK_RUNNING);
remove_wait_queue(&eni_dev->tx_wait,&wait);
if (eni_vcc->tx != eni_dev->ubr) {
/*
* Looping a few times in here is probably far cheaper than
* keeping track of TX completions all the time, so let's poll
* a bit ...
*/
while (eni_in(MID_TX_RDPTR(eni_vcc->tx->index)) !=
eni_in(MID_TX_DESCRSTART(eni_vcc->tx->index)))
schedule();
eni_free_mem(eni_dev,eni_vcc->tx->send,eni_vcc->tx->words << 2);
eni_vcc->tx->send = NULL;
eni_dev->tx_bw += eni_vcc->tx->reserved;
}
eni_vcc->tx = NULL;
}
static int start_tx(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
int i;
eni_dev = ENI_DEV(dev);
eni_dev->lost = 0;
eni_dev->tx_bw = ATM_OC3_PCR;
eni_dev->tx_mult = DEFAULT_TX_MULT;
init_waitqueue_head(&eni_dev->tx_wait);
eni_dev->ubr = NULL;
skb_queue_head_init(&eni_dev->tx_queue);
eni_out(0,MID_DMA_WR_TX);
for (i = 0; i < NR_CHAN; i++) {
eni_dev->tx[i].send = NULL;
eni_dev->tx[i].index = i;
}
return 0;
}
#if 0 /* may become useful again when tuning things */
static void foo(void)
{
printk(KERN_INFO
"tx_complete=%d,dma_complete=%d,queued=%d,requeued=%d,sub=%d,\n"
"backlogged=%d,rx_enqueued=%d,rx_dequeued=%d,putting=%d,pushed=%d\n",
tx_complete,dma_complete,queued,requeued,submitted,backlogged,
rx_enqueued,rx_dequeued,putting,pushed);
if (eni_boards) printk(KERN_INFO "loss: %ld\n",ENI_DEV(eni_boards)->lost);
}
#endif
static void bug_int(struct atm_dev *dev,unsigned long reason)
{
DPRINTK(">bug_int\n");
if (reason & MID_DMA_ERR_ACK)
printk(KERN_CRIT DEV_LABEL "(itf %d): driver error - DMA "
"error\n",dev->number);
if (reason & MID_TX_IDENT_MISM)
printk(KERN_CRIT DEV_LABEL "(itf %d): driver error - ident "
"mismatch\n",dev->number);
if (reason & MID_TX_DMA_OVFL)
printk(KERN_CRIT DEV_LABEL "(itf %d): driver error - DMA "
"overflow\n",dev->number);
EVENT("
printk(KERN_NOTICE "
event_dump();
}
static irqreturn_t eni_int(int irq,void *dev_id)
{
struct atm_dev *dev;
struct eni_dev *eni_dev;
u32 reason;
DPRINTK(">eni_int\n");
dev = dev_id;
eni_dev = ENI_DEV(dev);
reason = eni_in(MID_ISA);
DPRINTK(DEV_LABEL ": int 0x%lx\n",(unsigned long) reason);
/*
* Must handle these two right now, because reading ISA doesn't clear
* them, so they re-occur and we never make it to the tasklet. Since
* they're rare, we don't mind the occasional invocation of eni_tasklet
* with eni_dev->events == 0.
*/
if (reason & MID_STAT_OVFL) {
EVENT("stat overflow\n",0,0);
eni_dev->lost += eni_in(MID_STAT) & MID_OVFL_TRASH;
}
if (reason & MID_SUNI_INT) {
EVENT("SUNI int\n",0,0);
dev->phy->interrupt(dev);
#if 0
foo();
#endif
}
spin_lock(&eni_dev->lock);
eni_dev->events |= reason;
spin_unlock(&eni_dev->lock);
tasklet_schedule(&eni_dev->task);
return IRQ_HANDLED;
}
static void eni_tasklet(unsigned long data)
{
struct atm_dev *dev = (struct atm_dev *) data;
struct eni_dev *eni_dev = ENI_DEV(dev);
unsigned long flags;
u32 events;
DPRINTK("eni_tasklet (dev %p)\n",dev);
spin_lock_irqsave(&eni_dev->lock,flags);
events = xchg(&eni_dev->events,0);
<API key>(&eni_dev->lock,flags);
if (events & MID_RX_DMA_COMPLETE) {
EVENT("INT: RX DMA complete, starting dequeue_rx\n",0,0);
dequeue_rx(dev);
EVENT("dequeue_rx done, starting poll_rx\n",0,0);
poll_rx(dev);
EVENT("poll_rx done\n",0,0);
/* poll_tx ? */
}
if (events & MID_SERVICE) {
EVENT("INT: service, starting get_service\n",0,0);
get_service(dev);
EVENT("get_service done, starting poll_rx\n",0,0);
poll_rx(dev);
EVENT("poll_rx done\n",0,0);
}
if (events & MID_TX_DMA_COMPLETE) {
EVENT("INT: TX DMA COMPLETE\n",0,0);
dequeue_tx(dev);
}
if (events & MID_TX_COMPLETE) {
EVENT("INT: TX COMPLETE\n",0,0);
tx_complete++;
wake_up(&eni_dev->tx_wait);
/* poll_rx ? */
}
if (events & (MID_DMA_ERR_ACK | MID_TX_IDENT_MISM | MID_TX_DMA_OVFL)) {
EVENT("bug interrupt\n",0,0);
bug_int(dev,events);
}
poll_tx(dev);
}
static char * const media_name[] = {
"MMF", "SMF", "MMF", "03?", /* 0- 3 */
"UTP", "05?", "06?", "07?", /* 4- 7 */
"TAXI","09?", "10?", "11?", /* 8-11 */
"12?", "13?", "14?", "15?", /* 12-15 */
"MMF", "SMF", "18?", "19?", /* 16-19 */
"UTP", "21?", "22?", "23?", /* 20-23 */
"24?", "25?", "26?", "27?", /* 24-27 */
"28?", "29?", "30?", "31?" /* 28-31 */
};
#define SET_SEPROM \
({ if (!error && !pci_error) { \
pci_error = <API key>(eni_dev->pci_dev,PCI_TONGA_CTRL,tonga); \
udelay(10); /* 10 usecs */ \
} })
#define GET_SEPROM \
({ if (!error && !pci_error) { \
pci_error = <API key>(eni_dev->pci_dev,PCI_TONGA_CTRL,&tonga); \
udelay(10); /* 10 usecs */ \
} })
static int get_esi_asic(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
unsigned char tonga;
int error,failed,pci_error;
int address,i,j;
eni_dev = ENI_DEV(dev);
error = pci_error = 0;
tonga = SEPROM_MAGIC | SEPROM_DATA | SEPROM_CLK;
SET_SEPROM;
for (i = 0; i < ESI_LEN && !error && !pci_error; i++) {
/* start operation */
tonga |= SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
tonga &= ~SEPROM_DATA;
SET_SEPROM;
tonga &= ~SEPROM_CLK;
SET_SEPROM;
/* send address */
address = ((i+SEPROM_ESI_BASE) << 1)+1;
for (j = 7; j >= 0; j
tonga = (address >> j) & 1 ? tonga | SEPROM_DATA :
tonga & ~SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
tonga &= ~SEPROM_CLK;
SET_SEPROM;
}
/* get ack */
tonga |= SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
GET_SEPROM;
failed = tonga & SEPROM_DATA;
tonga &= ~SEPROM_CLK;
SET_SEPROM;
tonga |= SEPROM_DATA;
SET_SEPROM;
if (failed) error = -EIO;
else {
dev->esi[i] = 0;
for (j = 7; j >= 0; j
dev->esi[i] <<= 1;
tonga |= SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
GET_SEPROM;
if (tonga & SEPROM_DATA) dev->esi[i] |= 1;
tonga &= ~SEPROM_CLK;
SET_SEPROM;
tonga |= SEPROM_DATA;
SET_SEPROM;
}
/* get ack */
tonga |= SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
GET_SEPROM;
if (!(tonga & SEPROM_DATA)) error = -EIO;
tonga &= ~SEPROM_CLK;
SET_SEPROM;
tonga |= SEPROM_DATA;
SET_SEPROM;
}
/* stop operation */
tonga &= ~SEPROM_DATA;
SET_SEPROM;
tonga |= SEPROM_CLK;
SET_SEPROM;
tonga |= SEPROM_DATA;
SET_SEPROM;
}
if (pci_error) {
printk(KERN_ERR DEV_LABEL "(itf %d): error reading ESI "
"(0x%02x)\n",dev->number,pci_error);
error = -EIO;
}
return error;
}
#undef SET_SEPROM
#undef GET_SEPROM
static int get_esi_fpga(struct atm_dev *dev, void __iomem *base)
{
void __iomem *mac_base;
int i;
mac_base = base+EPROM_SIZE-sizeof(struct midway_eprom);
for (i = 0; i < ESI_LEN; i++) dev->esi[i] = readb(mac_base+(i^3));
return 0;
}
static int eni_do_init(struct atm_dev *dev)
{
struct midway_eprom __iomem *eprom;
struct eni_dev *eni_dev;
struct pci_dev *pci_dev;
unsigned long real_base;
void __iomem *base;
int error,i,last;
DPRINTK(">eni_init\n");
dev->ci_range.vpi_bits = 0;
dev->ci_range.vci_bits = NR_VCI_LD;
dev->link_rate = ATM_OC3_PCR;
eni_dev = ENI_DEV(dev);
pci_dev = eni_dev->pci_dev;
real_base = pci_resource_start(pci_dev, 0);
eni_dev->irq = pci_dev->irq;
if ((error = <API key>(pci_dev,PCI_COMMAND,
PCI_COMMAND_MEMORY |
(eni_dev->asic ? PCI_COMMAND_PARITY | PCI_COMMAND_SERR : 0)))) {
printk(KERN_ERR DEV_LABEL "(itf %d): can't enable memory "
"(0x%02x)\n",dev->number,error);
return -EIO;
}
printk(KERN_NOTICE DEV_LABEL "(itf %d): rev.%d,base=0x%lx,irq=%d,",
dev->number,pci_dev->revision,real_base,eni_dev->irq);
if (!(base = ioremap_nocache(real_base,MAP_MAX_SIZE))) {
printk("\n");
printk(KERN_ERR DEV_LABEL "(itf %d): can't set up page "
"mapping\n",dev->number);
return -ENOMEM;
}
eni_dev->ioaddr = base;
eni_dev->base_diff = real_base - (unsigned long) base;
/* id may not be present in ASIC Tonga boards - check this @@@ */
if (!eni_dev->asic) {
eprom = (base+EPROM_SIZE-sizeof(struct midway_eprom));
if (readl(&eprom->magic) != ENI155_MAGIC) {
printk("\n");
printk(KERN_ERR DEV_LABEL
"(itf %d): bad magic - expected 0x%x, got 0x%x\n",
dev->number, ENI155_MAGIC,
(unsigned)readl(&eprom->magic));
error = -EINVAL;
goto unmap;
}
}
eni_dev->phy = base+PHY_BASE;
eni_dev->reg = base+REG_BASE;
eni_dev->ram = base+RAM_BASE;
last = <API key>;
for (i = last-RAM_INCREMENT; i >= 0; i -= RAM_INCREMENT) {
writel(0x55555555,eni_dev->ram+i);
if (readl(eni_dev->ram+i) != 0x55555555) last = i;
else {
writel(0xAAAAAAAA,eni_dev->ram+i);
if (readl(eni_dev->ram+i) != 0xAAAAAAAA) last = i;
else writel(i,eni_dev->ram+i);
}
}
for (i = 0; i < last; i += RAM_INCREMENT)
if (readl(eni_dev->ram+i) != i) break;
eni_dev->mem = i;
memset_io(eni_dev->ram,0,eni_dev->mem);
/* TODO: should shrink allocation now */
printk("mem=%dkB (",eni_dev->mem >> 10);
/* TODO: check for non-SUNI, check for TAXI ? */
if (!(eni_in(MID_RES_ID_MCON) & 0x200) != !eni_dev->asic) {
printk(")\n");
printk(KERN_ERR DEV_LABEL "(itf %d): ERROR - wrong id 0x%x\n",
dev->number,(unsigned) eni_in(MID_RES_ID_MCON));
error = -EINVAL;
goto unmap;
}
error = eni_dev->asic ? get_esi_asic(dev) : get_esi_fpga(dev,base);
if (error)
goto unmap;
for (i = 0; i < ESI_LEN; i++)
printk("%s%02X",i ? "-" : "",dev->esi[i]);
printk(")\n");
printk(KERN_NOTICE DEV_LABEL "(itf %d): %s,%s\n",dev->number,
eni_in(MID_RES_ID_MCON) & 0x200 ? "ASIC" : "FPGA",
media_name[eni_in(MID_RES_ID_MCON) & DAUGTHER_ID]);
error = suni_init(dev);
if (error)
goto unmap;
out:
return error;
unmap:
iounmap(base);
goto out;
}
static void eni_do_release(struct atm_dev *dev)
{
struct eni_dev *ed = ENI_DEV(dev);
dev->phy->stop(dev);
dev->phy = NULL;
iounmap(ed->ioaddr);
}
static int eni_start(struct atm_dev *dev)
{
struct eni_dev *eni_dev;
void __iomem *buf;
unsigned long buffer_mem;
int error;
DPRINTK(">eni_start\n");
eni_dev = ENI_DEV(dev);
if (request_irq(eni_dev->irq,&eni_int,IRQF_SHARED,DEV_LABEL,dev)) {
printk(KERN_ERR DEV_LABEL "(itf %d): IRQ%d is already in use\n",
dev->number,eni_dev->irq);
error = -EAGAIN;
goto out;
}
pci_set_master(eni_dev->pci_dev);
if ((error = <API key>(eni_dev->pci_dev,PCI_COMMAND,
PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER |
(eni_dev->asic ? PCI_COMMAND_PARITY | PCI_COMMAND_SERR : 0)))) {
printk(KERN_ERR DEV_LABEL "(itf %d): can't enable memory+"
"master (0x%02x)\n",dev->number,error);
goto free_irq;
}
if ((error = <API key>(eni_dev->pci_dev,PCI_TONGA_CTRL,
END_SWAP_DMA))) {
printk(KERN_ERR DEV_LABEL "(itf %d): can't set endian swap "
"(0x%02x)\n",dev->number,error);
goto free_irq;
}
/* determine addresses of internal tables */
eni_dev->vci = eni_dev->ram;
eni_dev->rx_dma = eni_dev->ram+NR_VCI*16;
eni_dev->tx_dma = eni_dev->rx_dma+NR_DMA_RX*8;
eni_dev->service = eni_dev->tx_dma+NR_DMA_TX*8;
buf = eni_dev->service+NR_SERVICE*4;
DPRINTK("vci 0x%lx,rx 0x%lx, tx 0x%lx,srv 0x%lx,buf 0x%lx\n",
eni_dev->vci,eni_dev->rx_dma,eni_dev->tx_dma,
eni_dev->service,buf);
spin_lock_init(&eni_dev->lock);
tasklet_init(&eni_dev->task,eni_tasklet,(unsigned long) dev);
eni_dev->events = 0;
/* initialize memory management */
buffer_mem = eni_dev->mem - (buf - eni_dev->ram);
eni_dev->free_list_size = buffer_mem/MID_MIN_BUF_SIZE/2;
eni_dev->free_list = kmalloc_array(eni_dev->free_list_size + 1,
sizeof(*eni_dev->free_list),
GFP_KERNEL);
if (!eni_dev->free_list) {
printk(KERN_ERR DEV_LABEL "(itf %d): couldn't get free page\n",
dev->number);
error = -ENOMEM;
goto free_irq;
}
eni_dev->free_len = 0;
eni_put_free(eni_dev,buf,buffer_mem);
memset_io(eni_dev->vci,0,16*NR_VCI); /* clear VCI table */
/*
* byte_addr free (k)
* 0x00000000 512 VCI table
* 0x00004000 496 RX DMA
* 0x00005000 492 TX DMA
* 0x00006000 488 service list
* 0x00007000 484 buffers
* 0x00080000 0 end (512kB)
*/
eni_out(0xffffffff,MID_IE);
error = start_tx(dev);
if (error) goto free_list;
error = start_rx(dev);
if (error) goto free_list;
error = dev->phy->start(dev);
if (error) goto free_list;
eni_out(eni_in(MID_MC_S) | (1 << MID_INT_SEL_SHIFT) |
MID_TX_LOCK_MODE | MID_DMA_ENABLE | MID_TX_ENABLE | MID_RX_ENABLE,
MID_MC_S);
/* Tonga uses SBus INTReq1 */
(void) eni_in(MID_ISA); /* clear Midway interrupts */
return 0;
free_list:
kfree(eni_dev->free_list);
free_irq:
free_irq(eni_dev->irq, dev);
out:
return error;
}
static void eni_close(struct atm_vcc *vcc)
{
DPRINTK(">eni_close\n");
if (!ENI_VCC(vcc)) return;
clear_bit(ATM_VF_READY,&vcc->flags);
close_rx(vcc);
close_tx(vcc);
DPRINTK("eni_close: done waiting\n");
/* deallocate memory */
kfree(ENI_VCC(vcc));
vcc->dev_data = NULL;
clear_bit(ATM_VF_ADDR,&vcc->flags);
/*foo();*/
}
static int eni_open(struct atm_vcc *vcc)
{
struct eni_vcc *eni_vcc;
int error;
short vpi = vcc->vpi;
int vci = vcc->vci;
DPRINTK(">eni_open\n");
EVENT("eni_open\n",0,0);
if (!test_bit(ATM_VF_PARTIAL,&vcc->flags))
vcc->dev_data = NULL;
if (vci != ATM_VPI_UNSPEC && vpi != ATM_VCI_UNSPEC)
set_bit(ATM_VF_ADDR,&vcc->flags);
if (vcc->qos.aal != ATM_AAL0 && vcc->qos.aal != ATM_AAL5)
return -EINVAL;
DPRINTK(DEV_LABEL "(itf %d): open %d.%d\n",vcc->dev->number,vcc->vpi,
vcc->vci);
if (!test_bit(ATM_VF_PARTIAL,&vcc->flags)) {
eni_vcc = kmalloc(sizeof(struct eni_vcc),GFP_KERNEL);
if (!eni_vcc) return -ENOMEM;
vcc->dev_data = eni_vcc;
eni_vcc->tx = NULL; /* for eni_close after open_rx */
if ((error = open_rx_first(vcc))) {
eni_close(vcc);
return error;
}
if ((error = open_tx_first(vcc))) {
eni_close(vcc);
return error;
}
}
if (vci == ATM_VPI_UNSPEC || vpi == ATM_VCI_UNSPEC) return 0;
if ((error = open_rx_second(vcc))) {
eni_close(vcc);
return error;
}
if ((error = open_tx_second(vcc))) {
eni_close(vcc);
return error;
}
set_bit(ATM_VF_READY,&vcc->flags);
/* should power down SUNI while !ref_count @@@ */
return 0;
}
static int eni_change_qos(struct atm_vcc *vcc,struct atm_qos *qos,int flgs)
{
struct eni_dev *eni_dev = ENI_DEV(vcc->dev);
struct eni_tx *tx = ENI_VCC(vcc)->tx;
struct sk_buff *skb;
int error,rate,rsv,shp;
if (qos->txtp.traffic_class == ATM_NONE) return 0;
if (tx == eni_dev->ubr) return -EBADFD;
rate = atm_pcr_goal(&qos->txtp);
if (rate < 0) rate = -rate;
rsv = shp = 0;
if ((flgs & ATM_MF_DEC_RSV) && rate && rate < tx->reserved) rsv = 1;
if ((flgs & ATM_MF_INC_RSV) && (!rate || rate > tx->reserved)) rsv = 1;
if ((flgs & ATM_MF_DEC_SHP) && rate && rate < tx->shaping) shp = 1;
if ((flgs & ATM_MF_INC_SHP) && (!rate || rate > tx->shaping)) shp = 1;
if (!rsv && !shp) return 0;
error = reserve_or_set_tx(vcc,&qos->txtp,rsv,shp);
if (error) return error;
if (shp && !(flgs & ATM_MF_IMMED)) return 0;
/*
* Walk through the send buffer and patch the rate information in all
* segmentation buffer descriptors of this VCC.
*/
tasklet_disable(&eni_dev->task);
skb_queue_walk(&eni_dev->tx_queue, skb) {
void __iomem *dsc;
if (ATM_SKB(skb)->vcc != vcc) continue;
dsc = tx->send+ENI_PRV_POS(skb)*4;
writel((readl(dsc) & ~(MID_SEG_RATE | MID_SEG_PR)) |
(tx->prescaler << MID_SEG_PR_SHIFT) |
(tx->resolution << MID_SEG_RATE_SHIFT), dsc);
}
tasklet_enable(&eni_dev->task);
return 0;
}
static int eni_ioctl(struct atm_dev *dev,unsigned int cmd,void __user *arg)
{
struct eni_dev *eni_dev = ENI_DEV(dev);
if (cmd == ENI_MEMDUMP) {
if (!capable(CAP_NET_ADMIN)) return -EPERM;
printk(KERN_WARNING "Please use /proc/atm/" DEV_LABEL ":%d "
"instead of obsolete ioctl ENI_MEMDUMP\n",dev->number);
dump(dev);
return 0;
}
if (cmd == ENI_SETMULT) {
struct eni_multipliers mult;
if (!capable(CAP_NET_ADMIN)) return -EPERM;
if (copy_from_user(&mult, arg,
sizeof(struct eni_multipliers)))
return -EFAULT;
if ((mult.tx && mult.tx <= 100) || (mult.rx &&mult.rx <= 100) ||
mult.tx > 65536 || mult.rx > 65536)
return -EINVAL;
if (mult.tx) eni_dev->tx_mult = mult.tx;
if (mult.rx) eni_dev->rx_mult = mult.rx;
return 0;
}
if (cmd == ATM_SETCIRANGE) {
struct atm_cirange ci;
if (copy_from_user(&ci, arg,sizeof(struct atm_cirange)))
return -EFAULT;
if ((ci.vpi_bits == 0 || ci.vpi_bits == ATM_CI_MAX) &&
(ci.vci_bits == NR_VCI_LD || ci.vpi_bits == ATM_CI_MAX))
return 0;
return -EINVAL;
}
if (!dev->phy->ioctl) return -ENOIOCTLCMD;
return dev->phy->ioctl(dev,cmd,arg);
}
static int eni_getsockopt(struct atm_vcc *vcc,int level,int optname,
void __user *optval,int optlen)
{
return -EINVAL;
}
static int eni_setsockopt(struct atm_vcc *vcc,int level,int optname,
void __user *optval,unsigned int optlen)
{
return -EINVAL;
}
static int eni_send(struct atm_vcc *vcc,struct sk_buff *skb)
{
enum enq_res res;
DPRINTK(">eni_send\n");
if (!ENI_VCC(vcc)->tx) {
if (vcc->pop) vcc->pop(vcc,skb);
else dev_kfree_skb(skb);
return -EINVAL;
}
if (!skb) {
printk(KERN_CRIT "!skb in eni_send ?\n");
if (vcc->pop) vcc->pop(vcc,skb);
return -EINVAL;
}
if (vcc->qos.aal == ATM_AAL0) {
if (skb->len != ATM_CELL_SIZE-1) {
if (vcc->pop) vcc->pop(vcc,skb);
else dev_kfree_skb(skb);
return -EINVAL;
}
*(u32 *) skb->data = htonl(*(u32 *) skb->data);
}
submitted++;
ATM_SKB(skb)->vcc = vcc;
tasklet_disable(&ENI_DEV(vcc->dev)->task);
res = do_tx(skb);
tasklet_enable(&ENI_DEV(vcc->dev)->task);
if (res == enq_ok) return 0;
skb_queue_tail(&ENI_VCC(vcc)->tx->backlog,skb);
backlogged++;
tasklet_schedule(&ENI_DEV(vcc->dev)->task);
return 0;
}
static void eni_phy_put(struct atm_dev *dev,unsigned char value,
unsigned long addr)
{
writel(value,ENI_DEV(dev)->phy+addr*4);
}
static unsigned char eni_phy_get(struct atm_dev *dev,unsigned long addr)
{
return readl(ENI_DEV(dev)->phy+addr*4);
}
static int eni_proc_read(struct atm_dev *dev,loff_t *pos,char *page)
{
struct sock *s;
static const char *signal[] = { "LOST","unknown","okay" };
struct eni_dev *eni_dev = ENI_DEV(dev);
struct atm_vcc *vcc;
int left,i;
left = *pos;
if (!left)
return sprintf(page,DEV_LABEL "(itf %d) signal %s, %dkB, "
"%d cps remaining\n",dev->number,signal[(int) dev->signal],
eni_dev->mem >> 10,eni_dev->tx_bw);
if (!--left)
return sprintf(page,"%4sBursts: TX"
#if !defined(<API key>) && \
!defined(<API key>) && \
!defined(<API key>) && \
!defined(<API key>)
" none"
#endif
#ifdef <API key>
" 16W"
#endif
#ifdef <API key>
" 8W"
#endif
#ifdef <API key>
" 4W"
#endif
#ifdef <API key>
" 2W"
#endif
", RX"
#if !defined(<API key>) && \
!defined(<API key>) && \
!defined(<API key>) && \
!defined(<API key>)
" none"
#endif
#ifdef <API key>
" 16W"
#endif
#ifdef <API key>
" 8W"
#endif
#ifdef <API key>
" 4W"
#endif
#ifdef <API key>
" 2W"
#endif
#ifndef <API key>
" (default)"
#endif
"\n","");
if (!--left)
return sprintf(page,"%4sBuffer multipliers: tx %d%%, rx %d%%\n",
"",eni_dev->tx_mult,eni_dev->rx_mult);
for (i = 0; i < NR_CHAN; i++) {
struct eni_tx *tx = eni_dev->tx+i;
if (!tx->send) continue;
if (!--left) {
return sprintf(page, "tx[%d]: 0x%lx-0x%lx "
"(%6ld bytes), rsv %d cps, shp %d cps%s\n",i,
(unsigned long) (tx->send - eni_dev->ram),
tx->send-eni_dev->ram+tx->words*4-1,tx->words*4,
tx->reserved,tx->shaping,
tx == eni_dev->ubr ? " (UBR)" : "");
}
if (--left) continue;
return sprintf(page,"%10sbacklog %u packets\n","",
skb_queue_len(&tx->backlog));
}
read_lock(&vcc_sklist_lock);
for(i = 0; i < VCC_HTABLE_SIZE; ++i) {
struct hlist_head *head = &vcc_hash[i];
sk_for_each(s, head) {
struct eni_vcc *eni_vcc;
int length;
vcc = atm_sk(s);
if (vcc->dev != dev)
continue;
eni_vcc = ENI_VCC(vcc);
if (--left) continue;
length = sprintf(page,"vcc %4d: ",vcc->vci);
if (eni_vcc->rx) {
length += sprintf(page+length, "0x%lx-0x%lx "
"(%6ld bytes)",
(unsigned long) (eni_vcc->recv - eni_dev->ram),
eni_vcc->recv-eni_dev->ram+eni_vcc->words*4-1,
eni_vcc->words*4);
if (eni_vcc->tx) length += sprintf(page+length,", ");
}
if (eni_vcc->tx)
length += sprintf(page+length,"tx[%d], txing %d bytes",
eni_vcc->tx->index,eni_vcc->txing);
page[length] = '\n';
read_unlock(&vcc_sklist_lock);
return length+1;
}
}
read_unlock(&vcc_sklist_lock);
for (i = 0; i < eni_dev->free_len; i++) {
struct eni_free *fe = eni_dev->free_list+i;
unsigned long offset;
if (--left) continue;
offset = (unsigned long) eni_dev->ram+eni_dev->base_diff;
return sprintf(page,"free %p-%p (%6d bytes)\n",
fe->start-offset,fe->start-offset+(1 << fe->order)-1,
1 << fe->order);
}
return 0;
}
static const struct atmdev_ops ops = {
.open = eni_open,
.close = eni_close,
.ioctl = eni_ioctl,
.getsockopt = eni_getsockopt,
.setsockopt = eni_setsockopt,
.send = eni_send,
.phy_put = eni_phy_put,
.phy_get = eni_phy_get,
.change_qos = eni_change_qos,
.proc_read = eni_proc_read
};
static int eni_init_one(struct pci_dev *pci_dev,
const struct pci_device_id *ent)
{
struct atm_dev *dev;
struct eni_dev *eni_dev;
struct eni_zero *zero;
int rc;
rc = pci_enable_device(pci_dev);
if (rc < 0)
goto out;
rc = <API key>(&pci_dev->dev, DMA_BIT_MASK(32));
if (rc < 0)
goto out;
rc = -ENOMEM;
eni_dev = kmalloc(sizeof(struct eni_dev), GFP_KERNEL);
if (!eni_dev)
goto err_disable;
zero = &eni_dev->zero;
zero->addr = dma_alloc_coherent(&pci_dev->dev,
ENI_ZEROES_SIZE, &zero->dma, GFP_KERNEL);
if (!zero->addr)
goto err_kfree;
dev = atm_dev_register(DEV_LABEL, &pci_dev->dev, &ops, -1, NULL);
if (!dev)
goto err_free_consistent;
dev->dev_data = eni_dev;
pci_set_drvdata(pci_dev, dev);
eni_dev->pci_dev = pci_dev;
eni_dev->asic = ent->driver_data;
rc = eni_do_init(dev);
if (rc < 0)
goto err_unregister;
rc = eni_start(dev);
if (rc < 0)
goto err_eni_release;
eni_dev->more = eni_boards;
eni_boards = dev;
out:
return rc;
err_eni_release:
eni_do_release(dev);
err_unregister:
atm_dev_deregister(dev);
err_free_consistent:
dma_free_coherent(&pci_dev->dev, ENI_ZEROES_SIZE, zero->addr, zero->dma);
err_kfree:
kfree(eni_dev);
err_disable:
pci_disable_device(pci_dev);
goto out;
}
static struct pci_device_id eni_pci_tbl[] = {
{ PCI_VDEVICE(EF, <API key>), 0 /* FPGA */ },
{ PCI_VDEVICE(EF, <API key>), 1 /* ASIC */ },
{ 0, }
};
MODULE_DEVICE_TABLE(pci,eni_pci_tbl);
static void eni_remove_one(struct pci_dev *pdev)
{
struct atm_dev *dev = pci_get_drvdata(pdev);
struct eni_dev *ed = ENI_DEV(dev);
struct eni_zero *zero = &ed->zero;
eni_do_release(dev);
atm_dev_deregister(dev);
dma_free_coherent(&pdev->dev, ENI_ZEROES_SIZE, zero->addr, zero->dma);
kfree(ed);
pci_disable_device(pdev);
}
static struct pci_driver eni_driver = {
.name = DEV_LABEL,
.id_table = eni_pci_tbl,
.probe = eni_init_one,
.remove = eni_remove_one,
};
static int __init eni_init(void)
{
struct sk_buff *skb; /* dummy for sizeof */
if (sizeof(skb->cb) < sizeof(struct eni_skb_prv)) {
printk(KERN_ERR "eni_detect: skb->cb is too small (%Zd < %Zd)\n",
sizeof(skb->cb),sizeof(struct eni_skb_prv));
return -EIO;
}
return pci_register_driver(&eni_driver);
}
module_init(eni_init);
/* @@@ since exit routine not defined, this module can not be unloaded */
MODULE_LICENSE("GPL"); |
<#import "../layout/defaultLayout.ftl.html" as layout>
<@layout.myLayout "Profile">
<div class="panel panel-default">
<div class="panel panel-primary">
<div class="panel-heading">
Notifications
</div>
<ul class="list-group">
<#list requests as request>
<li href="#" class="list-group-item">
<div class="media">
<div class="media-left media-middle">
<a href="/profile/view/${request.user_a.username}">
<img class="media-object img-rounded avatar-48" src="/assets/img/general/icon-profile.png" alt="Profile picture">
</a>
</div>
<div class="media-body">
<div class="row">
<div class="col-md-10 col-xs-8">
<h4 class="media-heading">
<a href="/profile/view/${request.user_a.username}">
${request.user_a.full_name}
</a>
</h4>
<h6>${request.user_a.status}</h6>
</div>
<div class="col-md-2 col-xs-4">
<div class="btn-group-vertical pull-right">
<button type="button" onclick="location.href='/friends/accept/${request.id}';" class="btn btn-info"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></button>
<button type="button" onclick="location.href='/friends/reject/${request.id}';" class="btn btn-danger"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</div>
</div>
</div>
</div>
</li>
</#list>
</ul>
</div>
<div class="panel-heading">
<h3 class="panel-title">Control panel</h3>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<form method="POST" action="/profile/set">
<div class="input-group">
<input type="text" class="form-control" value="${user.status}" name="content">
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></button>
</span>
</div>
</form>
</div>
</div>
<hr>
<div class="row">
<div class="col-md-2">
<img class="img-rounded img-responsive center-block" src="/assets/img/general/icon-profile.png">
</div>
<!--<div class="col-md-10">-->
<!--<form method="POST" action="/upload">-->
<!--<input type="file" name="avatarimage" accept=".jpeg, .jpg, .jpe, .png">-->
<!--<button type="submit" class="btn btn-default btn-lg btn-block">Send...</button>-->
<!--</form>-->
<!--</div>-->
<form method="post" enctype="multipart/form-data" action="/uploadFinish">
Please specify file to upload: <input type="file" name="upfile"><br />
<input type="submit" value="submit">
</form>
</div>
<hr>
</div>
<div class="panel panel-primary">
<div class="panel-body">
<form method="POST" action="/profile_create">
<div class="input-group">
<input type="date" class="form-control" placeholder="birthday" name="birthday">
<input type="text" class="form-control" placeholder="gender" name="gender">
<input type="text" class="form-control" placeholder="about me" name="aboutme">
</div>
<span class="input-group-btn">
<button class="btn btn-default" type="submit"><span class="glyphicon glyphicon-ok" aria-hidden="true"></span></button>
</span>
</form>
</div>
</div>
</div>
</@layout.myLayout> |
<div class="postbox-container" style="width:20%;">
<div class="metabox-holder">
<div class="meta-box-sortables">
<div class="postbox qoate-right-box">
<h3 class="hndle"><span>Like this plugin?</span></h3>
<div class="inside">
<p>Consider the following options, please:</p>
<ul>
<li>Tell others about this plugin.</li>
<li><a href="http://wordpress.org/extend/plugins/<API key>/" target="_blank">Give a good rating on WordPress.org.</a></li>
<li><a href="http://Qoate.com/donate/" target="_blank">Buy me a beer</a></li>
</ul>
</div>
</div>
<div class="postbox qoate-right-box">
<h3 class="hdnle"><span>Qoate updates..</span></h3>
<div class="inside">
<?php require_once(ABSPATH.WPINC.'/rss.php');
if ( $rss = fetch_rss( 'http://feeds.feedburner.com/qoate' ) ) {
$content = '<ul>';
$rss->items = array_slice( $rss->items, 0, 3 );
foreach ( (array) $rss->items as $item ) {
$content .= '<li>';
$content .= '<a target="_blank" href="'.clean_url( $item['link'], $protocolls=null, 'display' ).'">'. htmlentities($item['title']) .'</a> ';
$content .= '</li>';
}
$content .= '</ul>';
} else {
$content = '<p>No updates..</p>';
} echo $content;?>
</div>
</div>
<div class="postbox qoate-right-box">
<h3 class="hndle"><span>More tools & tips?</span></h3>
<div class="inside">
<p>Looking for more plugins or tips on how to improve your WordPress blog/website?
Check out <a href="http://Qoate.com" target="_blank">Qoate.com</a>.</p>
</div>
</div>
</div>
<br/><br/><br/>
</div>
</div> |
#include <assert.h>
#include <arch/cpu.h>
#include <bootstate.h>
#include <console/console.h>
#include <device/device.h>
#include <device/pci.h>
#include <string.h>
#include <chip.h>
#include <cpu/x86/mtrr.h>
#include <cpu/x86/msr.h>
#include <cpu/x86/lapic.h>
#include <cpu/x86/mp.h>
#include <cpu/intel/common/common.h>
#include <cpu/intel/microcode.h>
#include <cpu/intel/speedstep.h>
#include <cpu/intel/turbo.h>
#include <cpu/x86/cache.h>
#include <cpu/x86/name.h>
#include <cpu/x86/smm.h>
#include <delay.h>
#include <intelblocks/cpulib.h>
#include <intelblocks/fast_spi.h>
#include <intelblocks/mp_init.h>
#include <intelblocks/sgx.h>
#include <intelblocks/smm.h>
#include <soc/cpu.h>
#include <soc/msr.h>
#include <soc/pci_devs.h>
#include <soc/pm.h>
#include <soc/ramstage.h>
#include <soc/smm.h>
#include <soc/systemagent.h>
#include <timer.h>
/* Convert time in seconds to POWER_LIMIT_1_TIME MSR value */
static const u8 <API key>[] = {
[0] = 0x00,
[1] = 0x0a,
[2] = 0x0b,
[3] = 0x4b,
[4] = 0x0c,
[5] = 0x2c,
[6] = 0x4c,
[7] = 0x6c,
[8] = 0x0d,
[10] = 0x2d,
[12] = 0x4d,
[14] = 0x6d,
[16] = 0x0e,
[20] = 0x2e,
[24] = 0x4e,
[28] = 0x6e,
[32] = 0x0f,
[40] = 0x2f,
[48] = 0x4f,
[56] = 0x6f,
[64] = 0x10,
[80] = 0x30,
[96] = 0x50,
[112] = 0x70,
[128] = 0x11,
};
/* Convert POWER_LIMIT_1_TIME MSR value to seconds */
static const u8 <API key>[] = {
[0x00] = 0,
[0x0a] = 1,
[0x0b] = 2,
[0x4b] = 3,
[0x0c] = 4,
[0x2c] = 5,
[0x4c] = 6,
[0x6c] = 7,
[0x0d] = 8,
[0x2d] = 10,
[0x4d] = 12,
[0x6d] = 14,
[0x0e] = 16,
[0x2e] = 20,
[0x4e] = 24,
[0x6e] = 28,
[0x0f] = 32,
[0x2f] = 40,
[0x4f] = 48,
[0x6f] = 56,
[0x10] = 64,
[0x30] = 80,
[0x50] = 96,
[0x70] = 112,
[0x11] = 128,
};
/*
* Configure processor power limits if possible
* This must be done AFTER set of BIOS_RESET_CPL
*/
void set_power_limits(u8 power_limit_1_time)
{
msr_t msr = rdmsr(MSR_PLATFORM_INFO);
msr_t limit;
unsigned int power_unit;
unsigned int tdp, min_power, max_power, max_time, tdp_pl2, tdp_pl1;
u8 power_limit_1_val;
struct device *dev = SA_DEV_ROOT;
config_t *conf = dev->chip_info;
if (power_limit_1_time > ARRAY_SIZE(<API key>))
power_limit_1_time = 28;
if (!(msr.lo & <API key>))
return;
/* Get units */
msr = rdmsr(<API key>);
power_unit = 1 << (msr.lo & 0xf);
/* Get power defaults for this SKU */
msr = rdmsr(MSR_PKG_POWER_SKU);
tdp = msr.lo & 0x7fff;
min_power = (msr.lo >> 16) & 0x7fff;
max_power = msr.hi & 0x7fff;
max_time = (msr.hi >> 16) & 0x7f;
printk(BIOS_DEBUG, "CPU TDP: %u Watts\n", tdp / power_unit);
if (<API key>[max_time] > power_limit_1_time)
power_limit_1_time = <API key>[max_time];
if (min_power > 0 && tdp < min_power)
tdp = min_power;
if (max_power > 0 && tdp > max_power)
tdp = max_power;
power_limit_1_val = <API key>[power_limit_1_time];
/* Set long term power limit to TDP */
limit.lo = 0;
tdp_pl1 = ((conf->tdp_pl1_override == 0) ?
tdp : (conf->tdp_pl1_override * power_unit));
limit.lo |= (tdp_pl1 & <API key>);
/* Set PL1 Pkg Power clamp bit */
limit.lo |= <API key>;
limit.lo |= PKG_POWER_LIMIT_EN;
limit.lo |= (power_limit_1_val & <API key>) <<
<API key>;
/* Set short term power limit to 1.25 * TDP if no config given */
limit.hi = 0;
tdp_pl2 = (conf->tdp_pl2_override == 0) ?
(tdp * 125) / 100 : (conf->tdp_pl2_override * power_unit);
printk(BIOS_DEBUG, "CPU PL2 = %u Watts\n", tdp_pl2 / power_unit);
limit.hi |= (tdp_pl2) & <API key>;
limit.hi |= <API key>;
limit.hi |= PKG_POWER_LIMIT_EN;
/* Power limit 2 time is only programmable on server SKU */
wrmsr(MSR_PKG_POWER_LIMIT, limit);
/* Set PL2 power limit values in MCHBAR and disable PL1 */
MCHBAR32(<API key>) = limit.lo & (~(PKG_POWER_LIMIT_EN));
MCHBAR32(<API key>) = limit.hi;
/* Set PsysPl2 */
if (conf->tdp_psyspl2) {
limit = rdmsr(<API key>);
limit.hi = 0;
printk(BIOS_DEBUG, "CPU PsysPL2 = %u Watts\n",
conf->tdp_psyspl2);
limit.hi |= (conf->tdp_psyspl2 * power_unit) &
<API key>;
limit.hi |= <API key>;
limit.hi |= PKG_POWER_LIMIT_EN;
wrmsr(<API key>, limit);
}
/* Set PsysPl3 */
if (conf->tdp_psyspl3) {
limit = rdmsr(MSR_PL3_CONTROL);
limit.lo = 0;
printk(BIOS_DEBUG, "CPU PsysPL3 = %u Watts\n",
conf->tdp_psyspl3);
limit.lo |= (conf->tdp_psyspl3 * power_unit) &
<API key>;
/* Enable PsysPl3 */
limit.lo |= PKG_POWER_LIMIT_EN;
/* set PsysPl3 time window */
limit.lo |= (conf->tdp_psyspl3_time &
<API key>) <<
<API key>;
/* set PsysPl3 duty cycle */
limit.lo |= (conf-><API key> &
<API key>) <<
<API key>;
wrmsr(MSR_PL3_CONTROL, limit);
}
/* Set Pl4 */
if (conf->tdp_pl4) {
limit = rdmsr(<API key>);
limit.lo = 0;
printk(BIOS_DEBUG, "CPU PL4 = %u Watts\n",
conf->tdp_pl4);
limit.lo |= (conf->tdp_pl4 * power_unit) &
<API key>;
wrmsr(<API key>, limit);
}
/* Set DDR RAPL power limit by copying from MMIO to MSR */
msr.lo = MCHBAR32(<API key>);
msr.hi = MCHBAR32(<API key>);
wrmsr(MSR_DDR_RAPL_LIMIT, msr);
/* Use nominal TDP values for CPUs with configurable TDP */
if (<API key>()) {
msr = rdmsr(<API key>);
limit.hi = 0;
limit.lo = <API key>();
wrmsr(<API key>, limit);
}
}
static void <API key>(void)
{
struct device *dev = SA_DEV_ROOT;
config_t *conf = dev->chip_info;
msr_t msr;
/* Set TCC activation offset if supported */
msr = rdmsr(MSR_PLATFORM_INFO);
if ((msr.lo & (1 << 30)) && conf->tcc_offset) {
msr = rdmsr(<API key>);
msr.lo &= ~(0xf << 24); /* Bits 27:24 */
msr.lo |= (conf->tcc_offset & 0xf) << 24;
wrmsr(<API key>, msr);
}
msr = rdmsr(<API key>);
msr.lo &= ~0x7f; /* Bits 6:0 */
msr.lo |= 0xe6; /* setting 100ms thermal time window */
wrmsr(<API key>, msr);
}
static void configure_isst(void)
{
struct device *dev = SA_DEV_ROOT;
config_t *conf = dev->chip_info;
msr_t msr;
if (conf->speed_shift_enable) {
/*
* Kernel driver checks CPUID.06h:EAX[Bit 7] to determine if HWP
is supported or not. coreboot needs to configure MSR 0x1AA
which is then reflected in the CPUID register.
*/
msr = rdmsr(MSR_MISC_PWR_MGMT);
msr.lo |= <API key>; /* Enable Speed Shift */
msr.lo |= <API key>; /* Enable Interrupt */
msr.lo |= <API key>; /* Enable EPP */
wrmsr(MSR_MISC_PWR_MGMT, msr);
} else {
msr = rdmsr(MSR_MISC_PWR_MGMT);
msr.lo &= ~<API key>; /* Disable Speed Shift */
msr.lo &= ~<API key>; /* Disable Interrupt */
msr.lo &= ~<API key>; /* Disable EPP */
wrmsr(MSR_MISC_PWR_MGMT, msr);
}
}
static void configure_misc(void)
{
struct device *dev = SA_DEV_ROOT;
if (!dev) {
printk(BIOS_ERR, "SA_DEV_ROOT device not found!\n");
return;
}
config_t *conf = dev->chip_info;
msr_t msr;
msr = rdmsr(IA32_MISC_ENABLE);
msr.lo |= (1 << 0); /* Fast String enable */
msr.lo |= (1 << 3); /* TM1/TM2/EMTTM enable */
if (conf->eist_enable)
msr.lo |= (1 << 16); /* Enhanced SpeedStep Enable */
else
msr.lo &= ~(1 << 16); /* Enhanced SpeedStep Disable */
wrmsr(IA32_MISC_ENABLE, msr);
/* Disable Thermal interrupts */
msr.lo = 0;
msr.hi = 0;
wrmsr(<API key>, msr);
/* Enable package critical interrupt only */
msr.lo = 1 << 4;
msr.hi = 0;
wrmsr(<API key>, msr);
msr = rdmsr(MSR_POWER_CTL);
msr.lo |= (1 << 0); /* Enable Bi-directional PROCHOT as an input*/
msr.lo &= ~POWER_CTL_C1E_MASK; /* Disable C1E */
msr.lo |= (1 << 23); /* Lock it */
wrmsr(MSR_POWER_CTL, msr);
}
static void enable_lapic_tpr(void)
{
msr_t msr;
msr = rdmsr(MSR_PIC_MSG_CONTROL);
msr.lo &= ~(1 << 10); /* Enable APIC TPR updates */
wrmsr(MSR_PIC_MSG_CONTROL, msr);
}
static void configure_dca_cap(void)
{
uint32_t feature_flag;
msr_t msr;
/* Check feature flag in CPUID.(EAX=1):ECX[18]==1 */
feature_flag = <API key>();
if (feature_flag & CPUID_DCA) {
msr = rdmsr(<API key>);
msr.lo |= 1;
wrmsr(<API key>, msr);
}
}
static void <API key>(u8 policy)
{
msr_t msr;
int ecx;
/* Determine if energy efficient policy is supported. */
ecx = cpuid_ecx(0x6);
if (!(ecx & (1 << 3)))
return;
/* Energy Policy is bits 3:0 */
msr = rdmsr(<API key>);
msr.lo &= ~0xf;
msr.lo |= policy & 0xf;
wrmsr(<API key>, msr);
printk(BIOS_DEBUG, "cpu: energy policy set to %u\n", policy);
}
static void configure_c_states(void)
{
msr_t msr;
/* C-state Interrupt Response Latency Control 0 - package C3 latency */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS | <API key>;
wrmsr(<API key>, msr);
/* C-state Interrupt Response Latency Control 1 - package C6/C7 short */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS | <API key>;
wrmsr(<API key>, msr);
/* C-state Interrupt Response Latency Control 2 - package C6/C7 long */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS | <API key>;
wrmsr(<API key>, msr);
/* C-state Interrupt Response Latency Control 3 - package C8 */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS |
<API key>;
wrmsr(<API key>, msr);
/* C-state Interrupt Response Latency Control 4 - package C9 */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS |
<API key>;
wrmsr(<API key>, msr);
/* C-state Interrupt Response Latency Control 5 - package C10 */
msr.hi = 0;
msr.lo = IRTL_VALID | IRTL_1024_NS |
<API key>;
wrmsr(<API key>, msr);
}
/*
* The emulated ACPI timer allows disabling of the ACPI timer
* (PM1_TMR) to have no impart on the system.
*/
static void <API key>(void)
{
/* ACPI PM timer emulation */
msr_t msr;
/*
* The derived frequency is calculated as follows:
* (CTC_FREQ * msr[63:32]) >> 32 = target frequency.
* Back solve the multiplier so the 3.579545MHz ACPI timer
* frequency is used.
*/
msr.hi = (3579545ULL << 32) / CTC_FREQ;
/* Set PM1 timer IO port and enable*/
msr.lo = (EMULATE_DELAY_VALUE << <API key>) |
EMULATE_PM_TMR_EN | (ACPI_BASE_ADDRESS + PM1_TMR);
wrmsr(MSR_EMULATE_PM_TMR, msr);
}
/* All CPUs including BSP will run the following function. */
void soc_core_init(struct device *cpu)
{
/* Clear out pending MCEs */
/* TODO(adurbin): This should only be done on a cold boot. Also, some
* of these banks are core vs package scope. For now every CPU clears
* every bank. */
mca_configure(NULL);
/* Enable the local CPU apics */
enable_lapic_tpr();
setup_lapic();
/* Configure c-state interrupt response time */
configure_c_states();
/* Configure Enhanced SpeedStep and Thermal Sensors */
configure_misc();
/* Configure Intel Speed Shift */
configure_isst();
/* Enable ACPI Timer Emulation via MSR 0x121 */
<API key>();
/* Enable Direct Cache Access */
configure_dca_cap();
/* Set energy policy */
<API key>(<API key>);
/* Enable Turbo */
enable_turbo();
/* Configure Core PRMRR for SGX. */
<API key>();
}
static void per_cpu_smm_trigger(void)
{
/* Relocate the SMM handler. */
smm_relocate();
}
static void vmx_configure(void *unused)
{
<API key>();
}
static void fc_lock_configure(void *unused)
{
<API key>();
}
static void post_mp_init(void)
{
/* Set Max Ratio */
cpu_set_max_ratio();
/*
* Now that all APs have been relocated as well as the BSP let SMIs
* start flowing.
*/
<API key>(GBL_EN);
/* Lock down the SMRAM space. */
#if IS_ENABLED(<API key>)
smm_lock();
#endif
mp_run_on_all_cpus(vmx_configure, NULL, 2 * USECS_PER_MSEC);
mp_run_on_all_cpus(sgx_configure, NULL, 14 * USECS_PER_MSEC);
mp_run_on_all_cpus(fc_lock_configure, NULL, 2 * USECS_PER_MSEC);
}
static const struct mp_ops mp_ops = {
/*
* Skip Pre MP init MTRR programming as MTRRs are mirrored from BSP,
* that are set prior to ramstage.
* Real MTRRs programming are being done after resource allocation.
*/
.pre_mp_init = soc_fsp_load,
.get_cpu_count = get_cpu_count,
.get_smm_info = smm_info,
.get_microcode_info = get_microcode_info,
.pre_mp_smm_init = smm_initialize,
.per_cpu_smm_trigger = per_cpu_smm_trigger,
.relocation_handler = <API key>,
.post_mp_init = post_mp_init,
};
void soc_init_cpus(struct bus *cpu_bus)
{
if (mp_init_with_smm(cpu_bus, &mp_ops))
printk(BIOS_ERR, "MP initialization failure.\n");
/* Thermal throttle activation offset */
<API key>();
}
int <API key>(u32 current_patch_id, u32 new_patch_id)
{
msr_t msr1;
msr_t msr2;
/*
* If PRMRR/SGX is supported the FIT microcode load will set the msr
* 0x08b with the Patch revision id one less than the id in the
* microcode binary. The PRMRR support is indicated in the MSR
* MTRRCAP[12]. If SGX is not enabled, check and avoid reloading the
* same microcode during CPU initialization. If SGX is enabled, as
* part of SGX BIOS initialization steps, the same microcode needs to
* be reloaded after the core PRMRR MSRs are programmed.
*/
msr1 = rdmsr(MTRR_CAP_MSR);
msr2 = rdmsr(PRMRR_PHYS_BASE_MSR);
if (msr2.lo && (current_patch_id == new_patch_id - 1))
return 0;
else
return (msr1.lo & PRMRR_SUPPORTED) &&
(current_patch_id == new_patch_id - 1);
}
void cpu_lock_sgx_memory(void)
{
msr_t msr;
msr = rdmsr(MSR_LT_LOCK_MEMORY);
if ((msr.lo & 1) == 0) {
msr.lo |= 1; /* Lock it */
wrmsr(MSR_LT_LOCK_MEMORY, msr);
}
}
int soc_fill_sgx_param(struct sgx_param *sgx_param)
{
struct device *dev = SA_DEV_ROOT;
config_t *conf;
if (!dev) {
printk(BIOS_ERR, "Failed to get root dev for checking SGX param\n");
return -1;
}
conf = dev->chip_info;
if (!conf) {
printk(BIOS_ERR, "Failed to get chip_info for SGX param\n");
return -1;
}
sgx_param->enable = conf->sgx_enable;
return 0;
} |
<?php
return array (
/**
* Menu items and titles
*/
'pages' => "Pagina's",
'pages:owner' => "Pagina's van %s",
'pages:friends' => "Pagina's van vrienden",
'pages:all' => "Alle sitepagina's",
'pages:add' => "Voeg pagina toe",
'pages:group' => "Groepspagina's",
'groups:enablepages' => 'Schakel groepspagina\'s in',
'pages:new' => "Een nieuwe pagina",
'pages:edit' => "Bewerk deze pagina",
'pages:delete' => "Verwijder deze pagina",
'pages:history' => "Paginageschiedenis",
'pages:view' => "Bekijk pagina",
'pages:revision' => "Revisie",
'pages:current_revision' => "Huidige revisie",
'pages:revert' => "Herstel",
'pages:navigation' => "Paginanavigatie",
'pages:notify:summary' => 'Nieuwe pagina met de titel %s',
'pages:notify:subject' => "Een nieuwe pagina: %s",
'pages:notify:body' => 'Hallo!
%s heeft een nieuwe pagina gemaakt.
%s
%s
Je kunt de pagina hier lezen:
%s
Dit is een automatisch aangemaakt bericht. Je kunt hier niet op reageren.
',
'item:object:page_top' => 'Hoofdpagina\'s',
'item:object:page' => 'Pagina\'s',
'pages:nogroup' => 'Deze groep heeft nog geen pagina\'s',
'pages:more' => 'Meer pagina\'s',
'pages:none' => 'Nog geen pagina\'s aangemaakt',
/**
* River
*/
'river:create:object:page' => '%s maakte de pagina \'%s\'',
'river:create:object:page_top' => '%s maakte de pagina \'%s\'',
'river:update:object:page' => '%s bewerkte de pagina \'%s\'',
'river:update:object:page_top' => '%s bewerkte de pagina \'%s\'',
'river:comment:object:page' => '%s reageerde op de pagina \'%s\'',
'river:comment:object:page_top' => '%s reageerde op de pagina \'%s\'',
/**
* Form fields
*/
'pages:title' => 'Paginatitel',
'pages:description' => 'Jouw tekst',
'pages:tags' => 'Tags',
'pages:parent_guid' => 'Hoofdpagina',
'pages:access_id' => 'Toegang',
'pages:write_access_id' => 'Schrijfrechten',
/**
* Status and error messages
*/
'pages:noaccess' => 'Geen toegang tot de pagina',
'pages:cantedit' => 'Je kunt deze pagina niet bewerken',
'pages:saved' => 'Pagina opgeslagen',
'pages:notsaved' => 'Pagina kon niet worden opgeslagen',
'pages:error:no_title' => 'Je moet een titel opgeven voor deze pagina.',
'pages:delete:success' => 'Je pagina is succesvol verwijderd.',
'pages:delete:failure' => 'De pagina kon niet worden verwijderd.',
'pages:revision:delete:success' => 'De paginarevisie is succesvol verwijderd.',
'pages:revision:delete:failure' => 'De paginarevisie kon niet worden verwijderd.',
'pages:revision:not_found' => 'Kan deze revisie niet vinden',
/**
* Page
*/
'pages:strapline' => 'Laatst bijgewerkt: \'%s\' door %s',
/**
* History
*/
'pages:revision:subtitle' => 'Revisie van de pagina \'%s\' door %s',
/**
* Widget
*/
'pages:num' => 'Aantal pagina\'s om weer te geven',
'pages:widget:description' => "Dit is een lijst met jouw pagina's.",
/**
* Submenu items
*/
'pages:label:view' => "Bekijk pagina",
'pages:label:edit' => "Bewerk pagina",
'pages:label:history' => "Paginageschiedenis",
/**
* Sidebar items
*/
'pages:sidebar:this' => "Deze pagina",
'pages:sidebar:children' => "Subpagina's",
'pages:sidebar:parent' => "Hoofdpagina",
'pages:newchild' => "Maak een subpagina",
'pages:backtoparent' => "Terug naar '%s'"
); |
<?php
// no direct access
defined('_JEXEC') or die('Restricted access');
$lang = JFactory::getLanguage();
$language_tag = $lang->getTag();
$lang->load('com_maqmahelpdesk', JPATH_SITE, $language_tag, true);
jimport('joomla.plugin.plugin');
$option = JRequest::getVar('option', '', 'REQUEST', 'string');
class plgSearchKB extends JPlugin
{
public function __construct(& $subject, $config)
{
parent::__construct($subject, $config);
}
function <API key>()
{
/*static $areas = array(
'kb' => JText::_('kb')
);
return $areas;*/
}
function onContentSearch($text, $phrase = '', $ordering = '', $areas = null)
{
$database = JFactory::getDBO();
$text = trim($text);
if ($text == '') {
return array();
}
$section = JText::_('kb');
$wheres = array();
switch ($phrase) {
case 'exact':
$wheres2 = array();
$wheres2[] = "LOWER(a.content) LIKE '%$text%'";
$where = '(' . implode(') OR (', $wheres2) . ')';
break;
case 'all':
case 'any':
default:
$words = explode(' ', $text);
$wheres = array();
foreach ($words as $word) {
$wheres2 = array();
$wheres2[] = "LOWER(a.content) LIKE '%$word%'";
$wheres2[] = "LOWER(a.keywords) LIKE '%$word%'";
$wheres[] = implode(' OR ', $wheres2);
}
$where = '(' . implode(($phrase == 'all' ? ') AND (' : ') OR ('), $wheres) . ')';
break;
}
switch ($ordering) {
case 'oldest':
$order = 'a.date_created ASC';
break;
case 'popular':
$order = 'a.views DESC';
break;
case 'alpha':
$order = 'a.kbtitle ASC';
break;
case 'category':
$order = 'd.wkdesc ASC, c.name ASC, a.kbtitle ASC';
break;
case 'newest':
default:
$order = 'a.date_created DESC';
}
// Get the Workgroups the user can access to filter below
// TODO ...
// Get the Item ID
$database->setQuery("select id from `#__menu` where link='index.php?option=com_maqmahelpdesk'");
$item_id = $database->loadResult();
$query = "SELECT a.kbtitle AS title,"
. "\n a.content AS text,"
. "\n a.date_created AS created,"
. "\n CONCAT_WS( ' / ', '$section', d.wkdesc, c.name ) AS section,"
. "\n '2' AS browsernav,"
. "\n CONCAT('index.php?option=com_maqmahelpdesk&Itemid=', $item_id, '&id_workgroup=', d.id, '&task=kb_view&id=', a.id) AS href"
. "\n FROM #__support_kb AS a"
. "\n INNER JOIN #<API key> AS b ON b.id_kb = a.id"
. "\n INNER JOIN #__support_category AS c ON c.id = b.id_category"
. "\n INNER JOIN #__support_workgroup AS d ON d.id = c.id_workgroup"
. "\n WHERE ($where)"
. "\n AND a.publish = 1"
. "\n ORDER BY $order";
$database->setQuery($query);
$rows = $database->loadObjectList();
return $rows;
}
} |
import os
import time
import cPickle
from Plugins.Plugin import PluginDescriptor
from Screens.Console import Console
from Screens.ChoiceBox import ChoiceBox
from Screens.MessageBox import MessageBox
from Screens.Screen import Screen
from Screens.Standby import TryQuitMainloop
from Screens.Ipkg import Ipkg
from Screens.SoftwareUpdate import UpdatePlugin
from Components.ActionMap import ActionMap, NumberActionMap
from Components.Input import Input
from Components.Ipkg import IpkgComponent
from Components.Sources.StaticText import StaticText
from Components.ScrollLabel import ScrollLabel
from Components.Pixmap import Pixmap
from Components.MenuList import MenuList
from Components.Sources.List import List
from Components.Slider import Slider
from Components.Harddisk import harddiskmanager
from Components.config import config,getConfigListEntry, ConfigSubsection, ConfigText, ConfigLocations, ConfigYesNo, ConfigSelection
from Components.ConfigList import ConfigListScreen
from Components.Console import Console
from Components.MultiContent import <API key>, <API key>
from Components.SelectionList import SelectionList
from Components.PluginComponent import plugins
from Components.About import about
from Components.PackageInfo import PackageInfoHandler
from Components.Language import language
from Components.AVSwitch import AVSwitch
from Components.Task import job_manager
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, <API key>, SCOPE_CURRENT_SKIN, SCOPE_METADIR
from Tools.LoadPixmap import LoadPixmap
from Tools.NumericalTextInput import NumericalTextInput
from enigma import eTimer, RT_HALIGN_LEFT, RT_VALIGN_CENTER, <API key>, eListbox, gFont, getDesktop, ePicLoad, eRCInput, getPrevAsciiCode, eEnv, iRecordableService
from twisted.web import client
from twisted.internet import reactor
from ImageWizard import ImageWizard
from BackupRestore import BackupSelection, RestoreMenu, BackupScreen, RestoreScreen, getBackupPath, getBackupFilename
from SoftwareTools import iSoftwareTools
config.plugins.configurationbackup = ConfigSubsection()
config.plugins.configurationbackup.backuplocation = ConfigText(default = '/media/hdd/', visible_width = 50, fixed_size = False)
config.plugins.configurationbackup.backupdirs = ConfigLocations(default=[eEnv.resolve('${sysconfdir}/enigma2/'), '/etc/network/interfaces', '/etc/wpa_supplicant.conf', '/etc/wpa_supplicant.ath0.conf', '/etc/wpa_supplicant.wlan0.conf', '/etc/resolv.conf', '/etc/default_gw', '/etc/hostname'])
config.plugins.softwaremanager = ConfigSubsection()
config.plugins.softwaremanager.<API key> = ConfigSelection(
[
("Y", _("Yes, always")),
("N", _("No, never")),
("ask", _("Always ask"))
], "Y")
config.plugins.softwaremanager.onSetupMenu = ConfigYesNo(default=False)
config.plugins.softwaremanager.onBlueButton = ConfigYesNo(default=False)
config.plugins.softwaremanager.epgcache = ConfigYesNo(default=False)
def write_cache(cache_file, cache_data):
try:
path = os.path.dirname(cache_file)
if not os.path.isdir(path):
os.mkdir(path)
cPickle.dump(cache_data, open(cache_file, 'w'), -1)
except Exception, ex:
print "Failed to write cache data to %s:" % cache_file, ex
def valid_cache(cache_file, cache_ttl):
#See if the cache file exists and is still living
try:
mtime = os.stat(cache_file)[os.stat.ST_MTIME]
except:
return 0
curr_time = time.time()
if (curr_time - mtime) > cache_ttl:
return 0
else:
return 1
def load_cache(cache_file):
return cPickle.load(open(cache_file))
class UpdatePluginMenu(Screen):
skin = """
<screen name="UpdatePluginMenu" position="center,center" size="610,410" title="Software management" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<ePixmap pixmap="skin_default/border_menu_350.png" position="5,50" zPosition="1" size="350,300" transparent="1" alphatest="on" />
<widget source="menu" render="Listbox" position="15,60" size="330,290" scrollbarMode="showOnDemand">
<convert type="<API key>">
{"template": [
<API key>(pos = (2, 2), size = (330, 24), flags = RT_HALIGN_LEFT, text = 1), # index 0 is the MenuText,
],
"fonts": [gFont("Regular", 22)],
"itemHeight": 25
}
</convert>
</widget>
<widget source="menu" render="Listbox" position="360,50" size="240,300" scrollbarMode="showNever" selectionDisabled="1">
<convert type="<API key>">
{"template": [
<API key>(pos = (2, 2), size = (240, 300), flags = RT_HALIGN_CENTER|RT_VALIGN_CENTER|RT_WRAP, text = 2), # index 2 is the Description,
],
"fonts": [gFont("Regular", 22)],
"itemHeight": 300
}
</convert>
</widget>
<widget source="status" render="Label" position="5,360" zPosition="10" size="600,50" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, args = 0):
Screen.__init__(self, session)
self.skin_path = plugin_path
self.menu = args
self.list = []
self.oktext = _("\nPress OK on your remote control to continue.")
self.menutext = _("Press MENU on your remote control for additional options.")
self.infotext = _("Press INFO on your remote control for additional information.")
self.text = ""
self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.value )
if self.menu == 0:
print "building menu entries"
self.list.append(("install-extensions", _("Manage extensions"), _("\nManage extensions or plugins for your receiver" ) + self.oktext, None))
self.list.append(("software-update", _("Software update"), _("\nOnline update of your receiver software." ) + self.oktext, None))
self.list.append(("software-restore", _("Software restore"), _("\nRestore your receiver with a new firmware." ) + self.oktext, None))
self.list.append(("system-backup", _("Backup system settings"), _("\nBackup your receiver settings." ) + self.oktext + "\n\n" + self.infotext, None))
self.list.append(("system-restore",_("Restore system settings"), _("\nRestore your receiver settings." ) + self.oktext, None))
self.list.append(("ipkg-install", _("Install local extension"), _("\nScan for local extensions and install them." ) + self.oktext, None))
for p in plugins.getPlugins(PluginDescriptor.<API key>):
if "SoftwareSupported" in p.__call__:
callFnc = p.__call__["SoftwareSupported"](None)
if callFnc is not None:
if "menuEntryName" in p.__call__:
menuEntryName = p.__call__["menuEntryName"](None)
else:
menuEntryName = _('Extended Software')
if "<API key>" in p.__call__:
<API key> = p.__call__["<API key>"](None)
else:
<API key> = _('Extended Software Plugin')
self.list.append(('default-plugin', menuEntryName, <API key> + self.oktext, callFnc))
if config.usage.setup_level.index >= 2: # expert+
self.list.append(("advanced", _("Advanced options"), _("\nAdvanced options and settings." ) + self.oktext, None))
elif self.menu == 1:
self.list.append(("advancedrestore", _("Advanced restore"), _("\nRestore your backups by date." ) + self.oktext, None))
self.list.append(("backuplocation", _("Select backup location"), _("\nSelect your backup device.\nCurrent device: " ) + config.plugins.configurationbackup.backuplocation.value + self.oktext, None))
self.list.append(("backupfiles", _("Select backup files"), _("Select files for backup.") + self.oktext + "\n\n" + self.infotext, None))
if config.usage.setup_level.index >= 2: # expert+
self.list.append(("ipkg-manager", _("Packet management"), _("\nView, install and remove available or installed packages." ) + self.oktext, None))
self.list.append(("ipkg-source",_("Select upgrade source"), _("\nEdit the upgrade source address." ) + self.oktext, None))
for p in plugins.getPlugins(PluginDescriptor.<API key>):
if "<API key>" in p.__call__:
callFnc = p.__call__["<API key>"](None)
if callFnc is not None:
if "menuEntryName" in p.__call__:
menuEntryName = p.__call__["menuEntryName"](None)
else:
menuEntryName = _('Advanced software')
if "<API key>" in p.__call__:
<API key> = p.__call__["<API key>"](None)
else:
<API key> = _('Advanced software plugin')
self.list.append(('advanced-plugin', menuEntryName, <API key> + self.oktext, callFnc))
self["menu"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["status"] = StaticText(self.menutext)
self["shortcuts"] = NumberActionMap(["ShortcutActions", "WizardActions", "InfobarEPGActions", "MenuActions", "NumberActions"],
{
"ok": self.go,
"back": self.close,
"red": self.close,
"menu": self.handleMenu,
"showEventInfo": self.handleInfo,
"1": self.go,
"2": self.go,
"3": self.go,
"4": self.go,
"5": self.go,
"6": self.go,
"7": self.go,
"8": self.go,
"9": self.go,
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
self.backuppath = getBackupPath()
self.backupfile = getBackupFilename()
self.fullbackupfilename = self.backuppath + "/" + self.backupfile
self.onShown.append(self.setWindowTitle)
self.onChangedEntry = []
self["menu"].onSelectionChanged.append(self.selectionChanged)
def createSummary(self):
from Screens.PluginBrowser import <API key>
return <API key>
def selectionChanged(self):
item = self["menu"].getCurrent()
if item:
name = item[1]
desc = item[2]
else:
name = "-"
desc = ""
for cb in self.onChangedEntry:
cb(name, desc)
def layoutFinished(self):
idx = 0
self["menu"].index = idx
def setWindowTitle(self):
self.setTitle(_("Software management"))
def cleanup(self):
iSoftwareTools.<API key>()
def getUpdateInfos(self):
if iSoftwareTools.<API key> is True:
if iSoftwareTools.available_updates is not 0:
self.text = _("There are at least %s updates available.") % (str(iSoftwareTools.available_updates))
else:
self.text = "" #_("There are no updates available.")
if iSoftwareTools.list_updating is True:
self.text += "\n" + _("A search for available updates is currently in progress.")
else:
self.text = _("No network connection available.")
self["status"].setText(self.text)
def handleMenu(self):
self.session.open(<API key>)
def handleInfo(self):
current = self["menu"].getCurrent()
if current:
currentEntry = current[0]
if currentEntry in ("system-backup","backupfiles"):
self.session.open(SoftwareManagerInfo, mode = "backupinfo")
def go(self, num = None):
if num is not None:
num -= 1
if not num < self["menu"].count():
return
self["menu"].setIndex(num)
current = self["menu"].getCurrent()
if current:
currentEntry = current[0]
if self.menu == 0:
if (currentEntry == "software-update"):
self.session.open(UpdatePlugin, self.skin_path)
elif (currentEntry == "software-restore"):
self.session.open(ImageWizard)
elif (currentEntry == "install-extensions"):
self.session.open(PluginManager, self.skin_path)
elif (currentEntry == "system-backup"):
self.session.openWithCallback(self.backupDone,BackupScreen, runBackup = True)
elif (currentEntry == "system-restore"):
if os.path.exists(self.fullbackupfilename):
self.session.openWithCallback(self.startRestore, MessageBox, _("Are you sure you want to restore the backup?\nYour receiver will restart after the backup has been restored!"))
else:
self.session.open(MessageBox, _("Sorry, no backups found!"), MessageBox.TYPE_INFO, timeout = 10)
elif (currentEntry == "ipkg-install"):
try:
from Plugins.Extensions.MediaScanner.plugin import main
main(self.session)
except:
self.session.open(MessageBox, _("Sorry, %s has not been installed!") % ("MediaScanner"), MessageBox.TYPE_INFO, timeout = 10)
elif (currentEntry == "default-plugin"):
self.extended = current[3]
self.extended(self.session, None)
elif (currentEntry == "advanced"):
self.session.open(UpdatePluginMenu, 1)
elif self.menu == 1:
if (currentEntry == "ipkg-manager"):
self.session.open(PacketManager, self.skin_path)
elif (currentEntry == "backuplocation"):
parts = [ (r.description, r.mountpoint, self.session) for r in harddiskmanager.<API key>(onlyhotplug = False)]
for x in parts:
if not os.access(x[1], os.F_OK|os.R_OK|os.W_OK) or x[1] == '/':
parts.remove(x)
if len(parts):
self.session.openWithCallback(self.<API key>, ChoiceBox, title = _("Please select medium to use as backup location"), list = parts)
elif (currentEntry == "backupfiles"):
self.session.openWithCallback(self.backupfiles_choosen,BackupSelection)
elif (currentEntry == "advancedrestore"):
self.session.open(RestoreMenu, self.skin_path)
elif (currentEntry == "ipkg-source"):
self.session.open(IPKGMenu, self.skin_path)
elif (currentEntry == "advanced-plugin"):
self.extended = current[3]
self.extended(self.session, None)
def backupfiles_choosen(self, ret):
self.backupdirs = ' '.join( config.plugins.configurationbackup.backupdirs.value )
config.plugins.configurationbackup.backupdirs.save()
config.plugins.configurationbackup.save()
config.save()
def <API key>(self, option):
oldpath = config.plugins.configurationbackup.backuplocation.getValue()
if option is not None:
config.plugins.configurationbackup.backuplocation.value = str(option[1])
config.plugins.configurationbackup.backuplocation.save()
config.plugins.configurationbackup.save()
config.save()
newpath = config.plugins.configurationbackup.backuplocation.getValue()
if newpath != oldpath:
self.createBackupfolders()
def createBackupfolders(self):
print "Creating backup folder if not already there..."
self.backuppath = getBackupPath()
try:
if (os.path.exists(self.backuppath) == False):
os.makedirs(self.backuppath)
except OSError:
self.session.open(MessageBox, _("Sorry, your backup destination is not writeable.\nPlease select a different one."), MessageBox.TYPE_INFO, timeout = 10)
def backupDone(self,retval = None):
if retval is True:
self.session.open(MessageBox, _("Backup completed."), MessageBox.TYPE_INFO, timeout = 10)
else:
self.session.open(MessageBox, _("Backup failed."), MessageBox.TYPE_INFO, timeout = 10)
def startRestore(self, ret = False):
if (ret == True):
self.exe = True
self.session.open(RestoreScreen, runRestore = True)
class <API key>(Screen, ConfigListScreen):
skin = """
<screen name="<API key>" position="center,center" size="560,440" title="SoftwareManager setup">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget name="config" position="5,50" size="550,350" scrollbarMode="showOnDemand" />
<ePixmap pixmap="skin_default/div-h.png" position="0,400" zPosition="1" size="560,2" />
<widget source="introduction" render="Label" position="5,410" size="550,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, skin_path = None):
Screen.__init__(self, session)
self.session = session
self.skin_path = skin_path
if self.skin_path is None:
self.skin_path = resolveFilename(<API key>, "SystemPlugins/SoftwareManager")
self.onChangedEntry = [ ]
self.setup_title = _("Software manager setup")
self.<API key> = None
self.list = [ ]
ConfigListScreen.__init__(self, self.list, session = session, on_change = self.changedEntry)
self["actions"] = ActionMap(["SetupActions", "MenuActions"],
{
"cancel": self.keyCancel,
"save": self.apply,
"menu": self.closeRecursive,
}, -2)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("OK"))
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText()
self["introduction"] = StaticText()
self.createSetup()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(self.setup_title)
def createSetup(self):
self.list = [ ]
self.<API key> = getConfigListEntry(_("Overwrite configuration files?"), config.plugins.softwaremanager.<API key>)
self.list.append(self.<API key>)
self.list.append(getConfigListEntry(_("show softwaremanager in setup menu"), config.plugins.softwaremanager.onSetupMenu))
self.list.append(getConfigListEntry(_("show softwaremanager on blue button"), config.plugins.softwaremanager.onBlueButton))
self.list.append(getConfigListEntry(_("epg cache backup"), config.plugins.softwaremanager.epgcache))
self["config"].list = self.list
self["config"].l.setSeperation(400)
self["config"].l.setList(self.list)
if not self.selectionChanged in self["config"].onSelectionChanged:
self["config"].onSelectionChanged.append(self.selectionChanged)
self.selectionChanged()
def selectionChanged(self):
if self["config"].getCurrent() == self.<API key>:
self["introduction"].setText(_("Overwrite configuration files during software upgrade?"))
else:
self["introduction"].setText("")
def newConfig(self):
pass
def keyLeft(self):
ConfigListScreen.keyLeft(self)
def keyRight(self):
ConfigListScreen.keyRight(self)
def confirm(self, confirmed):
if not confirmed:
print "not confirmed"
return
else:
self.keySave()
plugins.clearPluginList()
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
def apply(self):
self.session.openWithCallback(self.confirm, MessageBox, _("Use these settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
def cancelConfirm(self, result):
if not result:
return
for x in self["config"].list:
x[1].cancel()
self.close()
def keyCancel(self):
if self["config"].isChanged():
self.session.openWithCallback(self.cancelConfirm, MessageBox, _("Really close without saving settings?"), MessageBox.TYPE_YESNO, timeout = 20, default = True)
else:
self.close()
# for summary:
def changedEntry(self):
for x in self.onChangedEntry:
x()
self.selectionChanged()
def getCurrentEntry(self):
return self["config"].getCurrent()[0]
def getCurrentValue(self):
return str(self["config"].getCurrent()[1].value)
def createSummary(self):
from Screens.Setup import SetupSummary
return SetupSummary
class SoftwareManagerInfo(Screen):
skin = """
<screen name="SoftwareManagerInfo" position="center,center" size="560,440" title="SoftwareManager information">
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,340" scrollbarMode="showOnDemand" selectionDisabled="0">
<convert type="<API key>">
{"template": [
<API key>(pos = (5, 0), size = (540, 26), font=0, flags = RT_HALIGN_LEFT | RT_HALIGN_CENTER, text = 0), # index 0 is the name
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 26
}
</convert>
</widget>
<ePixmap pixmap="skin_default/div-h.png" position="0,400" zPosition="1" size="560,2" />
<widget source="introduction" render="Label" position="5,410" size="550,30" zPosition="10" font="Regular;21" halign="center" valign="center" backgroundColor="#25062748" transparent="1" />
</screen>"""
def __init__(self, session, skin_path = None, mode = None):
Screen.__init__(self, session)
self.session = session
self.mode = mode
self.skin_path = skin_path
if self.skin_path is None:
self.skin_path = resolveFilename(<API key>, "SystemPlugins/SoftwareManager")
self["actions"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.close,
"red": self.close,
}, -2)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText()
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText()
self["introduction"] = StaticText()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setTitle(_("Softwaremanager information"))
if self.mode is not None:
self.showInfos()
def showInfos(self):
if self.mode == "backupinfo":
self.list = []
backupfiles = config.plugins.configurationbackup.backupdirs.value
for entry in backupfiles:
self.list.append((entry,))
self['list'].setList(self.list)
class PluginManager(Screen, PackageInfoHandler):
skin = """
<screen name="PluginManager" position="center,center" size="560,440" title="Extensions management" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,360" scrollbarMode="showOnDemand">
<convert type="<API key>">
{"templates":
{"default": (51,[
<API key>(pos = (0, 1), size = (470, 24), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
<API key>(pos = (0, 25), size = (470, 24), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 2 is the description
<API key>(pos = (475, 0), size = (48, 48), png = 5), # index 5 is the status pixmap
<API key>(pos = (0, 49), size = (550, 2), png = 6), # index 6 is the div pixmap
]),
"category": (40,[
<API key>(pos = (30, 0), size = (500, 22), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
<API key>(pos = (30, 22), size = (500, 16), font=2, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the description
<API key>(pos = (0, 38), size = (550, 2), png = 3), # index 3 is the div pixmap
])
},
"fonts": [gFont("Regular", 22),gFont("Regular", 20),gFont("Regular", 16)],
"itemHeight": 52
}
</convert>
</widget>
<widget source="status" render="Label" position="5,410" zPosition="10" size="540,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path = None, args = None):
Screen.__init__(self, session)
self.session = session
self.skin_path = plugin_path
if self.skin_path == None:
self.skin_path = resolveFilename(<API key>, "SystemPlugins/SoftwareManager")
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions", "InfobarEPGActions", "HelpActions" ],
{
"ok": self.handleCurrent,
"back": self.exit,
"red": self.exit,
"green": self.handleCurrent,
"yellow": self.handleSelected,
"showEventInfo": self.handleSelected,
"displayHelp": self.handleHelp,
}, -1)
self.list = []
self.statuslist = []
self.selectedFiles = []
self.categoryList = []
self.packetlist = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText("")
self["key_yellow"] = StaticText("")
self["key_blue"] = StaticText("")
self["status"] = StaticText("")
self.cmdList = []
self.oktext = _("\nAfter pressing OK, please wait!")
if not self.selectionChanged in self["list"].onSelectionChanged:
self["list"].onSelectionChanged.append(self.selectionChanged)
self.currList = ""
self.currentSelectedTag = None
self.<API key> = None
self.<API key> = None
self.<API key> = None
self.restartRequired = False
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.getUpdateInfos)
def setWindowTitle(self):
self.setTitle(_("Extensions management"))
def exit(self):
if self.currList == "packages":
self.currList = "category"
self.currentSelectedTag = None
self["list"].style = "category"
self['list'].setList(self.categoryList)
self["list"].setIndex(self.<API key>)
self["list"].updateList(self.categoryList)
self.selectionChanged()
else:
iSoftwareTools.<API key>()
self.prepareInstall()
if len(self.cmdList):
self.session.openWithCallback(self.runExecute, PluginManagerInfo, self.skin_path, self.cmdList)
else:
self.close()
def handleHelp(self):
if self.currList != "status":
self.session.open(PluginManagerHelp, self.skin_path)
def setState(self,status = None):
if status:
self.currList = "status"
self.statuslist = []
self["key_green"].setText("")
self["key_blue"].setText("")
self["key_yellow"].setText("")
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
if status == 'update':
statuspng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Updating software catalog"), '', _("Searching for available updates. Please wait..." ),'', '', statuspng, divpng, None, '' ))
elif status == 'sync':
statuspng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Package list update"), '', _("Searching for new installed or removed packages. Please wait..." ),'', '', statuspng, divpng, None, '' ))
elif status == 'error':
self["key_green"].setText(_("Continue"))
statuspng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/remove.png"))
self.statuslist.append(( _("Error"), '', _("An error occurred while downloading the packetlist. Please try again." ),'', '', statuspng, divpng, None, '' ))
self["list"].style = "default"
self['list'].setList(self.statuslist)
def getUpdateInfos(self):
if (iSoftwareTools.lastDownloadDate is not None and iSoftwareTools.<API key> is False):
self.rebuildList()
else:
self.setState('update')
iSoftwareTools.startSoftwareTools(self.getUpdateInfosCB)
def getUpdateInfosCB(self, retval = None):
if retval is not None:
if retval is True:
if iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + _(" updates available."))
else:
self["status"].setText(_("There are no updates available."))
self.rebuildList()
elif retval is False:
if iSoftwareTools.lastDownloadDate is None:
self.setState('error')
if iSoftwareTools.<API key>:
self["status"].setText(_("Updatefeed not available."))
else:
self["status"].setText(_("No network connection available."))
else:
iSoftwareTools.lastDownloadDate = time.time()
iSoftwareTools.list_updating = True
self.setState('update')
iSoftwareTools.getUpdates(self.getUpdateInfosCB)
def rebuildList(self, retval = None):
if self.currentSelectedTag is None:
self.buildCategoryList()
else:
self.buildPacketList(self.currentSelectedTag)
def selectionChanged(self):
current = self["list"].getCurrent()
self["status"].setText("")
if current:
if self.currList == "packages":
self["key_red"].setText(_("Back"))
if current[4] == 'installed':
self["key_green"].setText(_("Uninstall"))
elif current[4] == 'installable':
self["key_green"].setText(_("Install"))
if iSoftwareTools.<API key> is False:
self["key_green"].setText("")
elif current[4] == 'remove':
self["key_green"].setText(_("Undo uninstall"))
elif current[4] == 'install':
self["key_green"].setText(_("Undo install"))
if iSoftwareTools.<API key> is False:
self["key_green"].setText("")
self["key_yellow"].setText(_("View details"))
self["key_blue"].setText("")
if len(self.selectedFiles) == 0 and iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + _(" updates available."))
elif len(self.selectedFiles) is not 0:
self["status"].setText(str(len(self.selectedFiles)) + _(" packages selected."))
else:
self["status"].setText(_("There are currently no outstanding actions."))
elif self.currList == "category":
self["key_red"].setText(_("Close"))
self["key_green"].setText("")
self["key_yellow"].setText("")
self["key_blue"].setText("")
if len(self.selectedFiles) == 0 and iSoftwareTools.available_updates is not 0:
self["status"].setText(_("There are at least ") + str(iSoftwareTools.available_updates) + _(" updates available."))
self["key_yellow"].setText(_("Update"))
elif len(self.selectedFiles) is not 0:
self["status"].setText(str(len(self.selectedFiles)) + _(" packages selected."))
self["key_yellow"].setText(_("Process"))
else:
self["status"].setText(_("There are currently no outstanding actions."))
def getSelectionState(self, detailsFile):
for entry in self.selectedFiles:
if entry[0] == detailsFile:
return True
return False
def handleCurrent(self):
current = self["list"].getCurrent()
if current:
if self.currList == "category":
self.<API key> = self["list"].index
selectedTag = current[2]
self.buildPacketList(selectedTag)
elif self.currList == "packages":
if current[7] is not '':
idx = self["list"].getIndex()
detailsFile = self.list[idx][1]
if self.list[idx][7] == True:
for entry in self.selectedFiles:
if entry[0] == detailsFile:
self.selectedFiles.remove(entry)
else:
alreadyinList = False
for entry in self.selectedFiles:
if entry[0] == detailsFile:
alreadyinList = True
if not alreadyinList:
if (iSoftwareTools.<API key> is False and current[4] in ('installable','install')):
pass
else:
self.selectedFiles.append((detailsFile,current[4],current[3]))
self.<API key> = ((detailsFile,current[4],current[3]))
if current[4] == 'installed':
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'remove', True)
elif current[4] == 'installable':
if iSoftwareTools.<API key>:
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'install', True)
elif current[4] == 'remove':
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'installed', False)
elif current[4] == 'install':
if iSoftwareTools.<API key>:
self.list[idx] = self.buildEntryComponent(current[0], current[1], current[2], current[3], 'installable',False)
self["list"].setList(self.list)
self["list"].setIndex(idx)
self["list"].updateList(self.list)
self.selectionChanged()
elif self.currList == "status":
iSoftwareTools.lastDownloadDate = time.time()
iSoftwareTools.list_updating = True
self.setState('update')
iSoftwareTools.getUpdates(self.getUpdateInfosCB)
def handleSelected(self):
current = self["list"].getCurrent()
if current:
if self.currList == "packages":
if current[7] is not '':
detailsfile = iSoftwareTools.directory[0] + "/" + current[1]
if (os.path.exists(detailsfile) == True):
self.<API key> = self.<API key>
self.session.openWithCallback(self.detailsClosed, PluginDetails, self.skin_path, current)
else:
self.session.open(MessageBox, _("Sorry, no details available!"), MessageBox.TYPE_INFO, timeout = 10)
elif self.currList == "category":
self.prepareInstall()
if len(self.cmdList):
self.session.openWithCallback(self.runExecute, PluginManagerInfo, self.skin_path, self.cmdList)
def detailsClosed(self, result = None):
if result is not None:
if result is not False:
self.setState('sync')
iSoftwareTools.lastDownloadDate = time.time()
for entry in self.selectedFiles:
if entry == self.<API key>:
self.selectedFiles.remove(entry)
iSoftwareTools.<API key>(self.rebuildList)
def buildEntryComponent(self, name, details, description, packagename, state, selected = False):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
installedpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installed.png"))
installablepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installable.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/remove.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/install.png"))
if state == 'installed':
return((name, details, description, packagename, state, installedpng, divpng, selected))
elif state == 'installable':
return((name, details, description, packagename, state, installablepng, divpng, selected))
elif state == 'remove':
return((name, details, description, packagename, state, removepng, divpng, selected))
elif state == 'install':
return((name, details, description, packagename, state, installpng, divpng, selected))
def buildPacketList(self, categorytag = None):
if categorytag is not None:
self.currList = "packages"
self.currentSelectedTag = categorytag
self.packetlist = []
for package in iSoftwareTools.packagesIndexlist[:]:
prerequisites = package[0]["prerequisites"]
if "tag" in prerequisites:
for foundtag in prerequisites["tag"]:
if categorytag == foundtag:
attributes = package[0]["attributes"]
if "packagetype" in attributes:
if attributes["packagetype"] == "internal":
continue
self.packetlist.append([attributes["name"], attributes["details"], attributes["shortdescription"], attributes["packagename"]])
else:
self.packetlist.append([attributes["name"], attributes["details"], attributes["shortdescription"], attributes["packagename"]])
self.list = []
for x in self.packetlist:
status = ""
name = x[0].strip()
details = x[1].strip()
description = x[2].strip()
if not description:
description = "No description available."
packagename = x[3].strip()
selectState = self.getSelectionState(details)
if packagename in iSoftwareTools.<API key>:
if selectState == True:
status = "remove"
else:
status = "installed"
self.list.append(self.buildEntryComponent(name, _(details), _(description), packagename, status, selected = selectState))
else:
if selectState == True:
status = "install"
else:
status = "installable"
self.list.append(self.buildEntryComponent(name, _(details), _(description), packagename, status, selected = selectState))
if len(self.list):
self.list.sort(key=lambda x: x[0])
self["list"].style = "default"
self['list'].setList(self.list)
self["list"].updateList(self.list)
self.selectionChanged()
def buildCategoryList(self):
self.currList = "category"
self.categories = []
self.categoryList = []
for package in iSoftwareTools.packagesIndexlist[:]:
prerequisites = package[0]["prerequisites"]
if "tag" in prerequisites:
for foundtag in prerequisites["tag"]:
attributes = package[0]["attributes"]
if foundtag not in self.categories:
self.categories.append(foundtag)
self.categoryList.append(self.<API key>(foundtag))
self.categoryList.sort(key=lambda x: x[0])
self["list"].style = "category"
self['list'].setList(self.categoryList)
self["list"].updateList(self.categoryList)
self.selectionChanged()
def <API key>(self, tag = None):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
if tag is not None:
if tag == 'System':
return(( _("System"), _("View list of available system extensions" ), tag, divpng ))
elif tag == 'Skin':
return(( _("Skins"), _("View list of available skins" ), tag, divpng ))
elif tag == 'Recording':
return(( _("Recordings"), _("View list of available recording extensions" ), tag, divpng ))
elif tag == 'Network':
return(( _("Network"), _("View list of available networking extensions" ), tag, divpng ))
elif tag == 'CI':
return(( _("Common Interface"), _("View list of available CommonInterface extensions" ), tag, divpng ))
elif tag == 'Default':
return(( _("Default settings"), _("View list of available default settings" ), tag, divpng ))
elif tag == 'SAT':
return(( _("Satellite equipment"), _("View list of available Satellite equipment extensions." ), tag, divpng ))
elif tag == 'Software':
return(( _("Software"), _("View list of available software extensions" ), tag, divpng ))
elif tag == 'Multimedia':
return(( _("Multimedia"), _("View list of available multimedia extensions." ), tag, divpng ))
elif tag == 'Display':
return(( _("Display and userinterface"), _("View list of available display and userinterface extensions." ), tag, divpng ))
elif tag == 'EPG':
return(( _("Electronic Program Guide"), _("View list of available EPG extensions." ), tag, divpng ))
elif tag == 'Communication':
return(( _("Communication"), _("View list of available communication extensions." ), tag, divpng ))
else: # dynamically generate non existent tags
return(( str(tag), _("View list of available ") + str(tag) + _(" extensions." ), tag, divpng ))
def prepareInstall(self):
self.cmdList = []
if iSoftwareTools.available_updates > 0:
self.cmdList.append((IpkgComponent.CMD_UPGRADE, { "test_only": False }))
if self.selectedFiles and len(self.selectedFiles):
for plugin in self.selectedFiles:
detailsfile = iSoftwareTools.directory[0] + "/" + plugin[0]
if (os.path.exists(detailsfile) == True):
iSoftwareTools.fillPackageDetails(plugin[0])
self.package = iSoftwareTools.packageDetails[0]
if "attributes" in self.package[0]:
self.attributes = self.package[0]["attributes"]
if "needsRestart" in self.attributes:
self.restartRequired = True
if "package" in self.attributes:
self.packagefiles = self.attributes["package"]
if plugin[1] == 'installed':
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package["name"] }))
else:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": plugin[2] }))
else:
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package["name"] }))
else:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": plugin[2] }))
else:
if plugin[1] == 'installed':
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": plugin[2] }))
else:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": plugin[2] }))
def runExecute(self, result = None):
if result is not None:
if result[0] is True:
self.session.openWithCallback(self.runExecuteFinished, Ipkg, cmdList = self.cmdList)
elif result[0] is False:
self.cmdList = result[1]
self.session.openWithCallback(self.runExecuteFinished, Ipkg, cmdList = self.cmdList)
else:
self.close()
def runExecuteFinished(self):
self.reloadPluginlist()
if plugins.restartRequired or self.restartRequired:
self.session.openWithCallback(self.ExecuteReboot, MessageBox, _("Installation or removal has completed.") + "\n" +_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
else:
self.selectedFiles = []
self.restartRequired = False
self.detailsClosed(True)
def ExecuteReboot(self, result):
if result:
self.session.open(TryQuitMainloop,retvalue=3)
else:
self.selectedFiles = []
self.restartRequired = False
self.detailsClosed(True)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
class PluginManagerInfo(Screen):
skin = """
<screen name="PluginManagerInfo" position="center,center" size="560,450" title="Plugin manager activity information" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,350" scrollbarMode="showOnDemand" selectionDisabled="1">
<convert type="<API key>">
{"template": [
<API key>(pos = (50, 0), size = (150, 26), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
<API key>(pos = (50, 27), size = (540, 23), font=1, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the state
<API key>(pos = (0, 1), size = (48, 48), png = 2), # index 2 is the status pixmap
<API key>(pos = (0, 48), size = (550, 2), png = 3), # index 3 is the div pixmap
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 50
}
</convert>
</widget>
<ePixmap pixmap="skin_default/div-h.png" position="0,404" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="status" render="Label" position="5,408" zPosition="10" size="550,44" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path, cmdlist = None):
Screen.__init__(self, session)
self.session = session
self.skin_path = plugin_path
self.cmdlist = cmdlist
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"ok": self.process_all,
"back": self.exit,
"red": self.exit,
"green": self.process_extensions,
}, -1)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Only extensions."))
self["status"] = StaticText(_("Following tasks will be done after you press OK!"))
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
def setWindowTitle(self):
self.setTitle(_("Plugin manager activity information"))
def rebuildList(self):
self.list = []
if self.cmdlist is not None:
for entry in self.cmdlist:
action = ""
info = ""
cmd = entry[0]
if cmd == 0:
action = 'install'
elif cmd == 2:
action = 'remove'
else:
action = 'upgrade'
args = entry[1]
if cmd == 0:
info = args['package']
elif cmd == 2:
info = args['package']
else:
info = _("receiver software because updates are available.")
self.list.append(self.buildEntryComponent(action,info))
self['list'].setList(self.list)
self['list'].updateList(self.list)
def buildEntryComponent(self, action,info):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
upgradepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/upgrade.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/install.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/remove.png"))
if action == 'install':
return(( _('Installing'), info, installpng, divpng))
elif action == 'remove':
return(( _('Removing'), info, removepng, divpng))
else:
return(( _('Upgrading'), info, upgradepng, divpng))
def exit(self):
self.close()
def process_all(self):
self.close((True,None))
def process_extensions(self):
self.list = []
if self.cmdlist is not None:
for entry in self.cmdlist:
cmd = entry[0]
if entry[0] in (0,2):
self.list.append((entry))
self.close((False,self.list))
class PluginManagerHelp(Screen):
skin = """
<screen name="PluginManagerHelp" position="center,center" size="560,450" title="Plugin manager help" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="550,350" scrollbarMode="showOnDemand" selectionDisabled="1">
<convert type="<API key>">
{"template": [
<API key>(pos = (50, 0), size = (540, 26), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
<API key>(pos = (50, 27), size = (540, 23), font=1, flags = RT_HALIGN_LEFT, text = 1), # index 1 is the state
<API key>(pos = (0, 1), size = (48, 48), png = 2), # index 2 is the status pixmap
<API key>(pos = (0, 48), size = (550, 2), png = 3), # index 3 is the div pixmap
],
"fonts": [gFont("Regular", 24),gFont("Regular", 22)],
"itemHeight": 50
}
</convert>
</widget>
<ePixmap pixmap="skin_default/div-h.png" position="0,404" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="status" render="Label" position="5,408" zPosition="10" size="550,44" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, plugin_path):
Screen.__init__(self, session)
self.session = session
self.skin_path = plugin_path
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.exit,
"red": self.exit,
}, -1)
self.list = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["status"] = StaticText(_("A small overview of the available icon states and actions."))
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
def setWindowTitle(self):
self.setTitle(_("Plugin manager help"))
def rebuildList(self):
self.list = []
self.list.append(self.buildEntryComponent('install'))
self.list.append(self.buildEntryComponent('installable'))
self.list.append(self.buildEntryComponent('installed'))
self.list.append(self.buildEntryComponent('remove'))
self['list'].setList(self.list)
self['list'].updateList(self.list)
def buildEntryComponent(self, state):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
installedpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installed.png"))
installablepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installable.png"))
removepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/remove.png"))
installpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/install.png"))
if state == 'installed':
return(( _('This plugin is installed.'), _('You can remove this plugin.'), installedpng, divpng))
elif state == 'installable':
return(( _('This plugin is not installed.'), _('You can install this plugin.'), installablepng, divpng))
elif state == 'install':
return(( _('This plugin will be installed.'), _('You can cancel the installation.'), installpng, divpng))
elif state == 'remove':
return(( _('This plugin will be removed.'), _('You can cancel the removal.'), removepng, divpng))
def exit(self):
self.close()
class PluginDetails(Screen, PackageInfoHandler):
skin = """
<screen name="PluginDetails" position="center,center" size="600,440" title="Plugin details" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="author" render="Label" position="10,50" size="500,25" zPosition="10" font="Regular;21" transparent="1" />
<widget name="statuspic" position="550,40" size="48,48" alphatest="on"/>
<widget name="divpic" position="0,80" size="600,2" alphatest="on"/>
<widget name="detailtext" position="10,90" size="270,330" zPosition="10" font="Regular;21" transparent="1" halign="left" valign="top"/>
<widget name="screenshot" position="290,90" size="300,330" alphatest="on"/>
</screen>"""
def __init__(self, session, plugin_path, packagedata = None):
Screen.__init__(self, session)
self.skin_path = plugin_path
self.language = language.getLanguage()[:2] # getLanguage returns e.g. "fi_FI" for "language_country"
self.attributes = None
PackageInfoHandler.__init__(self, self.statusCallback, blocking = False)
self.directory = resolveFilename(SCOPE_METADIR)
if packagedata:
self.pluginname = packagedata[0]
self.details = packagedata[1]
self.pluginstate = packagedata[4]
self.statuspicinstance = packagedata[5]
self.divpicinstance = packagedata[6]
self.fillPackageDetails(self.details)
self.thumbnail = ""
self["shortcuts"] = ActionMap(["ShortcutActions", "WizardActions"],
{
"back": self.exit,
"red": self.exit,
"green": self.go,
"up": self.pageUp,
"down": self.pageDown,
"left": self.pageUp,
"right": self.pageDown,
}, -1)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText("")
self["author"] = StaticText()
self["statuspic"] = Pixmap()
self["divpic"] = Pixmap()
self["screenshot"] = Pixmap()
self["detailtext"] = ScrollLabel()
self["statuspic"].hide()
self["screenshot"].hide()
self["divpic"].hide()
self.package = self.packageDetails[0]
if "attributes" in self.package[0]:
self.attributes = self.package[0]["attributes"]
self.restartRequired = False
self.cmdList = []
self.oktext = _("\nAfter pressing OK, please wait!")
self.picload = ePicLoad()
self.picload.PictureData.get().append(self.<API key>)
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.setInfos)
def setWindowTitle(self):
self.setTitle(_("Details for plugin: ") + self.pluginname )
def exit(self):
self.close(False)
def pageUp(self):
self["detailtext"].pageUp()
def pageDown(self):
self["detailtext"].pageDown()
def statusCallback(self, status, progress):
pass
def setInfos(self):
if "screenshot" in self.attributes:
self.loadThumbnail(self.attributes)
if "name" in self.attributes:
self.pluginname = self.attributes["name"]
else:
self.pluginname = _("unknown")
if "author" in self.attributes:
self.author = self.attributes["author"]
else:
self.author = _("unknown")
if "description" in self.attributes:
self.description = _(self.attributes["description"].replace("\\n", "\n"))
else:
self.description = _("No description available.")
self["author"].setText(_("Author: ") + self.author)
self["detailtext"].setText(_(self.description))
if self.pluginstate in ('installable', 'install'):
if iSoftwareTools.<API key>:
self["key_green"].setText(_("Install"))
else:
self["key_green"].setText("")
else:
self["key_green"].setText(_("Remove"))
def loadThumbnail(self, entry):
thumbnailUrl = None
if "screenshot" in entry:
thumbnailUrl = entry["screenshot"]
if self.language == "de":
if thumbnailUrl[-7:] == "_en.jpg":
thumbnailUrl = thumbnailUrl[:-7] + "_de.jpg"
if thumbnailUrl is not None:
self.thumbnail = "/tmp/" + thumbnailUrl.split('/')[-1]
print "[PluginDetails] downloading screenshot " + thumbnailUrl + " to " + self.thumbnail
if iSoftwareTools.<API key>:
client.downloadPage(thumbnailUrl,self.thumbnail).addCallback(self.setThumbnail).addErrback(self.fetchFailed)
else:
self.setThumbnail(noScreenshot = True)
else:
self.setThumbnail(noScreenshot = True)
def setThumbnail(self, noScreenshot = False):
if not noScreenshot:
filename = self.thumbnail
else:
filename = resolveFilename(<API key>, "SystemPlugins/SoftwareManager/noprev.png")
sc = AVSwitch().getFramebufferScale()
self.picload.setPara((self["screenshot"].instance.size().width(), self["screenshot"].instance.size().height(), sc[0], sc[1], False, 1, "#00000000"))
self.picload.startDecode(filename)
if self.statuspicinstance is not None:
self["statuspic"].instance.setPixmap(self.statuspicinstance.__deref__())
self["statuspic"].show()
if self.divpicinstance is not None:
self["divpic"].instance.setPixmap(self.divpicinstance.__deref__())
self["divpic"].show()
def <API key>(self, picInfo=None):
ptr = self.picload.getData()
if ptr is not None:
self["screenshot"].instance.setPixmap(ptr.__deref__())
self["screenshot"].show()
else:
self.setThumbnail(noScreenshot = True)
def go(self):
if "package" in self.attributes:
self.packagefiles = self.attributes["package"]
if "needsRestart" in self.attributes:
self.restartRequired = True
self.cmdList = []
if self.pluginstate in ('installed', 'remove'):
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package["name"] }))
if len(self.cmdList):
self.session.openWithCallback(self.runRemove, MessageBox, _("Do you want to remove the package:\n") + self.pluginname + "\n" + self.oktext)
else:
if iSoftwareTools.<API key>:
if self.packagefiles:
for package in self.packagefiles[:]:
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package["name"] }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to install the package:\n") + self.pluginname + "\n" + self.oktext)
def runUpgrade(self, result):
if result:
self.session.openWithCallback(self.runUpgradeFinished, Ipkg, cmdList = self.cmdList)
def runUpgradeFinished(self):
self.reloadPluginlist()
if plugins.restartRequired or self.restartRequired:
self.session.openWithCallback(self.UpgradeReboot, MessageBox, _("Installation has completed.") + "\n" + _("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
else:
self.close(True)
def UpgradeReboot(self, result):
if result:
self.session.open(TryQuitMainloop,retvalue=3)
self.close(True)
def runRemove(self, result):
if result:
self.session.openWithCallback(self.runRemoveFinished, Ipkg, cmdList = self.cmdList)
def runRemoveFinished(self):
self.close(True)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
def fetchFailed(self,string):
self.setThumbnail(noScreenshot = True)
print "[PluginDetails] fetch failed " + string.getErrorMessage()
class IPKGMenu(Screen):
skin = """
<screen name="IPKGMenu" position="center,center" size="560,400" title="Select upgrade source to edit." >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="filelist" position="5,50" size="550,340" scrollbarMode="showOnDemand" />
</screen>"""
def __init__(self, session, plugin_path):
Screen.__init__(self, session)
self.skin_path = plugin_path
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Edit"))
self.sel = []
self.val = []
self.entry = False
self.exe = False
self.path = ""
self["actions"] = NumberActionMap(["SetupActions"],
{
"ok": self.KeyOk,
"cancel": self.keyCancel
}, -1)
self["shortcuts"] = ActionMap(["ShortcutActions"],
{
"red": self.keyCancel,
"green": self.KeyOk,
})
self["filelist"] = MenuList([])
self.fill_list()
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setWindowTitle()
def setWindowTitle(self):
self.setTitle(_("Select upgrade source to edit."))
def fill_list(self):
flist = []
self.path = '/etc/opkg/'
if (os.path.exists(self.path) == False):
self.entry = False
return
for file in os.listdir(self.path):
if file.endswith(".conf"):
if file not in ('arch.conf', 'opkg.conf'):
flist.append((file))
self.entry = True
self["filelist"].l.setList(flist)
def KeyOk(self):
if (self.exe == False) and (self.entry == True):
self.sel = self["filelist"].getCurrent()
self.val = self.path + self.sel
self.session.open(IPKGSource, self.val)
def keyCancel(self):
self.close()
def Exit(self):
self.close()
class IPKGSource(Screen):
skin = """
<screen name="IPKGSource" position="center,center" size="560,80" title="Edit upgrade source url." >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget name="text" position="5,50" size="550,25" font="Regular;20" backgroundColor="background" foregroundColor="#cccccc" />
</screen>"""
def __init__(self, session, configfile = None):
Screen.__init__(self, session)
self.session = session
self.configfile = configfile
text = ""
if self.configfile:
try:
fp = file(configfile, 'r')
sources = fp.readlines()
if sources:
text = sources[0]
fp.close()
except IOError:
pass
desk = getDesktop(0)
x= int(desk.size().width())
y= int(desk.size().height())
self["key_red"] = StaticText(_("Cancel"))
self["key_green"] = StaticText(_("Save"))
if (y>=720):
self["text"] = Input(text, maxSize=False, type=Input.TEXT)
else:
self["text"] = Input(text, maxSize=False, visible_width = 55, type=Input.TEXT)
self["actions"] = NumberActionMap(["WizardActions", "InputActions", "TextEntryActions", "<API key>","ShortcutActions"],
{
"ok": self.go,
"back": self.close,
"red": self.close,
"green": self.go,
"left": self.keyLeft,
"right": self.keyRight,
"home": self.keyHome,
"end": self.keyEnd,
"deleteForward": self.keyDeleteForward,
"deleteBackward": self.keyDeleteBackward,
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
}, -1)
self.onLayoutFinish.append(self.layoutFinished)
def layoutFinished(self):
self.setWindowTitle()
self["text"].right()
def setWindowTitle(self):
self.setTitle(_("Edit upgrade source url."))
def go(self):
text = self["text"].getText()
if text:
fp = file(self.configfile, 'w')
fp.write(text)
fp.write("\n")
fp.close()
self.close()
def keyLeft(self):
self["text"].left()
def keyRight(self):
self["text"].right()
def keyHome(self):
self["text"].home()
def keyEnd(self):
self["text"].end()
def keyDeleteForward(self):
self["text"].delete()
def keyDeleteBackward(self):
self["text"].deleteBackward()
def keyNumberGlobal(self, number):
self["text"].number(number)
class PacketManager(Screen, NumericalTextInput):
skin = """
<screen name="PacketManager" position="center,center" size="530,420" title="Packet manager" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="list" render="Listbox" position="5,50" size="520,365" scrollbarMode="showOnDemand">
<convert type="<API key>">
{"template": [
<API key>(pos = (5, 1), size = (440, 28), font=0, flags = RT_HALIGN_LEFT, text = 0), # index 0 is the name
<API key>(pos = (5, 26), size = (440, 20), font=1, flags = RT_HALIGN_LEFT, text = 2), # index 2 is the description
<API key>(pos = (445, 2), size = (48, 48), png = 4), # index 4 is the status pixmap
<API key>(pos = (5, 50), size = (510, 2), png = 5), # index 4 is the div pixmap
],
"fonts": [gFont("Regular", 22),gFont("Regular", 14)],
"itemHeight": 52
}
</convert>
</widget>
</screen>"""
def __init__(self, session, plugin_path, args = None):
Screen.__init__(self, session)
NumericalTextInput.__init__(self)
self.session = session
self.skin_path = plugin_path
self.setUseableChars(u'<API key>')
self["shortcuts"] = NumberActionMap(["ShortcutActions", "WizardActions", "NumberActions", "InputActions", "InputAsciiActions", "<API key>" ],
{
"ok": self.go,
"back": self.exit,
"red": self.exit,
"green": self.reload,
"gotAsciiCode": self.keyGotAscii,
"1": self.keyNumberGlobal,
"2": self.keyNumberGlobal,
"3": self.keyNumberGlobal,
"4": self.keyNumberGlobal,
"5": self.keyNumberGlobal,
"6": self.keyNumberGlobal,
"7": self.keyNumberGlobal,
"8": self.keyNumberGlobal,
"9": self.keyNumberGlobal,
"0": self.keyNumberGlobal
}, -1)
self.list = []
self.statuslist = []
self["list"] = List(self.list)
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Reload"))
self.list_updating = True
self.packetlist = []
self.<API key> = {}
self.<API key> = {}
self.Console = Console()
self.cmdList = []
self.cachelist = []
self.cache_ttl = 86400 #600 is default, 0 disables, Seconds cache is considered valid (24h should be ok for caching ipkgs)
self.cache_file = eEnv.resolve('${libdir}/enigma2/python/Plugins/SystemPlugins/SoftwareManager/packetmanager.cache') #Path to cache directory
self.oktext = _("\nAfter pressing OK, please wait!")
self.unwanted_extensions = ('-dbg', '-dev', '-doc', '-staticdev', '-src', 'busybox')
self.ipkg = IpkgComponent()
self.ipkg.addCallback(self.ipkgCallback)
self.onShown.append(self.setWindowTitle)
self.onLayoutFinish.append(self.rebuildList)
rcinput = eRCInput.getInstance()
rcinput.setKeyboardMode(rcinput.kmAscii)
def keyNumberGlobal(self, val):
key = self.getKey(val)
if key is not None:
keyvalue = key.encode("utf-8")
if len(keyvalue) == 1:
self.setNextIdx(keyvalue[0])
def keyGotAscii(self):
keyvalue = unichr(getPrevAsciiCode()).encode("utf-8")
if len(keyvalue) == 1:
self.setNextIdx(keyvalue[0])
def setNextIdx(self,char):
if char in ("0", "1", "a"):
self["list"].setIndex(0)
else:
idx = self.getNextIdx(char)
if idx and idx <= self["list"].count:
self["list"].setIndex(idx)
def getNextIdx(self,char):
for idx, i in enumerate(self["list"].list):
if i[0] and (i[0][0] == char):
return idx
def exit(self):
self.ipkg.stop()
if self.Console is not None:
if len(self.Console.appContainers):
for name in self.Console.appContainers.keys():
self.Console.kill(name)
rcinput = eRCInput.getInstance()
rcinput.setKeyboardMode(rcinput.kmNone)
self.close()
def reload(self):
if (os.path.exists(self.cache_file) == True):
os.unlink(self.cache_file)
self.list_updating = True
self.rebuildList()
def setWindowTitle(self):
self.setTitle(_("Packet manager"))
def setStatus(self,status = None):
if status:
self.statuslist = []
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
if status == 'update':
statuspng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/upgrade.png"))
self.statuslist.append(( _("Package list update"), '', _("Trying to download a new packetlist. Please wait..." ),'',statuspng, divpng ))
self['list'].setList(self.statuslist)
elif status == 'error':
statuspng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/remove.png"))
self.statuslist.append(( _("Error"), '', _("An error occurred while downloading the packetlist. Please try again." ),'',statuspng, divpng ))
self['list'].setList(self.statuslist)
def rebuildList(self):
self.setStatus('update')
self.inv_cache = 0
self.vc = valid_cache(self.cache_file, self.cache_ttl)
if self.cache_ttl > 0 and self.vc != 0:
try:
self.buildPacketList()
except:
self.inv_cache = 1
if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
self.run = 0
self.ipkg.startCmd(IpkgComponent.CMD_UPDATE)
def go(self, returnValue = None):
cur = self["list"].getCurrent()
if cur:
status = cur[3]
package = cur[0]
self.cmdList = []
if status == 'installed':
self.cmdList.append((IpkgComponent.CMD_REMOVE, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runRemove, MessageBox, _("Do you want to remove the package:\n") + package + "\n" + self.oktext)
elif status == 'upgradeable':
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to upgrade the package:\n") + package + "\n" + self.oktext)
elif status == "installable":
self.cmdList.append((IpkgComponent.CMD_INSTALL, { "package": package }))
if len(self.cmdList):
self.session.openWithCallback(self.runUpgrade, MessageBox, _("Do you want to install the package:\n") + package + "\n" + self.oktext)
def runRemove(self, result):
if result:
self.session.openWithCallback(self.runRemoveFinished, Ipkg, cmdList = self.cmdList)
def runRemoveFinished(self):
self.session.openWithCallback(self.RemoveReboot, MessageBox, _("Removal has completed.") + "\n" + _("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
def RemoveReboot(self, result):
if result is None:
return
if result is False:
cur = self["list"].getCurrent()
if cur:
item = self['list'].getIndex()
self.list[item] = self.buildEntryComponent(cur[0], cur[1], cur[2], 'installable')
self.cachelist[item] = [cur[0], cur[1], cur[2], 'installable']
self['list'].setList(self.list)
write_cache(self.cache_file, self.cachelist)
self.reloadPluginlist()
if result:
self.session.open(TryQuitMainloop,retvalue=3)
def runUpgrade(self, result):
if result:
self.session.openWithCallback(self.runUpgradeFinished, Ipkg, cmdList = self.cmdList)
def runUpgradeFinished(self):
self.session.openWithCallback(self.UpgradeReboot, MessageBox, _("Update has completed.") + "\n" +_("Do you want to reboot your receiver?"), MessageBox.TYPE_YESNO)
def UpgradeReboot(self, result):
if result is None:
return
if result is False:
cur = self["list"].getCurrent()
if cur:
item = self['list'].getIndex()
self.list[item] = self.buildEntryComponent(cur[0], cur[1], cur[2], 'installed')
self.cachelist[item] = [cur[0], cur[1], cur[2], 'installed']
self['list'].setList(self.list)
write_cache(self.cache_file, self.cachelist)
self.reloadPluginlist()
if result:
self.session.open(TryQuitMainloop,retvalue=3)
def ipkgCallback(self, event, param):
if event == IpkgComponent.EVENT_ERROR:
self.list_updating = False
self.setStatus('error')
elif event == IpkgComponent.EVENT_DONE:
if self.list_updating:
self.list_updating = False
if not self.Console:
self.Console = Console()
cmd = self.ipkg.ipkg + " list"
self.Console.ePopen(cmd, self.IpkgList_Finished)
pass
def IpkgList_Finished(self, result, retval, extra_args = None):
if result:
self.packetlist = []
last_name = ""
for x in result.splitlines():
if ' - ' in x:
tokens = x.split(' - ')
name = tokens[0].strip()
if name and not any(name.endswith(x) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 1 and tokens[1].strip() or ""
descr = l > 2 and tokens[2].strip() or ""
if name == last_name:
continue
last_name = name
self.packetlist.append([name, version, descr])
elif len(self.packetlist) > 0:
# no ' - ' in the text, assume that this is the description
# therefore add this text to the last packet description
last_packet = self.packetlist[-1]
last_packet[2] = last_packet[2] + x
self.packetlist[:-1] + last_packet
if not self.Console:
self.Console = Console()
cmd = self.ipkg.ipkg + " list_installed"
self.Console.ePopen(cmd, self.<API key>)
def <API key>(self, result, retval, extra_args = None):
if result:
self.<API key> = {}
for x in result.splitlines():
tokens = x.split(' - ')
name = tokens[0].strip()
if not any(name.endswith(x) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 1 and tokens[1].strip() or ""
self.<API key>[name] = version
if not self.Console:
self.Console = Console()
cmd = "opkg list-upgradable"
self.Console.ePopen(cmd, self.<API key>)
def <API key>(self, result, retval, extra_args = None):
if result:
self.<API key> = {}
for x in result.splitlines():
tokens = x.split(' - ')
name = tokens[0].strip()
if not any(name.endswith(x) for x in self.unwanted_extensions):
l = len(tokens)
version = l > 2 and tokens[2].strip() or ""
self.<API key>[name] = version
self.buildPacketList()
def buildEntryComponent(self, name, version, description, state):
divpng = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/div-h.png"))
if not description:
description = "No description available."
if state == 'installed':
installedpng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installed.png"))
return((name, version, _(description), state, installedpng, divpng))
elif state == 'upgradeable':
upgradeablepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/upgradeable.png"))
return((name, version, _(description), state, upgradeablepng, divpng))
else:
installablepng = LoadPixmap(cached=True, path=resolveFilename(<API key>, "SystemPlugins/SoftwareManager/installable.png"))
return((name, version, _(description), state, installablepng, divpng))
def buildPacketList(self):
self.list = []
self.cachelist = []
if self.cache_ttl > 0 and self.vc != 0:
print 'Loading packagelist cache from ',self.cache_file
try:
self.cachelist = load_cache(self.cache_file)
if len(self.cachelist) > 0:
for x in self.cachelist:
self.list.append(self.buildEntryComponent(x[0], x[1], x[2], x[3]))
self['list'].setList(self.list)
except:
self.inv_cache = 1
if self.cache_ttl == 0 or self.inv_cache == 1 or self.vc == 0:
print 'rebuilding fresh package list'
for x in self.packetlist:
status = ""
if x[0] in self.<API key>:
if x[0] in self.<API key>:
status = "upgradeable"
else:
status = "installed"
else:
status = "installable"
self.list.append(self.buildEntryComponent(x[0], x[1], x[2], status))
self.cachelist.append([x[0], x[1], x[2], status])
write_cache(self.cache_file, self.cachelist)
self['list'].setList(self.list)
def reloadPluginlist(self):
plugins.readPluginList(resolveFilename(SCOPE_PLUGINS))
class IpkgInstaller(Screen):
skin = """
<screen name="IpkgInstaller" position="center,center" size="550,450" title="Install extensions" >
<ePixmap pixmap="skin_default/buttons/red.png" position="0,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/green.png" position="140,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/yellow.png" position="280,0" size="140,40" alphatest="on" />
<ePixmap pixmap="skin_default/buttons/blue.png" position="420,0" size="140,40" alphatest="on" />
<widget source="key_red" render="Label" position="0,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#9f1313" transparent="1" />
<widget source="key_green" render="Label" position="140,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#1f771f" transparent="1" />
<widget source="key_yellow" render="Label" position="280,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#a08500" transparent="1" />
<widget source="key_blue" render="Label" position="420,0" zPosition="1" size="140,40" font="Regular;20" halign="center" valign="center" backgroundColor="#18188b" transparent="1" />
<widget name="list" position="5,50" size="540,360" />
<ePixmap pixmap="skin_default/div-h.png" position="0,410" zPosition="10" size="560,2" transparent="1" alphatest="on" />
<widget source="introduction" render="Label" position="5,420" zPosition="10" size="550,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session, list):
Screen.__init__(self, session)
self.list = SelectionList()
self["list"] = self.list
p = 0
if len(list):
p = list[0].rfind("/")
title = list[0][:p]
self.title = ("%s %s %s") % (_("Install extensions"), _("from"), title)
for listindex in range(len(list)):
self.list.addSelection(list[listindex][p+1:], list[listindex], listindex, False)
self.list.sort()
self["key_red"] = StaticText(_("Close"))
self["key_green"] = StaticText(_("Install"))
self["key_yellow"] = StaticText()
self["key_blue"] = StaticText(_("Invert"))
self["introduction"] = StaticText(_("Press OK to toggle the selection."))
self["actions"] = ActionMap(["OkCancelActions", "ColorActions"],
{
"ok": self.list.toggleSelection,
"cancel": self.close,
"red": self.close,
"green": self.install,
"blue": self.list.toggleAllSelection
}, -1)
def install(self):
list = self.list.getSelectionsList()
cmdList = []
for item in list:
cmdList.append((IpkgComponent.CMD_INSTALL, { "package": item[1] }))
self.session.open(Ipkg, cmdList = cmdList)
def filescan_open(list, session, **kwargs):
filelist = [x.path for x in list]
session.open(IpkgInstaller, filelist) # list
def filescan(**kwargs):
from Components.Scanner import Scanner, ScanPath
return \
Scanner(mimetypes = ["application/x-debian-package"],
paths_to_scan =
[
ScanPath(path = "ipk", with_subdirs = True),
ScanPath(path = "", with_subdirs = False),
],
name = "Ipkg",
description = _("Install extensions."),
openfnc = filescan_open, )
def UpgradeMain(session, **kwargs):
session.open(UpdatePluginMenu)
def startSetup(menuid):
if menuid == "setup" :
return [(_("Software management"), UpgradeMain, "software_manager", 50)]
return [ ]
def Plugins(path, **kwargs):
global plugin_path
plugin_path = path
list = [
PluginDescriptor(name=_("Software management"), description=_("Manage your receiver's software"), where = PluginDescriptor.WHERE_MENU, needsRestart = False, fnc=startSetup),
PluginDescriptor(name=_("Ipkg"), where = PluginDescriptor.WHERE_FILESCAN, needsRestart = False, fnc = filescan)
]
if not config.plugins.softwaremanager.onSetupMenu.value and not config.plugins.softwaremanager.onBlueButton.value:
list.append(PluginDescriptor(name=_("Software management"), description=_("Manage your receiver's software"), where = PluginDescriptor.WHERE_PLUGINMENU, needsRestart = False, fnc=UpgradeMain))
if config.plugins.softwaremanager.onBlueButton.value:
list.append(PluginDescriptor(name=_("Software management"), description=_("Manage your receiver's software"), where = PluginDescriptor.<API key>, needsRestart = False, fnc=UpgradeMain))
return list |
<!DOCTYPE HTML>
<html lang="ru">
<head>
<title>Социальные сети</title>
<meta charset="utf-8">
<meta name="description" content="">
<meta name="keywords" content="">
<script src="js/jquery.min.js"></script>
<script src="js/config.js"></script>
<!-- Library for adaptive and responsive design-->
<script src="js/skel.min.js"></script>
<noscript>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/style-desktop.css">
<link rel="stylesheet" href="css/noscript.css">
</noscript>
</head>
<body class="homepage">
<!-- Wrapper-->
<div id="wrapper">
<!-- Nav -->
<nav id="nav">
<a href="#home" class="icon icon-home active"><span>Home</span></a><!--email me work -->
<a href="#facebook" class="icon icon-facebook"><span>Facebook</span></a>
<a href="#vk" class="icon icon-vk"><span>VK</span></a>
<a href="#twitter" class="icon icon-twitter"><span>Twitter</span></a>
</nav>
<!-- Main -->
<div id="main">
<!-- Main Panel -->
<article id="home" class="panel">
<header>
<h2>Home page</h2>
<span class="byline">Welcome to our page! We created our service, because we want, that we'll feel comfort from reading news feed of different social networks</span>
</header>
</article>
<!-- Facebook -->
<article id="facebook" class="panel">
<header>
<h2>News Feed</h2>
<!--New of Facebook
<span class="byline">News of Facebook</span>
</header>
<p>
In this area you can read and follow the news of Facebook. To continue input login and password.
<form action="#" method="post">
<div>
<div class="row half">
<div class="6u">
<input type="text" class="text" name="Login" placeholder="Login">
</div>
<div class="6u">
<input type="text" class="text" name="Password" placeholder="Password">
</div>
<div class="row">
<div class="12u">
<input type="submit" class="button" value="Login">
</div>
</div>
</div>
</form>
</p>
</article>
<article id="vk" class="panel">
<header>
<h2>News Feed</h2>
<!--New of VK.com
<span class="byline">News of VK</span>
</header>
<p>
In this area you can read and follow the new of vkontakte. To continue input login and password.
<form action="#" method="post">
<div>
<div class="row half">
<div class="6u">
<input type="text" class="text" name="Login" placeholder="Login">
</div>
<div class="6u">
<input type="text" class="text" name="Password" placeholder="Password">
</div>
<div class="row">
<div class="12u">
<input type="submit" class="button" value="Login">
</div>
</div>
</div>
</form>
</p>
</article>
<!--Twitter
<artile id="twitter" class="panel">
<header>
<h2>New Feed</h2>
<!--Twitter news
<span class="byline">New of Twitter</span>
</header>
<p>
In this area you can read and follow the new of Twitter. To continue input login and password.
<form action="#" method="post">
<div>
<div class="row half">
<div class="6u">
<input type="text" class="text" name="Login" placeholder="Login">
</div>
<div class="6u">
<input type="text" class="text" name="Password" placeholder="Password">
</div>
<div class="row">
<div class="12u">
<input type="submit" class="button" value="Login">
</div>
</div>
</div>
</form>
</p>
</div>
<!-- Footer -->
<div id="footer">
<ul class="links">
<li>© Roman Kozar</li>
<li>2013</li>
</ul>
</div>
</div>
</body>
</html> |
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/percpu.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/sysdev.h>
#include <linux/clocksource.h>
#include <linux/jiffies.h>
#include <linux/time.h>
#include <linux/tick.h>
#include <linux/stop_machine.h>
#include <linux/pram.h>
/* Structure holding internal timekeeping values. */
struct timekeeper {
/* Current clocksource used for timekeeping. */
struct clocksource *clock;
/* The shift value of the current clocksource. */
int shift;
/* Number of clock cycles in one NTP interval. */
cycle_t cycle_interval;
/* Number of clock shifted nano seconds in one NTP interval. */
u64 xtime_interval;
/* Raw nano seconds accumulated per NTP interval. */
u32 raw_interval;
/* Clock shifted nano seconds remainder not stored in xtime.tv_nsec. */
u64 xtime_nsec;
/* Difference between accumulated time and NTP time in ntp
* shifted nano seconds. */
s64 ntp_error;
/* Shift conversion between clock shifted nano seconds and
* ntp shifted nano seconds. */
int ntp_error_shift;
/* NTP adjusted clock multiplier */
u32 mult;
};
struct timekeeper timekeeper;
/**
* <API key> - Set up internals to use clocksource clock.
*
* @clock: Pointer to clocksource.
*
* Calculates a fixed cycle/nsec interval for a given clocksource/adjustment
* pair and interval request.
*
* Unless you're the timekeeping code, you should not be using this!
*/
static void <API key>(struct clocksource *clock)
{
cycle_t interval;
u64 tmp;
timekeeper.clock = clock;
clock->cycle_last = clock->read(clock);
/* Do the ns -> cycle conversion first, using original mult */
tmp = NTP_INTERVAL_LENGTH;
tmp <<= clock->shift;
tmp += clock->mult/2;
do_div(tmp, clock->mult);
if (tmp == 0)
tmp = 1;
interval = (cycle_t) tmp;
timekeeper.cycle_interval = interval;
/* Go back from cycles -> shifted ns */
timekeeper.xtime_interval = (u64) interval * clock->mult;
timekeeper.raw_interval =
((u64) interval * clock->mult) >> clock->shift;
timekeeper.xtime_nsec = 0;
timekeeper.shift = clock->shift;
timekeeper.ntp_error = 0;
timekeeper.ntp_error_shift = NTP_SCALE_SHIFT - clock->shift;
/*
* The timekeeper keeps its own mult values for the currently
* active clocksource. These value will be adjusted via NTP
* to counteract clock drifting.
*/
timekeeper.mult = clock->mult;
}
/* Timekeeper helper functions. */
static inline s64 timekeeping_get_ns(void)
{
cycle_t cycle_now, cycle_delta;
struct clocksource *clock;
/* read clocksource: */
clock = timekeeper.clock;
cycle_now = clock->read(clock);
/* calculate the delta since the last update_wall_time: */
cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
/* return delta convert to nanoseconds using ntp adjusted mult. */
return clocksource_cyc2ns(cycle_delta, timekeeper.mult,
timekeeper.shift);
}
static inline s64 <API key>(void)
{
cycle_t cycle_now, cycle_delta;
struct clocksource *clock;
/* read clocksource: */
clock = timekeeper.clock;
cycle_now = clock->read(clock);
/* calculate the delta since the last update_wall_time: */
cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
/* return delta convert to nanoseconds using ntp adjusted mult. */
return clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
}
/*
* This read-write spinlock protects us from races in SMP while
* playing with xtime.
*/
<API key> DEFINE_SEQLOCK(xtime_lock);
/*
* The current time
* wall_to_monotonic is what we need to add to xtime (or xtime corrected
* for sub jiffie times) to get to monotonic time. Monotonic is pegged
* at zero at system boot time, so wall_to_monotonic will be negative,
* however, we will ALWAYS keep the tv_nsec part positive so we can use
* the usual normalization.
*
* wall_to_monotonic is moved after resume from suspend for the monotonic
* time not to jump. We need to add total_sleep_time to wall_to_monotonic
* to get the real boot based time offset.
*
* - wall_to_monotonic is no longer the boot time, getboottime must be
* used instead.
*/
struct timespec xtime __attribute__ ((aligned (16)));
EXPORT_SYMBOL(xtime);
struct timespec wall_to_monotonic __attribute__ ((aligned (16)));
static struct timespec total_sleep_time;
/*
* The raw monotonic time for the CLOCK_MONOTONIC_RAW posix clock.
*/
struct timespec raw_time;
/* flag for if timekeeping is suspended */
int __read_mostly <API key>;
static struct timespec xtime_cache __attribute__ ((aligned (16)));
void update_xtime_cache(u64 nsec)
{
xtime_cache = xtime;
timespec_add_ns(&xtime_cache, nsec);
}
/* must hold xtime_lock */
void <API key>(int leapsecond)
{
xtime.tv_sec += leapsecond;
wall_to_monotonic.tv_sec -= leapsecond;
update_vsyscall(&xtime, timekeeper.clock, timekeeper.mult);
}
#ifdef CONFIG_GENERIC_TIME
/**
* <API key> - update clock to the current time
*
* Forward the current clock to update its state since the last call to
* update_wall_time(). This is useful before significant clock changes,
* as it avoids having to deal with this time offset explicitly.
*/
static void <API key>(void)
{
cycle_t cycle_now, cycle_delta;
struct clocksource *clock;
s64 nsec;
clock = timekeeper.clock;
cycle_now = clock->read(clock);
cycle_delta = (cycle_now - clock->cycle_last) & clock->mask;
clock->cycle_last = cycle_now;
nsec = clocksource_cyc2ns(cycle_delta, timekeeper.mult,
timekeeper.shift);
/* If arch requires, add in gettimeoffset() */
nsec += arch_gettimeoffset();
timespec_add_ns(&xtime, nsec);
nsec = clocksource_cyc2ns(cycle_delta, clock->mult, clock->shift);
timespec_add_ns(&raw_time, nsec);
}
/**
* getnstimeofday - Returns the time of day in a timespec
* @ts: pointer to the timespec to be set
*
* Returns the time of day in a timespec.
*/
void getnstimeofday(struct timespec *ts)
{
unsigned long seq;
s64 nsecs;
WARN_ON(<API key>);
do {
seq = read_seqbegin(&xtime_lock);
*ts = xtime;
nsecs = timekeeping_get_ns();
/* If arch requires, add in gettimeoffset() */
nsecs += arch_gettimeoffset();
} while (read_seqretry(&xtime_lock, seq));
timespec_add_ns(ts, nsecs);
}
EXPORT_SYMBOL(getnstimeofday);
ktime_t ktime_get(void)
{
unsigned int seq;
s64 secs, nsecs;
WARN_ON(<API key>);
do {
seq = read_seqbegin(&xtime_lock);
secs = xtime.tv_sec + wall_to_monotonic.tv_sec;
nsecs = xtime.tv_nsec + wall_to_monotonic.tv_nsec;
nsecs += timekeeping_get_ns();
} while (read_seqretry(&xtime_lock, seq));
/*
* Use ktime_set/ktime_add_ns to create a proper ktime on
* 32-bit architectures without CONFIG_KTIME_SCALAR.
*/
return ktime_add_ns(ktime_set(secs, 0), nsecs);
}
EXPORT_SYMBOL(ktime_get);
/**
* ktime_get_ts - get the monotonic clock in timespec format
* @ts: pointer to timespec variable
*
* The function calculates the monotonic clock from the realtime
* clock and the wall_to_monotonic offset and stores the result
* in normalized timespec format in the variable pointed to by @ts.
*/
void ktime_get_ts(struct timespec *ts)
{
struct timespec tomono;
unsigned int seq;
s64 nsecs;
WARN_ON(<API key>);
do {
seq = read_seqbegin(&xtime_lock);
*ts = xtime;
tomono = wall_to_monotonic;
nsecs = timekeeping_get_ns();
} while (read_seqretry(&xtime_lock, seq));
<API key>(ts, ts->tv_sec + tomono.tv_sec,
ts->tv_nsec + tomono.tv_nsec + nsecs);
}
EXPORT_SYMBOL_GPL(ktime_get_ts);
/**
* do_gettimeofday - Returns the time of day in a timeval
* @tv: pointer to the timeval to be set
*
* NOTE: Users should be converted to using getnstimeofday()
*/
void do_gettimeofday(struct timeval *tv)
{
struct timespec now;
getnstimeofday(&now);
tv->tv_sec = now.tv_sec;
tv->tv_usec = now.tv_nsec/1000;
}
EXPORT_SYMBOL(do_gettimeofday);
/**
* do_settimeofday - Sets the time of day
* @tv: pointer to the timespec variable containing the new time
*
* Sets the time of day to the new time and update NTP and notify hrtimers
*/
int do_settimeofday(struct timespec *tv)
{
struct timespec ts_delta;
unsigned long flags;
if ((unsigned long)tv->tv_nsec >= NSEC_PER_SEC)
return -EINVAL;
<API key>(&xtime_lock, flags);
<API key>();
ts_delta.tv_sec = tv->tv_sec - xtime.tv_sec;
ts_delta.tv_nsec = tv->tv_nsec - xtime.tv_nsec;
wall_to_monotonic = timespec_sub(wall_to_monotonic, ts_delta);
xtime = *tv;
update_xtime_cache(0);
timekeeper.ntp_error = 0;
ntp_clear();
update_vsyscall(&xtime, timekeeper.clock, timekeeper.mult);
<API key>(&xtime_lock, flags);
/* signal hrtimers about time change */
clock_was_set();
return 0;
}
EXPORT_SYMBOL(do_settimeofday);
/**
* change_clocksource - Swaps clocksources if a new one is available
*
* Accumulates current time interval and initializes new clocksource
*/
static int change_clocksource(void *data)
{
struct clocksource *new, *old;
new = (struct clocksource *) data;
<API key>();
if (!new->enable || new->enable(new) == 0) {
old = timekeeper.clock;
<API key>(new);
if (old->disable)
old->disable(old);
}
return 0;
}
/**
* timekeeping_notify - Install a new clock source
* @clock: pointer to the clock source
*
* This function is called from clocksource.c after a new, better clock
* source has been registered. The caller holds the clocksource_mutex.
*/
void timekeeping_notify(struct clocksource *clock)
{
if (timekeeper.clock == clock)
return;
stop_machine(change_clocksource, clock, NULL);
tick_clock_notify();
}
#else /* GENERIC_TIME */
static inline void <API key>(void) { }
/**
* ktime_get - get the monotonic time in ktime_t format
*
* returns the time in ktime_t format
*/
ktime_t ktime_get(void)
{
struct timespec now;
ktime_get_ts(&now);
return timespec_to_ktime(now);
}
EXPORT_SYMBOL_GPL(ktime_get);
/**
* ktime_get_ts - get the monotonic clock in timespec format
* @ts: pointer to timespec variable
*
* The function calculates the monotonic clock from the realtime
* clock and the wall_to_monotonic offset and stores the result
* in normalized timespec format in the variable pointed to by @ts.
*/
void ktime_get_ts(struct timespec *ts)
{
struct timespec tomono;
unsigned long seq;
do {
seq = read_seqbegin(&xtime_lock);
getnstimeofday(ts);
tomono = wall_to_monotonic;
} while (read_seqretry(&xtime_lock, seq));
<API key>(ts, ts->tv_sec + tomono.tv_sec,
ts->tv_nsec + tomono.tv_nsec);
}
EXPORT_SYMBOL_GPL(ktime_get_ts);
#endif /* !GENERIC_TIME */
/**
* ktime_get_real - get the real (wall-) time in ktime_t format
*
* returns the time in ktime_t format
*/
ktime_t ktime_get_real(void)
{
struct timespec now;
getnstimeofday(&now);
return timespec_to_ktime(now);
}
EXPORT_SYMBOL_GPL(ktime_get_real);
void getrawmonotonic(struct timespec *ts)
{
unsigned long seq;
s64 nsecs;
do {
seq = read_seqbegin(&xtime_lock);
nsecs = <API key>();
*ts = raw_time;
} while (read_seqretry(&xtime_lock, seq));
timespec_add_ns(ts, nsecs);
}
EXPORT_SYMBOL(getrawmonotonic);
/**
* <API key> - Check if timekeeping is suitable for hres
*/
int <API key>(void)
{
unsigned long seq;
int ret;
do {
seq = read_seqbegin(&xtime_lock);
ret = timekeeper.clock->flags & <API key>;
} while (read_seqretry(&xtime_lock, seq));
return ret;
}
/**
* <API key> - Returns max time the clocksource can be deferred
*
* Caller must observe xtime_lock via read_seqbegin/read_seqretry to
* ensure that the clocksource does not change!
*/
u64 <API key>(void)
{
return timekeeper.clock->max_idle_ns;
}
/**
* <API key> - Return time from the persistent clock.
*
* Weak dummy function for arches that do not yet support it.
* Reads the time from the battery backed persistent clock.
* Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
*
* XXX - Do be sure to remove it once all arches implement it.
*/
void __attribute__((weak)) <API key>(struct timespec *ts)
{
ts->tv_sec = 0;
ts->tv_nsec = 0;
}
/**
* read_boot_clock - Return time of the system start.
*
* Weak dummy function for arches that do not yet support it.
* Function to read the exact time the system has been started.
* Returns a timespec with tv_sec=0 and tv_nsec=0 if unsupported.
*
* XXX - Do be sure to remove it once all arches implement it.
*/
void __attribute__((weak)) read_boot_clock(struct timespec *ts)
{
ts->tv_sec = 0;
ts->tv_nsec = 0;
}
#if defined(CONFIG_KEXEC) && defined(CONFIG_PRAM)
int <API key> = 1;
static struct timespec preserved_uptime;
static inline void <API key>(struct timespec *ts)
{
*ts = timespec_add_safe(*ts, preserved_uptime);
}
static inline void <API key>(struct timespec *ts)
{
*ts = timespec_sub(*ts, preserved_uptime);
}
#define <API key> "uptime"
static void preserve_uptime(void)
{
struct pram_stream stream;
static struct timespec uptime;
__u64 uptime_raw;
int err;
if (!<API key>)
return;
<API key>(&uptime);
<API key>(&uptime);
uptime_raw = (((__u64)uptime.tv_sec) << 32) + uptime.tv_nsec;
err = pram_open(<API key>, PRAM_WRITE, &stream);
if (err)
goto out;
if (pram_write(&stream, &uptime_raw, 8) != 8)
err = -EIO;
pram_close(&stream, err);
out:
if (err)
printk(KERN_ERR "Failed to preserve uptime: %d\n", err);
else
printk(KERN_INFO "Uptime preserved (%llu)\n",
(unsigned long long)uptime_raw);
}
static void __init <API key>(void)
{
struct pram_stream stream;
__u64 uptime_raw;
int err;
err = pram_open(<API key>, PRAM_READ, &stream);
if (err)
goto out;
if (pram_read(&stream, &uptime_raw, 8) != 8)
err = -EIO;
pram_close(&stream, err);
out:
if (err && err != -ENOENT)
printk(KERN_ERR "Failed to preserve uptime: %d\n", err);
if (!err) {
preserved_uptime.tv_sec = uptime_raw >> 32;
preserved_uptime.tv_nsec = uptime_raw & 0xFFFFFFFF;
printk(KERN_INFO "Uptime preserved (%llu)\n",
(unsigned long long)uptime_raw);
}
}
#else
static inline void <API key>(struct timespec *ts) { }
static inline void <API key>(struct timespec *ts) { }
static inline void preserve_uptime(void) { }
static inline void <API key>(void) { }
#endif
/*
* timekeeping_init - Initializes the clocksource and common timekeeping values
*/
void __init timekeeping_init(void)
{
struct clocksource *clock;
unsigned long flags;
struct timespec now, boot;
<API key>(&now);
read_boot_clock(&boot);
<API key>(&xtime_lock, flags);
ntp_init();
clock = <API key>();
if (clock->enable)
clock->enable(clock);
<API key>(clock);
xtime.tv_sec = now.tv_sec;
xtime.tv_nsec = now.tv_nsec;
raw_time.tv_sec = 0;
raw_time.tv_nsec = 0;
if (boot.tv_sec == 0 && boot.tv_nsec == 0) {
boot.tv_sec = xtime.tv_sec;
boot.tv_nsec = xtime.tv_nsec;
}
<API key>(&wall_to_monotonic,
-boot.tv_sec, -boot.tv_nsec);
update_xtime_cache(0);
total_sleep_time.tv_sec = 0;
total_sleep_time.tv_nsec = 0;
<API key>(&xtime_lock, flags);
<API key>();
}
static int <API key>(struct sys_device *dev)
{
preserve_uptime();
return 0;
}
/* time in seconds when suspend began */
static struct timespec <API key>;
/**
* timekeeping_resume - Resumes the generic timekeeping subsystem.
* @dev: unused
*
* This is for the generic clocksource timekeeping.
* xtime/wall_to_monotonic/jiffies/etc are
* still managed by arch specific suspend/resume code.
*/
static int timekeeping_resume(struct sys_device *dev)
{
unsigned long flags;
struct timespec ts;
<API key>(&ts);
clocksource_resume();
<API key>(&xtime_lock, flags);
if (timespec_compare(&ts, &<API key>) > 0) {
ts = timespec_sub(ts, <API key>);
xtime = timespec_add_safe(xtime, ts);
wall_to_monotonic = timespec_sub(wall_to_monotonic, ts);
total_sleep_time = timespec_add_safe(total_sleep_time, ts);
}
update_xtime_cache(0);
/* re-base the last cycle value */
timekeeper.clock->cycle_last = timekeeper.clock->read(timekeeper.clock);
timekeeper.ntp_error = 0;
<API key> = 0;
<API key>(&xtime_lock, flags);
<API key>();
clockevents_notify(<API key>, NULL);
/* Resume hrtimers */
hres_timers_resume();
return 0;
}
static int timekeeping_suspend(struct sys_device *dev, pm_message_t state)
{
unsigned long flags;
<API key>(&<API key>);
<API key>(&xtime_lock, flags);
<API key>();
<API key> = 1;
<API key>(&xtime_lock, flags);
clockevents_notify(<API key>, NULL);
return 0;
}
/* sysfs resume/suspend bits for timekeeping */
static struct sysdev_class <API key> = {
.name = "timekeeping",
.shutdown = <API key>,
.resume = timekeeping_resume,
.suspend = timekeeping_suspend,
};
static struct sys_device device_timer = {
.id = 0,
.cls = &<API key>,
};
static int __init <API key>(void)
{
int error = <API key>(&<API key>);
if (!error)
error = sysdev_register(&device_timer);
return error;
}
device_initcall(<API key>);
/*
* If the error is already larger, we look ahead even further
* to compensate for late or lost adjustments.
*/
static __always_inline int <API key>(s64 error, s64 *interval,
s64 *offset)
{
s64 tick_error, i;
u32 look_ahead, adj;
s32 error2, mult;
/*
* Use the current error value to determine how much to look ahead.
* The larger the error the slower we adjust for it to avoid problems
* with losing too many ticks, otherwise we would overadjust and
* produce an even larger error. The smaller the adjustment the
* faster we try to adjust for it, as lost ticks can do less harm
* here. This is tuned so that an error of about 1 msec is adjusted
* within about 1 sec (or 2^20 nsec in 2^SHIFT_HZ ticks).
*/
error2 = timekeeper.ntp_error >> (NTP_SCALE_SHIFT + 22 - 2 * SHIFT_HZ);
error2 = abs(error2);
for (look_ahead = 0; error2 > 0; look_ahead++)
error2 >>= 2;
/*
* Now calculate the error in (1 << look_ahead) ticks, but first
* remove the single look ahead already included in the error.
*/
tick_error = tick_length >> (timekeeper.ntp_error_shift + 1);
tick_error -= timekeeper.xtime_interval >> 1;
error = ((error - tick_error) >> look_ahead) + tick_error;
/* Finally calculate the adjustment shift value. */
i = *interval;
mult = 1;
if (error < 0) {
error = -error;
*interval = -*interval;
*offset = -*offset;
mult = -1;
}
for (adj = 0; error > i; adj++)
error >>= 1;
*interval <<= adj;
*offset <<= adj;
return mult << adj;
}
/*
* Adjust the multiplier to reduce the error value,
* this is optimized for the most common adjustments of -1,0,1,
* for other values we can do a bit more work.
*/
static void timekeeping_adjust(s64 offset)
{
s64 error, interval = timekeeper.cycle_interval;
int adj;
error = timekeeper.ntp_error >> (timekeeper.ntp_error_shift - 1);
if (error > interval) {
error >>= 2;
if (likely(error <= interval))
adj = 1;
else
adj = <API key>(error, &interval, &offset);
} else if (error < -interval) {
error >>= 2;
if (likely(error >= -interval)) {
adj = -1;
interval = -interval;
offset = -offset;
} else
adj = <API key>(error, &interval, &offset);
} else
return;
timekeeper.mult += adj;
timekeeper.xtime_interval += interval;
timekeeper.xtime_nsec -= offset;
timekeeper.ntp_error -= (interval - offset) <<
timekeeper.ntp_error_shift;
}
/**
* <API key> - shifted accumulation of cycles
*
* This functions accumulates a shifted interval of cycles into
* into a shifted interval nanoseconds. Allows for O(log) accumulation
* loop.
*
* Returns the unconsumed cycles.
*/
static cycle_t <API key>(cycle_t offset, int shift)
{
u64 nsecps = (u64)NSEC_PER_SEC << timekeeper.shift;
/* If the offset is smaller then a shifted interval, do nothing */
if (offset < timekeeper.cycle_interval<<shift)
return offset;
/* Accumulate one shifted interval */
offset -= timekeeper.cycle_interval << shift;
timekeeper.clock->cycle_last += timekeeper.cycle_interval << shift;
timekeeper.xtime_nsec += timekeeper.xtime_interval << shift;
while (timekeeper.xtime_nsec >= nsecps) {
timekeeper.xtime_nsec -= nsecps;
xtime.tv_sec++;
second_overflow();
}
/* Accumulate into raw time */
raw_time.tv_nsec += timekeeper.raw_interval << shift;;
while (raw_time.tv_nsec >= NSEC_PER_SEC) {
raw_time.tv_nsec -= NSEC_PER_SEC;
raw_time.tv_sec++;
}
/* Accumulate error between NTP and clock interval */
timekeeper.ntp_error += tick_length << shift;
timekeeper.ntp_error -= timekeeper.xtime_interval <<
(timekeeper.ntp_error_shift + shift);
return offset;
}
/**
* update_wall_time - Uses the current clocksource to increment the wall time
*
* Called from the timer interrupt, must hold a write on xtime_lock.
*/
void update_wall_time(void)
{
struct clocksource *clock;
cycle_t offset;
u64 nsecs;
int shift = 0, maxshift;
/* Make sure we're fully resumed: */
if (unlikely(<API key>))
return;
clock = timekeeper.clock;
#ifdef CONFIG_GENERIC_TIME
offset = (clock->read(clock) - clock->cycle_last) & clock->mask;
#else
offset = timekeeper.cycle_interval;
#endif
timekeeper.xtime_nsec = (s64)xtime.tv_nsec << timekeeper.shift;
/*
* With NO_HZ we may have to accumulate many cycle_intervals
* (think "ticks") worth of time at once. To do this efficiently,
* we calculate the largest doubling multiple of cycle_intervals
* that is smaller then the offset. We then accumulate that
* chunk in one go, and then try to consume the next smaller
* doubled multiple.
*/
shift = ilog2(offset) - ilog2(timekeeper.cycle_interval);
shift = max(0, shift);
/* Bound shift to one less then what overflows tick_length */
maxshift = (8*sizeof(tick_length) - (ilog2(tick_length)+1)) - 1;
shift = min(shift, maxshift);
while (offset >= timekeeper.cycle_interval) {
offset = <API key>(offset, shift);
if(offset < timekeeper.cycle_interval<<shift)
shift
}
/* correct the clock when NTP error is too big */
timekeeping_adjust(offset);
/*
* Since in the loop above, we accumulate any amount of time
* in xtime_nsec over a second into xtime.tv_sec, its possible for
* xtime_nsec to be fairly small after the loop. Further, if we're
* slightly speeding the clocksource up in timekeeping_adjust(),
* its possible the required corrective factor to xtime_nsec could
* cause it to underflow.
*
* Now, we cannot simply roll the accumulated second back, since
* the NTP subsystem has been notified via second_overflow. So
* instead we push xtime_nsec forward by the amount we underflowed,
* and add that amount into the error.
*
* We'll correct this error next time through this function, when
* xtime_nsec is not as small.
*/
if (unlikely((s64)timekeeper.xtime_nsec < 0)) {
s64 neg = -(s64)timekeeper.xtime_nsec;
timekeeper.xtime_nsec = 0;
timekeeper.ntp_error += neg << timekeeper.ntp_error_shift;
}
/* store full nanoseconds into xtime after rounding it up and
* add the remainder to the error difference.
*/
xtime.tv_nsec = ((s64) timekeeper.xtime_nsec >> timekeeper.shift) + 1;
timekeeper.xtime_nsec -= (s64) xtime.tv_nsec << timekeeper.shift;
timekeeper.ntp_error += timekeeper.xtime_nsec <<
timekeeper.ntp_error_shift;
nsecs = clocksource_cyc2ns(offset, timekeeper.mult, timekeeper.shift);
update_xtime_cache(nsecs);
/* check to see if there is a new clocksource to use */
update_vsyscall(&xtime, timekeeper.clock, timekeeper.mult);
}
/**
* getboottime - Return the real time of system boot.
* @ts: pointer to the timespec to be set
*
* Returns the time of day in a timespec.
*
* This is based on the wall_to_monotonic offset and the total suspend
* time. Calls to settimeofday will affect the value returned (which
* basically means that however wrong your real time clock is at boot time,
* you get the right time here).
*/
void getrealboottime(struct timespec *ts)
{
struct timespec boottime = {
.tv_sec = wall_to_monotonic.tv_sec + total_sleep_time.tv_sec,
.tv_nsec = wall_to_monotonic.tv_nsec + total_sleep_time.tv_nsec
};
<API key>(ts, -boottime.tv_sec, -boottime.tv_nsec);
}
EXPORT_SYMBOL_GPL(getrealboottime);
void getboottime(struct timespec *ts)
{
getrealboottime(ts);
<API key>(ts);
}
EXPORT_SYMBOL_GPL(getboottime);
/**
* <API key> - Convert the monotonic time to boot based.
* @ts: pointer to the timespec to be converted
*/
void <API key>(struct timespec *ts)
{
*ts = timespec_add_safe(*ts, total_sleep_time);
<API key>(ts);
}
EXPORT_SYMBOL_GPL(<API key>);
unsigned long get_seconds(void)
{
return xtime_cache.tv_sec;
}
EXPORT_SYMBOL(get_seconds);
struct timespec <API key>(void)
{
return xtime_cache;
}
struct timespec current_kernel_time(void)
{
struct timespec now;
unsigned long seq;
do {
seq = read_seqbegin(&xtime_lock);
now = xtime_cache;
} while (read_seqretry(&xtime_lock, seq));
return now;
}
EXPORT_SYMBOL(current_kernel_time);
struct timespec <API key>(void)
{
struct timespec now, mono;
unsigned long seq;
do {
seq = read_seqbegin(&xtime_lock);
now = xtime_cache;
mono = wall_to_monotonic;
} while (read_seqretry(&xtime_lock, seq));
<API key>(&now, now.tv_sec + mono.tv_sec,
now.tv_nsec + mono.tv_nsec);
return now;
}
/**
* * <API key>() - get wall_to_monotonic in ktime_t format
* */
ktime_t <API key>(void)
{
unsigned long seq;
struct timespec wtom;
do {
seq = read_seqbegin(&xtime_lock);
wtom = wall_to_monotonic;
} while (read_seqretry(&xtime_lock, seq));
return timespec_to_ktime(wtom);
} |
#ifndef <API key>
#define <API key>
#include <glib-object.h>
#include "gdm-login-extension.h"
G_BEGIN_DECLS
#define <API key> (<API key> ())
#define <API key>(obj) (<API key> ((obj), <API key>, GdmUnifiedExtension))
#define <API key>(klass) (<API key> ((klass), <API key>, <API key>))
#define <API key>(obj) (<API key> ((obj), <API key>))
#define <API key>(klass) (<API key> ((klass), <API key>))
#define <API key>(obj) (<API key>((obj), <API key>, <API key>))
#define <API key> "<API key>"
typedef struct <API key> <API key>;
typedef struct
{
GObject parent;
<API key> *priv;
} GdmUnifiedExtension;
typedef struct
{
GObjectClass parent_class;
} <API key>;
GType <API key> (void);
void <API key> (void);
G_END_DECLS
#endif /* <API key> */ |
#!/usr/bin/python
# -*- encoding: utf-8; py-indent-offset: 4 -*-
# This file is part of Check_MK.
# check_mk is free software; you can redistribute it and/or modify it
# the Free Software Foundation in version 2. check_mk is distributed
# tails. You should have received a copy of the GNU General Public
# to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
# Boston, MA 02110-1301 USA.
import utils
import bi, views, visuals
import sites
from valuespec import *
import cmk.defines as defines
import cmk.paths
import cmk.store as store
<API key> = [
( "up", "state0", _("UP"), None ),
( "down", "state2", _("DOWN"), None ),
( "unreach", "state3", _("UNREACH"), None ),
( "flapping", "flapping", _("Flapping"), None ),
( "in_downtime", "downtime", _("Downtime"), _("The host was in a scheduled downtime") ),
( "<API key>", "", _("OO/Notif"), _("Out of Notification Period") ),
( "<API key>", "ooservice", _("OO/Service") , _("Out of Service Period") ),
( "unmonitored", "unmonitored", _("N/A"), _("During this time period no monitoring data is available") ),
]
<API key> = [
( "ok", "state0", _("OK"), None ),
( "warn", "state1", _("WARN"), None ),
( "crit", "state2", _("CRIT"), None ),
( "unknown", "state3", _("UNKNOWN"), None ),
( "flapping", "flapping", _("Flapping"), None ),
( "host_down", "hostdown", _("H.Down"), _("The host was down") ),
( "in_downtime", "downtime", _("Downtime"), _("The host or service was in a scheduled downtime") ),
( "<API key>", "", _("OO/Notif"), _("Out of Notification Period") ),
( "<API key>", "ooservice", _("OO/Service"), _("Out of Service Period") ),
( "unmonitored", "unmonitored", _("N/A"), _("During this time period no monitoring data is available") ),
]
<API key> = [
( "ok", "state0", _("OK"), None ),
( "warn", "state1", _("WARN"), None ),
( "crit", "state2", _("CRIT"), None ),
( "unknown", "state3", _("UNKNOWN"), None ),
( "in_downtime", "downtime", _("Downtime"), _("The aggregate was in a scheduled downtime") ),
( "unmonitored", "unmonitored", _("N/A"), _("During this time period no monitoring data is available") ),
]
<API key> = {
"host" : <API key>,
"service" : <API key>,
"bi" : <API key>,
}
statistics_headers = {
"min" : _("Shortest"),
"max" : _("Longest"),
"avg" : _("Average"),
"cnt" : _("Count"),
}
# | Handling of all options for tuning availability computation and |
# | display. |
# Options for availability computation and rendering. These are four-tuple
# with the columns:
# 1. variable name
# 2. show in single or double height box
# 3. use this in reporting
# 4. the valuespec
def <API key>(what):
if what == "bi":
grouping_choices = [
( None, _("Do not group") ),
( "host", _("By Aggregation Group") ),
]
else:
grouping_choices = [
( None, _("Do not group") ),
( "host", _("By Host") ),
( "host_groups", _("By Host group") ),
( "service_groups", _("By Service group") ),
]
def aligned_label(text):
return "<div style=\"width: 186px; display: inline-block;\">%s:</div>" % text
return [
# Time range selection
( "rangespec",
"double",
False,
Timerange(
title = _("Time Range"),
default_value = 'd0',
)),
# Labelling and Texts
( "labelling",
"double",
True,
ListChoice(
title = _("Labelling Options"),
choices = [
( "omit_headers", _("Do not display column headers")),
( "omit_host", _("Do not display the host name")),
( "show_alias", _("Display the host alias")),
( "use_display_name", _("Use alternative display name for services")),
( "omit_buttons", _("Do not display icons for history and timeline")),
( "<API key>", _("Display legend for timeline")),
( "omit_av_levels", _("Do not display legend for availability levels")),
]
)),
# How to deal with downtimes
( "downtimes",
"double",
True,
Dictionary(
title = _("Scheduled Downtimes"),
columns = 2,
elements = [
( "include",
DropdownChoice(
choices = [
( "honor", _("Honor scheduled downtimes") ),
( "ignore", _("Ignore scheduled downtimes") ),
( "exclude", _("Exclude scheduled downtimes" ) ),
],
default_value = "honor",
)
),
( "exclude_ok",
Checkbox(label = _("Treat phases of UP/OK as non-downtime"))
),
],
optional_keys = False,
)),
# How to deal with downtimes, etc.
( "consider",
"double",
True,
Dictionary(
title = _("Status Classification"),
columns = 2,
elements = [
( "flapping",
Checkbox(
label = _("Consider periods of flapping states"),
default_value = True),
),
( "host_down",
Checkbox(
label = _("Consider times where the host is down"),
default_value = True),
),
( "unmonitored",
Checkbox(
label = _("Include unmonitored time"),
default_value = True),
),
],
optional_keys = False,
)),
( "state_grouping",
"double",
True,
Dictionary(
title = _("Service Status Grouping"),
columns = 2,
elements = [
( "warn",
DropdownChoice(
label = aligned_label(_("Treat Warning as")),
choices = [
( "ok", _("OK") ),
( "warn", _("WARN") ),
( "crit", _("CRIT") ),
( "unknown", _("UNKNOWN") ),
],
default_value = "warn",
),
),
( "unknown",
DropdownChoice(
label = aligned_label(_("Treat Unknown/Unreachable as")),
choices = [
( "ok", _("OK") ),
( "warn", _("WARN") ),
( "crit", _("CRIT") ),
( "unknown", _("UNKNOWN") ),
],
default_value = "unknown",
),
),
( "host_down",
DropdownChoice(
label = aligned_label(_("Treat Host Down as")),
choices = [
( "ok", _("OK") ),
( "warn", _("WARN") ),
( "crit", _("CRIT") ),
( "unknown", _("UNKNOWN") ),
( "host_down", _("Host Down") ),
],
default_value = "host_down",
),
),
],
optional_keys = False,
)),
# Visual levels for the availability
( "av_levels",
"double",
True,
Optional(
Tuple(
elements = [
Percentage(title = _("Warning below"), default_value = 99, display_format="%.3f", size=7),
Percentage(title = _("Critical below"), default_value = 95, display_format="%.3f", size=7),
]
),
title = _("Visual levels for the availability (OK percentage)"),
)),
# Filter rows according to actual availability
( "av_filter_outages",
"double",
True,
Dictionary(
title = _("Only show objects with outages"),
columns = 2,
elements = [
( "warn", Percentage(title = _("Show only rows with WARN of at least"), default_value = 0.0)),
( "crit", Percentage(title = _("Show only rows with CRIT of at least"), default_value = 0.0)),
( "non-ok", Percentage(title = _("Show only rows with non-OK of at least"), default_value = 0.0)),
],
optional_keys = False,
)),
# Show colummns for min, max, avg duration and count
( "outage_statistics",
"double",
True,
Tuple(
title = _("Outage statistics"),
orientation = "horizontal",
elements = [
ListChoice(
title = _("Aggregations"),
choices = [
( "min", _("min. duration" )),
( "max", _("max. duration" )),
( "avg", _("avg. duration" )),
( "cnt", _("count" )),
]
),
ListChoice(
title = _("For these states:"),
columns = 2,
choices = [
( "ok", _("OK/Up") ),
( "warn", _("Warn") ),
( "crit", _("Crit/Down") ),
( "unknown", _("Unknown/Unreach") ),
( "flapping", _("Flapping") ),
( "host_down", _("Host Down") ),
( "in_downtime", _("Downtime") ),
( "<API key>", _("OO/Notif") ),
]
)
]
)),
( "timeformat",
"double",
True,
Tuple(
title = _("Format time ranges"),
elements = [
RadioChoice(
choices = [
("both", _("Percent and time")),
("perc", _("Only percent")),
("time", _("Only time")),
],
default_value = "perc",
),
DropdownChoice(
choices = [
("percentage_0", _("Percentage - XX %") ),
("percentage_1", _("Percentage - XX.X %") ),
("percentage_2", _("Percentage - XX.XX %") ),
("percentage_3", _("Percentage - XX.XXX %") ),
],
default_value = "percentage_2"
),
DropdownChoice(
choices = [
("seconds", _("Seconds") ),
("minutes", _("Minutes") ),
("hours", _("Hours") ),
("hhmmss", _("HH:MM:SS") ),
],
default_value = None
),
],
)),
# Optionally group some states together
( "host_state_grouping",
"single",
True,
Dictionary(
title = _("Host Status Grouping"),
columns = 2,
elements = [
( "unreach",
DropdownChoice(
label = aligned_label(_("Treat Unreachable as")),
choices = [
( "up", _("UP") ),
( "down", _("DOWN") ),
( "unreach", _("UNREACH") ),
],
default_value = "unreach",
),
),
],
optional_keys = False,
)),
# Omit all non-OK columns
( "av_mode",
"single",
True,
Checkbox(
title = _("Availability"),
label = _("Just show the availability (i.e. OK/UP)"),
)),
# How to deal with the service periods
( "service_period",
"single",
True,
DropdownChoice(
title = _("Service Time"),
choices = [
( "honor", _("Base report only on service times") ),
( "ignore", _("Include both service and non-service times" ) ),
( "exclude", _("Base report only on non-service times" ) ),
],
default_value = "honor",
)),
# How to deal with times out of the notification period
( "notification_period",
"single",
True,
DropdownChoice(
title = _("Notification Period"),
choices = [
( "honor", _("Distinguish times in and out of notification period") ),
( "exclude", _("Exclude times out of notification period" ) ),
( "ignore", _("Ignore notification period") ),
],
default_value = "ignore",
)),
# Group by Host, Hostgroup or Servicegroup?
( "grouping",
"single",
True,
DropdownChoice(
title = _("Grouping"),
choices = grouping_choices,
default_value = None,
)),
# Format of numbers
( "dateformat",
"single",
True,
DropdownChoice(
title = _("Format time stamps as"),
choices = [
("yyyy-mm-dd hh:mm:ss", _("YYYY-MM-DD HH:MM:SS") ),
("epoch", _("Unix Timestamp (Epoch)") ),
],
default_value = "yyyy-mm-dd hh:mm:ss",
)),
# Short time intervals
( "short_intervals",
"single",
True,
Integer(
title = _("Short Time Intervals"),
label = _("Ignore intervals shorter or equal"),
minvalue = 0,
unit = _("sec"),
default_value = 0,
)),
# Merging
( "dont_merge",
"single",
True,
Checkbox(
title = _("Phase Merging"),
label = _("Do not merge consecutive phases with equal state"),
)),
# Summary line
( "summary",
"single",
True,
DropdownChoice(
title = _("Summary line"),
choices = [
( None, _("Do not show a summary line") ),
( "sum", _("Display total sum (for % the average)") ),
( "average", _("Display average") ),
],
default_value = "sum",
)),
# Timeline
( "show_timeline",
"single",
True,
Checkbox(
title = _("Timeline"),
label = _("Show timeline of each object directly in table"),
)),
( "timelimit",
"single",
False,
Age(
title = _("Query Time Limit"),
help = _("Limit the execution time of the query, in order to "
"avoid a hanging system."),
unit = _("sec"),
default_value = 30,
)),
( "logrow_limit",
"single",
True,
Integer(
title = _("Limit processed data"),
help = _("The availability is computed by processing entries from a data table "
"of historic events and state phases. In order to avoid a hanging system "
"in cases where your time range and filtering would accept a vast amount "
"of data entries, the number of processed entries is limited. You can raise "
"this limit here if you really need to process a huge amount of data. Set this "
"to zero in order to disable the limit."),
label = _("Process at most"),
unit = _("status entries"),
minvalue = 0,
default_value = 5000,
)),
]
# Creates a function for rendering time values according to
# the avoptions of the report.
def <API key>(timeformat):
if timeformat.startswith("percentage_"):
def render_number(n, d):
if not d:
return _("n/a")
else:
return ("%." + timeformat[11:] + "f%%") % ( float(n) / float(d) * 100.0)
elif timeformat == "seconds":
def render_number(n, d):
return "%d s" % n
elif timeformat == "minutes":
def render_number(n, d):
return "%d min" % (n / 60)
elif timeformat == "hours":
def render_number(n, d):
return "%d h" % (n / 3600)
else:
def render_number(n, d):
minn, sec = divmod(n, 60)
hours, minn = divmod(minn, 60)
return "%02d:%02d:%02d" % (hours, minn, sec)
return render_number
def <API key>(timeformat):
this_timeformat = [ ("percentage_2", <API key>("percentage_2")) ]
if type(timeformat) in [ list, tuple ]:
if timeformat[0] == "both":
this_timeformat = map(lambda x: (x, <API key>(x)), timeformat[1:])
elif timeformat[0] == "perc":
this_timeformat = [ (timeformat[1], <API key>(timeformat[1])) ]
elif timeformat[0] == "time":
this_timeformat = [ (timeformat[2], <API key>(timeformat[2])) ]
elif timeformat.startswith("percentage_") or \
timeformat in [ "seconds", "minutes", "hours", "hhmmss" ]:
# Old style
this_timeformat = [ (timeformat, <API key>(timeformat)) ]
return this_timeformat
def <API key>():
return {
"range" : (time.time() - 86400, time.time()),
"rangespec" : "d0",
"labelling" : [],
"av_levels" : None,
"av_filter_outages" : { "warn" : 0.0, "crit" : 0.0, "non-ok" : 0.0 },
"outage_statistics" : ([],[]),
"av_mode" : False,
"service_period" : "honor",
"notification_period" : "ignore",
"grouping" : None,
"dateformat" : "yyyy-mm-dd hh:mm:ss",
"timeformat" : ("perc", "percentage_2", None),
"short_intervals" : 0,
"dont_merge" : False,
"summary" : "sum",
"show_timeline" : False,
"timelimit" : 30,
"logrow_limit" : 5000,
"downtimes" : {
"include" : "honor",
"exclude_ok" : False,
},
"consider" : {
"flapping" : True,
"host_down" : True,
"unmonitored" : True,
},
"host_state_grouping" : {
"unreach" : "unreach",
},
"state_grouping" : {
"warn" : "warn",
"unknown" : "unknown",
"host_down" : "host_down",
},
}
def <API key>(avoptions):
# Outage options are stored with keys matching service states (like "ok" and "crit").
# For hosts we use the same checkbox but mean "up" and "down". We simply add these states
# to the list of selected states.
aggrs, states = avoptions.get("outage_statistics", ([], []))
fixed_states = states[:]
for os, oh in [ ("ok","up"), ("crit","down"), ("unknown", "unreach") ]:
if os in fixed_states:
fixed_states.append(oh)
return aggrs, fixed_states
# | Computation of availability data into abstract data structures. |
# | These are being used for rendering in HTML and also for the re- |
# | porting module. Could also be a source for exporting data into |
# | files like CSV or spread sheets. |
# | This code might be moved to another file. |
# Get raw availability data via livestatus. The result is a list
# of spans. Each span is a dictionary that describes one span of time where
# a specific host or service has one specific state.
# what is either "host" or "service" or "bi".
def <API key>(what, context, filterheaders, only_sites, av_object, include_output, avoptions):
if what == "bi":
return <API key>(filterheaders, only_sites, av_object, include_output, avoptions)
time_range, range_title = avoptions["range"]
av_filter = "Filter: time >= %d\nFilter: time < %d\n" % time_range
if av_object:
tl_site, tl_host, tl_service = av_object
av_filter += "Filter: host_name = %s\nFilter: service_description = %s\n" % (
tl_host, tl_service)
only_sites = [ tl_site ]
elif what == "service":
av_filter += "Filter: service_description !=\n"
else:
av_filter += "Filter: service_description =\n"
query = "GET statehist\n" + av_filter
query += "Timelimit: %d\n" % avoptions["timelimit"]
logrow_limit = avoptions["logrow_limit"]
if logrow_limit:
query += "Limit: %d\n" % (logrow_limit + 1)
# Add Columns needed for object identification
columns = [ "host_name", "service_description" ]
# Columns for availability
columns += [
"duration", "from", "until", "state", "host_down", "in_downtime",
"in_host_downtime", "<API key>", "in_service_period", "is_flapping", ]
if include_output:
columns.append("log_output")
if "use_display_name" in avoptions["labelling"]:
columns.append("<API key>")
if "show_alias" in avoptions["labelling"]:
columns.append("host_alias")
# If we group by host/service group then make sure that that information is available
if avoptions["grouping"] not in [ None, "host" ]:
columns.append(avoptions["grouping"])
query += "Columns: %s\n" % " ".join(columns)
query += filterheaders
sites.live().set_prepend_site(True)
sites.live().set_only_sites(only_sites)
data = sites.live().query(query)
sites.live().set_only_sites(None)
sites.live().set_prepend_site(False)
columns = ["site"] + columns
spans = [ dict(zip(columns, span)) for span in data ]
# When a group filter is set, only care about these groups in the group fields
if avoptions["grouping"] not in [ None, "host" ]:
<API key>(context, avoptions, spans)
# Now we find out if the log row limit was exceeded or
# if the log's length is the limit by accident.
# If this limit was exceeded then we cut off the last element
# in spans_by_object because it might be incomplete.
<API key> = None
if logrow_limit and len(data) >= logrow_limit + 1:
<API key> = dict(zip(columns, data[-1]))
return spans_by_object(spans, <API key>)
def <API key>(context, avoptions, spans):
group_by = avoptions["grouping"]
only_groups = set()
# TODO: This is a dirty hack. The logic of the filters needs to be moved to the filters.
# They need to be able to filter the list of all groups.
# TODO: Negated filters are not handled here. :(
if group_by == "service_groups":
if "servicegroups" not in context and "optservicegroup" not in context:
return
# Extract from context:
# 'servicegroups': {'servicegroups': 'cpu|disk', 'neg_servicegroups': 'off'},
# 'optservicegroup': {'optservice_group': '', '<API key>': 'off'},
negated = context.get("servicegroups", {}).get("neg_servicegroups") == "on"
if negated:
return
only_groups.update([ e for e in context.get("servicegroups", {}).get("servicegroups", "").split("|") if e ])
negated = context.get("optservicegroup", {}).get("<API key>") == "on"
if negated:
return
group_name = context.get("optservicegroup", {}).get("optservice_group")
if group_name and not negated:
only_groups.add(group_name)
elif group_by == "host_groups":
if "hostgroups" not in context and "opthostgroup" not in context:
return
negated = context.get("hostgroups", {}).get("neg_hostgroups") == "on"
if negated:
return
only_groups.update([ e for e in context.get("hostgroups", {}).get("hostgroups", "").split("|") if e ])
negated = context.get("opthostgroup", {}).get("neg_opthost_group") == "on"
if negated:
return
group_name = context.get("opthostgroup", {}).get("opthost_group")
if group_name and not negated:
only_groups.add(group_name)
else:
raise NotImplementedError()
for span in spans:
filtered_groups = list(set(span[group_by]).intersection(only_groups))
span[group_by] = filtered_groups
# Sort the raw spans into a tree of dicts, so that we
# have easy access to the timeline of each object
def spans_by_object(spans, <API key>):
# Sort by site/host and service, while keeping native order
av_rawdata = {}
for span in spans:
site_host = span["site"], span["host_name"]
service = span["service_description"]
av_rawdata.setdefault(site_host, {})
av_rawdata[site_host].setdefault(service, []).append(span)
if <API key>:
site_host = (<API key>["site"], <API key>["host_name"])
if <API key>["service_description"]:
del av_rawdata[site_host][<API key>["service_description"]]
else:
del av_rawdata[site_host]
# We have to remember if rawdata was modified
return av_rawdata, <API key> != None
# Compute an availability table. what is one of "bi", "host", "service".
def <API key>(what, av_rawdata, avoptions):
<API key> = <API key>(what, av_rawdata)
# Now compute availability table. We have the following possible states:
# 1. "unmonitored"
# 2. monitored -->
# 2.1 "<API key>"
# 2.2 in service period -->
# 2.2.1 "<API key>"
# 2.2.2 in notification period -->
# 2.2.2.1 "in_downtime" (also in_host_downtime)
# 2.2.2.2 not in downtime -->
# 2.2.2.2.1 "host_down"
# 2.2.2.2.2 host not down -->
# 2.2.2.2.2.1 "ok"
# 2.2.2.2.2.2 "warn"
# 2.2.2.2.2.3 "crit"
# 2.2.2.2.2.4 "unknown"
availability_table = []
os_aggrs, os_states = <API key>(avoptions)
need_statistics = os_aggrs and os_states
grouping = avoptions["grouping"]
# Note: in case of timeline, we have data from exacly one host/service
for site_host, site_host_entry in <API key>.iteritems():
for service, service_entry in site_host_entry.iteritems():
if grouping == "host":
group_ids = [site_host]
elif grouping:
group_ids = set([])
else:
group_ids = None
# First compute timeline
timeline_rows = []
total_duration = 0
considered_duration = 0
for span in service_entry:
# Information about host/service groups are in the actual entries
if grouping and grouping != "host" and what != "bi":
group_ids.update(span[grouping]) # List of host/service groups
display_name = span.get("<API key>", service)
state = span["state"]
host_alias = span.get("host_alias", site_host[1])
consider = True
if avoptions["service_period"] != "ignore" and \
(( span["in_service_period"] and avoptions["service_period"] != "honor" )
or \
( not span["in_service_period"] and avoptions["service_period"] == "honor" )):
s = "<API key>"
consider = False
elif state == -1:
s = "unmonitored"
if not avoptions["consider"]["unmonitored"]:
consider = False
elif span["<API key>"] == 0 and avoptions["notification_period"] == "exclude":
consider = False
elif span["<API key>"] == 0 and avoptions["notification_period"] == "honor":
s = "<API key>"
elif (span["in_downtime"] or span["in_host_downtime"]) and not \
(avoptions["downtimes"]["exclude_ok"] and state == 0) and not \
avoptions["downtimes"]["include"] == "ignore":
if avoptions["downtimes"]["include"] == "exclude":
consider = False
else:
s = "in_downtime"
elif what != "host" and span["host_down"] and avoptions["consider"]["host_down"]:
# Reclassification due to state grouping
s = avoptions["state_grouping"].get("host_down", "host_down")
elif span["is_flapping"] and avoptions["consider"]["flapping"]:
s = "flapping"
else:
if what in [ "service", "bi" ]:
s = { 0: "ok", 1:"warn", 2:"crit", 3:"unknown" }.get(state, "unmonitored")
else:
s = { 0: "up", 1:"down", 2:"unreach" }.get(state, "unmonitored")
# Reclassification due to state grouping
if s in avoptions["state_grouping"]:
s = avoptions["state_grouping"][s]
elif s in avoptions["host_state_grouping"]:
s = avoptions["host_state_grouping"][s]
total_duration += span["duration"]
if consider:
timeline_rows.append((span, s))
considered_duration += span["duration"]
# Now merge consecutive rows with identical state
if not avoptions["dont_merge"]:
merge_timeline(timeline_rows)
# Melt down short intervals
if avoptions["short_intervals"]:
<API key>(timeline_rows, avoptions["short_intervals"], avoptions["dont_merge"])
# Condense into availability
states = {}
statistics = {}
for span, s in timeline_rows:
states.setdefault(s, 0)
duration = span["duration"]
states[s] += duration
if need_statistics:
entry = statistics.get(s)
if entry:
entry[0] += 1
entry[1] = min(entry[1], duration)
entry[2] = max(entry[2], duration)
else:
statistics[s] = [ 1, duration, duration ] # count, min, max
availability_entry = {
"site" : site_host[0],
"host" : site_host[1],
"alias" : host_alias,
"service" : service,
"display_name" : display_name,
"states" : states,
"considered_duration" : considered_duration,
"total_duration" : total_duration,
"statistics" : statistics,
"groups" : group_ids,
"timeline" : timeline_rows,
}
availability_table.append(availability_entry)
availability_table.sort(cmp = cmp_av_entry)
# Apply filters
filtered_table = []
for row in availability_table:
if <API key>(row, avoptions):
filtered_table.append(row)
return filtered_table
# Note: Reclassifications of host/service periods do currently *not* have
# any impact on BI aggregations.
def <API key>(what, av_rawdata):
annotations = load_annotations()
if not annotations:
return av_rawdata
<API key> = {}
for (site, host_name), service_entries in av_rawdata.iteritems():
new_entries = {}
<API key>[(site, host_name)] = new_entries
for service_description, service_history in service_entries.iteritems():
cycles = [ ((site, host_name, service_description or None), "in_downtime") ]
if what == "service":
cycles = [ ((site, host_name, None), "in_host_downtime") ] + cycles
for anno_key, key_to_change in cycles:
if anno_key in annotations:
new_entries[service_description] = \
<API key>(service_history, annotations[anno_key], key_to_change)
service_history = new_entries[service_description]
else:
new_entries[service_description] = service_history
return <API key>
def <API key>(service_history, annotation_entries, key_to_change):
new_history = service_history
for annotation in annotation_entries:
downtime = annotation.get("downtime")
if downtime == None:
continue
new_history = <API key>(new_history, annotation, key_to_change)
return new_history
def <API key>(service_history, annotation, key_to_change):
new_history = []
for history_entry in service_history:
new_history += <API key>(history_entry, annotation, key_to_change)
return new_history
def <API key>(history_entry, annotation, key_to_change):
new_history = []
if annotation["from"] < history_entry["until"] and annotation["until"] > history_entry["from"]:
for is_in, p_from, p_until in [
( False, history_entry["from"], max(history_entry["from"], annotation["from"]) ),
( True, max(history_entry["from"], annotation["from"]), min(history_entry["until"], annotation["until"]) ),
( False, min(history_entry["until"], annotation["until"]), history_entry["until"] ),
]:
if p_from < p_until:
new_entry = history_entry.copy()
new_entry["from"] = p_from
new_entry["until"] = p_until
new_entry["duration"] = p_until - p_from
if is_in:
new_entry[key_to_change] = annotation["downtime"] and 1 or 0
# If the annotation removes a downtime from the services, but
# the actual reason for the service being in downtime is a host
# downtime, then we must cancel the host downtime (also), or else
# that would override the unset service downtime.
if key_to_change == "in_downtime" \
and history_entry.get("in_host_downtime") \
and annotation["downtime"] == False:
new_entry["in_host_downtime"] = 0
new_history.append(new_entry)
else:
new_history.append(history_entry)
return new_history
def <API key>(row, avoptions):
if row["considered_duration"] == 0:
return True
for key, level in avoptions["av_filter_outages"].items():
if level == 0.0:
continue
if key == "warn":
ref_value = row["states"].get("warn", 0)
elif key == "crit":
ref_value = row["states"].get("crit", row["states"].get("down", 0))
elif key == "non-ok":
ref_value = 0.0
for key, value in row["states"].items():
if key not in [ "ok", "up", "unmonitored" ]:
ref_value += value
else:
continue # undefined key. Should never happen
percentage = 100.0 * ref_value / row["considered_duration"]
if percentage < level:
return False
return True
# Compute a list of availability tables - one for each group.
# Each entry is a pair of group_name and availability_table.
# It is sorted by the group names
def <API key>(what, av_data, avoptions):
grouping = avoptions["grouping"]
if not grouping:
return [ (None, av_data) ]
else:
availability_tables = []
# Grouping is one of host/hostgroup/servicegroup
# 1. Get complete list of all groups
all_group_ids = get_av_groups(av_data, avoptions)
# 2. Compute names for the groups and sort according to these names
if grouping != "host":
group_titles = dict(visuals.all_groups(grouping[:-7]))
titled_groups = []
for group_id in all_group_ids:
if grouping == "host":
titled_groups.append((group_id[1], group_id)) # omit the site name
else:
if group_id == ():
title = _("Not contained in any group")
else:
title = group_titles.get(group_id, group_id)
titled_groups.append((title, group_id)) ## ACHTUNG
titled_groups.sort(cmp = lambda a,b: cmp(a[1], b[1]))
# 3. Loop over all groups and render them
for title, group_id in titled_groups:
group_table = []
for entry in av_data:
group_ids = entry["groups"]
if group_id == () and group_ids:
continue # This is not an ungrouped object
elif group_id and group_id not in group_ids:
continue # Not this group
group_table.append(entry)
availability_tables.append((title, group_table))
return availability_tables
def object_title(what, av_entry):
if what == "host":
return av_entry["host"]
else: # service and BI
return av_entry["host"] + " / " + av_entry["service"]
# Merge consecutive rows with same state
def merge_timeline(entries):
n = 1
while n < len(entries):
if entries[n][1] == entries[n-1][1] and entries[n][0]["from"] == entries[n-1][0]["until"]:
entries[n-1][0]["duration"] += entries[n][0]["duration"]
entries[n-1][0]["until"] = entries[n][0]["until"]
del entries[n]
else:
n += 1
def <API key>(entries, duration, dont_merge):
n = 1
need_merge = False
while n < len(entries) - 1:
if entries[n][0]["duration"] <= duration and \
entries[n-1][1] == entries[n+1][1]:
entries[n] = (entries[n][0], entries[n-1][1])
need_merge = True
n += 1
# Due to melting, we need to merge again
if need_merge and not dont_merge:
merge_timeline(entries)
<API key>(entries, duration, dont_merge)
# | This code deals with retrospective annotations and downtimes. |
# Example for annotations:
# ( "mysite", "foohost", "myservice" ) : # service might be None
# "from" : 1238288548,
# "until" : 1238292845,
# "date" : 12348854885, # Time of entry
# "author" : "mk",
# "downtime" : True, # Can also be False or None or missing. None is like missing
# # ... further entries
def save_annotations(annotations):
path = cmk.paths.var_dir + "/<API key>.mk"
store.save_data_to_file(path, annotations)
def load_annotations(lock = False):
path = cmk.paths.var_dir + "/<API key>.mk"
if not os.path.exists(path):
# Support legacy old wrong name-clashing path
path = cmk.paths.var_dir + "/web/<API key>.mk"
return store.load_data_from_file(path, {}, lock)
def update_annotations(site_host_svc, annotation, replace_existing):
annotations = load_annotations(lock = True)
entries = annotations.get(site_host_svc, [])
new_entries = []
for entry in entries:
if entry == replace_existing:
continue # Skip existing entries with same identity
new_entries.append(entry)
new_entries.append(annotation)
annotations[site_host_svc] = new_entries
save_annotations(annotations)
def find_annotation(annotations, site_host_svc, fromtime, untiltime):
entries = annotations.get(site_host_svc)
if not entries:
return None
for annotation in entries:
if annotation["from"] == fromtime \
and annotation["until"] == untiltime:
return annotation
return None
def delete_annotation(annotations, site_host_svc, fromtime, untiltime):
entries = annotations.get(site_host_svc)
if not entries:
return
found = None
for nr, annotation in enumerate(entries):
if annotation["from"] == fromtime \
and annotation["until"] == untiltime:
found = nr
break
if found != None:
del entries[found]
# When grouping is enabled, this function is called once for each group
# TODO: range_title sollte hier ueberfluessig sein
# TODO: Hier jetzt nicht direkt HTML erzeugen, sondern eine saubere
# "title" : "Hostgroup foobar",
# "headers" : [ "OK, "CRIT", "Downtime" ],
# "rows" : [ ... ],
# "summary" : [ ("84.50%", "crit"), ("15.50%", "crit"), ("0.00%", "p"), ("0.00%", "p") ],
# row ist ein dict: {
# "cells" : [ ("84.50%", "crit"), ("15.50%", "crit"), ("0.00%", "p"), ("0.00%", "p") ],
# "urls" : { "timeline": "view.py..." },
# "object" : ( "Host123", "Foobar" ),
def <API key>(what, group_title, availability_table, avoptions):
time_range, range_title = avoptions["range"]
from_time, until_time = time_range
total_duration = until_time - from_time
timeformats = <API key>(avoptions["timeformat"])
show_timeline = avoptions["show_timeline"]
labelling = avoptions["labelling"]
av_levels = avoptions["av_levels"]
show_summary = avoptions.get("summary")
summary = {}
summary_counts = {}
unmonitored_objects = 0
av_table = { "title" : group_title,
"rows" : [], }
# Titles for the columns that specify the object
titles = []
if what == "bi":
titles.append(_("Aggregate"))
else:
# in service availability we can only omit the host. In the
# host availability this is only possible if the alias is
# being displayed, Otherwise the table wouldn't make sense
# and the pdf renderer would crash
if "omit_host" not in labelling or\
(what == "host" and "show_alias" not in labelling):
titles.append(_("Host"))
if "show_alias" in labelling:
titles.append(_("Alias"))
if what != "host":
titles.append(_("Service"))
av_table["object_titles"] = titles
# Headers for availability cells
av_table["cell_titles"] = []
os_aggrs, os_states = <API key>(avoptions)
for timeformat, render_number in timeformats:
for sid, css, sname, help in <API key>[what]:
ssid = "%s-%s" % (sid, timeformat)
if not cell_active(sid, avoptions):
continue
if avoptions["av_mode"]:
sname = _("Avail.")
av_table["cell_titles"].append((sname, help))
if sid in os_states:
for aggr in os_aggrs:
title = statistics_headers[aggr]
av_table["cell_titles"].append((title, None))
# Actual rows
for entry in availability_table:
site = entry["site"]
host = entry["host"]
alias = entry["alias"]
service = entry["service"]
row = {}
av_table["rows"].append(row)
# Iconbuttons with URLs
urls = []
if not "omit_buttons" in labelling:
if what != "bi":
timeline_url = html.makeuri([
("av_mode", "timeline"),
("av_site", site),
("av_host", host),
("av_service", service)])
else:
timeline_url = html.makeuri([("av_mode", "timeline"), ("av_aggr_group", host), ("aggr_name", service), ("view_name", "aggr_single")])
urls.append(( "timeline", _("Timeline"), timeline_url ))
if what != "bi":
urls.append(("history", _("Event History"), history_url_of((site, host, service), time_range)))
row["urls"] = urls
# Column with host/service or aggregate name
objectcells = [] # List of pairs of (text, url)
if what == "bi":
bi_url = "view.py?" + html.urlencode_vars([("view_name", "aggr_single"), ("aggr_group", host), ("aggr_name", service)])
objectcells.append((service, bi_url))
else:
host_url = "view.py?" + html.urlencode_vars([("view_name", "hoststatus"), ("site", site), ("host", host)])
if "omit_host" not in labelling or\
(what == "host" and "show_alias" not in labelling):
objectcells.append((host, host_url))
if "show_alias" in labelling:
objectcells.append((alias, host_url))
if what == "service":
if "use_display_name" in labelling:
service_name = entry["display_name"]
else:
service_name = service
service_url = "view.py?" + html.urlencode_vars([("view_name", "service"), ("site", site), ("host", host), ("service", service)])
objectcells.append((service_name, service_url))
row["object"] = objectcells
# Inline timeline
if show_timeline:
row["timeline"] = layout_timeline(what, entry["timeline"], entry["considered_duration"], avoptions, style="inline")
# Actuall cells with availability data
row["cells"] = []
for timeformat, render_number in timeformats:
for sid, css, sname, help in <API key>[what]:
ssid = "%s-%s" % (sid, timeformat)
if not cell_active(sid, avoptions):
continue
number = entry["states"].get(sid, 0)
if not number:
css = "unused"
elif show_summary:
summary.setdefault(ssid, 0.0)
if timeformat.startswith("percentage"):
if entry["considered_duration"] > 0:
summary[ssid] += float(number) / entry["considered_duration"]
else:
summary[ssid] += number
# Apply visual availability levels (render OK in yellow/red, if too low)
if number and av_levels and sid in [ "ok", "up" ]:
css = "state%d" % check_av_levels(number, av_levels, entry["considered_duration"])
css = css + " narrow number"
row["cells"].append((render_number(number, entry["considered_duration"]), css))
# Statistics?
x_cnt, x_min, x_max = entry["statistics"].get(sid, (None, None, None))
os_aggrs, os_states = <API key>(avoptions)
if sid in os_states:
for aggr in os_aggrs:
if x_cnt != None:
if aggr == "avg":
r = render_number(number / x_cnt, entry["considered_duration"])
elif aggr == "min":
r = render_number(x_min, entry["considered_duration"])
elif aggr == "max":
r = render_number(x_max, entry["considered_duration"])
else:
r = str(x_cnt)
summary_counts.setdefault(ssid, 0)
summary_counts[ssid] += x_cnt
row["cells"].append((r, css))
else:
row["cells"].append(("", ""))
# If timeline == [] and states == {} then this objects has complete unmonitored state
if entry["timeline"] == [] and entry["states"] == {}:
unmonitored_objects += 1
# Summary line. It has the same format as each entry in cells
# We ignore unmonitored objects
<API key> = len(availability_table) - unmonitored_objects
if show_summary and <API key> > 0:
summary_cells = []
for timeformat, render_number in timeformats:
for sid, css, sname, help in <API key>[what]:
ssid = "%s-%s" % (sid, timeformat)
if not cell_active(sid, avoptions):
continue
number = summary.get(ssid, 0)
if show_summary == "average" or timeformat.startswith("percentage"):
number /= <API key>
if timeformat.startswith("percentage"):
number *= total_duration
if not number:
css = "unused"
if number and av_levels and sid in [ "ok", "up" ]:
css = "state%d" % check_av_levels(number, av_levels, total_duration)
css = css + " narrow number"
summary_cells.append((render_number(number, total_duration), css))
if sid in os_states:
for aggr in os_aggrs:
if aggr == "cnt":
count = summary_counts.get(ssid, 0)
if show_summary == "average":
count = float(count) / <API key>
text = "%.2f" % count
else:
text = str(count)
summary_cells.append((text, css))
else:
summary_cells.append(("", ""))
av_table["summary"] = summary_cells
return av_table
# Compute layout of timeline independent of the output device (HTML, PDF, whatever)...
# style is either "inline" or "standalone"
# Output format:
# "spans" : [ spans... ],
# "legend" : [ legendentries... ],
def layout_timeline(what, timeline_rows, considered_duration, avoptions, style):
timeformats = <API key>(avoptions["timeformat"])
time_range, range_title = avoptions["range"]
from_time, until_time = time_range
total_duration = until_time - from_time
# Timeformat: show date only if the displayed time range spans over
# more than one day.
time_format = "%H:%M:%S"
if time.localtime(from_time)[:3] != time.localtime(until_time-1)[:3]:
time_format = "%Y-%m-%d " + time_format
def render_date_func(time_format):
def render_date(ts):
if avoptions["dateformat"] == "epoch":
return str(int(ts))
else:
return time.strftime(time_format, time.localtime(ts))
return render_date
render_date = render_date_func(time_format)
spans = []
table = []
timeline_layout = {
"range" : time_range,
"spans" : spans,
"time_choords" : [],
"render_date" : render_date,
"table" : table,
}
# Render graphical representation
# Make sure that each cell is visible, if possible
if timeline_rows:
min_percentage = min(100.0 / len(timeline_rows), style == "inline" and 0.0 or 0.5)
else:
min_percentage = 0
rest_percentage = 100 - len(timeline_rows) * min_percentage
chaos_begin = None
chaos_end = None
chaos_count = 0
chaos_width = 0
def <API key>(n, d):
texts = []
for timeformat, render_number in timeformats:
texts.append(render_number(n, d))
return ", ".join(texts)
def chaos_period(chaos_begin, chaos_end, chaos_count, chaos_width):
title = _("%d chaotic state changes from %s until %s (%s)") % (
chaos_count,
render_date(chaos_begin), render_date(chaos_end),
<API key>(chaos_end - chaos_begin, considered_duration))
return (None, title, chaos_width, "chaos")
current_time = from_time
for row_nr, (row, state_id) in enumerate(timeline_rows):
this_from_time = row["from"]
this_until_time = row["until"]
if this_from_time > current_time: # GAP
spans.append((None, "", 100.0 * (this_from_time - current_time) / total_duration, "unmonitored"))
current_time = this_until_time
from_text = render_date(this_from_time)
until_text = render_date(this_until_time)
duration_text = <API key>(row["duration"], considered_duration)
for sid, css, sname, help in <API key>[what]:
if sid != state_id:
continue
title = _("From %s until %s (%s) %s") % (from_text, until_text, duration_text, help and help or sname)
if "log_output" in row and row["log_output"]:
title += " - " + row["log_output"]
width = rest_percentage * row["duration"] / total_duration
# Information for table of detailed events
if style == "standalone":
table.append({
"state" : state_id,
"css" : css,
"state_name" : sname,
"from" : row["from"],
"until" : row["until"],
"from_text" : from_text,
"until_text" : until_text,
"duration_text" : duration_text,
})
if "log_output" in row and row["log_output"]:
table[-1]["log_output"] = row["log_output"]
# If the width is very small then we group several phases into
# one single "chaos period".
if style == "inline" and width < 0.05:
if not chaos_begin:
chaos_begin = row["from"]
chaos_width += width
chaos_count += 1
chaos_end = row["until"]
continue
# Chaos period has ended? One not-small phase:
elif chaos_begin:
# Only output chaos phases with a certain length
if chaos_count >= 4:
spans.append(chaos_period(chaos_begin, chaos_end, chaos_count, chaos_width))
chaos_begin = None
chaos_count = 0
chaos_width = 0
width += min_percentage
spans.append((row_nr, title, width, css))
if chaos_count > 1:
spans.append(chaos_period(chaos_begin, chaos_end, chaos_count, chaos_width))
if style == "inline":
timeline_layout["time_choords"] = <API key>(time_range)
return timeline_layout
def <API key>(time_range):
from_time, until_time = time_range
duration = until_time - from_time
# Now comes the difficult part: decide automatically, whether to use
# hours, days, weeks or months. Days and weeks needs to take local time
# into account. Months are irregular.
hours = duration / 3600
if hours < 12:
scale = "hours"
elif hours < 24:
scale = "2hours"
elif hours < 48:
scale = "6hours"
elif hours < 24 * 14:
scale = "days"
elif hours < 24 * 60:
scale = "weeks"
else:
scale = "months"
broken = list(time.localtime(from_time))
while True:
next_choord, title = find_next_choord(broken, scale)
if next_choord >= until_time:
break
position = (next_choord - from_time) / float(duration) # ranges from 0.0 to 1.0
yield position, title
def find_next_choord(broken, scale):
# Elements in broken:
# 0: year
# 1: month (1 = January)
# 2: day of month
# 3: hour
# 4: minute
# 5: second
# 6: day of week (0 = monday)
# 7: day of year
# 8: isdst (0 or 1)
broken[4:6] = [0, 0] # always set min/sec to 00:00
old_dst = broken[8]
if scale == "hours":
epoch = time.mktime(broken)
epoch += 3600
broken[:] = list(time.localtime(epoch))
title = time.strftime("%H:%M", broken)
elif scale == "2hours":
broken[3] = broken[3] / 2 * 2
epoch = time.mktime(broken)
epoch += 2 * 3600
broken[:] = list(time.localtime(epoch))
title = defines.weekday_name(broken[6]) + time.strftime(" %H:%M", broken)
elif scale == "6hours":
broken[3] = broken[3] / 6 * 6
epoch = time.mktime(broken)
epoch += 6 * 3600
broken[:] = list(time.localtime(epoch))
title = defines.weekday_name(broken[6]) + time.strftime(" %H:%M", broken)
elif scale == "days":
broken[3] = 0
epoch = time.mktime(broken)
epoch += 24 * 3600
broken[:] = list(time.localtime(epoch))
title = defines.weekday_name(broken[6]) + time.strftime(", %d.%m. 00:00", broken)
elif scale == "weeks":
broken[3] = 0
at_00 = int(time.mktime(broken))
at_monday = at_00 - 86400 * broken[6]
epoch = at_monday + 7 * 86400
broken[:] = list(time.localtime(epoch))
title = defines.weekday_name(broken[6]) + time.strftime(", %d.%m.", broken)
else: # scale == "months":
broken[3] = 0
broken[2] = 0
broken[1] += 1
if broken[1] > 12:
broken[1] = 1
broken[0] += 1
epoch = time.mktime(broken)
title = "%s %d" % (month_names[broken[1]-1], broken[0])
dst = broken[8]
if old_dst == 1 and dst == 0:
epoch += 3600
elif old_dst == 0 and dst == 1:
epoch -= 3600
return epoch, title
# | Availability computation in BI aggregates. Here we generate the |
# | same availability raw data. We fill the field "host" with the BI |
# | group and the field "service" with the BI aggregate's name. |
def <API key>(filterheaders, only_sites, av_object, include_output, avoptions):
raise Exception("Not implemented yet. Sorry.")
def <API key>(aggr_rows, avoptions, timewarp, livestatus_limit):
time_range, range_title = avoptions["range"]
phases_list, timeline_containers, fetched_rows = get_bi_leaf_history(aggr_rows, time_range, livestatus_limit)
return <API key>(timeline_containers, time_range, timewarp, phases_list), fetched_rows
# Not a real class, more a struct
class TimelineContainer(object):
def __init__(self, aggr_row):
self._aggr_row = aggr_row
# PUBLIC accessible data
self.aggr_tree = self._aggr_row["aggr_tree"]
self.aggr_group = self._aggr_row["aggr_group"]
# Data fetched from livestatus query
self.host_service_info = None
# Computed data
self.timeline = []
self.states = {}
self.timewarp_state = None
self.tree_time = None
self.tree_state = None
def get_bi_leaf_history(aggr_rows, time_range, livestatus_limit):
# Get state history of all hosts and services contained in the tree.
# In order to simplify the query, we always fetch the information for
# all hosts of the aggregates.
only_sites = set()
hosts = set()
for row in aggr_rows:
tree = row["aggr_tree"]
for site, host in tree["reqhosts"]:
only_sites.add(site)
hosts.add(host)
columns = [ "host_name", "service_description", "from", "until", "log_output", "state", "in_downtime", "in_service_period" ]
sites.live().set_only_sites(list(only_sites))
sites.live().set_prepend_site(True)
sites.live().set_limit(livestatus_limit)
query = "GET statehist\n" + \
"Columns: " + " ".join(columns) + "\n" +\
"Filter: time >= %d\nFilter: time < %d\n" % time_range
# Create a specific filter. We really only want the services and hosts
# of the aggregation in question. That prevents status changes
# irrelevant services from introducing new phases.
by_host = {}
timeline_containers = []
for row in aggr_rows:
tree = row["aggr_tree"]
host_service_info = set()
for site, host, service in bi.find_all_leaves(tree):
by_host.setdefault(host, set([])).add(service)
host_service_info.add((host, service and service or ""))
host_service_info.add((host, ""))
timeline_container = TimelineContainer(row)
timeline_container.host_service_info = host_service_info
timeline_containers.append(timeline_container)
for host, services in by_host.items():
query += "Filter: host_name = %s\n" % host
query += "Filter: service_description = \n"
for service in services:
query += "Filter: service_description = %s\n" % service
query += "Or: %d\nAnd: 2\n" % (len(services) + 1)
if len(hosts) != 1:
query += "Or: %d\n" % len(hosts)
data = sites.live().query(query)
if not data:
return [], [], None
sites.live().set_prepend_site(False)
sites.live().set_only_sites(None)
columns = ["site"] + columns
rows = [ dict(zip(columns, row)) for row in data ]
# Reclassify base data due to annotations
rows = reclassify_bi_rows(rows)
# Now comes the tricky part: recompute the state of the aggregate
# for each step in the state history and construct a timeline from
# it. As a first step we need the start state for each of the
# hosts/services. They will always be the first consecute rows
# in the statehist table
# First partition the rows into sequences with equal start time
phases = {}
for row in rows:
phases.setdefault(row["from"], {})[(row["host_name"], row["service_description"])] = row
# Convert phases to sorted list
sorted_times = phases.keys()
sorted_times.sort()
phases_list = []
for from_time in sorted_times:
phases_list.append((from_time, phases[from_time]))
return phases_list, timeline_containers, len(rows)
def <API key>(timeline_containers, time_range, timewarp, phases_list):
bi.load_assumptions()
if not timeline_containers:
return timeline_containers
def update_states(states, use_entries, phase_entries):
for element in use_entries:
hostname, svc_desc = element
values = phase_entries.get(element)
key = values["site"], hostname, svc_desc
states[key] = values["state"], values["log_output"], values["in_downtime"], (values["in_service_period"] != 0)
# Initial phase, this includes all elements
from_time, first_phase = phases_list[0]
first_phase_keys = set(first_phase.keys())
for timeline_container in timeline_containers:
timeline_container.states = {}
use_elements = timeline_container.host_service_info.intersection(first_phase_keys)
update_states(timeline_container.states, use_elements, first_phase)
# States does now reflect the host/services states at the beginning of the query range.
tree_state = <API key>(timeline_container.aggr_tree,
timeline_container.states)
tree_time = time_range[0]
timeline_container.timewarp_state = timewarp == int(tree_time) and tree_state or None
timeline_container.tree_state = tree_state
timeline_container.tree_time = tree_time
# Remaining phases, may include some elements
for from_time, phase_hst_svc in phases_list[1:]:
phase_keys = set(phase_hst_svc.keys())
for timeline_container in timeline_containers:
use_elements = timeline_container.host_service_info.intersection(phase_keys)
if not use_elements:
continue
update_states(timeline_container.states, use_elements, phase_hst_svc)
next_tree_state = <API key>(timeline_container.aggr_tree,
timeline_container.states)
timeline_container.timeline.append(<API key>(timeline_container.aggr_tree,
timeline_container.aggr_group,
timeline_container.tree_time,
from_time,
timeline_container.tree_state))
timeline_container.tree_state = next_tree_state
timeline_container.tree_time = from_time
if timewarp == timeline_container.tree_time:
timeline_container.timewarp_state = timeline_container.tree_state
# Each element gets a final timeline_entry - to the end of the interval
for timeline_container in timeline_containers:
timeline_container.timeline.append((<API key>(timeline_container.aggr_tree,
timeline_container.aggr_group,
timeline_container.tree_time,
time_range[1],
timeline_container.tree_state)))
return timeline_containers
def <API key>(tree, aggr_group, from_time, until_time, tree_state):
return {
"state" : tree_state[0]['state'],
"log_output" : tree_state[0]['output'],
"from" : from_time,
"until" : until_time,
"site" : "",
"host_name" : aggr_group,
"service_description" : tree['title'],
"<API key>" : 1,
"in_service_period" : tree_state[0]['in_service_period'],
"in_downtime" : tree_state[0]['in_downtime'],
"in_host_downtime" : 0,
"host_down" : 0,
"is_flapping" : 0,
"duration" : until_time - from_time,
}
def <API key>(tree, status):
# Convert our status format into that needed by BI
services_by_host = {}
hosts = {}
for site_host_service, state_output in status.items():
site_host = site_host_service[:2]
service = site_host_service[2]
state = state_output[0]
if state == -1:
state = None # Means: consider this object as missing
if service:
services_by_host.setdefault(site_host, []).append((
service, # service description
state,
1, # has_been_checked
state_output[1], # output
state, # hard state (we use the soft state here)
1, # attempt
1, # max_attempts (not relevant)
state_output[2], # in_downtime
False, # acknowledged
state_output[3], # in_service_period
))
else:
hosts[site_host] = state_output
status_info = {}
for site_host, state_output in hosts.items():
state = state_output[0]
if state == -1:
state = None # Means: consider this object as missing
status_info[site_host] = [
state,
state, # host hard state
state_output[1],
state_output[2], # in_downtime
False, # acknowledged
state_output[3], # in_service_period
services_by_host.get(site_host,[])
]
# Finally we can execute the tree
tree_state = bi.execute_tree(tree, status_info)
return tree_state
def reclassify_bi_rows(rows):
annotations = load_annotations()
if not annotations:
return rows
new_rows = []
for row in rows:
site = row["site"]
host_name = row["host_name"]
service_description = row["service_description"]
anno_key = (site, host_name, service_description or None)
if anno_key in annotations:
new_rows += <API key>([row], annotations[anno_key], "in_downtime")
else:
new_rows.append(row)
return new_rows
# | Various other functions |
# Helper function, needed in row and in summary line. Determines whether
# a certain cell should be visiable. For example when WARN is mapped
# to CRIT because of state grouping, then the WARN column should not be
# displayed.
def cell_active(sid, avoptions):
# Some columns might be unneeded due to state treatment options
sg = avoptions["state_grouping"]
hsg = avoptions["host_state_grouping"]
if sid not in [ "up", "ok" ] and avoptions["av_mode"]:
return False
if sid == "<API key>" and avoptions["notification_period"] != "honor":
return False
elif sid == "<API key>": # Never show this as a column
return False
elif sid == "in_downtime" and avoptions["downtimes"]["include"] != "honor":
return False
elif sid == "unmonitored" and not avoptions["consider"]["unmonitored"]:
return False
elif sid == "flapping" and not avoptions["consider"]["flapping"]:
return False
elif sid == "host_down" and not avoptions["consider"]["host_down"]:
return False
elif sid in sg and sid not in sg.values():
return False
elif sid in hsg and sid not in hsg.values():
return False
else:
return True
# Check if the availability of some object is below the levels
# that are configured in the avoptions.
def check_av_levels(ok_seconds, av_levels, considered_duration):
if considered_duration == 0:
return 0
perc = 100 * float(ok_seconds) / float(considered_duration)
warn, crit = av_levels
if perc < crit:
return 2
elif perc < warn:
return 1
else:
return 0
def get_av_groups(availability_table, avoptions):
grouping = avoptions["grouping"]
all_group_ids = set([])
for entry in availability_table:
all_group_ids.update(entry["groups"])
if len(entry["groups"]) == 0:
all_group_ids.add(()) # null-tuple denotes ungrouped objects
return all_group_ids
# Sort according to host and service. First after site, then
# host (natural sort), then service
def cmp_av_entry(a, b):
return utils.cmp_num_split(a["site"], b["site"]) or \
utils.cmp_num_split(a["host"], b["host"]) or \
cmp(views.<API key>(a["service"]), views.<API key>(b["service"])) or \
utils.cmp_num_split(a["service"], b["service"])
def history_url_of(av_object, time_range):
site, host, service = av_object
from_time, until_time = time_range
history_url_vars = [
("site", site),
("host", host),
("logtime_from_range", "unix"), # absolute timestamp
("logtime_until_range", "unix"), # absolute timestamp
("logtime_from", str(int(from_time))),
("logtime_until", str(int(until_time)))]
if service:
history_url_vars += [
("service", service),
("view_name", "svcevents"),
]
else:
history_url_vars += [
("view_name", "hostevents"),
]
return "view.py?" + html.urlencode_vars(history_url_vars) |
require_dependency 'discourse_hub'
require_dependency 'user_name_suggester'
class UsersController < <API key>
skip_before_filter :check_xhr, only: [:show, :password_reset, :update, :activate_account, :avatar, :authorize_email, :<API key>]
skip_before_filter :<API key>, only: [:avatar]
before_filter :ensure_logged_in, only: [:username, :update, :change_email, :<API key>]
# we need to allow account creation with bad CSRF tokens, if people are caching, the CSRF token on the
# page is going to be empty, this means that server will see an invalid CSRF and blow the session
# once that happens you can't log in with social
skip_before_filter :<API key>, only: [:create]
skip_before_filter :<API key>, only: [:check_username,
:create,
:get_honeypot_value,
:activate_account,
:<API key>,
:authorize_email,
:password_reset]
def show
@user = <API key>
user_serializer = UserSerializer.new(@user, scope: guardian, root: 'user')
respond_to do |format|
format.html do
store_preloaded("user_#{@user.username}", MultiJson.dump(user_serializer))
end
format.json do
render_json_dump(user_serializer)
end
end
end
def <API key>
redirect_to <API key>(current_user.username_lower)
end
def update
user = User.where(username_lower: params[:username].downcase).first
guardian.ensure_can_edit!(user)
json_result(user, serializer: UserSerializer) do |u|
website = params[:website]
if website
website = "http://" + website unless website =~ /^http/
end
u.bio_raw = params[:bio_raw] || u.bio_raw
u.name = params[:name] || u.name
u.website = website || u.website
u.digest_after_days = params[:digest_after_days] || u.digest_after_days
u.<API key> = params[:<API key>].to_i if params[:<API key>]
u.<API key> = params[:<API key>].to_i if params[:<API key>]
u.title = params[:title] || u.title if guardian.can_grant_title?(u)
[:email_digests, :email_direct, :<API key>,
:<API key>, :enable_quoting, :dynamic_favicon].each do |i|
if params[i].present?
u.send("#{i.to_s}=", params[i] == 'true')
end
end
if u.save
u
else
nil
end
end
end
def username
params.require(:new_username)
user = <API key>
guardian.ensure_can_edit!(user)
result = user.change_username(params[:new_username])
raise Discourse::InvalidParameters.new(:new_username) unless result
render nothing: true
end
def preferences
render nothing: true
end
def invited
invited_list = InvitedList.new(<API key>)
render_serialized(invited_list, <API key>)
end
def is_local_username
params.require(:username)
u = params[:username].downcase
r = User.exec_sql('select 1 from users where username_lower = ?', u).values
render json: {valid: r.length == 1}
end
def check_username
params.require(:username)
# The special case where someone is changing the case of their own username
return render(json: {available: true}) if current_user and params[:username].downcase == current_user.username.downcase
validator = UsernameValidator.new(params[:username])
if !validator.valid_format?
render json: {errors: validator.errors}
elsif !SiteSetting.call_discourse_hub?
if User.username_available?(params[:username])
render json: {available: true}
else
render json: {available: false, suggestion: UserNameSuggester.suggest(params[:username])}
end
else
# Contact the Discourse Hub server
email_given = (params[:email].present? || current_user.present?)
available_locally = User.username_available?(params[:username])
global_match = false
available_globally, <API key> = begin
if email_given
global_match, available, suggestion = DiscourseHub.nickname_match?( params[:username], params[:email] || current_user.email )
[available || global_match, suggestion]
else
DiscourseHub.nickname_available?(params[:username])
end
end
if available_globally && available_locally
render json: {available: true, global_match: (global_match ? true : false)}
elsif available_locally && !available_globally
if email_given
# Nickname and email do not match what's registered on the discourse hub.
render json: {available: false, global_match: false, suggestion: <API key>}
else
# The nickname is available locally, but is registered on the discourse hub.
# We need an email to see if the nickname belongs to this person.
# Don't give a suggestion until we get the email and try to match it with on the discourse hub.
render json: {available: false}
end
elsif available_globally && !available_locally
# Already registered on this site with the matching nickname and email address. Why are you signing up again?
render json: {available: false, suggestion: UserNameSuggester.suggest(params[:username])}
else
# Not available anywhere.
render json: {available: false, suggestion: <API key>}
end
end
rescue RestClient::Forbidden
render json: {errors: [I18n.t("discourse_hub.<API key>")]}
end
def create
return <API key> if suspicious? params
user = User.new_from_params(params)
auth = session[:authentication]
if <API key>?(auth, params[:email])
user.active = true
end
user.password_required! unless auth
if user.valid? && SiteSetting.call_discourse_hub?
DiscourseHub.register_nickname(user.username, user.email)
end
if user.save
if SiteSetting.must_approve_users?
message = I18n.t("login.wait_approval")
elsif !user.active?
message = I18n.t("login.activate_email", email: user.email)
Jobs.enqueue(:user_email,
type: :signup,
user_id: user.id,
email_token: user.email_tokens.first.token
)
else
message = I18n.t("login.active")
log_on_user(user)
user.<API key>('welcome_user')
end
<API key>(user, auth) if auth.present?
# Clear authentication session.
session[:authentication] = nil
render json: { success: true, active: user.active?, message: message }
else
render json: {
success: false,
message: I18n.t("login.errors", errors: user.errors.full_messages.join("\n"))
}
end
rescue ActiveRecord::StatementInvalid
render json: { success: false, message: I18n.t("login.<API key>") }
rescue DiscourseHub::NicknameUnavailable
render json: { success: false,
message: I18n.t(
"login.errors",
errors:I18n.t(
"login.not_available", suggestion: UserNameSuggester.suggest(params[:username])
)
)
}
rescue RestClient::Forbidden
render json: { errors: [I18n.t("discourse_hub.<API key>")] }
end
def get_honeypot_value
render json: {value: honeypot_value, challenge: challenge_value}
end
# all avatars are funneled through here
def avatar
# TEMP to catch all missing spots
# raise ActiveRecord::RecordNotFound
user = User.select(:email).where(username_lower: params[:username].downcase).first
if user.present?
# for now we only support gravatar in square (redirect cached for a day),
# later we can use x-sendfile and/or a cdn to serve local
size = <API key>(params[:size])
url = user.avatar_template.gsub("{size}", size.to_s)
expires_in 1.day
redirect_to url
else
raise ActiveRecord::RecordNotFound
end
end
def password_reset
expires_now()
@user = EmailToken.confirm(params[:token])
if @user.blank?
flash[:error] = I18n.t('password_reset.no_token')
else
if request.put? && params[:password].present?
@user.password = params[:password]
if @user.save
if Guardian.new(@user).can_access_forum?
# Log in the user
log_on_user(@user)
flash[:success] = I18n.t('password_reset.success')
else
@requires_approval = true
flash[:success] = I18n.t('password_reset.success_unapproved')
end
end
end
end
render layout: 'no_js'
end
def change_email
params.require(:email)
user = <API key>
guardian.ensure_can_edit!(user)
lower_email = Email.downcase(params[:email]).strip
# Raise an error if the email is already in use
if User.where("email = ?", lower_email).exists?
raise Discourse::InvalidParameters.new(:email)
end
email_token = user.email_tokens.create(email: lower_email)
Jobs.enqueue(
:user_email,
to_address: lower_email,
type: :authorize_email,
user_id: user.id,
email_token: email_token.token
)
render nothing: true
end
def authorize_email
expires_now()
if @user = EmailToken.confirm(params[:token])
log_on_user(@user)
else
flash[:error] = I18n.t('change_email.error')
end
render layout: 'no_js'
end
def activate_account
expires_now()
if @user = EmailToken.confirm(params[:token])
# Log in the user unless they need to be approved
if Guardian.new(@user).can_access_forum?
@user.<API key>('welcome_user') if @user.<API key>
log_on_user(@user)
else
@needs_approval = true
end
else
flash[:error] = I18n.t('activation.already_done')
end
render layout: 'no_js'
end
def <API key>
@user = <API key>
@email_token = @user.email_tokens.unconfirmed.active.first
if @user
@email_token ||= @user.email_tokens.create(email: @user.email)
Jobs.enqueue(:user_email, type: :signup, user_id: @user.id, email_token: @email_token.token)
end
render nothing: true
end
def search_users
term = params[:term].to_s.strip
topic_id = params[:topic_id]
topic_id = topic_id.to_i if topic_id
results = UserSearch.search term, topic_id
render json: { users: results.as_json(only: [ :username, :name ],
methods: :avatar_template) }
end
private
def honeypot_value
Digest::SHA1::hexdigest("#{Discourse.current_hostname}:#{Discourse::Application.config.secret_token}")[0,15]
end
def challenge_value
'3019774c067cc2b'
end
def suspicious?(params)
<API key>?(params) || SiteSetting.invite_only?
end
def <API key>
render(
json: {
success: true,
active: false,
message: I18n.t("login.activate_email", email: params[:email])
}
)
end
def <API key>?(params)
params[:<API key>] != honeypot_value ||
params[:challenge] != challenge_value.try(:reverse)
end
def <API key>?(auth, email)
auth && auth[:email] == email && auth[:email_valid]
end
def <API key>(user, auth)
if twitter_auth?(auth)
TwitterUserInfo.create(
user_id: user.id,
screen_name: auth[:<TwitterConsumerkey>],
twitter_user_id: auth[:twitter_user_id]
)
end
if facebook_auth?(auth)
FacebookUserInfo.create!(auth[:facebook].merge(user_id: user.id))
end
if github_auth?(auth)
GithubUserInfo.create(
user_id: user.id,
screen_name: auth[:github_screen_name],
github_user_id: auth[:github_user_id]
)
end
end
def twitter_auth?(auth)
auth[:twitter_user_id] && auth[:<TwitterConsumerkey>] &&
TwitterUserInfo.<API key>(auth[:twitter_user_id]).nil?
end
def facebook_auth?(auth)
auth[:facebook].present? &&
FacebookUserInfo.<API key>(auth[:facebook][:facebook_user_id]).nil?
end
def github_auth?(auth)
auth[:github_user_id] && auth[:github_screen_name] &&
GithubUserInfo.<API key>(auth[:github_user_id]).nil?
end
def <API key>(size)
size = size.to_i
size = 64 if size == 0
size = 10 if size < 10
size = 128 if size > 128
size
end
end |
#ifndef __TXTEXCACHE_H__
#define __TXTEXCACHE_H__
#include "TxCache.h"
class TxTexCache : public TxCache
{
public:
~TxTexCache();
TxTexCache(int options, int cachesize, const char *path, const char *ident,
dispInfoFuncExt callback);
boolean add(uint64 checksum, /* checksum hi:palette low:texture */
GHQTexInfo *info);
};
#endif /* __TXTEXCACHE_H__ */ |
package org.wordpress.android.models;
import android.support.annotation.StringRes;
import org.wordpress.android.R;
import org.wordpress.android.WordPress;
public enum CommentStatus implements FilterCriteria {
UNKNOWN(R.string.comment_status_all),
UNAPPROVED(R.string.<API key>),
APPROVED(R.string.<API key>),
TRASH(R.string.<API key>),
SPAM(R.string.comment_status_spam);
private final int mLabelResId;
CommentStatus(@StringRes int labelResId) {
mLabelResId = labelResId;
}
@Override
public String getLabel() {
return WordPress.getContext().getString(mLabelResId);
}
/*
* returns the string representation of the passed status, as used by the XMLRPC API
*/
public static String toString(CommentStatus status) {
if (status == null){
return "";
}
switch (status) {
case UNAPPROVED:
return "hold";
case APPROVED:
return "approve";
case SPAM:
return "spam";
case TRASH:
return "trash";
default:
return "";
}
}
/*
* returns the string representation of the passed status, as used by the REST API
*/
public static String toRESTString(CommentStatus status) {
switch (status) {
case UNAPPROVED:
return "unapproved";
case APPROVED:
return "approved";
case SPAM:
return "spam";
case TRASH:
return "trash";
default:
return "all";
}
}
/*
* returns the status associated with the passed strings - handles both XMLRPC and REST
*/
public static CommentStatus fromString(String value) {
if (value == null)
return CommentStatus.UNKNOWN;
if (value.equals("approve") || value.equals("approved"))
return CommentStatus.APPROVED;
if (value.equals("hold") || value.equals("unapproved"))
return CommentStatus.UNAPPROVED;
if (value.equals("spam"))
return SPAM;
if (value.equals("trash"))
return TRASH;
return CommentStatus.UNKNOWN;
}
} |
package util;
public class Consts {
public static final int HCS = ImageManager.getInstance().getGround().getWidth(null);
public static final int VCS = ImageManager.getInstance().getGround().getHeight(null);
public static final int GROUND = 1;
} |
package shakestudios.musicplayer.Service;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.content.<API key>;
import android.util.Log;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import shakestudios.musicplayer.MainScreenActivity;
import shakestudios.musicplayer.POJO.MusicController;
import shakestudios.musicplayer.POJO.Song;
import shakestudios.musicplayer.R;
public class MusicService extends Service implements MediaPlayer.OnErrorListener,
MediaPlayer.<API key>, MediaPlayer.OnPreparedListener
{
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
//binder
private final IBinder musicBind = new MusicBinder();
//title of current song
private String songTitle = "";
private String artist;
//notification id
private static final int NOTIFY_ID = 1;
//shuffle flag and random
private boolean shuffle = true;
MusicController controller;
long currSong;
public void onCreate() {
//create the service
super.onCreate();
//initialize position
songPosn = 0;
//create player
player = new MediaPlayer();
//initialize
initMusicPlayer();
}
public MediaPlayer getPlayer() {
if (player == null) {
initMusicPlayer();
}
return player;
}
public void initMusicPlayer() {
//set player properties
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setWakeMode(<API key>(),
PowerManager.PARTIAL_WAKE_LOCK);
//set listeners
player.<API key>(this);
player.<API key>(this);
player.setOnErrorListener(this);
}
//pass song list
public void setList(ArrayList<Song> theSongs) {
songs = theSongs;
}
public void setController(MusicController contorl) {
controller = contorl;
}
@Override
public void onPrepared(MediaPlayer mp) {
player.start();
controller.show();
Intent notIntent = new Intent(<API key>(), MainScreenActivity.class);
notIntent.addFlags(Intent.<API key>);
notIntent.setAction(Intent.ACTION_MAIN);
notIntent.addCategory(Intent.CATEGORY_LAUNCHER);
notIntent.addFlags(Intent.<API key>);
PendingIntent pendInt = PendingIntent.getActivity(<API key>(), 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(<API key>());
String message = songTitle + "\n" + artist;
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setStyle(new Notification.BigTextStyle()
.bigText(message))
.setContentText(message);
Notification not = builder.build();
not.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
Intent onPreparedIntent = new Intent("<API key>");
<API key>.getInstance(<API key>()).sendBroadcast(onPreparedIntent);
startForeground(NOTIFY_ID, not);
}
//binder
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
//activity will bind to service
@Override
public IBinder onBind(Intent intent) {
Log.e("this is in ", "bind");
return musicBind;
}
//release resources when unbind
@Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
player = null;
return false;
}
//play a song
public void playSong() {
//play
player.reset();
//get song
Song playSong = songs.get(songPosn);
//get title
songTitle = playSong.getTitle();
artist = playSong.getArtist();
//get id
currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.<API key>,
currSong);
//set the data source
try {
player.setDataSource(<API key>(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
//set the song
public void setSong(int songIndex) {
songPosn = songIndex;
}
@Override
public void onCompletion(MediaPlayer mp) {
//check if playback has reached the end of a track
if (player.getCurrentPosition() > 0) {
mp.reset();
playNext();
}
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.v("MUSIC PLAYER", "Playback Error");
mp.reset();
return false;
}
//playback methods
public int getPosn() {
return player.getCurrentPosition();
}
public int getDur() {
return player.getDuration();
}
public boolean isPng() {
return player.isPlaying();
}
public void pausePlayer() {
player.pause();
}
public void seek(int posn) {
player.seekTo(posn);
}
public void go() {
player.start();
}
//skip to previous track
public void playPrev() {
songPosn
if (songPosn < 0) songPosn = songs.size() - 1;
playSong();
}
//skip to next
public void playNext() {
songPosn++;
if (songPosn >= songs.size())
songPosn = 0;
playSong();
}
public int currentSongPosition() {
return songPosn;
}
@Override
public void onDestroy() {
stopForeground(true);
}
//toggle shuffle
public ArrayList<Song> setShuffle() {
if (shuffle) {
shuffle = false;
String currSongName = songs.get(songPosn).getTitle();
Collections.shuffle(songs);
for (int i = 0; i < songs.size(); i++) {
if (songs.get(i).getTitle().equalsIgnoreCase(currSongName)) {
songPosn = i;
break;
}
}
} else {
shuffle = true;
String currSongName = songs.get(songPosn).getTitle();
Collections.sort(songs, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
for (int i = 0; i < songs.size(); i++) {
if (songs.get(i).getTitle().equalsIgnoreCase(currSongName)) {
songPosn = i;
break;
}
}
}
return songs;
}
} |
<API key>=yes
NAMEEXTRA=
run_bench() {
if [ "$RINGTEST_MAX_TASKS" -gt 1000 ]; then
RINGTEST_MAX_TASKS=1000
fi
$SCRIPTDIR/shellpacks/<API key> \
--min-tasks $RINGTEST_MIN_TASKS \
--max-tasks $RINGTEST_MAX_TASKS \
--iterations $RINGTEST_ITERATIONS
return $?
} |
#include <linux/platform_device.h>
#include <linux/device.h>
#include <linux/delay.h>
#include <linux/proc_fs.h>
#include <linux/uaccess.h>
#include <linux/input.h>
#include <linux/sysfs.h>
#include <linux/uaccess.h>
#include <linux/miscdevice.h>
#include <linux/hrtimer.h>
//#include <linux/i2c.h>
#include "nvcommon.h"
#include "nvodm_services.h"
#include "nvodm_query.h"
#include "<API key>.h"
#include "star_accel.h"
#include "lge_sensor_verify.h"
#include "gyro_accel.h"
#define STAR_ACCEL_DEBUG 0
#define G_MAX 8000
/* OUTPUT REGISTERS */
#define XOUT_L 0x06
#define XOUT_H 0x07
#define YOUT_L 0x08
#define YOUT_H 0x09
#define ZOUT_L 0x0A
#define ZOUT_H 0x0B
#define INT_SRC_REG1 0x15
#define INT_STATUS_REG 0x16
#define TILT_POS_CUR 0x10
#define INT_REL 0x1A
#define WHO_AM_I 0x0F
/* CONTROL REGISTERS */
#define DATA_CTRL 0x21
#define CTRL_REG1 0x1B
#define INT_CTRL1 0x1E
#define CTRL_REG3 0x1D
#define TILT_TIMER 0x28
#define WUF_TIMER 0x29
#define WUF_THRESH 0x5A
#define TDT_TIMER 0x2B
/* CONTROL REGISTER 1 BITS */
#define PC1_OFF 0x00
#define PC1_ON 0x80
/* INTERRUPT SOURCE 2 BITS */
#define TPS 0x01
#define TDTS0 0x04
#define TDTS1 0x08
/* INPUT_ABS CONSTANTS */
#define FUZZ 32
#define FLAT 32
/* RESUME STATE INDICES */
#define RES_DATA_CTRL 0
#define RES_CTRL_REG1 1
#define RES_INT_CTRL1 2
#define RES_TILT_TIMER 3
#define RES_CTRL_REG3 4
#define RES_WUF_TIMER 5
#define RES_WUF_THRESH 6
#define RES_TDT_TIMER 7
#define RES_TDT_H_THRESH 8
#define RES_TDT_L_THRESH 9
#define RES_TAP_TIMER 10
#define RES_TOTAL_TIMER 11
#define RES_LAT_TIMER 12
#define RES_WIN_TIMER 13
#define RESUME_ENTRIES 14
static atomic_t tap_flag;
static atomic_t flip_flag;
#define <API key> 5
#define <API key> 10
char brdrev[5];
#define BD_REVB "B"
#define BD_REVC "C"
struct accelerometer_data {
NvU32 x;
NvU32 y;
NvU32 z;
};
typedef struct <API key>
{
struct work_struct work;
NvBool use_irq;
<API key> h_gen2_i2c;
<API key> h_accel_gpio;
NvOdmGpioPinHandle h_accel_gpio_pin;
<API key> h_accel_intr;
<API key> h_accel_pmu;
NvU32 i2c_address;
NvU32 vdd_id;
NvU32 intr_pin;
NvU32 intr_port;
struct input_dev *input_dev;
struct delayed_work delayed_work_accel;
struct accelerometer_data prev_data;
struct accelerometer_data min_data;
struct accelerometer_data max_data;
}star_accel_device;
static star_accel_device *g_accel;
int flip_pre_pre_state = 0;
int call_once = 1;
unsigned char* transfer_data_read;
unsigned char* transfer_data_write;
extern int reboot;
void <API key>(void)
{
<API key>(g_accel->h_accel_intr, NV_FALSE);
//<API key>(g_accel->h_accel_intr);
}
void <API key>(void)
{
<API key>(g_accel->h_accel_intr, NV_TRUE);
}
static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf)
{
u32 val;
val = atomic_read(&tap_flag);
return sprintf(buf, "%d\n",val);
}
static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
u32 val;
val = simple_strtoul(buf, NULL, 10);
//lprintk("[<API key>] tap.... flag [%d]\n",val);
if (val) {
atomic_set(&tap_flag, 1);
} else {
atomic_set(&tap_flag, 0);
}
return count;
}
static ssize_t <API key>(struct device *dev, struct device_attribute *attr, char *buf)
{
u32 val;
val = atomic_read(&flip_flag);
return sprintf(buf, "%d\n",val);
}
static ssize_t <API key>(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
u32 val;
val = simple_strtoul(buf, NULL, 10);
//lprintk("[<API key>] flag [%d]\n",val);
if (val) {
atomic_set(&flip_flag, 1);
} else {
atomic_set(&flip_flag, 0);
}
return count;
}
static DEVICE_ATTR(tap_onoff, 0666, <API key>, <API key>);
static DEVICE_ATTR(flip_onoff, 0666, <API key>, <API key>);
static struct attribute *<API key>[] = {
&dev_attr_tap_onoff.attr,
&dev_attr_flip_onoff.attr,
NULL
};
static const struct attribute_group star_motion_group = {
.attrs = <API key>,
};
static bool <API key>( star_accel_device *accel, unsigned char reg, unsigned char* data, unsigned char len )
{
int i;
NvOdmI2cStatus i2c_status = <API key>;
<API key> info;
//unsigned char* transfer_data;
// this code is assumed that length should be under 10
if (len > 10) {
printk("[star accel driver] %s : length should be 1 ( len = %d)\n", __func__, len);
return false;
}
//transfer_data = (unsigned char*)NvOdmOsAlloc(len+1);
for (i = 0; i < <API key> && i2c_status != <API key>; i++)
{
//transfer_data[0] = reg;
//NvOdmOsMemcpy( &transfer_data[1], data, (size_t)len);
transfer_data_write[0] = reg;
NvOdmOsMemcpy( &transfer_data_write[1], data, (size_t)len);
info.Address = accel->i2c_address;
//info.Buf = transfer_data;
info.Buf = transfer_data_write;
info.Flags = NVODM_I2C_IS_WRITE;
info.NumBytes = len+1;
i2c_status = NvOdmI2cTransaction( accel->h_gen2_i2c, &info, 1, 400, <API key> );
}
if( i2c_status != <API key> )
{
printk("[star accel driver] %s : i2c transaction error(Number = %d)!\n",__func__,i2c_status);
//NvOdmOsFree(transfer_data);
//reboot sensors
reboot = 1;
return false;
}
//NvOdmOsFree(transfer_data);
return true;
}
static bool <API key>( star_accel_device *accel, unsigned char reg, unsigned char* data, unsigned char len )
{
int i;
NvOdmI2cStatus i2c_status = <API key>;
<API key> info[2];
//unsigned char* transfer_data;
// this code is assumed that length should be under 10
if (len > 10) {
printk("[star accel driver] %s : length should be 1 ( len = %d)\n", __func__, len);
return false;
}
//transfer_data = (unsigned char*)NvOdmOsAlloc(len);
for (i = 0; i < <API key> && i2c_status != <API key>; i++)
{
info[0].Address = g_accel->i2c_address;
info[0].Buf = ®
info[0].Flags = NVODM_I2C_IS_WRITE;
info[0].NumBytes = 1;
info[1].Address = ( g_accel->i2c_address | 0x01 );
//info[1].Buf = transfer_data;
info[1].Buf = transfer_data_read;
info[1].Flags = 0;
info[1].NumBytes = len;
i2c_status = NvOdmI2cTransaction( g_accel->h_gen2_i2c, info, 2, 400, <API key> );
}
if( i2c_status != <API key> )
{
printk("[star driver] %s : i2c transaction error(Number= %d)!\n",__func__, i2c_status);
//NvOdmOsFree(transfer_data);
//reboot sensors
reboot = 1;
return false;
}
NvOdmOsMemcpy( data, transfer_data_read, len );
//NvOdmOsMemcpy( data, transfer_data, len );
//NvOdmOsFree(transfer_data);
return true;
}
static void <API key>( star_accel_device *accel, unsigned int samplerate )
{
unsigned int sampledata[7][2] =
{
{ 12, 0x00 },
{ 25, 0x01 },
{ 50, 0x02 },
{ 100, 0x03 },
{ 200, 0x04 },
{ 400, 0x05 },
{ 800, 0x06 },
};
unsigned char i;
unsigned char rate;
for( i= 0; i< 7; i++ )
{
if(sampledata[i][0] == samplerate )
{
rate = (unsigned char)sampledata[i][1];
break;
}
}
#if STAR_ACCEL_DEBUG
printk("[skhwang][%s] i = %d, rate = %d, rate of index = %d\n", __func__, i, sampledata[i][0], rate);
#endif
<API key>( accel, <API key>, &rate, 1 );
}
NvBool <API key>(NvU8 offset, NvU8* value, NvU32 len)
{
int status = 1;
status = <API key>( g_accel, offset, value, 1 );
return status;
}
NvBool <API key>(NvU8 offset, NvU8* value, NvU32 len)
{
int status = 1;
status = <API key>( g_accel, offset, value, 1 );
return status;
}
static int <API key>(int *xyz_mg)
{
#ifndef KXTF9_I2C_XOUT_L
#define KXTF9_I2C_XOUT_L 0x06
#endif
int err;
u8 acc_data[6]; // xyz data bytes from hardware
char buf, Res = 0, G_range = 0;
int range = 0, sensitivity;
int x_sign, y_sign, z_sign;
int hw_cnt[3] ; // calculated count value
int hw_mg[3]; // calculated mg value
int xyz_cnt[3];
int temp;
//int xyz_mg[3]; // acceleration data by mg (last return value)
// err = kxtf9_i2c_read(tf9, 0x1B, &buf, 1);
// if(err < 0 ) {
// dev_err(&tf9->client->dev, "can't get acceleration data, err=%d\n", err);
// return err;
<API key>(g_accel, 0x1B, &buf, 1);
G_range = (buf & 0x18) >> 3;
switch(G_range)
{
case 0:
range = 2;
break;
case 1:
range = 4;
break;
case 2:
range = 8;
break;
default:
break;
}
// err = kxtf9_i2c_read(tf9, KXTF9_XOUT_L, acc_data, 6);
// if(err < 0){
// dev_err(&tf9->client->dev, "can't get acceleration data, err=%d\n", err);
// return err;
<API key>(g_accel, KXTF9_I2C_XOUT_L, &acc_data[0], 6);
//printk("YJ- raw_data=[%02x, %02x, %02x, %02x, %02x, %02x] \n", acc_data[0], acc_data[1], acc_data[2], acc_data[3], acc_data[4] , acc_data[5] );
Res = buf & 0x40;
// switch(Res)
// case 0x00: // 8-bit : low resolution state
// break;
// case 0x40: // 12-bit : high-resolution state
temp = (int)((acc_data[1]<<4) + (acc_data[0]>>4));
// adjust for twos complement
if(temp < 2048)
temp = 2048 + temp;
else
temp = 2048- (4096-temp);
hw_cnt[0] = temp;
// convert raw data
hw_mg[0] = ((temp-2048)*1000)/1024;
//printk("YJ- temp1=[%02x] \n", temp);
temp = (int)((acc_data[3]<<4) + (acc_data[2]>>4));
// adjust for twos complement
if(temp < 2048)
temp = 2048 + temp;
else
temp = 2048- (4096-temp);
hw_cnt[1] = temp;
// convert raw data
hw_mg[1] = ((temp-2048)*1000)/1024;
//printk("YJ- temp2=[%02x] \n", temp);
temp = (int)((acc_data[5]<<4) + (acc_data[4]>>4));
// adjust for twos complement
if(temp < 2048)
temp = 2048 + temp;
else
temp = 2048- (4096-temp);
hw_cnt[2] = temp;
// convert raw data
hw_mg[2] = ((temp-2048)*1000)/1024;
//printk("YJ- temp3=[%02x] \n", temp);
// break;
#if defined(STAR_COUNTRY_COM) && defined(STAR_OPERATOR_OPEN)
xyz_mg[0] = hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = hw_mg[2];
#elif defined(STAR_COUNTRY_KR) && defined(STAR_OPERATOR_SKT)
xyz_mg[0] = -hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = -hw_mg[2];
#elif defined(STAR_COUNTRY_US) && defined(STAR_OPERATOR_TMO)
if(!strncmp(brdrev,BD_REVB,1)){
xyz_mg[0] = hw_mg[0];
xyz_mg[1] = -hw_mg[1];
xyz_mg[2] = -hw_mg[2];
} else {
xyz_mg[0] = hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = hw_mg[2];
}
#elif defined(STAR_COUNTRY_CA) && defined(STAR_OPERATOR_AWC)
if(!strncmp(brdrev,BD_REVB,1)){
xyz_mg[0] = hw_mg[0];
xyz_mg[1] = -hw_mg[1];
xyz_mg[2] = -hw_mg[2];
} else {
xyz_mg[0] = hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = hw_mg[2];
}
#elif defined(STAR_COUNTRY_CA) && defined(STAR_OPERATOR_AVC)
if(!strncmp(brdrev,BD_REVB,1)){
xyz_mg[0] = hw_mg[0];
xyz_mg[1] = -hw_mg[1];
xyz_mg[2] = -hw_mg[2];
} else {
xyz_mg[0] = hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = hw_mg[2];
}
#else
if(!strncmp(brdrev,BD_REVB,1)){
xyz_mg[0] = hw_mg[0];
xyz_mg[1] = -hw_mg[1];
xyz_mg[2] = -hw_mg[2];
} else {
xyz_mg[0] = hw_mg[1];
xyz_mg[1] = -hw_mg[0];
xyz_mg[2] = hw_mg[2];
}
#endif
//printk("YJ- CNT=[ %4d, %4d, %4d] , ACC=[ %4d, %4d, %4d] \n", hw_cnt[0], hw_cnt[1], hw_cnt[2], hw_mg[0], hw_mg[1] , hw_mg[2] );
return 0;
}
int <API key>(int *xyz_data)
{
int xyz[3] = { 0 };
int err;
err = <API key>(xyz);
if (err < 0){
return err;
} else{
xyz_data[0] = xyz[0];
xyz_data[1] = xyz[1];
xyz_data[2] = xyz[2];
return 0;
}
}
static void star_accel_whoami( void )
{
#define WHO_AM_I 0x0f
unsigned char value;
<API key>( g_accel, WHO_AM_I, &value, 1 );
#if STAR_ACCEL_DEBUG
printk("[skhwang][%s]: WHO AM I = %#x \n", __func__, value );
#endif
}
// 20100702 Power control bug fix [START]
static void <API key>(NvU32 vdd_id, NvBool is_enable )
{
<API key> vddrailcap;
NvU32 settletime;
<API key> h_pmu = <API key>();
if(h_pmu)
{
<API key>( h_pmu, vdd_id, &vddrailcap );
if( is_enable )
{
#if STAR_ACCEL_DEBUG
printk("[skhwang] PMU enable\n");
#endif
<API key>(h_pmu, vdd_id, vddrailcap.requestMilliVolts, &settletime);
}
else
{
#if STAR_ACCEL_DEBUG
printk("[skhwang] PMU do not enable\n");
#endif
<API key>(h_pmu, vdd_id, NVODM_VOLTAGE_OFF, &settletime);
}
if(settletime)
NvOdmOsWaitUS(settletime);
}
#if STAR_ACCEL_DEBUG
printk("[skhwang] voltage = %d or %d \n", vddrailcap.requestMilliVolts, vddrailcap.MinMilliVolts);
#endif
<API key>(h_pmu);
}
// 20100702 Power control bug fix [END]
int <API key>(void)
{
unsigned char value = 0;
<API key>( g_accel, 0x0F, &value, 1 );
printk("[%s] ### Accelerometer ## KXTF9 ## WHO_AM_I = 0x%x \n",MOD_TAG,value);
if(KXTF9_WHID != value)
return SENSOR_ERROR;
return SENSOR_OK;
}
int <API key>(void)
{
NvU32 I2cInstance = 0;
const <API key> *pcon;
int err;
NvBool found_gpio=NV_FALSE, found_i2c=NV_FALSE;
int loop;
printk("[%s:%d] \n", __FUNCTION__, __LINE__);
#if STAR_ACCEL_DEBUG
printk("[skhwang]%s\n", __func__);
#endif
pcon = (<API key>*)<API key>(NV_ODM_GUID('a','c','c','e','l','e','r','o'));
for(loop = 0; loop< pcon->NumAddress; loop++)
{
switch(pcon->AddressList[loop].Interface)
{
case NvOdmIoModule_I2c:
g_accel->i2c_address = (pcon->AddressList[loop].Address<<1);
I2cInstance = pcon->AddressList[loop].Instance;
found_i2c = NV_TRUE;
break;
case NvOdmIoModule_Gpio:
g_accel->intr_port = pcon->AddressList[loop].Instance;
g_accel->intr_pin = pcon->AddressList[loop].Address;
found_gpio = NV_TRUE;
break;
case NvOdmIoModule_Vdd:
g_accel->vdd_id = pcon->AddressList[loop].Address;
<API key>(g_accel->vdd_id, NV_FALSE);
NvOdmOsWaitUS(30);
break;
default:
break;
}
}
return SENSOR_OK;
}
int <API key>(void)
{
NvU32 I2cInstance = 0;
const <API key> *pcon;
int err;
NvBool found_gpio=NV_FALSE, found_i2c=NV_FALSE;
int loop;
printk("[%s:%d] \n", __FUNCTION__, __LINE__);
#if STAR_ACCEL_DEBUG
printk("[skhwang]%s\n", __func__);
#endif
pcon = (<API key>*)<API key>(NV_ODM_GUID('a','c','c','e','l','e','r','o'));
for(loop = 0; loop< pcon->NumAddress; loop++)
{
switch(pcon->AddressList[loop].Interface)
{
case NvOdmIoModule_I2c:
g_accel->i2c_address = (pcon->AddressList[loop].Address<<1);
I2cInstance = pcon->AddressList[loop].Instance;
found_i2c = NV_TRUE;
break;
case NvOdmIoModule_Gpio:
g_accel->intr_port = pcon->AddressList[loop].Instance;
g_accel->intr_pin = pcon->AddressList[loop].Address;
found_gpio = NV_TRUE;
break;
case NvOdmIoModule_Vdd:
g_accel->vdd_id = pcon->AddressList[loop].Address;
<API key>(g_accel->vdd_id, NV_TRUE);
NvOdmOsWaitUS(30);
break;
default:
break;
}
}
return SENSOR_OK;
}
static int <API key>( struct inode *inode, struct file *file )
{
#if STAR_ACCEL_DEBUG
printk("[skhwang][%s] function...\n");
#endif
return nonseekable_open(inode, file);
}
static long <API key>(struct file *file, unsigned int cmd, unsigned long arg )
{
void __user *argp = (void __user *)arg;
NvS32 x=0, y=0, z=0;
int xyz[3] = { 0 };
#if 0
switch(cmd)
{
case <API key>:
star_accel_get_data( g_accel, &x, &y, &z );
xyz[0] = x; xyz[1] = y; xyz[2] = z;
if( copy_to_user(argp, xyz, sizeof(int)*3))
return -EINVAL;
break;
default:
return -EINVAL;
}
#endif
return 0;
}
static const struct file_operations star_accel_misc_fop =
{
.owner = THIS_MODULE,
.open = <API key>,
.unlocked_ioctl = <API key>,
};
static struct miscdevice <API key> =
{
.minor = MISC_DYNAMIC_MINOR,
.name = "kxtf9",
.fops = &star_accel_misc_fop,
};
int tegra_accel_hw_init(void)
{
unsigned char val_shadow, dummy;
int err = -1;
u8 buf[7];
unsigned char tdt_timer_val = 0x78;
unsigned char tdt_tap_timer = 0xF2;
unsigned char tdt_total_timer = 0x36;
unsigned char tdt_latency_timer = 0x3c;
unsigned char tdt_window_timer = 0xb4;
unsigned char x_gain, y_gain, z_gain;
unsigned char tap_threshold = 0x1e;
<API key>(g_accel, <API key>, &val_shadow, 1);
printk("[%s:%d] [MOTION] Device ID (0x%02x) \n", __FUNCTION__, __LINE__, val_shadow);
/* Need 50ms until the RAM load is finished after Power-up */
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
val_shadow |= PC1_ON;
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
<API key>(200);
//KXTF9_set_G_range(2)
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
val_shadow &= ~(0x18); //G range 2
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
//<API key>(12);
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
val_shadow |= 0x40; //resolution 12bit
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
//KXTF9_set_hpf_odr(50);
<API key>(g_accel, DATA_CTRL, &val_shadow, 1);
val_shadow &= ~(0x30); /* set tap ODR to 50Hz */
<API key>(g_accel, DATA_CTRL, &val_shadow, 1);
//KXTF9_set_lpf_odr(100);
<API key>(g_accel, DATA_CTRL, &val_shadow, 1);
val_shadow &= ~(0x03); /* set LPF rolloff to 100 Hz */
val_shadow |= 0x04; /* set LPF rolloff to 100 Hz */
<API key>(g_accel, DATA_CTRL, &val_shadow, 1);
//KXTF9_set_odr_tilt(12);
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
val_shadow &= ~(0x20); /* set all ODR's to 12.5Hz */
val_shadow |= 0x40; /* set all ODR's to 12.5Hz */
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
//<API key>
<API key>(g_accel, 0x1C, &val_shadow, 1); //CTRL_REG2
val_shadow |= 0x03;
<API key>(g_accel, 0x1C, &val_shadow, 1);
//<API key>
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
val_shadow |= 0x01;/* sets TPE bit to enable tilt position function*/
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
//<API key>(g_accel, TILT_TIMER, &val_shadow, 1);
//val_shadow |= 0x05;/* tilt timer 80ms*/
//<API key>(g_accel, TILT_TIMER, &val_shadow, 1);
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
val_shadow &= ~(0x04); /* set all ODR's to 200Hz */
val_shadow |= 0x08; /* set all ODR's to 200Hz */
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
//KXTF9_tap_mask_TFU
<API key>(g_accel, 0x20, &val_shadow, 1);
val_shadow |= 0x3f;
<API key>(g_accel, 0x20, &val_shadow, 1);
/* <API key> */
//tapping 200 -> 400hz
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
val_shadow |= 0x0c; /* set all ODR's to 400Hz */
<API key>(g_accel, CTRL_REG3, &val_shadow, 1);
//tap sensitivity
<API key>(g_accel, 0x2d, &tap_threshold, 1);
<API key>(g_accel, 0x2b, &tdt_timer_val, 1); // TDT_TIMER
<API key>(g_accel, 0x2E, &tdt_tap_timer, 1); // TDT_TAP_TIMER
<API key>(g_accel, 0x2F, &tdt_total_timer, 1); // TDT_TOTAL_TIMER
<API key>(g_accel, 0x30, &tdt_latency_timer, 1); // TDT_LATENCY_TIMER
<API key>(g_accel, 0x31, &tdt_window_timer, 1); // TDT_WINDOW_TIMER
// X-gain control
<API key>(g_accel, 0x50, &x_gain, 1); // X_GAIN
//<API key>(0x50, 200 );
// Y-gain control
<API key>(g_accel, 0x51, &y_gain, 1); // Y_GAIN
//<API key>(0x51, 200 );
// Z-gain control
<API key>(g_accel, 0x52, &z_gain, 1); // Z_GAIN
//<API key>(0x52, (z_gain)>>1 );
//<API key>
//KXTF9_tap_mask_TFU
<API key>(g_accel, 0x20, &val_shadow, 1);
val_shadow |= 0x3f;
<API key>(g_accel, 0x20, &val_shadow, 1);
//<API key>
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
val_shadow |= 0x04; /* set TDTE bit to enable tap function */
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
//<API key>
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
val_shadow |= 0x10; //the polarity of physical interrupt pin to active high.
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
//<API key>
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
val_shadow &= ~(0x08); //sets the physical interrupt to a latch state.
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
<API key>(g_accel, 0x1a, &dummy, 1);
//<API key>
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
val_shadow |= 0x20; //enable interrupt
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
//<API key>
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
val_shadow |= 0x80; /* sets PC1 bit to be in power up state */
<API key>(g_accel, CTRL_REG1, &val_shadow, 1);
return 0;
}
void <API key>(unsigned char tap_mode, unsigned char tap_direction)
{
int type =0,direction =0;
if(tap_mode == 2)
type = <API key>;
else
type = <API key>;
#if defined(STAR_COUNTRY_COM) && defined(STAR_OPERATOR_OPEN)
switch(tap_direction)
{
case INT_CTRL_REG3_TFUM :
direction = ACCEL_TAP_BACK;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TFDM :
direction = ACCEL_TAP_FRONT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TUPM :
direction = ACCEL_TAP_LEFT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TDOM :
direction = ACCEL_TAP_RIGHT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TRIM :
direction = ACCEL_TAP_UP;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TLEM :
direction = ACCEL_TAP_DOWN;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
}
#elif defined(STAR_COUNTRY_KR) && defined(STAR_OPERATOR_SKT)
switch(tap_direction)
{
case INT_CTRL_REG3_TFUM :
direction = ACCEL_TAP_FRONT;//ACCEL_TAP_BACK;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TFDM :
direction = ACCEL_TAP_BACK;//ACCEL_TAP_FRONT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TUPM :
direction = ACCEL_TAP_RIGHT;//ACCEL_TAP_LEFT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TDOM :
direction = ACCEL_TAP_LEFT;//ACCEL_TAP_RIGHT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TRIM :
direction = ACCEL_TAP_UP;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TLEM :
direction = ACCEL_TAP_DOWN;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
}
#elif defined(STAR_COUNTRY_US) && defined(STAR_OPERATOR_TMO)
switch(tap_direction)
{
case INT_CTRL_REG3_TFUM :
direction = ACCEL_TAP_BACK;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TFDM :
direction = ACCEL_TAP_FRONT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TUPM :
direction = ACCEL_TAP_LEFT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TDOM :
direction = ACCEL_TAP_RIGHT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TRIM :
direction = ACCEL_TAP_UP;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TLEM :
direction = ACCEL_TAP_DOWN;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
}
#else
switch(tap_direction)
{
case INT_CTRL_REG3_TFUM :
direction = ACCEL_TAP_BACK;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TFDM :
direction = ACCEL_TAP_FRONT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TUPM :
direction = ACCEL_TAP_LEFT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TDOM :
direction = ACCEL_TAP_RIGHT;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TRIM :
direction = ACCEL_TAP_UP;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
case INT_CTRL_REG3_TLEM :
direction = ACCEL_TAP_DOWN;
if(tap_mode == 2) printk("[%s:%d]
else printk("[%s:%d]
break;
}
#endif
<API key>(type, direction);
return ;
}
void <API key>(unsigned char tilt_pos_pre, unsigned char tilt_pos_cur)
{
int flip_data=0;
switch(tilt_pos_cur)
{
case CTRL_REG2_RIM :
printk("[%s:%d]
break;
case CTRL_REG2_LEM :
printk("[%s:%d]
break;
case CTRL_REG2_UPM :
printk("[%s:%d]
break;
case CTRL_REG2_DOM : // Y- // <API key>
printk("[%s:%d]
break;
case CTRL_REG2_FUM :
printk("[%s:%d]
break;
case CTRL_REG2_FDM : // Z- // <API key>
printk("[%s:%d]
break;
}
//if((tilt_pos_cur == 0x01) || (tilt_pos_cur == 0x02))
{
if(call_once == 1)
{
flip_pre_pre_state = tilt_pos_cur;
call_once = 0;
}
if(flip_pre_pre_state != tilt_pos_cur)
{
if(tilt_pos_cur == 0x01)
{
#if defined(STAR_COUNTRY_COM) && defined(STAR_OPERATOR_OPEN)
flip_data = <API key>;
#elif defined(STAR_COUNTRY_KR) && defined(STAR_OPERATOR_SKT)
flip_data= <API key>;
#elif defined(STAR_COUNTRY_US) && defined(STAR_OPERATOR_TMO)
flip_data = <API key>;
#else
flip_data = <API key>;
#endif
}
else if(tilt_pos_cur == 0x02)
{
#if defined(STAR_COUNTRY_COM) && defined(STAR_OPERATOR_OPEN)
flip_data= <API key>;
#elif defined(STAR_COUNTRY_KR) && defined(STAR_OPERATOR_SKT)
flip_data = <API key>;
#elif defined(STAR_COUNTRY_US) && defined(STAR_OPERATOR_TMO)
flip_data= <API key>;
#else
flip_data= <API key>;
#endif
}
if((flip_data== <API key>)||(flip_data==<API key>))
{
<API key>(flip_data);
}
}
flip_pre_pre_state = tilt_pos_cur;
}
}
static void <API key>(void *arg)
{
//printk("%s() -- start\n\n", __func__);
schedule_work(&g_accel->work);
}
static void <API key>(struct work_struct *work)
{
unsigned char val_shadow;
unsigned char int_src_reg1, int_src_reg2;
unsigned char tilt_pos_cur, tilt_pos_pre;
//printk("%s() -- start\n\n", __func__);
//disable accelerometer interrupt first
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
val_shadow &= ~(0x20); //disable interrupt
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
// read status register
<API key>(g_accel, 0x18, &val_shadow, 1);
//printk("<API key> = %x \n",val_shadow);
//check interrupt
if(!(val_shadow & (1<<4)) ) {
printk("%s() -- not gesture interrupt\n\n", __func__);
goto RELEASE_INT;
}
<API key>(g_accel, INT_SRC_REG1, &int_src_reg1, 1);
<API key>(g_accel, INT_STATUS_REG, &int_src_reg2, 1);
//printk("<API key> = %x \n",int_src_reg1);
//printk("<API key> = %x \n",int_src_reg2);
if((int_src_reg2 & (0x3<<2)) && is_tap_enabled() ) { // Direction tap
unsigned char tap_mode ;
tap_mode = ((int_src_reg2&(0x3<<2))>>2);
// Processing Directional-Tap
<API key>(tap_mode, int_src_reg1);
}
if((int_src_reg2 & (1<<0)) && is_flip_enabled()) { // TPS : Screen Rotation
<API key>(g_accel, 0x10, &tilt_pos_cur, 1);
<API key>(g_accel, 0x11, &tilt_pos_pre, 1);
//printk("<API key> = %x <API key> = %x \n",tilt_pos_cur,tilt_pos_pre);
<API key>(tilt_pos_pre, tilt_pos_cur);
}
RELEASE_INT:
//printk("%s() -- interrupt released\n\n", __func__);
//interrupt released
<API key>(g_accel, 0x1A, &val_shadow, 1);
// enable accelerometer interrupt again
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
val_shadow |= 0x20; //enable interrupt
<API key>(g_accel, INT_CTRL1, &val_shadow, 1);
<API key>(g_accel->h_accel_intr);
return ;
}
static int __devinit star_accel_probe( struct platform_device *pdev )
{
NvU32 I2cInstance = 0;
const <API key> *pcon;
struct device* dev = &pdev->dev;
int err;
NvBool found_gpio=NV_FALSE, found_i2c=NV_FALSE;
unsigned char ctr_reg[4];
unsigned char ctr_val[4];
unsigned char reg_val;
int loop;
#if STAR_ACCEL_DEBUG
printk("[skhwang]%s\n", __func__);
#endif
g_accel = kzalloc(sizeof(*g_accel), GFP_KERNEL);
if( g_accel == NULL )
{
err = -ENOMEM;
printk("[skhwang][%s], Failed to alloc the memory\n", __func__);
goto failtomemorydev;
}
transfer_data_read = kzalloc(12, GFP_KERNEL);
transfer_data_write = kzalloc(12, GFP_KERNEL);
if (transfer_data_read == NULL || transfer_data_write == NULL) {
err = -ENOMEM;
printk("[skhwang][%s], Failed to alloc the memory\n", __func__);
goto failtomemorydev;
}
// 20100702 Power control bug fix [START]
/*g_accel->h_accel_pmu = <API key>();
if( !g_accel->h_accel_pmu )
{err=-ENOSYS; goto failtomemorydev;}*/
// 20100702 Power control bug fix [START]
pcon = (<API key>*)<API key>(NV_ODM_GUID('a','c','c','e','l','e','r','o'));
//pcon = (<API key>*)<API key>(NV_ODM_GUID('p','r','o','x','i','m','i','t'));
for(loop = 0; loop< pcon->NumAddress; loop++)
{
switch(pcon->AddressList[loop].Interface)
{
case NvOdmIoModule_I2c:
g_accel->i2c_address = (pcon->AddressList[loop].Address<<1);
I2cInstance = pcon->AddressList[loop].Instance;
found_i2c = NV_TRUE;
break;
case NvOdmIoModule_Gpio:
g_accel->intr_port = pcon->AddressList[loop].Instance;
g_accel->intr_pin = pcon->AddressList[loop].Address;
found_gpio = NV_TRUE;
break;
case NvOdmIoModule_Vdd:
g_accel->vdd_id = pcon->AddressList[loop].Address;
#if STAR_ACCEL_DEBUG
printk("[skhwang] KXTF9 POWER %d\n", g_accel->vdd_id );
#endif
// 20100702 Power control bug fix
<API key>(g_accel->vdd_id, NV_TRUE);
NvOdmOsWaitUS(30);
break;
default:
break;
}
}
#if STAR_ACCEL_DEBUG
printk("[skhwang][%s] : I2c Address = %#x, Int Port = %c, Int Pin = %d\n", __func__,
g_accel->i2c_address, (g_accel->intr_port+'a'), g_accel->intr_pin);
#endif
if( found_i2c != NV_TRUE || found_gpio != NV_TRUE )
{printk("[skhwang][%s] : I2c or Gpio not found...\n",__func__); err = -ENOMEM; goto failtomemorydev;}
g_accel->h_accel_gpio = NvOdmGpioOpen();
if(!g_accel->h_accel_gpio )
{
printk("[skhwang][%s] : Failed to open gpio\n",__func__);
err = - ENOSYS;
goto err_open_gpio;
}
g_accel->h_accel_gpio_pin = <API key>( g_accel->h_accel_gpio, g_accel->intr_port, g_accel->intr_pin );
if(!g_accel->h_accel_gpio_pin)
{
printk("[skhwang][%s] : Failed to acquire the pin handle\n",__func__);
err = -ENOSYS;
goto err_acquire_pin;
}
#if STAR_ACCEL_DEBUG
printk("[skhwang]Hu~~~ accel initialization end!!\n");
#endif
INIT_WORK(&g_accel->work, <API key>);
g_accel->h_gen2_i2c = NvOdmI2cPinMuxOpen(NvOdmIoModule_I2c, 1, <API key> );
if( !g_accel->h_gen2_i2c )
{
printk("[skhwang][%s] : failed to open I2c\n", __func__ );
err = -ENOSYS;
goto err_open_i2c;
}
NvOdmGpioConfig(g_accel->h_accel_gpio, g_accel->h_accel_gpio_pin, <API key>);
/* device interrupt registration */
g_accel->use_irq = <API key>(g_accel->h_accel_gpio, &g_accel->h_accel_intr, g_accel->h_accel_gpio_pin, <API key>, <API key>, (void*)g_accel, 0);
g_accel->input_dev = <API key>();
if(!g_accel->input_dev)
{
printk("[skhwang][%s] fail to allocate a input device\n", __func__ );
err = -ENOMEM;
goto err_input_alloc_dev;
}
if ((err = sysfs_create_group(&dev->kobj, &star_motion_group))) {
#if DEBUG
lprintk("[motion_sensor] sysfs_create_group FAIL \n");
#endif
goto err_sysfs_create;
}
g_accel->input_dev->name = "nvodm_accelerometer";
err = <API key>(g_accel->input_dev);
if(err)
{
printk("[%s] error to register input device\n",__func__);
goto <API key>;
}
//for ioctl
if( misc_register(&<API key>))
{
printk("[star accel, KXTF9] failed to register misc device\n");
err = -ENOSYS;
goto err_misc_register;
}
return 0;
err_sysfs_create:
printk("## sensor: star motion <API key>\n");
err_misc_register:
<API key>:
input_free_device(g_accel->input_dev);
err_input_alloc_dev:
err_open_i2c:
NvOdmOsFree(g_accel->h_gen2_i2c);
err_acquire_pin:
NvOdmOsFree(g_accel->h_accel_gpio_pin);
err_open_gpio:
NvOdmOsFree(g_accel->h_accel_gpio);
failtomemorydev:
g_accel = 0;
return err;
}
static int star_accel_remove( struct platform_device *pdev )
{
<API key>(g_accel->input_dev);
if (transfer_data_read != NULL) {
kfree(transfer_data_read);
}
if (transfer_data_write != NULL) {
kfree(transfer_data_write);
}
return 0;
}
extern int <API key>(void);
int star_accel_suspend(struct platform_device *dev, pm_message_t state)
{
if (!<API key>())
<API key>();
return 0;
}
int star_accel_resume(struct platform_device *dev)
{
if (!<API key>())
<API key>();
return 0;
}
static struct platform_driver star_accel_driver = {
.probe = star_accel_probe,
.remove = star_accel_remove,
.suspend = star_accel_suspend,
.resume = star_accel_resume,
.driver = {
.name = "tegra_accelerometer",
},
};
static int __init star_accel_init(void)
{
return <API key>(&star_accel_driver);
}
static void __exit star_accel_exit(void)
{
<API key>(&star_accel_driver);
}
module_init(star_accel_init);
module_exit(star_accel_exit);
MODULE_AUTHOR("sk.hwang@lge.com");
MODULE_DESCRIPTION("driver of star accelerometer sensor");
MODULE_LICENSE("GPL"); |
<?php
/**
* Single Portfolio Post Related Section
*/
global $helper,$super_options,$portfolio_taxonomy,$ioa_portfolio_slug;
/**
* Related Posts Logic
*/
$filter = wp_get_post_terms($post->ID, $portfolio_taxonomy );
$f_c = array();
foreach($filter as $f)
$f_c[] = $f->name;
if(count($filter) >0 ) :
$args = array(
'post_type' => $ioa_portfolio_slug,
'posts_per_page' => 4,
'post__not_in' => array($post->ID),
'tax_query' => array(
array(
'taxonomy' => $portfolio_taxonomy,
'field' => 'slug',
'terms' => $f_c
)
)
);
if( count($f_c) == 0 ) return;
$rel = new WP_Query( $args );
?>
<?php if( $super_options[SN.'<API key>']!="false" && $rel->have_posts()) : ?>
<div class="related_posts <API key> clearfix" itemscope itemtype="http://schema.org/ItemList">
<div class="clearfix <API key> ">
<h3 itemprop='name' class="<API key> custom-title"><?php echo stripslashes($super_options[SN.'<API key>']) ?></h3>
</div>
<?php
?>
<div class="related-posts-wrap clearfix">
<ul class="clearfix active <API key> related" >
<?php
$i=0;
while ($rel->have_posts()) : $rel->the_post(); $i++;
$dbg = '' ; $dc = '';
$ioa_options = get_post_meta( get_the_ID(), 'ioa_options', true );
if($ioa_options =="") $ioa_options = array();
if(isset( $ioa_options['dominant_bg_color'] )) $dbg = $ioa_options['dominant_bg_color'];
if(isset( $ioa_options['dominant_color'] )) $dc = $ioa_options['dominant_color'];
?>
<li class="clearfix <?php if($i==4) echo 'last'; ?>" itemscope itemtype="http://schema.org/Article">
<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) : /* if post has post thumbnail */ ?>
<div class="image">
<a class="hover" href="<?php the_permalink() ?>" style='background-color:<?php echo $dbg ?>;color:<?php echo $dc ?>;'>
<h3 itemprop="name" style='color:<?php echo $dc ?>;'><?php the_title(); ?></h3>
<i style='color:<?php echo $dbg ?>;background-color:<?php echo $dc ?>;' class='link link-2icon- ioa-front-icon'></i>
</a>
<?php
$id = <API key>();
$ar = <API key>( $id, array(9999,9999) );
echo $helper->imageDisplay( array( "src"=> $ar[0] ,"height" => 140 , "width" => 180 , "parent_wrap" => false, 'link' => get_permalink() ) );
?>
</div>
<?php endif; ?>
</li>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul>
</div>
</div>
<?php endif; endif; ?> |
#ifndef _JABBERINFO_H
#define _JABBERINFO_H
#include "ui_jabberinfobase.h"
#include "event.h"
class JabberUserData;
class JabberClient;
class JabberInfo : public QWidget, public Ui::JabberInfo, public SIM::EventReceiver
{
Q_OBJECT
public:
JabberInfo(QWidget *parent, JabberUserData *data, JabberClient *client);
signals:
void raise(QWidget*);
public slots:
void apply();
void apply(SIM::Client*, void*);
void goUrl();
void urlChanged(const QString&);
void resourceActivated(int);
protected:
virtual bool processEvent(SIM::Event *e);
void fill();
JabberUserData *m_data;
JabberClient *m_client;
};
#endif |
#include "common.h"
#include "dballe/core/shortcuts.h"
#include <wreport/subset.h>
#include <dballe/msg/context.h>
using namespace wreport;
using namespace std;
namespace dballe {
namespace impl {
namespace msg {
namespace wr {
static const Trange tr_std_past_wtr3(205, 0, 10800);
static const Trange tr_std_past_wtr6(205, 0, 21600);
// If var is not NULL and has a B04194 attribute, return its value
// otherwise, return orig
static int override_trange(const Var* var, int orig)
{
if (var)
if (const Var* a = var->enqa(WR_VAR(0, 4, 194)))
return a->enq(orig);
return orig;
}
void ExporterModule::init(const Message& msg, wreport::Subset& subset)
{
this->msg = &msg;
this->subset = ⊂
c_surface_instant = 0;
c_ana = 0;
}
void ExporterModule::scan_context(const msg::Context& c)
{
switch (c.level.ltype1)
{
case 1:
if (c.trange.pind == 254)
c_surface_instant = &c;
break;
case MISSING_INT: c_ana = &c; break;
}
}
void ExporterModule::add(Varcode code, const msg::Context* ctx, const Shortcut& shortcut) const
{
if (!ctx)
subset-><API key>(code);
else if (const Var* var = ctx->values.maybe_var(shortcut.code))
subset->store_variable(code, *var);
else
subset-><API key>(code);
}
void ExporterModule::add(Varcode code, const msg::Context* ctx, Varcode srccode) const
{
if (!ctx)
subset-><API key>(code);
else if (const Var* var = ctx->values.maybe_var(srccode))
subset->store_variable(code, *var);
else
subset-><API key>(code);
}
void ExporterModule::add(Varcode code, const msg::Context* ctx) const
{
if (!ctx)
subset-><API key>(code);
else if (const Var* var = ctx->values.maybe_var(code))
subset->store_variable(*var);
else
subset-><API key>(code);
}
void ExporterModule::add(wreport::Varcode code, const wreport::Var* var) const
{
if (var)
subset->store_variable(code, *var);
else
subset-><API key>(code);
}
void ExporterModule::<API key>()
{
add(WR_VAR(0, 1, 1), c_ana);
add(WR_VAR(0, 1, 2), c_ana);
add(WR_VAR(0, 2, 1), c_ana);
}
void CommonSynopExporter::init(const Message& msg, wreport::Subset& subset)
{
ExporterModule::init(msg, subset);
c_geopotential = 0;
c_thermo = 0;
c_tmax = 0;
c_tmin = 0;
c_prec1 = 0;
c_prec2 = 0;
c_prec24 = 0;
c_cloud_cover = 0;
for (int i = 0; i < 4; ++i)
c_cloud_data[i] = 0;
for (unsigned i = 0; i < sizeof(c_cloud_group) / sizeof(c_cloud_group[0]); ++i)
c_cloud_group[i] = 0;
c_wind = 0;
c_gust1 = 0;
c_gust2 = 0;
c_visib = 0;
c_past_wtr = 0;
c_depth = 0;
for (unsigned i = 0; i < sizeof(c_swell_waves) / sizeof(c_swell_waves[0]); ++i)
c_swell_waves[i] = 0;
v_press = 0;
v_pressmsl = 0;
v_pchange3 = 0;
v_pchange24 = 0;
v_ptend = 0;
v_geopotential = 0;
}
void CommonSynopExporter::scan_context(const msg::Context& c)
{
ExporterModule::scan_context(c);
switch (c.level.ltype1)
{
case 1:
switch (c.trange.pind)
{
case 1:
if (c.values.maybe_var(WR_VAR(0, 13, 11)))
{
if (c.trange.p2 == 86400)
c_prec24 = &c;
else if (!c_prec1)
c_prec1 = &c;
else if (!c_prec2)
c_prec2 = &c;
}
break;
case 2:
if (c.values.maybe_var(WR_VAR(0, 12, 101))) c_tmax = &c;
break;
case 3:
if (c.values.maybe_var(WR_VAR(0, 12, 101))) c_tmin = &c;
break;
case 4:
if (const Var* v = c.values.maybe_var(sc::press_3h.code))
switch (c.trange.p2)
{
case 3*3600: v_pchange3 = v; break;
case 24*3600: v_pchange24 = v; break;
}
break;
case 205:
if (const Var* v = c.values.maybe_var(sc::press_tend.code))
v_ptend = v;
if (c.values.maybe_var(WR_VAR(0, 20, 4)) || c.values.maybe_var(WR_VAR(0, 20, 5)))
c_past_wtr = &c;
break;
case 254:
if (const Var* v = c.values.maybe_var(sc::press.code))
v_press = v;
if (const Var* v = c.values.maybe_var(sc::press_msl.code))
v_pressmsl = v;
if (c.values.maybe_var(sc::visibility.code))
c_visib = &c;
if (c.values.maybe_var(WR_VAR(0, 22, 43)))
c_depth = &c;
break;
}
break;
case 100:
// Look for geopotential
if (const Var* v = c.values.maybe_var(WR_VAR(0, 10, 8)))
{
c_geopotential = &c;
v_geopotential = v;
}
break;
case 101:
case 102:
switch (c.trange.pind)
{
case 4:
if (const Var* v = c.values.maybe_var(sc::press_3h.code))
switch (c.trange.p2)
{
case 3*3600: v_pchange3 = v; break;
case 24*3600: v_pchange24 = v; break;
}
break;
case 205:
if (const Var* v = c.values.maybe_var(sc::press_tend.code))
v_ptend = v;
break;
case 254:
if (const Var* v = c.values.maybe_var(sc::press.code))
v_press = v;
if (const Var* v = c.values.maybe_var(sc::press_msl.code))
v_pressmsl = v;
break;
}
break;
case 103:
if (c.values.maybe_var(WR_VAR(0, 11, 1)) || c.values.maybe_var(WR_VAR(0, 11, 2)))
if (!c_wind)
c_wind = &c;
if (c.values.maybe_var(WR_VAR(0, 11, 41)) || c.values.maybe_var(WR_VAR(0, 11, 43)))
{
if (!c_gust1)
c_gust1 = &c;
else if (!c_gust2)
c_gust2 = &c;
}
if (c.values.maybe_var(sc::visibility.code))
c_visib = &c;
switch (c.trange.pind)
{
case 1:
if (c.values.maybe_var(WR_VAR(0, 13, 11)))
{
if (c.trange.p2 == 86400)
c_prec24 = &c;
else if (!c_prec1)
c_prec1 = &c;
else if (!c_prec2)
c_prec2 = &c;
}
break;
case 2:
if (c.values.maybe_var(WR_VAR(0, 12, 101))) c_tmax = &c;
break;
case 3:
if (c.values.maybe_var(WR_VAR(0, 12, 101))) c_tmin = &c;
break;
case 254:
if (c.values.maybe_var(sc::temp_2m.code) || c.values.maybe_var(sc::dewpoint_2m.code) || c.values.maybe_var(sc::humidity.code))
c_thermo = &c;
break;
}
break;
case 160:
case 161:
if (c.values.maybe_var(WR_VAR(0, 22, 43)))
c_depth = &c;
break;
case 256:
// Clouds
switch (c.level.ltype2)
{
case 258:
if (c.level.l2 >= 0 && c.level.l2 < 4)
c_cloud_data[c.level.l2] = &c;
break;
case 259:
if (c.level.l2 >= 0 && c.level.l2 < (int)(sizeof(c_cloud_group) / sizeof(c_cloud_group[0])))
c_cloud_group[c.level.l2] = &c;
break;
case MISSING_INT:
c_cloud_cover = &c;
break;
}
break;
case 264:
// Swell wave groups
switch (c.level.ltype2)
{
case 261:
if (c.level.l2 >= 1 && c.level.l2 <= (int)(sizeof(c_swell_waves) / sizeof(c_swell_waves[0])))
c_swell_waves[c.level.l2 - 1] = &c;
break;
}
break;
}
}
void CommonSynopExporter::add_D02001()
{
add(WR_VAR(0, 10, 4), v_press);
add(WR_VAR(0, 10, 51), v_pressmsl);
add(WR_VAR(0, 10, 61), v_pchange3);
add(WR_VAR(0, 10, 63), v_ptend);
}
void CommonSynopExporter::add_D02031()
{
add_D02001();
add(WR_VAR(0, 10, 62), v_pchange24);
add_pressure();
add_geopotential(WR_VAR(0, 10, 9));
}
void CommonSynopExporter::add_pressure()
{
if (c_geopotential)
{
if (c_geopotential->level.l1 == MISSING_INT)
subset-><API key>(WR_VAR(0, 7, 4));
else
subset->store_variable_d(WR_VAR(0, 7, 4), c_geopotential->level.l1);
}
else
subset-><API key>(WR_VAR(0, 7, 4));
}
void CommonSynopExporter::add_geopotential(wreport::Varcode code)
{
add(code, v_geopotential);
}
void CommonSynopExporter::add_D02032()
{
if (!c_thermo)
{
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 12, 101));
subset-><API key>(WR_VAR(0, 12, 103));
subset-><API key>(WR_VAR(0, 13, 3));
} else {
const Var* var_t = c_thermo->values.maybe_var(sc::temp_2m.code);
const Var* var_d = c_thermo->values.maybe_var(sc::dewpoint_2m.code);
const Var* var_h = c_thermo->values.maybe_var(sc::humidity.code);
add_sensor_height(*c_thermo, var_t ? var_t : var_d ? var_d : var_h);
add(WR_VAR(0, 12, 101), var_t);
add(WR_VAR(0, 12, 103), var_d);
add(WR_VAR(0, 13, 3), var_h);
}
}
void CommonSynopExporter::add_D02052()
{
if (!c_thermo)
{
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 7, 33));
subset-><API key>(WR_VAR(0, 12, 101));
subset-><API key>(WR_VAR(0, 2, 39));
subset-><API key>(WR_VAR(0, 12, 102));
subset-><API key>(WR_VAR(0, 12, 103));
subset-><API key>(WR_VAR(0, 13, 3));
} else {
const Var* var_t = c_thermo->values.maybe_var(sc::temp_2m.code);
const Var* var_w = c_thermo->values.maybe_var(sc::wet_temp_2m.code);
const Var* var_d = c_thermo->values.maybe_var(sc::dewpoint_2m.code);
const Var* var_h = c_thermo->values.maybe_var(sc::humidity.code);
<API key>(*c_thermo, var_t ? var_t : var_w ? var_w : var_d ? var_d : var_h);
add(WR_VAR(0, 12, 101), var_t);
add(WR_VAR(0, 2, 39), c_ana);
add(WR_VAR(0, 12, 102), var_w);
add(WR_VAR(0, 12, 103), var_d);
add(WR_VAR(0, 13, 3), var_h);
}
}
void CommonSynopExporter::add_D02041()
{
if (c_tmax || c_tmin)
{
const msg::Context* c_first = c_tmax ? c_tmax : c_tmin;
add_sensor_height(*c_first, c_first->values.maybe_var(WR_VAR(0, 12, 101)));
}
else
subset-><API key>(WR_VAR(0, 7, 32));
add_xtemp_group(WR_VAR(0, 12, 111), c_tmax);
add_xtemp_group(WR_VAR(0, 12, 112), c_tmin);
}
void CommonSynopExporter::add_D02058()
{
if (c_tmax || c_tmin)
{
const msg::Context* c_first = c_tmax ? c_tmax : c_tmin;
<API key>(*c_first, c_first->values.maybe_var(WR_VAR(0, 12, 101)));
}
else
{
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 7, 33));
}
add_xtemp_group(WR_VAR(0, 12, 111), c_tmax);
add_xtemp_group(WR_VAR(0, 12, 112), c_tmin);
}
void CommonSynopExporter::add_D02034()
{
if (c_prec24)
{
const Var* var = c_prec24->values.maybe_var(WR_VAR(0, 13, 11));
add_sensor_height(*c_prec24, var);
add(WR_VAR(0, 13, 23), c_prec24, sc::tot_prec24);
} else {
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 13, 23));
}
subset-><API key>(WR_VAR(0, 7, 32));
}
void CommonSynopExporter::add_D02040()
{
if (c_prec1)
{
const Var* prec_var = c_prec1->values.maybe_var(WR_VAR(0, 13, 11));
add_sensor_height(*c_prec1, prec_var);
} else {
subset-><API key>(WR_VAR(0, 7, 32));
}
add_prec_group(c_prec1);
add_prec_group(c_prec2);
}
void CommonSynopExporter::add_D02042()
{
if (c_wind || c_gust1 || c_gust2)
{
// Look for the sensor height in the context of any of the found levels
const msg::Context* c_first = c_wind ? c_wind : c_gust1 ? c_gust1 : c_gust2;
const Var* sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 1));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 2));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 41));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 43));
add_sensor_height(*c_first, sample_var);
add(WR_VAR(0, 2, 2), c_ana);
subset->store_variable_i(WR_VAR(0, 8, 21), 2);
if (c_wind)
{
// Compute time range from level and attrs
const Var* var_dir = c_wind->values.maybe_var(WR_VAR(0, 11, 1));
const Var* var_speed = c_wind->values.maybe_var(WR_VAR(0, 11, 2));
int tr = MISSING_INT;
if (c_wind->trange.pind == 200)
tr = c_wind->trange.p2;
tr = override_trange(var_dir, override_trange(var_speed, tr));
if (tr == MISSING_INT)
subset-><API key>(WR_VAR(0, 4, 25));
else
subset->store_variable_d(WR_VAR(0, 4, 25), -tr / 60.0);
add(WR_VAR(0, 11, 1), var_dir);
add(WR_VAR(0, 11, 2), var_speed);
} else {
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 1));
subset-><API key>(WR_VAR(0, 11, 2));
}
subset-><API key>(WR_VAR(0, 8, 21));
add_wind_gust(c_gust1);
add_wind_gust(c_gust2);
} else {
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 2, 2));
subset->store_variable_i(WR_VAR(0, 8, 21), 2);
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 1));
subset-><API key>(WR_VAR(0, 11, 2));
subset-><API key>(WR_VAR(0, 8, 21));
for (int i = 1; i <= 2; ++i)
{
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 43));
subset-><API key>(WR_VAR(0, 11, 41));
}
}
}
void CommonSynopExporter::add_D02059()
{
if (c_wind || c_gust1 || c_gust2)
{
// Look for the sensor height in the context of any of the found levels
const msg::Context* c_first = c_wind ? c_wind : c_gust1 ? c_gust1 : c_gust2;
const Var* sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 1));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 2));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 41));
if (!sample_var) sample_var = c_first->values.maybe_var(WR_VAR(0, 11, 43));
<API key>(*c_first, sample_var);
add(WR_VAR(0, 2, 2), c_ana);
subset->store_variable_i(WR_VAR(0, 8, 21), 2);
if (c_wind)
{
// Compute time range from level and attrs
const Var* var_dir = c_wind->values.maybe_var(WR_VAR(0, 11, 1));
const Var* var_speed = c_wind->values.maybe_var(WR_VAR(0, 11, 2));
int tr = MISSING_INT;
if (c_wind->trange.pind == 200)
tr = c_wind->trange.p2;
tr = override_trange(var_dir, override_trange(var_speed, tr));
if (tr == MISSING_INT)
subset-><API key>(WR_VAR(0, 4, 25));
else
subset->store_variable_d(WR_VAR(0, 4, 25), -tr / 60.0);
add(WR_VAR(0, 11, 1), var_dir);
add(WR_VAR(0, 11, 2), var_speed);
} else {
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 1));
subset-><API key>(WR_VAR(0, 11, 2));
}
subset-><API key>(WR_VAR(0, 8, 21));
add_wind_gust(c_gust1);
add_wind_gust(c_gust2);
} else {
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 7, 33));
subset-><API key>(WR_VAR(0, 2, 2));
subset->store_variable_i(WR_VAR(0, 8, 21), 2);
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 1));
subset-><API key>(WR_VAR(0, 11, 2));
subset-><API key>(WR_VAR(0, 8, 21));
for (int i = 1; i <= 2; ++i)
{
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 43));
subset-><API key>(WR_VAR(0, 11, 41));
}
}
}
void CommonSynopExporter::add_wind_gust(const msg::Context* c)
{
if (c)
{
// Compute time range from level and attrs
const Var* var_dir = c->values.maybe_var(WR_VAR(0, 11, 43));
const Var* var_speed = c->values.maybe_var(WR_VAR(0, 11, 41));
int tr = MISSING_INT;
if (c->trange.pind == 205)
tr = c->trange.p2;
else if (c->trange.pind == 254)
tr = 600;
tr = override_trange(var_dir, override_trange(var_speed, tr));
if (tr == MISSING_INT)
subset-><API key>(WR_VAR(0, 4, 25));
else
subset->store_variable_d(WR_VAR(0, 4, 25), -tr / 60.0);
add(WR_VAR(0, 11, 43), var_dir);
add(WR_VAR(0, 11, 41), var_speed);
} else {
subset-><API key>(WR_VAR(0, 4, 25));
subset-><API key>(WR_VAR(0, 11, 43));
subset-><API key>(WR_VAR(0, 11, 41));
}
}
void CommonSynopExporter::add_cloud_data()
{
// Cloud data
add(WR_VAR(0, 20, 10), c_cloud_cover);
add(WR_VAR(0, 8, 2), c_cloud_data[0]);
add(WR_VAR(0, 20, 11), c_cloud_data[0]);
add(WR_VAR(0, 20, 13), c_cloud_data[0]);
add(WR_VAR(0, 20, 12), c_cloud_data[1]);
add(WR_VAR(0, 20, 12), c_cloud_data[2]);
add(WR_VAR(0, 20, 12), c_cloud_data[3]);
// Individual cloud layers or masses
int count = 0;
for (unsigned i = 0; i < sizeof(c_cloud_group) / sizeof(c_cloud_group[0]); ++i)
if (c_cloud_group[i])
++count;
// Number of individual cloud layers or masses
subset->store_variable_i(WR_VAR(0, 1, 31), count);
for (unsigned i = 0; i < sizeof(c_cloud_group) / sizeof(c_cloud_group[0]); ++i)
{
if (!c_cloud_group[i]) continue;
add(WR_VAR(0, 8, 2), c_cloud_group[i]);
add(WR_VAR(0, 20, 11), c_cloud_group[i]);
add(WR_VAR(0, 20, 12), c_cloud_group[i]);
add(WR_VAR(0, 20, 13), c_cloud_group[i]);
}
}
void CommonSynopExporter::add_prec_group(const msg::Context* c)
{
if (c)
{
if (c->trange.p2 != MISSING_INT)
subset->store_variable_d(WR_VAR(0, 4, 24), -c->trange.p2 / 3600);
else
subset-><API key>(WR_VAR(0, 4, 24));
if (const Var* var = c->values.maybe_var(WR_VAR(0, 13, 11)))
subset->store_variable(*var);
else
subset-><API key>(WR_VAR(0, 13, 11));
} else {
subset-><API key>(WR_VAR(0, 4, 24));
subset-><API key>(WR_VAR(0, 13, 11));
}
}
void CommonSynopExporter::add_sensor_height(const msg::Context& c, const Var* sample_var)
{
// Try with attributes first
if (sample_var)
{
if (const Var* a = sample_var->enqa(WR_VAR(0, 7, 32)))
{
subset->store_variable_d(WR_VAR(0, 7, 32), a->enqd());
return;
}
}
// Use level
if (c.level.ltype1 == 1)
// Ground level
subset->store_variable_d(WR_VAR(0, 7, 32), 0);
else if (c.level.ltype1 == 103)
{
// Height above ground level
if (c.level.l1 == MISSING_INT)
subset-><API key>(WR_VAR(0, 7, 32));
else
subset->store_variable_d(WR_VAR(0, 7, 32), double(c.level.l1) / 1000.0);
}
else
error_consistency::throwf("Cannot add sensor height from unsupported level type %d", c.level.ltype1);
}
void CommonSynopExporter::<API key>(const msg::Context& c, const Var* sample_var)
{
// FIXME: B07033 is hardcoded as undef for now, until we actually found
// bulletins in which it is set
// Try with attributes first
if (sample_var)
{
if (const Var* a = sample_var->enqa(WR_VAR(0, 7, 32)))
{
subset->store_variable_d(WR_VAR(0, 7, 32), a->enqd());
subset-><API key>(WR_VAR(0, 7, 33));
return;
}
}
// Use level
if (c.level.ltype1 == 1)
{
// Ground level
subset->store_variable_d(WR_VAR(0, 7, 32), 0);
subset-><API key>(WR_VAR(0, 7, 33));
}
else if (c.level.ltype1 == 103)
{
// Height above ground level
if (c.level.l1 == MISSING_INT)
subset-><API key>(WR_VAR(0, 7, 32));
else
subset->store_variable_d(WR_VAR(0, 7, 32), double(c.level.l1) / 1000.0);
subset-><API key>(WR_VAR(0, 7, 33));
}
else
error_consistency::throwf("Cannot add sensor height from unsupported level type %d", c.level.ltype1);
}
void CommonSynopExporter::add_xtemp_group(Varcode code, const msg::Context* c)
{
if (c)
{
// Duration of statistical processing
if (c->trange.p2 != MISSING_INT)
subset->store_variable_d(WR_VAR(0, 4, 24), -c->trange.p2 / 3600);
else
subset-><API key>(WR_VAR(0, 4, 24));
// Offset from end of interval to synop reference time
if (c->trange.p1 != 0 && c->trange.p1 != MISSING_INT)
subset->store_variable_d(WR_VAR(0, 4, 24), c->trange.p1 / 3600);
else if (c->trange.p1 == MISSING_INT || c->trange.p2 == MISSING_INT)
subset-><API key>(WR_VAR(0, 4, 24));
else
subset->store_variable_d(WR_VAR(0, 4, 24), 0);
add(code, c, WR_VAR(0, 12, 101));
} else {
subset-><API key>(WR_VAR(0, 4, 24));
subset-><API key>(WR_VAR(0, 4, 24));
subset-><API key>(code);
}
}
void CommonSynopExporter::<API key>()
{
add(WR_VAR(0, 11, 11), c_wind, sc::wind_dir);
add(WR_VAR(0, 11, 12), c_wind, sc::wind_speed);
add(WR_VAR(0, 12, 4), c_thermo, sc::temp_2m);
add(WR_VAR(0, 12, 6), c_thermo, sc::dewpoint_2m);
add(WR_VAR(0, 13, 3), c_thermo, sc::humidity);
add(WR_VAR(0, 20, 1), c_visib);
add(WR_VAR(0, 20, 3), c_surface_instant, sc::pres_wtr);
add(WR_VAR(0, 20, 4), c_past_wtr);
add(WR_VAR(0, 20, 5), c_past_wtr);
}
void CommonSynopExporter::add_D02038()
{
// Present and past weather
add(WR_VAR(0, 20, 3), c_surface_instant);
if (c_past_wtr)
{
int hour = msg->get_datetime().hour;
// Look for a p2 override in the attributes
const Var* v = c_past_wtr->values.maybe_var(WR_VAR(0, 20, 4));
if (!v) v = c_past_wtr->values.maybe_var(WR_VAR(0, 20, 5));
add_time_period(WR_VAR(0, 4, 24), *c_past_wtr, v, hour % 6 == 0 ? tr_std_past_wtr6 : tr_std_past_wtr3);
} else
subset-><API key>(WR_VAR(0, 4, 24));
add(WR_VAR(0, 20, 4), c_past_wtr);
add(WR_VAR(0, 20, 5), c_past_wtr);
}
void CommonSynopExporter::add_time_period(Varcode code, const msg::Context& c, const Var* sample_var, const Trange& tr_std)
{
int p2;
if (c.trange.pind == 254)
p2 = tr_std.p2;
else
p2 = c.trange.p2;
// Look for a p2 override in the attributes
if (sample_var)
if (const Var* a = sample_var->enqa(WR_VAR(0, 4, 194)))
p2 = a->enqi();
if (p2 == MISSING_INT)
{
subset-><API key>(WR_VAR(0, 4, 24));
return;
}
double res = -p2;
switch (code)
{
case WR_VAR(0, 4, 24): res /= 3600.0; break;
case WR_VAR(0, 4, 25): res /= 60.0; break;
}
subset->store_variable_d(code, res);
}
void CommonSynopExporter::add_D02035()
{
// Temperature and humidity data
add_D02032();
// Visibility data
if (c_visib)
{
const Var* var = c_visib->values.maybe_var(sc::visibility.code);
add_sensor_height(*c_visib, var);
} else
subset-><API key>(WR_VAR(0, 7, 32));
add(WR_VAR(0, 20, 1), c_visib, sc::visibility);
// Precipitation past 24 hours
add_D02034();
// Cloud data
add_cloud_data();
}
void CommonSynopExporter::add_D02053()
{
// Visibility data
if (c_visib)
{
const Var* var = c_visib->values.maybe_var(sc::visibility.code);
<API key>(*c_visib, var);
} else {
subset-><API key>(WR_VAR(0, 7, 32));
subset-><API key>(WR_VAR(0, 7, 33));
}
add(WR_VAR(0, 20, 1), c_visib, sc::visibility);
subset-><API key>(WR_VAR(0, 7, 33));
}
void CommonSynopExporter::add_D02055()
{
add(WR_VAR(0, 20, 31), c_surface_instant);
add(WR_VAR(0, 20, 32), c_surface_instant);
add(WR_VAR(0, 20, 33), c_surface_instant);
add(WR_VAR(0, 20, 34), c_surface_instant);
add(WR_VAR(0, 20, 35), c_surface_instant);
add(WR_VAR(0, 20, 36), c_surface_instant);
add(WR_VAR(0, 20, 37), c_surface_instant);
add(WR_VAR(0, 20, 38), c_surface_instant);
}
void CommonSynopExporter::add_ecmwf_ice()
{
add(WR_VAR(0, 20, 33), c_surface_instant);
add(WR_VAR(0, 20, 31), c_surface_instant);
add(WR_VAR(0, 20, 32), c_surface_instant);
add(WR_VAR(0, 20, 34), c_surface_instant);
add(WR_VAR(0, 20, 37), c_surface_instant);
add(WR_VAR(0, 20, 38), c_surface_instant);
add(WR_VAR(0, 20, 36), c_surface_instant);
}
void CommonSynopExporter::add_D02056()
{
add(WR_VAR(0, 2, 38), c_ana);
if (c_depth)
{
if (c_depth->level.ltype1 == 160)
subset->store_variable_d(WR_VAR(0, 7, 63), (double)c_depth->level.l1 / 1000.0);
else
subset-><API key>(WR_VAR(0, 7, 63));
add(WR_VAR(0, 22, 43), c_depth);
} else {
subset-><API key>(WR_VAR(0, 7, 63));
subset-><API key>(WR_VAR(0, 22, 43));
}
subset-><API key>(WR_VAR(0, 7, 63));
}
void CommonSynopExporter::add_plain_waves()
{
add(WR_VAR(0, 22, 1), c_surface_instant);
add(WR_VAR(0, 22, 11), c_surface_instant);
add(WR_VAR(0, 22, 21), c_surface_instant);
}
void CommonSynopExporter::add_D02024()
{
// Wind waves
add(WR_VAR(0, 22, 2), c_surface_instant);
add(WR_VAR(0, 22, 12), c_surface_instant);
add(WR_VAR(0, 22, 22), c_surface_instant);
// 2 systems of swell waves
unsigned src_idx = 0;
for (int i = 0; i < 2; ++i)
{
// Look for the next available swell waves group
const msg::Context* c = 0;
for ( ; src_idx < sizeof(c_swell_waves) / sizeof(c_swell_waves[0]); ++src_idx)
if (c_swell_waves[src_idx])
{
c = c_swell_waves[src_idx];
break;
}
add(WR_VAR(0, 22, 3), c);
add(WR_VAR(0, 22, 13), c);
add(WR_VAR(0, 22, 23), c);
++src_idx;
}
}
}
}
}
} |
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <rtems/system.h>
#include <rtems/score/object.h>
#include <rtems/score/thread.h>
#include <stdlib.h>
#include <ctype.h>
#include <inttypes.h>
/*
* This method objects the name of an object and returns its name
* in the form of a C string. It attempts to be careful about
* overflowing the user's string and about returning unprintable characters.
*/
char *<API key>(
Objects_Id id,
size_t length,
char *name
)
{
Objects_Information *information;
const char *s;
char *d;
uint32_t i;
char lname[5];
Objects_Control *the_object;
Objects_Locations location;
Objects_Id tmpId;
if ( length == 0 )
return NULL;
if ( name == NULL )
return NULL;
tmpId = (id == OBJECTS_ID_OF_SELF) ? _Thread_Executing->Object.id : id;
information = <API key>( tmpId );
if ( !information )
return NULL;
the_object = _Objects_Get( information, tmpId, &location );
switch ( location ) {
#if defined(<API key>)
case OBJECTS_REMOTE:
/* not supported */
#endif
case OBJECTS_ERROR:
return NULL;
case OBJECTS_LOCAL:
#if defined(<API key>)
if ( information->is_string ) {
s = the_object->name.name_p;
} else
#endif
{
uint32_t u32_name = (uint32_t) the_object->name.name_u32;
lname[ 0 ] = (u32_name >> 24) & 0xff;
lname[ 1 ] = (u32_name >> 16) & 0xff;
lname[ 2 ] = (u32_name >> 8) & 0xff;
lname[ 3 ] = (u32_name >> 0) & 0xff;
lname[ 4 ] = '\0';
s = lname;
}
d = name;
if ( s ) {
for ( i=0 ; i<(length-1) && *s ; i++, s++, d++ ) {
*d = (isprint((unsigned char)*s)) ? *s : '*';
}
}
*d = '\0';
<API key>();
return name;
}
return NULL; /* unreachable path */
} |
<?php require("../../includes/header.php"); ?><h1>The Black Riders</h1><div class="content">
<p><html> <body></body></html></p>
<h1 style="font-family: Arial;"><small>ACM International Collegiate Programming Contest, Asia-Amritapuri Site, 2012</small></h1>
<h2>The Black Riders<br /> </h2>
<p> <i>'Hush!' said Frodo. 'I think I hear hoofs again.'<br /> They stopped suddenly and stood as silent as tree-shadows, listening. There was a sound of hoofs in the lane, some way behind, but coming slow and clear down the wind. Quickly and quietly they slipped off the path, and ran into the deeper shade under the oak-trees.<br /> The hoofs drew nearer. They had no time to find any hiding-place better than the general darkness under the trees.</i> <br /> - Frodo, Sam and Pippin, when they encounter a Black Rider.</p>
<p> Indeed, the Black Riders are in the Shire, and they are looking for the One Ring. There are <b>N</b> hobbits out in their fields, but when they hear the Riders approaching, or feel the fear cast by their presence, they immediately wish to run and hide in <b>M</b> holes located nearby.</p>
<p> Now, each hole has space for just 1 hobbit; however, once a hobbit reaches a hole, he is able to make room for one more hobbit by digging away at the earth. The time required to make enough space for a second hobbit is <b>C</b> units. Also, each hole CANNOT hold more than 2 hobbits, even after digging. Also note that a hobbit can begin making space for the next hobbit only after he reaches the hole.</p>
<p> You are given the time required to travel from each hobbit's current location to each hole. Find the minimum amount of time it will take before at least <b>K</b> of the hobbits are hiding safely.</p>
<p></p>
<h3>Input (STDIN):</h3>
<p> The first line contains <b>T</b>, the number of test cases.<br /> The first line of each test case contains 4 integers - <b>N</b> (no of hobbits), <b>M</b> (no of holes), <b>K</b> (minimum number of hobbits to hide) and <b>C</b> (time taken to expand a hole).<br /> The next <b>N</b> lines contain <b>M</b> integers each, denoting the time taken for each hobbit to each hole.</p>
<p></p>
<h3>Output (STDOUT):</h3>
<p> Output one line per test case which contains the minimum time. </p>
<p></p>
<h3>Constraints:</h3>
<p><b> 1 <= T <= 6<br /> 1 <= N, M <= 100<br /> 1 <= K <= min(N, 2 * M)<br /> 0 < C < 10,000,000<br /> 0 < Time taken by the hobbits to the holes < 10,000,000</b></p>
<p></p>
<h3>Sample Input:</h3>
<p> <span style="font-family: Courier New,Courier,monospace;"> 2<br /> 3 3 2 10<br /> 9 11 13<br /> 2 10 14<br /> 12 15 12<br /> 4 3 3 8<br /> 1 10 100<br /> 1 10 100<br /> 100 100 6<br /> 12 10 10<br /> </span></p>
<h3>Sample Output:</h3>
<p> <span style="font-family: Courier New,Courier,monospace;"> 10<br /> 9<br /> </span></p>
<h3>Notes/Explanation of Sample Input:</h3>
<p> For the first test case, there are 3 hobbits and 3 holes, and we need to get atleast 2 of them to safety. We can send the first hobbit to the first hole, and the second hobbit to the second hole, thereby taking 10 time units.<br /> For the second test case, we can make hobbit #1 reach hole 1 at time 1, hobbit #2 reach hole 1 at time 9 (by when hobbit #1 would have finished digging the hole), and hobbit #3 reach hole 3 at time 6.</p>
<p> </p>
</div><table cellspacing="0" cellpadding="0" align="left">
<tr>
<td width="14%">Author:</td>
<td><a href="/users/admin">admin</a></td>
</tr>
<tr>
<td width="14%">Date Added:</td>
<td>22-01-2013</td>
</tr>
<tr>
<td width="14%">Time Limit:</td>
<td>2 sec</td>
</tr>
<tr>
<td width="14%">Source Limit:</td>
<td>50000 Bytes</td>
</tr>
<tr>
<td width="14%">Languages:</td>
<td>ADA, ASM, BASH, BF, C, C99 strict, CAML, CLOJ, CLPS, CPP 4.3.2, CPP 4.8.1, CPP11, CS2, D, ERL, FORT, FS, GO, HASK, ICK, ICON, JAR, JAVA, JS, LISP clisp, LISP sbcl, LUA, NEM, NICE, NODEJS, PAS fpc, PAS gpc, PERL, PERL6, PHP, PIKE, PRLG, PYTH, PYTH 3.1.2, RUBY, SCALA, SCM guile, SCM qobi, ST, TCL, TEXT, WSPC</td>
</tr>
</table> <?php require("../../includes/footer.php"); ?> |
<?php
/**
* Factory Adapter for the Joomla! framework
*
* @author Johan Janssens <johan@nooku.org>
* @category Koowa
* @package Koowa_Factory
* @subpackage Adapter
*/
class <API key> extends <API key>
{
/**
* The adapter type
*
* @var string
*/
protected $_type = 'joomla';
/**
* The alias type map
*
* @var array
*/
protected $_alias_map = array(
'Database' => 'DBO',
'Authorization' => 'ACL',
'Xml' => 'XMLParser'
);
/**
* Create an instance of a class based on a class identifier
*
* @param mixed Identifier or Identifier object - joomla.[.path].name
* @param object An optional KConfig object with configuration options
* @return object|false Return object on success, returns FALSE on failure
*/
public function instantiate($identifier, KConfig $config)
{
$name = ucfirst($identifier->package);
//Check to see of the type is an alias
if(array_key_exists($name, $this->_alias_map)) {
$name = $this->_alias_map[$name];
}
$instance = <API key>(array('JFactory', 'get'.$name), $config->toArray());
return $instance;
}
} |
<?php
namespace Magento\Framework\Exception\Test\Unit\State;
use \Magento\Framework\Exception\State\<API key>;
use Magento\Framework\Phrase;
class <API key> extends \PHPUnit\Framework\TestCase
{
/**
* @return void
*/
public function testConstructor()
{
$instanceClass = \Magento\Framework\Exception\State\<API key>::class;
$message = 'message %1 %2';
$params = [
'parameter1',
'parameter2',
];
$cause = new \Exception();
$stateException = new <API key>(new Phrase($message, $params), $cause);
$this->assertInstanceOf($instanceClass, $stateException);
}
} |
#!/usr/bin/perl -w
use strict;
use Test::Unit::TkTestRunner;
warn "$0 is deprecated, please use punit-tk\n"
unless $ENV{<API key>};
exit Test::Unit::TkTestRunner::main(@ARGV); |
package dbpedia.dataparsers.util
import scala.collection.mutable.ArrayBuffer
/**
* Used to collect parsing errors.
* Not thread-safe.
*/
private class ParsingErrors
{
private val errors = new ArrayBuffer[String]()
def add(msg : String) = errors += msg
override def toString = if(errors.isEmpty) "Error not logged" else "Errors:\n" + errors.mkString("\t- ", "\n\t- ", "")
} |
/**
* @author 130201108 Ata Niyazov 4. Sinif I. Ogretim <130201108@kocaeli.edu.tr>
* @version 1.0
* @since 1.0
*/
public class DiziIslemlerTest {
public static class DiziIslemler {
int[] diziOlustur(int length, int start, int end) {
if (start > end) {
int temp = start;
start = end;
end = temp;
}
int[] array = new int[length];
for (int i = 0; i < length; i++) {
array[i] = start + ((int) (Math.random() * (end - start))) + 1;
}
return array;
}
void diziGoster(int[] array) {
for (int index : array) {
System.out.print(index + " ");
}
System.out.println();
}
int[] matrisAktar(int[][] matrix) {
int[] array = new int[(matrix[0].length + matrix[1].length)];
int i0 = 0;
int i1 = 0;
int i = 0;
while (i0 < matrix[0].length && i1 < matrix[1].length) {
if (matrix[0][i0] < matrix[1][i1]) {
array[i++] = matrix[0][i0++];
} else {
array[i++] = matrix[1][i1++];
}
}
if (i0 < matrix[0].length) {
while (i0 < matrix[0].length) {
array[i++] = matrix[0][i0++];
}
}
if (i1 < matrix[1].length) {
while (i1 < matrix[1].length) {
array[i++] = matrix[1][i1++];
}
}
return array;
}
int buyukElemanBul(int[] array) {
int mostValue = 0;
for (int index : array) {
if (mostValue < index) {
mostValue = index;
}
}
return mostValue;
}
}
public static void main(String[] args) {
DiziIslemler islem = new DiziIslemler();
int[] array = islem.diziOlustur(10, 1, 100);
islem.diziGoster(array);
System.out.println(islem.buyukElemanBul(array));
System.out.println();
int[][] matrix = { { 1, 3, 5, 7, 9 }, { 2, 4, 6, 8, 10 } };
// System.out.println("0: " + matrix.length + "\n1: " + matrix[0].length + "\n1: " + matrix[1].length);
int[] arrayFromMatrix = islem.matrisAktar(matrix);
islem.diziGoster(arrayFromMatrix);
System.out.println(islem.buyukElemanBul(arrayFromMatrix));
}
} |
#include "quacrc32.h"
#include <zlib.h>
QuaCrc32::QuaCrc32()
{
reset();
}
quint32 QuaCrc32::calculate(const QByteArray &data)
{
return crc32( crc32(0L, Z_NULL, 0), (const Bytef*)data.data(), data.size() );
}
void QuaCrc32::reset()
{
checksum = crc32(0L, Z_NULL, 0);
}
void QuaCrc32::update(const QByteArray &buf)
{
checksum = crc32( checksum, (const Bytef*)buf.data(), buf.size() );
}
quint32 QuaCrc32::value()
{
return checksum;
} |
#include "cache.h"
#include "color.h"
#include "refs.h"
#include "commit.h"
#include "builtin.h"
#include "remote.h"
#include "parse-options.h"
#include "branch.h"
#include "diff.h"
#include "revision.h"
static const char * const <API key>[] = {
"git branch [options] [-r | -a] [--merged | --no-merged]",
"git branch [options] [-l] [-f] <branchname> [<start-point>]",
"git branch [options] [-r] (-d | -D) <branchname>",
"git branch [options] (-m | -M) [<oldbranch>] <newbranch>",
NULL
};
#define REF_LOCAL_BRANCH 0x01
#define REF_REMOTE_BRANCH 0x02
static const char *head;
static unsigned char head_sha1[20];
static int branch_use_color = -1;
static char branch_colors[][COLOR_MAXLEN] = {
GIT_COLOR_RESET,
GIT_COLOR_NORMAL, /* PLAIN */
GIT_COLOR_RED, /* REMOTE */
GIT_COLOR_NORMAL, /* LOCAL */
GIT_COLOR_GREEN, /* CURRENT */
};
enum color_branch {
BRANCH_COLOR_RESET = 0,
BRANCH_COLOR_PLAIN = 1,
BRANCH_COLOR_REMOTE = 2,
BRANCH_COLOR_LOCAL = 3,
<API key> = 4,
};
static enum merge_filter {
NO_FILTER = 0,
SHOW_NOT_MERGED,
SHOW_MERGED,
} merge_filter;
static unsigned char merge_filter_ref[20];
static int <API key>(const char *var, int ofs)
{
if (!strcasecmp(var+ofs, "plain"))
return BRANCH_COLOR_PLAIN;
if (!strcasecmp(var+ofs, "reset"))
return BRANCH_COLOR_RESET;
if (!strcasecmp(var+ofs, "remote"))
return BRANCH_COLOR_REMOTE;
if (!strcasecmp(var+ofs, "local"))
return BRANCH_COLOR_LOCAL;
if (!strcasecmp(var+ofs, "current"))
return <API key>;
die("bad config variable '%s'", var);
}
static int git_branch_config(const char *var, const char *value, void *cb)
{
if (!strcmp(var, "color.branch")) {
branch_use_color = <API key>(var, value, -1);
return 0;
}
if (!prefixcmp(var, "color.branch.")) {
int slot = <API key>(var, 13);
if (!value)
return <API key>(var);
color_parse(value, var, branch_colors[slot]);
return 0;
}
return <API key>(var, value, cb);
}
static const char *branch_get_color(enum color_branch ix)
{
if (branch_use_color > 0)
return branch_colors[ix];
return "";
}
static int delete_branches(int argc, const char **argv, int force, int kinds)
{
struct commit *rev, *head_rev = head_rev;
unsigned char sha1[20];
char *name = NULL;
const char *fmt, *remote;
int i;
int ret = 0;
struct strbuf bname = STRBUF_INIT;
switch (kinds) {
case REF_REMOTE_BRANCH:
fmt = "refs/remotes/%s";
remote = "remote ";
force = 1;
break;
case REF_LOCAL_BRANCH:
fmt = "refs/heads/%s";
remote = "";
break;
default:
die("cannot use -a with -d");
}
if (!force) {
head_rev = <API key>(head_sha1);
if (!head_rev)
die("Couldn't look up commit object for HEAD");
}
for (i = 0; i < argc; i++, strbuf_release(&bname)) {
strbuf_branchname(&bname, argv[i]);
if (kinds == REF_LOCAL_BRANCH && !strcmp(head, bname.buf)) {
error("Cannot delete the branch '%s' "
"which you are currently on.", bname.buf);
ret = 1;
continue;
}
free(name);
name = xstrdup(mkpath(fmt, bname.buf));
if (!resolve_ref(name, sha1, 1, NULL)) {
error("%sbranch '%s' not found.",
remote, bname.buf);
ret = 1;
continue;
}
rev = <API key>(sha1);
if (!rev) {
error("Couldn't look up commit object for '%s'", name);
ret = 1;
continue;
}
/* This checks whether the merge bases of branch and
* HEAD contains branch -- which means that the HEAD
* contains everything in both.
*/
if (!force &&
!in_merge_bases(rev, &head_rev, 1)) {
error("The branch '%s' is not an ancestor of "
"your current HEAD.\n"
"If you are sure you want to delete it, "
"run 'git branch -D %s'.", bname.buf, bname.buf);
ret = 1;
continue;
}
if (delete_ref(name, sha1, 0)) {
error("Error deleting %sbranch '%s'", remote,
bname.buf);
ret = 1;
} else {
struct strbuf buf = STRBUF_INIT;
printf("Deleted %sbranch %s (was %s).\n", remote,
bname.buf,
find_unique_abbrev(sha1, DEFAULT_ABBREV));
strbuf_addf(&buf, "branch.%s", bname.buf);
if (<API key>(buf.buf, NULL) < 0)
warning("Update of config-file failed");
strbuf_release(&buf);
}
}
free(name);
return(ret);
}
struct ref_item {
char *name;
char *dest;
unsigned int kind, len;
struct commit *commit;
};
struct ref_list {
struct rev_info revs;
int index, alloc, maxwidth;
struct ref_item *list;
struct commit_list *with_commit;
int kinds;
};
static char *resolve_symref(const char *src, const char *prefix)
{
unsigned char sha1[20];
int flag;
const char *dst, *cp;
dst = resolve_ref(src, sha1, 0, &flag);
if (!(dst && (flag & REF_ISSYMREF)))
return NULL;
if (prefix && (cp = skip_prefix(dst, prefix)))
dst = cp;
return xstrdup(dst);
}
static int append_ref(const char *refname, const unsigned char *sha1, int flags, void *cb_data)
{
struct ref_list *ref_list = (struct ref_list*)(cb_data);
struct ref_item *newitem;
struct commit *commit;
int kind, i;
const char *prefix, *orig_refname = refname;
static struct {
int kind;
const char *prefix;
int pfxlen;
} ref_kind[] = {
{ REF_LOCAL_BRANCH, "refs/heads/", 11 },
{ REF_REMOTE_BRANCH, "refs/remotes/", 13 },
};
/* Detect kind */
for (i = 0; i < ARRAY_SIZE(ref_kind); i++) {
prefix = ref_kind[i].prefix;
if (strncmp(refname, prefix, ref_kind[i].pfxlen))
continue;
kind = ref_kind[i].kind;
refname += ref_kind[i].pfxlen;
break;
}
if (ARRAY_SIZE(ref_kind) <= i)
return 0;
commit = <API key>(sha1, 1);
if (!commit)
return error("branch '%s' does not point at a commit", refname);
/* Filter with with_commit if specified */
if (!is_descendant_of(commit, ref_list->with_commit))
return 0;
/* Don't add types the caller doesn't want */
if ((kind & ref_list->kinds) == 0)
return 0;
if (merge_filter != NO_FILTER)
add_pending_object(&ref_list->revs,
(struct object *)commit, refname);
/* Resize buffer */
if (ref_list->index >= ref_list->alloc) {
ref_list->alloc = alloc_nr(ref_list->alloc);
ref_list->list = xrealloc(ref_list->list,
ref_list->alloc * sizeof(struct ref_item));
}
/* Record the new item */
newitem = &(ref_list->list[ref_list->index++]);
newitem->name = xstrdup(refname);
newitem->kind = kind;
newitem->commit = commit;
newitem->len = strlen(refname);
newitem->dest = resolve_symref(orig_refname, prefix);
/* adjust for "remotes/" */
if (newitem->kind == REF_REMOTE_BRANCH &&
ref_list->kinds != REF_REMOTE_BRANCH)
newitem->len += 8;
if (newitem->len > ref_list->maxwidth)
ref_list->maxwidth = newitem->len;
return 0;
}
static void free_ref_list(struct ref_list *ref_list)
{
int i;
for (i = 0; i < ref_list->index; i++) {
free(ref_list->list[i].name);
free(ref_list->list[i].dest);
}
free(ref_list->list);
}
static int ref_cmp(const void *r1, const void *r2)
{
struct ref_item *c1 = (struct ref_item *)(r1);
struct ref_item *c2 = (struct ref_item *)(r2);
if (c1->kind != c2->kind)
return c1->kind - c2->kind;
return strcmp(c1->name, c2->name);
}
static void fill_tracking_info(struct strbuf *stat, const char *branch_name,
int show_upstream_ref)
{
int ours, theirs;
struct branch *branch = branch_get(branch_name);
if (!stat_tracking_info(branch, &ours, &theirs)) {
if (branch && branch->merge && branch->merge[0]->dst &&
show_upstream_ref)
strbuf_addf(stat, "[%s] ",
<API key>(branch->merge[0]->dst, 0));
return;
}
strbuf_addch(stat, '[');
if (show_upstream_ref)
strbuf_addf(stat, "%s: ",
<API key>(branch->merge[0]->dst, 0));
if (!ours)
strbuf_addf(stat, "behind %d] ", theirs);
else if (!theirs)
strbuf_addf(stat, "ahead %d] ", ours);
else
strbuf_addf(stat, "ahead %d, behind %d] ", ours, theirs);
}
static int <API key>(struct commit *commit)
{
int is_merged;
if (merge_filter == NO_FILTER)
return 1;
is_merged = !!(commit->object.flags & UNINTERESTING);
return (is_merged == (merge_filter == SHOW_MERGED));
}
static void print_ref_item(struct ref_item *item, int maxwidth, int verbose,
int abbrev, int current, char *prefix)
{
char c;
int color;
struct commit *commit = item->commit;
struct strbuf out = STRBUF_INIT, name = STRBUF_INIT;
if (!<API key>(commit))
return;
switch (item->kind) {
case REF_LOCAL_BRANCH:
color = BRANCH_COLOR_LOCAL;
break;
case REF_REMOTE_BRANCH:
color = BRANCH_COLOR_REMOTE;
break;
default:
color = BRANCH_COLOR_PLAIN;
break;
}
c = ' ';
if (current) {
c = '*';
color = <API key>;
}
strbuf_addf(&name, "%s%s", prefix, item->name);
if (verbose)
strbuf_addf(&out, "%c %s%-*s%s", c, branch_get_color(color),
maxwidth, name.buf,
branch_get_color(BRANCH_COLOR_RESET));
else
strbuf_addf(&out, "%c %s%s%s", c, branch_get_color(color),
name.buf, branch_get_color(BRANCH_COLOR_RESET));
if (item->dest)
strbuf_addf(&out, " -> %s", item->dest);
else if (verbose) {
struct strbuf subject = STRBUF_INIT, stat = STRBUF_INIT;
const char *sub = " **** invalid ref ****";
commit = item->commit;
if (commit && !parse_commit(commit)) {
pretty_print_commit(CMIT_FMT_ONELINE, commit,
&subject, 0, NULL, NULL, 0, 0);
sub = subject.buf;
}
if (item->kind == REF_LOCAL_BRANCH)
fill_tracking_info(&stat, item->name, verbose > 1);
strbuf_addf(&out, " %s %s%s",
find_unique_abbrev(item->commit->object.sha1, abbrev),
stat.buf, sub);
strbuf_release(&stat);
strbuf_release(&subject);
}
printf("%s\n", out.buf);
strbuf_release(&name);
strbuf_release(&out);
}
static int calc_maxwidth(struct ref_list *refs)
{
int i, w = 0;
for (i = 0; i < refs->index; i++) {
if (!<API key>(refs->list[i].commit))
continue;
if (refs->list[i].len > w)
w = refs->list[i].len;
}
return w;
}
static void print_ref_list(int kinds, int detached, int verbose, int abbrev, struct commit_list *with_commit)
{
int i;
struct ref_list ref_list;
struct commit *head_commit = <API key>(head_sha1, 1);
memset(&ref_list, 0, sizeof(ref_list));
ref_list.kinds = kinds;
ref_list.with_commit = with_commit;
if (merge_filter != NO_FILTER)
init_revisions(&ref_list.revs, NULL);
for_each_ref(append_ref, &ref_list);
if (merge_filter != NO_FILTER) {
struct commit *filter;
filter = <API key>(merge_filter_ref, 0);
filter->object.flags |= UNINTERESTING;
add_pending_object(&ref_list.revs,
(struct object *) filter, "");
ref_list.revs.limited = 1;
<API key>(&ref_list.revs);
if (verbose)
ref_list.maxwidth = calc_maxwidth(&ref_list);
}
qsort(ref_list.list, ref_list.index, sizeof(struct ref_item), ref_cmp);
detached = (detached && (kinds & REF_LOCAL_BRANCH));
if (detached && head_commit &&
is_descendant_of(head_commit, with_commit)) {
struct ref_item item;
item.name = xstrdup("(no branch)");
item.len = strlen(item.name);
item.kind = REF_LOCAL_BRANCH;
item.dest = NULL;
item.commit = head_commit;
if (item.len > ref_list.maxwidth)
ref_list.maxwidth = item.len;
print_ref_item(&item, ref_list.maxwidth, verbose, abbrev, 1, "");
free(item.name);
}
for (i = 0; i < ref_list.index; i++) {
int current = !detached &&
(ref_list.list[i].kind == REF_LOCAL_BRANCH) &&
!strcmp(ref_list.list[i].name, head);
char *prefix = (kinds != REF_REMOTE_BRANCH &&
ref_list.list[i].kind == REF_REMOTE_BRANCH)
? "remotes/" : "";
print_ref_item(&ref_list.list[i], ref_list.maxwidth, verbose,
abbrev, current, prefix);
}
free_ref_list(&ref_list);
}
static void rename_branch(const char *oldname, const char *newname, int force)
{
struct strbuf oldref = STRBUF_INIT, newref = STRBUF_INIT, logmsg = STRBUF_INIT;
unsigned char sha1[20];
struct strbuf oldsection = STRBUF_INIT, newsection = STRBUF_INIT;
int recovery = 0;
if (!oldname)
die("cannot rename the current branch while not on any.");
if (<API key>(&oldref, oldname)) {
if (resolve_ref(oldref.buf, sha1, 1, NULL))
recovery = 1;
else
die("Invalid branch name: '%s'", oldname);
}
if (<API key>(&newref, newname))
die("Invalid branch name: '%s'", newname);
if (resolve_ref(newref.buf, sha1, 1, NULL) && !force)
die("A branch named '%s' already exists.", newref.buf + 11);
strbuf_addf(&logmsg, "Branch: renamed %s to %s",
oldref.buf, newref.buf);
if (rename_ref(oldref.buf, newref.buf, logmsg.buf))
die("Branch rename failed");
strbuf_release(&logmsg);
if (recovery)
warning("Renamed a misnamed branch '%s' away", oldref.buf + 11);
/* no need to pass logmsg here as HEAD didn't really move */
if (!strcmp(oldname, head) && create_symref("HEAD", newref.buf, NULL))
die("Branch renamed to %s, but HEAD is not updated!", newname);
strbuf_addf(&oldsection, "branch.%s", oldref.buf + 11);
strbuf_release(&oldref);
strbuf_addf(&newsection, "branch.%s", newref.buf + 11);
strbuf_release(&newref);
if (<API key>(oldsection.buf, newsection.buf) < 0)
die("Branch is renamed, but update of config-file failed");
strbuf_release(&oldsection);
strbuf_release(&newsection);
}
static int <API key>(const struct option *opt, const char *arg, int unset)
{
merge_filter = ((opt->long_name[0] == 'n')
? SHOW_NOT_MERGED
: SHOW_MERGED);
if (unset)
merge_filter = SHOW_NOT_MERGED; /* b/c for --no-merged */
if (!arg)
arg = "HEAD";
if (get_sha1(arg, merge_filter_ref))
die("malformed object name %s", arg);
return 0;
}
int cmd_branch(int argc, const char **argv, const char *prefix)
{
int delete = 0, rename = 0, force_create = 0;
int verbose = 0, abbrev = DEFAULT_ABBREV, detached = 0;
int reflog = 0;
enum branch_track track;
int kinds = REF_LOCAL_BRANCH;
struct commit_list *with_commit = NULL;
struct option options[] = {
OPT_GROUP("Generic options"),
OPT__VERBOSE(&verbose),
OPT_SET_INT('t', "track", &track, "set up tracking mode (see git-pull(1))",
<API key>),
OPT_BOOLEAN( 0 , "color", &branch_use_color, "use colored output"),
OPT_SET_INT('r', NULL, &kinds, "act on remote-tracking branches",
REF_REMOTE_BRANCH),
{
OPTION_CALLBACK, 0, "contains", &with_commit, "commit",
"print only branches that contain the commit",
<API key>,
<API key>, (intptr_t)"HEAD",
},
{
OPTION_CALLBACK, 0, "with", &with_commit, "commit",
"print only branches that contain the commit",
PARSE_OPT_HIDDEN | <API key>,
<API key>, (intptr_t) "HEAD",
},
OPT__ABBREV(&abbrev),
OPT_GROUP("Specific git-branch actions:"),
OPT_SET_INT('a', NULL, &kinds, "list both remote-tracking and local branches",
REF_REMOTE_BRANCH | REF_LOCAL_BRANCH),
OPT_BIT('d', NULL, &delete, "delete fully merged branch", 1),
OPT_BIT('D', NULL, &delete, "delete branch (even if not merged)", 2),
OPT_BIT('m', NULL, &rename, "move/rename a branch and its reflog", 1),
OPT_BIT('M', NULL, &rename, "move/rename a branch, even if target exists", 2),
OPT_BOOLEAN('l', NULL, &reflog, "create the branch's reflog"),
OPT_BOOLEAN('f', NULL, &force_create, "force creation (when already exists)"),
{
OPTION_CALLBACK, 0, "no-merged", &merge_filter_ref,
"commit", "print only not merged branches",
<API key> | PARSE_OPT_NONEG,
<API key>, (intptr_t) "HEAD",
},
{
OPTION_CALLBACK, 0, "merged", &merge_filter_ref,
"commit", "print only merged branches",
<API key> | PARSE_OPT_NONEG,
<API key>, (intptr_t) "HEAD",
},
OPT_END(),
};
git_config(git_branch_config, NULL);
if (branch_use_color == -1)
branch_use_color = <API key>;
track = git_branch_track;
head = resolve_ref("HEAD", head_sha1, 0, NULL);
if (!head)
die("Failed to resolve HEAD as a valid ref.");
head = xstrdup(head);
if (!strcmp(head, "HEAD")) {
detached = 1;
} else {
if (prefixcmp(head, "refs/heads/"))
die("HEAD not found below refs/heads!");
head += 11;
}
hashcpy(merge_filter_ref, head_sha1);
argc = parse_options(argc, argv, prefix, options, <API key>,
0);
if (!!delete + !!rename + !!force_create > 1)
usage_with_options(<API key>, options);
if (delete)
return delete_branches(argc, argv, delete > 1, kinds);
else if (argc == 0)
print_ref_list(kinds, detached, verbose, abbrev, with_commit);
else if (rename && (argc == 1))
rename_branch(head, argv[0], rename > 1);
else if (rename && (argc == 2))
rename_branch(argv[0], argv[1], rename > 1);
else if (argc <= 2)
create_branch(head, argv[0], (argc == 2) ? argv[1] : head,
force_create, reflog, track);
else
usage_with_options(<API key>, options);
return 0;
} |
#include "CreatureAI.h"
#include "Creature.h"
#include "DBCStores.h"
#include "Spell.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "CellImpl.h"
static_assert(<API key> <= 32, "Maximal 32 AI_EVENTs supported with EventAI");
CreatureAI::~CreatureAI()
{
}
void CreatureAI::EnterEvadeMode()
{
m_creature-><API key>();
}
void CreatureAI::AttackedBy(Unit* attacker)
{
if (!m_creature->getVictim())
{
AttackStart(attacker);
}
}
CanCastResult CreatureAI::CanCastSpell(Unit* pTarget, const SpellEntry* pSpell, bool isTriggered)
{
// If not triggered, we check
if (!isTriggered)
{
// State does not allow
if (m_creature->hasUnitState(<API key>))
{
return CAST_FAIL_STATE;
}
if (pSpell->PreventionType == <API key> && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_SILENCED))
{
return CAST_FAIL_STATE;
}
if (pSpell->PreventionType == <API key> && m_creature->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_PACIFIED))
{
return CAST_FAIL_STATE;
}
// Check for power (also done by Spell::CheckCast())
if (m_creature->GetPower((Powers)pSpell->powerType) < Spell::CalculatePowerCost(pSpell, m_creature))
{
return CAST_FAIL_POWER;
}
// Spell school check; for the mobs, only non-triggered spells are affected
if (pSpell->SchoolMask && !m_creature->IsSchoolAllowed(SpellSchoolMask(pSpell->SchoolMask)))
{
return CAST_FAIL_STATE;
}
}
if (!m_creature->IsWithinLOSInMap(pTarget))
{
return CAST_FAIL_NO_LOS;
}
if (const SpellRangeEntry* pSpellRange = sSpellRangeStore.LookupEntry(pSpell->rangeIndex))
{
if (pTarget != m_creature)
{
// pTarget is out of range of this spell (also done by Spell::CheckCast())
float fDistance = m_creature->GetCombatDistance(pTarget, pSpell->rangeIndex == <API key>);
if (fDistance > pSpellRange->maxRange)
{
return CAST_FAIL_TOO_FAR;
}
float fMinRange = pSpellRange->minRange;
if (fMinRange && fDistance < fMinRange)
{
return CAST_FAIL_TOO_CLOSE;
}
}
return CAST_OK;
}
else
{
return CAST_FAIL_OTHER;
}
}
CanCastResult CreatureAI::DoCastSpellIfCan(Unit* pTarget, uint32 uiSpell, uint32 uiCastFlags, ObjectGuid <API key>)
{
Unit* pCaster = m_creature;
if (uiCastFlags & <API key>)
{
pCaster = pTarget;
}
// Allowed to cast only if not casting (unless we interrupt ourself) or if spell is triggered
if (!pCaster-><API key>(false) || (uiCastFlags & (CAST_TRIGGERED | <API key>)))
{
if (const SpellEntry* pSpell = sSpellStore.LookupEntry(uiSpell))
{
// If cast flag <API key> is active, check if target already has aura on them
if (uiCastFlags & <API key>)
{
if (pTarget->HasAura(uiSpell))
{
return <API key>;
}
}
// Check if can not cast spell
if (!(uiCastFlags & (<API key> | CAST_FORCE_CAST)))
{
CanCastResult castResult = CanCastSpell(pTarget, pSpell, uiCastFlags & CAST_TRIGGERED);
if (castResult != CAST_OK)
{
return castResult;
}
}
// Interrupt any previous spell
if ((uiCastFlags & <API key>) && pCaster-><API key>(false))
{
pCaster-><API key>(false);
}
pCaster->CastSpell(pTarget, pSpell, uiCastFlags & CAST_TRIGGERED, NULL, NULL, <API key>);
return CAST_OK;
}
else
{
sLog.outErrorDb("DoCastSpellIfCan by creature entry %u attempt to cast spell %u but spell does not exist.", m_creature->GetEntry(), uiSpell);
return CAST_FAIL_OTHER;
}
}
else
{
return <API key>;
}
}
bool CreatureAI::<API key>()
{
return m_creature-><API key>();
}
void CreatureAI::<API key>(uint32 cmFlags)
{
if (!m_combatMovement)
{
m_creature->clearUnitState(<API key>);
}
m_combatMovement |= cmFlags;
}
void CreatureAI::<API key>(uint32 cmFlags)
{
m_combatMovement &= ~cmFlags;
if (!m_combatMovement)
{
m_creature->addUnitState(<API key>);
}
}
void CreatureAI::SetCombatMovement(bool enable, bool stopOrStartMovement /*=false*/)
{
if (stopOrStartMovement && m_creature->getVictim()) // Only change current movement while in combat
{
MotionMaster* creatureMotion = m_creature->GetMotionMaster();
creatureMotion->MovementExpired(false);
if (enable)
{
switch(creatureMotion-><API key>())
{
case CHASE_MOTION_TYPE:
case FOLLOW_MOTION_TYPE:
creatureMotion->Clear(false);
break;
default:
break;
}
creatureMotion->MoveChase(m_creature->getVictim(), m_attackDistance, m_creature->GetAngle(m_creature->getVictim()));
}
else if (creatureMotion-><API key>() == CHASE_MOTION_TYPE)
{
creatureMotion->Clear(false);
m_creature->StopMoving();
creatureMotion->MoveIdle();
}
}
}
void CreatureAI::<API key>(Unit* victim)
{
MotionMaster* creatureMotion = m_creature->GetMotionMaster();
<API key> mmgen = creatureMotion-><API key>();
creatureMotion->MovementExpired(false);
if (IsCombatMovement())
{
creatureMotion->MoveChase(victim, m_attackDistance, m_attackAngle);
}
// TODO - adapt this to only stop OOC-MMGens when MotionMaster rewrite is finished
else if (mmgen == <API key> || mmgen == RANDOM_MOTION_TYPE)
{
creatureMotion->MoveIdle();
m_creature->StopMoving();
}
}
// Event system
class AiDelayEventAround : public BasicEvent
{
public:
AiDelayEventAround(AIEventType eventType, ObjectGuid invokerGuid, Creature& owner, std::list<Creature*> const& receivers, uint32 miscValue) :
BasicEvent(),
m_eventType(eventType),
m_invokerGuid(invokerGuid),
m_owner(owner),
m_miscValue(miscValue)
{
// Pushing guids because in delay can happen some creature gets despawned => invalid pointer
m_receiverGuids.reserve(receivers.size());
for (std::list<Creature*>::const_iterator itr = receivers.begin(); itr != receivers.end(); ++itr)
{
m_receiverGuids.push_back((*itr)->GetObjectGuid());
}
}
bool Execute(uint64 /*e_time*/, uint32 /*p_time*/) override
{
Unit* pInvoker = m_owner.GetMap()->GetUnit(m_invokerGuid);
for (GuidVector::<API key> itr = m_receiverGuids.rbegin(); itr != m_receiverGuids.rend(); ++itr)
{
if (Creature* pReceiver = m_owner.GetMap()->GetAnyTypeCreature(*itr))
{
pReceiver->AI()->ReceiveAIEvent(m_eventType, &m_owner, pInvoker, m_miscValue);
// Special case for type 0 (call-assistance)
if (m_eventType == <API key> && pInvoker && pReceiver->CanAssistTo(&m_owner, pInvoker))
{
pReceiver->SetNoCallAssistance(true);
pReceiver->AI()->AttackStart(pInvoker);
}
}
}
m_receiverGuids.clear();
return true;
}
private:
AiDelayEventAround();
AIEventType m_eventType;
ObjectGuid m_invokerGuid;
Creature& m_owner;
uint32 m_miscValue;
GuidVector m_receiverGuids;
};
void CreatureAI::SendAIEventAround(AIEventType eventType, Unit* pInvoker, uint32 uiDelay, float fRadius, uint32 miscValue ) const
{
if (fRadius > 0)
{
std::list<Creature*> receiverList;
// Allow sending custom AI events to all units in range
if (eventType == <API key> || eventType == <API key>)
{
MaNGOS::<API key> u_check(m_creature, fRadius);
MaNGOS::<API key><MaNGOS::<API key>> searcher(receiverList, u_check);
Cell::VisitGridObjects(m_creature, searcher, fRadius);
}
else
{
// Use this check here to collect only assitable creatures in case of CALL_ASSISTANCE, else be less strict
MaNGOS::<API key> u_check(m_creature, eventType == <API key> ? pInvoker : NULL, fRadius);
MaNGOS::<API key><MaNGOS::<API key>> searcher(receiverList, u_check);
Cell::VisitGridObjects(m_creature, searcher, fRadius);
}
if (!receiverList.empty())
{
AiDelayEventAround* e = new AiDelayEventAround(eventType, pInvoker ? pInvoker->GetObjectGuid() : ObjectGuid(), *m_creature, receiverList, miscValue);
m_creature->m_Events.AddEvent(e, m_creature->m_Events.CalculateTime(uiDelay));
}
}
}
void CreatureAI::SendAIEvent(AIEventType eventType, Unit* pInvoker, Creature* pReceiver, uint32 miscValue ) const
{
MANGOS_ASSERT(pReceiver);
pReceiver->AI()->ReceiveAIEvent(eventType, m_creature, pInvoker, miscValue);
} |
import java.io.IOException;
import java.util.*;
public class Main
{
public static void main (String[] args) throws IOException
{
// Enter your code here
// Compile in terminal:> javac main.java
// Execute in terminal:> java main
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
int a = sc.nextInt();
int b = sc.nextInt();
if (a < b)
{
int aux = a;
a = b;
b = aux;
}
if (a % b == 0)
System.out.printf("Sao Multiplos\n");
else
System.out.printf("Nao sao Multiplos\n");
}
} |
<nav class="transparent z-depth-0">
<div class="nav-wrapper">
<div class="col s12">
<a href="#/" class="breadcrumb">Todos os Produtos</a>
</div>
</div>
</nav>
<div class="row">
<!-- Start Filters -->
<div class="col l3 m5 s12">
<div class="card z-depth-2">
<div class="card-content">
<h5>Filtre por: </h5>
<div class="filters_list"></div>
<div ng-repeat="filter in filters">
<ol class="list-filter-header">
<li> {{ filter.name }}:
<ol class="list-filter">
<li ng-repeat="f in filter.items">
<a id="{{ f.id_caller }}" ng-click="addFilter($parent.$index, $index)" href>{{ f.text }}</a>
</li>
</ol>
</li>
</ol>
</div>
</div>
</div>
</div>
<!-- End Filters -->
<!-- Start List Items -->
<div class="col l9 m7 s12">
<div class="row">
<!--<div infinite-scroll='product.nextPage()' <API key>='product.busy' <API key>='1'>-->
<div ng-repeat='item in items | filter: query'>
<div class="col s12 l4">
<div class="row">
<div class="col s12">
<div class="card z-depth-2">
<div class="card-image card-image-fixed">
<a href="#/show/343" class="waves-effect waves-ripple">
<img ng-src="{{ item.images[0] }}">
</a>
</div>
<div class="card-content">
<div class="card-title black-text" style="height: 2em;">
<p style="line-height: 25px !important;">{{ item.category.name | truncate: 35 }}</p>
</div>
<div class="star-rating mg-top mg-bot">
<span class="right"> {{ item.price | currency : "R$ "}} </span>
<span class="left" ng-bind-html="stars_html(item)"></span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div ng-show='product.busy'>
<div class="col s6 offset-s3 center">
<div class="preloader-wrapper big active">
<div class="spinner-layer spinner-blue-only">
<div class="circle-clipper left">
<div class="circle"></div>
</div>
<div class="gap-patch">
<div class="circle"></div>
</div>
<div class="circle-clipper right">
<div class="circle"></div>
</div>
</div>
</div>
</div>
</div>
<!--</div>-->
</div>
</div>
<!-- End List Items -->
</div> |
#include "config.h"
#if defined(LEAN_IEEE80211)
# error LEAN_IEEE80211: Should not be build
#endif
#include <string.h>
#include <gtk/gtk.h>
#include "epan/packet.h"
#include <epan/stat_cmd_args.h>
#include <epan/tap.h>
#include <epan/dissectors/packet-ieee80211.h>
#include "../stat_menu.h"
#include "ui/gtk/gui_stat_menu.h"
#include "ui/gtk/hostlist_table.h"
static int
<API key>(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip)
{
hostlist_table *hosts=(hostlist_table *)pit;
const wlan_hdr *whdr=vip;
/* Take two "add" passes per packet, adding for each direction, ensures that all
packets are counted properly (even if address is sending to itself)
XXX - this could probably be done more efficiently inside hostlist_table */
<API key>(hosts, &whdr->src, 0, TRUE, 1, pinfo->fd->pkt_len, SAT_WLAN, PT_NONE);
<API key>(hosts, &whdr->dst, 0, FALSE, 1, pinfo->fd->pkt_len, SAT_WLAN, PT_NONE);
return 1;
}
static void
<API key>(const char *opt_arg, void* userdata _U_)
{
const char *filter=NULL;
if(!strncmp(opt_arg,"hosts,wlan,",11)){
filter=opt_arg+11;
} else {
filter=NULL;
}
init_hostlist_table(TRUE, "WLAN", "wlan", filter, <API key>);
}
void
<API key>(GtkAction *action _U_, gpointer user_data _U_)
{
<API key>("hosts,wlan",NULL);
}
void
<API key>(void)
{
<API key>("hosts,wlan", <API key>,NULL);
<API key>(TRUE, "WLAN", "wlan", NULL /*filter*/, <API key>);
} |
/*
* Handle hardware traps and faults.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/context_tracking.h>
#include <linux/interrupt.h>
#include <linux/kallsyms.h>
#include <linux/spinlock.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/kdebug.h>
#include <linux/kgdb.h>
#include <linux/kernel.h>
#include <linux/export.h>
#include <linux/ptrace.h>
#include <linux/uprobes.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/kexec.h>
#include <linux/sched.h>
#include <linux/sched/task_stack.h>
#include <linux/timer.h>
#include <linux/init.h>
#include <linux/bug.h>
#include <linux/nmi.h>
#include <linux/mm.h>
#include <linux/smp.h>
#include <linux/io.h>
#include <linux/hardirq.h>
#include <linux/atomic.h>
#include <asm/stacktrace.h>
#include <asm/processor.h>
#include <asm/debugreg.h>
#include <asm/realmode.h>
#include <asm/text-patching.h>
#include <asm/ftrace.h>
#include <asm/traps.h>
#include <asm/desc.h>
#include <asm/fpu/internal.h>
#include <asm/cpu.h>
#include <asm/cpu_entry_area.h>
#include <asm/mce.h>
#include <asm/fixmap.h>
#include <asm/mach_traps.h>
#include <asm/alternative.h>
#include <asm/fpu/xstate.h>
#include <asm/vm86.h>
#include <asm/umip.h>
#include <asm/insn.h>
#include <asm/insn-eval.h>
#ifdef CONFIG_X86_64
#include <asm/x86_init.h>
#include <asm/proto.h>
#else
#include <asm/processor-flags.h>
#include <asm/setup.h>
#include <asm/proto.h>
#endif
DECLARE_BITMAP(system_vectors, NR_VECTORS);
static inline void <API key>(struct pt_regs *regs)
{
if (regs->flags & X86_EFLAGS_IF)
local_irq_enable();
}
static inline void <API key>(struct pt_regs *regs)
{
if (regs->flags & X86_EFLAGS_IF)
local_irq_disable();
}
__always_inline int is_valid_bugaddr(unsigned long addr)
{
if (addr < TASK_SIZE_MAX)
return 0;
/*
* We got #UD, if the text isn't readable we'd have gotten
* a different exception.
*/
return *(unsigned short *)addr == INSN_UD2;
}
static nokprobe_inline int
do_trap_no_signal(struct task_struct *tsk, int trapnr, const char *str,
struct pt_regs *regs, long error_code)
{
if (v8086_mode(regs)) {
/*
* Traps 0, 1, 3, 4, and 5 should be forwarded to vm86.
* On nmi (interrupt 2), do_trap should not be called.
*/
if (trapnr < X86_TRAP_UD) {
if (!handle_vm86_trap((struct kernel_vm86_regs *) regs,
error_code, trapnr))
return 0;
}
} else if (!user_mode(regs)) {
if (fixup_exception(regs, trapnr, error_code, 0))
return 0;
tsk->thread.error_code = error_code;
tsk->thread.trap_nr = trapnr;
die(str, regs, error_code);
}
/*
* We want error_code and trap_nr set for userspace faults and
* kernelspace faults which result in die(), but not
* kernelspace faults which are fixed up. die() gives the
* process no chance to handle the signal and notice the
* kernel fault information, so that won't result in polluting
* the information about previously queued, but not yet
* delivered, faults. See also <API key> below.
*/
tsk->thread.error_code = error_code;
tsk->thread.trap_nr = trapnr;
return -1;
}
static void show_signal(struct task_struct *tsk, int signr,
const char *type, const char *desc,
struct pt_regs *regs, long error_code)
{
if (<API key> && unhandled_signal(tsk, signr) &&
printk_ratelimit()) {
pr_info("%s[%d] %s%s ip:%lx sp:%lx error:%lx",
tsk->comm, task_pid_nr(tsk), type, desc,
regs->ip, regs->sp, error_code);
print_vma_addr(KERN_CONT " in ", regs->ip);
pr_cont("\n");
}
}
static void
do_trap(int trapnr, int signr, char *str, struct pt_regs *regs,
long error_code, int sicode, void __user *addr)
{
struct task_struct *tsk = current;
if (!do_trap_no_signal(tsk, trapnr, str, regs, error_code))
return;
show_signal(tsk, signr, "trap ", str, regs, error_code);
if (!sicode)
force_sig(signr);
else
force_sig_fault(signr, sicode, addr);
}
NOKPROBE_SYMBOL(do_trap);
static void do_error_trap(struct pt_regs *regs, long error_code, char *str,
unsigned long trapnr, int signr, int sicode, void __user *addr)
{
RCU_LOCKDEP_WARN(!rcu_is_watching(), "entry code didn't wake RCU");
if (notify_die(DIE_TRAP, str, regs, error_code, trapnr, signr) !=
NOTIFY_STOP) {
<API key>(regs);
do_trap(trapnr, signr, str, regs, error_code, sicode, addr);
<API key>(regs);
}
}
/*
* Posix requires to provide the address of the faulting instruction for
* SIGILL (#UD) and SIGFPE (#DE) in the si_addr member of siginfo_t.
*
* This address is usually regs->ip, but when an uprobe moved the code out
* of line then regs->ip points to the XOL code which would confuse
* anything which analyzes the fault address vs. the unmodified binary. If
* a trap happened in XOL code then uprobe maps regs->ip back to the
* original instruction address.
*/
static __always_inline void __user *error_get_trap_addr(struct pt_regs *regs)
{
return (void __user *)<API key>(regs);
}
DEFINE_IDTENTRY(exc_divide_error)
{
do_error_trap(regs, 0, "divide error", X86_TRAP_DE, SIGFPE,
FPE_INTDIV, error_get_trap_addr(regs));
}
DEFINE_IDTENTRY(exc_overflow)
{
do_error_trap(regs, 0, "overflow", X86_TRAP_OF, SIGSEGV, 0, NULL);
}
#ifdef CONFIG_X86_F00F_BUG
void handle_invalid_op(struct pt_regs *regs)
#else
static inline void handle_invalid_op(struct pt_regs *regs)
#endif
{
do_error_trap(regs, 0, "invalid opcode", X86_TRAP_UD, SIGILL,
ILL_ILLOPN, error_get_trap_addr(regs));
}
static noinstr bool handle_bug(struct pt_regs *regs)
{
bool handled = false;
if (!is_valid_bugaddr(regs->ip))
return handled;
/*
* All lies, just get the WARN/BUG out.
*/
<API key>();
/*
* Since we're emulating a CALL with exceptions, restore the interrupt
* state to what it was at the exception site.
*/
if (regs->flags & X86_EFLAGS_IF)
<API key>();
if (report_bug(regs->ip, regs) == BUG_TRAP_TYPE_WARN) {
regs->ip += LEN_UD2;
handled = true;
}
if (regs->flags & X86_EFLAGS_IF)
<API key>();
instrumentation_end();
return handled;
}
DEFINE_IDTENTRY_RAW(exc_invalid_op)
{
irqentry_state_t state;
/*
* We use UD2 as a short encoding for 'CALL __WARN', as such
* handle it before exception entry to avoid recursive WARN
* in case exception entry is the one triggering WARNs.
*/
if (!user_mode(regs) && handle_bug(regs))
return;
state = irqentry_enter(regs);
<API key>();
handle_invalid_op(regs);
instrumentation_end();
irqentry_exit(regs, state);
}
DEFINE_IDTENTRY(<API key>)
{
do_error_trap(regs, 0, "coprocessor segment overrun",
X86_TRAP_OLD_MF, SIGFPE, 0, NULL);
}
<API key>(exc_invalid_tss)
{
do_error_trap(regs, error_code, "invalid TSS", X86_TRAP_TS, SIGSEGV,
0, NULL);
}
<API key>(<API key>)
{
do_error_trap(regs, error_code, "segment not present", X86_TRAP_NP,
SIGBUS, 0, NULL);
}
<API key>(exc_stack_segment)
{
do_error_trap(regs, error_code, "stack segment", X86_TRAP_SS, SIGBUS,
0, NULL);
}
<API key>(exc_alignment_check)
{
char *str = "alignment check";
if (notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_AC, SIGBUS) == NOTIFY_STOP)
return;
if (!user_mode(regs))
die("Split lock detected\n", regs, error_code);
local_irq_enable();
if (<API key>(regs, error_code))
goto out;
do_trap(X86_TRAP_AC, SIGBUS, "alignment check", regs,
error_code, BUS_ADRALN, NULL);
out:
local_irq_disable();
}
#ifdef CONFIG_VMAP_STACK
__visible void __noreturn <API key>(const char *message,
struct pt_regs *regs,
unsigned long fault_address)
{
printk(KERN_EMERG "BUG: stack guard page was hit at %p (stack is %p..%p)\n",
(void *)fault_address, current->stack,
(char *)current->stack + THREAD_SIZE - 1);
die(message, regs, 0);
/* Be absolutely certain we don't return. */
panic("%s", message);
}
#endif
/*
* Runs on an IST stack for x86_64 and on a special task stack for x86_32.
*
* On x86_64, this is more or less a normal kernel entry. Notwithstanding the
* SDM's warnings about double faults being unrecoverable, returning works as
* expected. Presumably what the SDM actually means is that the CPU may get
* the register state wrong on entry, so returning could be a bad idea.
*
* Various CPU engineers have promised that double faults due to an IRET fault
* while the stack is read-only are, in fact, recoverable.
*
* On x86_32, this is entered through a task gate, and regs are synthesized
* from the TSS. Returning is, in principle, okay, but changes to regs will
* be lost. If, for some reason, we need to return to a context with modified
* regs, the shim code could be adjusted to synchronize the registers.
*
* The 32bit #DF shim provides CR2 already as an argument. On 64bit it needs
* to be read before doing anything else.
*/
DEFINE_IDTENTRY_DF(exc_double_fault)
{
static const char str[] = "double fault";
struct task_struct *tsk = current;
#ifdef CONFIG_VMAP_STACK
unsigned long address = read_cr2();
#endif
#ifdef CONFIG_X86_ESPFIX64
extern unsigned char <API key>[];
/*
* If IRET takes a non-IST fault on the espfix64 stack, then we
* end up promoting it to a doublefault. In that case, take
* advantage of the fact that we're not using the normal (TSS.sp0)
* stack right now. We can write a fake #GP(0) frame at TSS.sp0
* and then modify our own IRET frame so that, when we return,
* we land directly at the #GP(0) vector with the stack already
* set up according to its expectations.
*
* The net result is that our #GP handler will think that we
* entered from usermode with the bad user context.
*
* No need for nmi_enter() here because we don't use RCU.
*/
if (((long)regs->sp >> P4D_SHIFT) == ESPFIX_PGD_ENTRY &&
regs->cs == __KERNEL_CS &&
regs->ip == (unsigned long)<API key>)
{
struct pt_regs *gpregs = (struct pt_regs *)this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
unsigned long *p = (unsigned long *)regs->sp;
/*
* regs->sp points to the failing IRET frame on the
* ESPFIX64 stack. Copy it to the entry stack. This fills
* in gpregs->ss through gpregs->ip.
*
*/
gpregs->ip = p[0];
gpregs->cs = p[1];
gpregs->flags = p[2];
gpregs->sp = p[3];
gpregs->ss = p[4];
gpregs->orig_ax = 0; /* Missing (lost) #GP error code */
/*
* Adjust our frame so that we return straight to the #GP
* vector with the expected RSP value. This is safe because
* we won't enable interupts or schedule before we invoke
* general_protection, so nothing will clobber the stack
* frame we just set up.
*
* We will enter general_protection with kernel GSBASE,
* which is what the stub expects, given that the faulting
* RIP will be the IRET instruction.
*/
regs->ip = (unsigned long)<API key>;
regs->sp = (unsigned long)&gpregs->orig_ax;
return;
}
#endif
idtentry_enter_nmi(regs);
<API key>();
notify_die(DIE_TRAP, str, regs, error_code, X86_TRAP_DF, SIGSEGV);
tsk->thread.error_code = error_code;
tsk->thread.trap_nr = X86_TRAP_DF;
#ifdef CONFIG_VMAP_STACK
/*
* If we overflow the stack into a guard page, the CPU will fail
* to deliver #PF and will send #DF instead. Similarly, if we
* take any non-IST exception while too close to the bottom of
* the stack, the processor will get a page fault while
* delivering the exception and will generate a double fault.
*
* According to the SDM (footnote in 6.15 under "Interrupt 14 -
* Page-Fault Exception (#PF):
*
* Processors update CR2 whenever a page fault is detected. If a
* second page fault occurs while an earlier page fault is being
* delivered, the faulting linear address of the second fault will
* overwrite the contents of CR2 (replacing the previous
* address). These updates to CR2 occur even if the page fault
* results in a double fault or occurs during the delivery of a
* double fault.
*
* The logic below has a small possibility of incorrectly diagnosing
* some errors as stack overflows. For example, if the IDT or GDT
* gets corrupted such that #GP delivery fails due to a bad descriptor
* causing #GP and we hit this condition while CR2 coincidentally
* points to the stack guard page, we'll think we overflowed the
* stack. Given that we're going to panic one way or another
* if this happens, this isn't necessarily worth fixing.
*
* If necessary, we could improve the test by only diagnosing
* a stack overflow if the saved RSP points within 47 bytes of
* the bottom of the stack: if RSP == tsk_stack + 48 and we
* take an exception, the stack is already aligned and there
* will be enough room SS, RSP, RFLAGS, CS, RIP, and a
* possible error code, so a stack overflow would *not* double
* fault. With any less space left, exception delivery could
* fail, and, as a practical matter, we've overflowed the
* stack even if the actual trigger for the double fault was
* something else.
*/
if ((unsigned long)task_stack_page(tsk) - 1 - address < PAGE_SIZE) {
<API key>("kernel stack overflow (double-fault)",
regs, address);
}
#endif
pr_emerg("PANIC: double fault, error_code: 0x%lx\n", error_code);
die("double fault", regs, error_code);
panic("Machine halted.");
instrumentation_end();
}
DEFINE_IDTENTRY(exc_bounds)
{
if (notify_die(DIE_TRAP, "bounds", regs, 0,
X86_TRAP_BR, SIGSEGV) == NOTIFY_STOP)
return;
<API key>(regs);
if (!user_mode(regs))
die("bounds", regs, 0);
do_trap(X86_TRAP_BR, SIGSEGV, "bounds", regs, 0, 0, NULL);
<API key>(regs);
}
enum kernel_gp_hint {
GP_NO_HINT,
GP_NON_CANONICAL,
GP_CANONICAL
};
/*
* When an uncaught #GP occurs, try to determine the memory address accessed by
* the instruction and return that address to the caller. Also, try to figure
* out whether any part of the access to that address was non-canonical.
*/
static enum kernel_gp_hint <API key>(struct pt_regs *regs,
unsigned long *addr)
{
u8 insn_buf[MAX_INSN_SIZE];
struct insn insn;
if (<API key>(insn_buf, (void *)regs->ip,
MAX_INSN_SIZE))
return GP_NO_HINT;
kernel_insn_init(&insn, insn_buf, MAX_INSN_SIZE);
insn_get_modrm(&insn);
insn_get_sib(&insn);
*addr = (unsigned long)insn_get_addr_ref(&insn, regs);
if (*addr == -1UL)
return GP_NO_HINT;
#ifdef CONFIG_X86_64
/*
* Check that:
* - the operand is not in the kernel half
* - the last byte of the operand is not in the user canonical half
*/
if (*addr < ~__VIRTUAL_MASK &&
*addr + insn.opnd_bytes - 1 > __VIRTUAL_MASK)
return GP_NON_CANONICAL;
#endif
return GP_CANONICAL;
}
#define GPFSTR "general protection fault"
<API key>(<API key>)
{
char desc[sizeof(GPFSTR) + 50 + 2*sizeof(unsigned long) + 1] = GPFSTR;
enum kernel_gp_hint hint = GP_NO_HINT;
struct task_struct *tsk;
unsigned long gp_addr;
int ret;
<API key>(regs);
if (static_cpu_has(X86_FEATURE_UMIP)) {
if (user_mode(regs) && <API key>(regs))
goto exit;
}
if (v8086_mode(regs)) {
local_irq_enable();
handle_vm86_fault((struct kernel_vm86_regs *) regs, error_code);
local_irq_disable();
return;
}
tsk = current;
if (user_mode(regs)) {
tsk->thread.error_code = error_code;
tsk->thread.trap_nr = X86_TRAP_GP;
show_signal(tsk, SIGSEGV, "", desc, regs, error_code);
force_sig(SIGSEGV);
goto exit;
}
if (fixup_exception(regs, X86_TRAP_GP, error_code, 0))
goto exit;
tsk->thread.error_code = error_code;
tsk->thread.trap_nr = X86_TRAP_GP;
/*
* To be potentially processing a kprobe fault and to trust the result
* from kprobe_running(), we have to be non-preemptible.
*/
if (!preemptible() &&
kprobe_running() &&
<API key>(regs, X86_TRAP_GP))
goto exit;
ret = notify_die(DIE_GPF, desc, regs, error_code, X86_TRAP_GP, SIGSEGV);
if (ret == NOTIFY_STOP)
goto exit;
if (error_code)
snprintf(desc, sizeof(desc), "segment-related " GPFSTR);
else
hint = <API key>(regs, &gp_addr);
if (hint != GP_NO_HINT)
snprintf(desc, sizeof(desc), GPFSTR ", %s 0x%lx",
(hint == GP_NON_CANONICAL) ? "probably for non-canonical address"
: "maybe for address",
gp_addr);
/*
* KASAN is interested only in the non-canonical case, clear it
* otherwise.
*/
if (hint != GP_NON_CANONICAL)
gp_addr = 0;
die_addr(desc, regs, error_code, gp_addr);
exit:
<API key>(regs);
}
static bool do_int3(struct pt_regs *regs)
{
int res;
#ifdef <API key>
if (kgdb_ll_trap(DIE_INT3, "int3", regs, 0, X86_TRAP_BP,
SIGTRAP) == NOTIFY_STOP)
return true;
#endif /* <API key> */
#ifdef CONFIG_KPROBES
if (kprobe_int3_handler(regs))
return true;
#endif
res = notify_die(DIE_INT3, "int3", regs, 0, X86_TRAP_BP, SIGTRAP);
return res == NOTIFY_STOP;
}
static void do_int3_user(struct pt_regs *regs)
{
if (do_int3(regs))
return;
<API key>(regs);
do_trap(X86_TRAP_BP, SIGTRAP, "int3", regs, 0, 0, NULL);
<API key>(regs);
}
DEFINE_IDTENTRY_RAW(exc_int3)
{
/*
* poke_int3_handler() is completely self contained code; it does (and
* must) *NOT* call out to anything, lest it hits upon yet another
* INT3.
*/
if (poke_int3_handler(regs))
return;
/*
* <API key>() uses static_branch_{,un}likely()
* and therefore can trigger INT3, hence poke_int3_handler() must
* be done before. If the entry came from kernel mode, then use
* nmi_enter() because the INT3 could have been hit in any context
* including NMI.
*/
if (user_mode(regs)) {
<API key>(regs);
<API key>();
do_int3_user(regs);
instrumentation_end();
<API key>(regs);
} else {
bool irq_state = idtentry_enter_nmi(regs);
<API key>();
if (!do_int3(regs))
die("int3", regs, 0);
instrumentation_end();
idtentry_exit_nmi(regs, irq_state);
}
}
#ifdef CONFIG_X86_64
/*
* Help handler running on a per-cpu (IST or entry trampoline) stack
* to switch to the normal thread stack if the interrupted code was in
* user mode. The actual stack switch is done in entry_64.S
*/
asmlinkage __visible noinstr struct pt_regs *sync_regs(struct pt_regs *eregs)
{
struct pt_regs *regs = (struct pt_regs *)this_cpu_read(<API key>) - 1;
if (regs != eregs)
*regs = *eregs;
return regs;
}
#ifdef <API key>
asmlinkage __visible noinstr struct pt_regs *vc_switch_off_ist(struct pt_regs *regs)
{
unsigned long sp, *stack;
struct stack_info info;
struct pt_regs *regs_ret;
/*
* In the SYSCALL entry path the RSP value comes from user-space - don't
* trust it and switch to the current kernel stack
*/
if (regs->ip >= (unsigned long)entry_SYSCALL_64 &&
regs->ip < (unsigned long)<API key>) {
sp = this_cpu_read(<API key>);
goto sync;
}
/*
* From here on the RSP value is trusted. Now check whether entry
* happened from a safe stack. Not safe are the entry or unknown stacks,
* use the fall-back stack instead in this case.
*/
sp = regs->sp;
stack = (unsigned long *)sp;
if (!<API key>(stack, current, &info) || info.type == STACK_TYPE_ENTRY ||
info.type >= <API key>)
sp = <API key>(VC2);
sync:
/*
* Found a safe stack - switch to it as if the entry didn't happen via
* IST stack. The code below only copies pt_regs, the real switch happens
* in assembly code.
*/
sp = ALIGN_DOWN(sp, 8) - sizeof(*regs_ret);
regs_ret = (struct pt_regs *)sp;
*regs_ret = *regs;
return regs_ret;
}
#endif
struct bad_iret_stack {
void *error_entry_ret;
struct pt_regs regs;
};
asmlinkage __visible noinstr
struct bad_iret_stack *fixup_bad_iret(struct bad_iret_stack *s)
{
/*
* This is called from entry_64.S early in handling a fault
* caused by a bad iret to user mode. To handle the fault
* correctly, we want to move our stack frame to where it would
* be had we entered directly on the entry stack (rather than
* just below the IRET frame) and we want to pretend that the
* exception came from the IRET target.
*/
struct bad_iret_stack tmp, *new_stack =
(struct bad_iret_stack *)__this_cpu_read(cpu_tss_rw.x86_tss.sp0) - 1;
/* Copy the IRET target to the temporary storage. */
__memcpy(&tmp.regs.ip, (void *)s->regs.sp, 5*8);
/* Copy the remainder of the stack from the current stack. */
__memcpy(&tmp, s, offsetof(struct bad_iret_stack, regs.ip));
/* Update the entry stack */
__memcpy(new_stack, &tmp, sizeof(tmp));
BUG_ON(!user_mode(&new_stack->regs));
return new_stack;
}
#endif
static bool <API key>(struct pt_regs *regs)
{
/*
* We don't try for precision here. If we're anywhere in the region of
* code that can be single-stepped in the SYSENTER entry path, then
* assume that this is a useless single-step trap due to SYSENTER
* being invoked with TF set. (We don't know in advance exactly
* which instructions will be hit because BTF could plausibly
* be set.)
*/
#ifdef CONFIG_X86_32
return (regs->ip - (unsigned long)<API key>) <
(unsigned long)<API key> -
(unsigned long)<API key>;
#elif defined(<API key>)
return (regs->ip - (unsigned long)<API key>) <
(unsigned long)<API key> -
(unsigned long)<API key>;
#else
return false;
#endif
}
static __always_inline unsigned long <API key>(void)
{
unsigned long dr6;
/*
* The Intel SDM says:
*
* Certain debug exceptions may clear bits 0-3. The remaining
* contents of the DR6 register are never cleared by the
* processor. To avoid confusion in identifying debug
* exceptions, debug handlers should clear the register before
* returning to the interrupted task.
*
* Keep it simple: clear DR6 immediately.
*/
get_debugreg(dr6, 6);
set_debugreg(DR6_RESERVED, 6);
dr6 ^= DR6_RESERVED; /* Flip to positive polarity */
return dr6;
}
/*
* Our handling of the processor debug registers is non-trivial.
* We do not clear them on entry and exit from the kernel. Therefore
* it is possible to get a watchpoint trap here from inside the kernel.
* However, the code in ./ptrace.c has ensured that the user can
* only set watchpoints on userspace addresses. Therefore the in-kernel
* watchpoint trap can only occur in code which is reading/writing
* from user space. Such code must not hold kernel locks (since it
* can equally take a page fault), therefore it is safe to call
* force_sig_info even though that claims and releases locks.
*
* Code in ./signal.c ensures that the debug control register
* is restored before we deliver any signal, and therefore that
* user code runs with the correct debug control register even though
* we clear it here.
*
* Being careful here means that we don't have to be as careful in a
* lot of more complicated places (task switching can be a bit lazy
* about restoring all the debug state, and ptrace doesn't have to
* find every occurrence of the TF bit that could be saved away even
* by user code)
*
* May run on IST stack.
*/
static bool notify_debug(struct pt_regs *regs, unsigned long *dr6)
{
/*
* Notifiers will clear bits in @dr6 to indicate the event has been
* consumed - <API key>(), single_stop_cont().
*
* Notifiers will set bits in @virtual_dr6 to indicate the desire
* for signals - ptrace_triggered(), <API key>().
*/
if (notify_die(DIE_DEBUG, "debug", regs, (long)dr6, 0, SIGTRAP) == NOTIFY_STOP)
return true;
return false;
}
static __always_inline void exc_debug_kernel(struct pt_regs *regs,
unsigned long dr6)
{
/*
* Disable breakpoints during exception handling; recursive exceptions
* are exceedingly 'fun'.
*
* Since this function is NOKPROBE, and that also applies to
* HW_BREAKPOINT_X, we can't hit a breakpoint before this (XXX except a
* HW_BREAKPOINT_W on our stack)
*
* Entry text is excluded for HW_BP_X and cpu_entry_area, which
* includes the entry stack is excluded for everything.
*/
unsigned long dr7 = local_db_save();
bool irq_state = idtentry_enter_nmi(regs);
<API key>();
/*
* If something gets miswired and we end up here for a user mode
* #DB, we will malfunction.
*/
WARN_ON_ONCE(user_mode(regs));
if (test_thread_flag(TIF_BLOCKSTEP)) {
/*
* The SDM says "The processor clears the BTF flag when it
* generates a debug exception." but PTRACE_BLOCKSTEP requested
* it for userspace, but we just took a kernel #DB, so re-set
* BTF.
*/
unsigned long debugctl;
rdmsrl(<API key>, debugctl);
debugctl |= DEBUGCTLMSR_BTF;
wrmsrl(<API key>, debugctl);
}
/*
* Catch SYSENTER with TF set and clear DR_STEP. If this hit a
* watchpoint at the same time then that will still be handled.
*/
if ((dr6 & DR_STEP) && <API key>(regs))
dr6 &= ~DR_STEP;
if (<API key>(regs))
goto out;
/*
* The kernel doesn't use INT1
*/
if (!dr6)
goto out;
if (notify_debug(regs, &dr6))
goto out;
/*
* The kernel doesn't use TF single-step outside of:
*
* - Kprobes, consumed through <API key>()
* - KGDB, consumed through notify_debug()
*
* So if we get here with DR_STEP set, something is wonky.
*
* A known way to trigger this is through QEMU's GDB stub,
* which leaks #DB into the guest and causes IST recursion.
*/
if (WARN_ON_ONCE(dr6 & DR_STEP))
regs->flags &= ~X86_EFLAGS_TF;
out:
instrumentation_end();
idtentry_exit_nmi(regs, irq_state);
local_db_restore(dr7);
}
static __always_inline void exc_debug_user(struct pt_regs *regs,
unsigned long dr6)
{
bool icebp;
/*
* If something gets miswired and we end up here for a kernel mode
* #DB, we will malfunction.
*/
WARN_ON_ONCE(!user_mode(regs));
/*
* NB: We can't easily clear DR7 here because
* <API key>() can invoke ptrace, schedule, access
* user memory, etc. This means that a recursive #DB is possible. If
* this happens, that #DB will hit exc_debug_kernel() and clear DR7.
* Since we're not on the IST stack right now, everything will be
* fine.
*/
<API key>(regs);
<API key>();
/*
* Start the virtual/ptrace DR6 value with just the DR_STEP mask
* of the real DR6. ptrace_triggered() will set the DR_TRAPn bits.
*
* Userspace expects DR_STEP to be visible in ptrace_get_debugreg(6)
* even if it is not the result of PTRACE_SINGLESTEP.
*/
current->thread.virtual_dr6 = (dr6 & DR_STEP);
/*
* The SDM says "The processor clears the BTF flag when it
* generates a debug exception." Clear TIF_BLOCKSTEP to keep
* TIF_BLOCKSTEP in sync with the hardware BTF flag.
*/
clear_thread_flag(TIF_BLOCKSTEP);
/*
* If dr6 has no reason to give us about the origin of this trap,
* then it's very likely the result of an icebp/int01 trap.
* User wants a sigtrap for that.
*/
icebp = !dr6;
if (notify_debug(regs, &dr6))
goto out;
/* It's safe to allow irq's after DR6 has been saved */
local_irq_enable();
if (v8086_mode(regs)) {
handle_vm86_trap((struct kernel_vm86_regs *)regs, 0, X86_TRAP_DB);
goto out_irq;
}
/* Add the virtual_dr6 bits for signals. */
dr6 |= current->thread.virtual_dr6;
if (dr6 & (DR_STEP | DR_TRAP_BITS) || icebp)
send_sigtrap(regs, 0, get_si_code(dr6));
out_irq:
local_irq_disable();
out:
instrumentation_end();
<API key>(regs);
}
#ifdef CONFIG_X86_64
/* IST stack entry */
<API key>(exc_debug)
{
exc_debug_kernel(regs, <API key>());
}
/* User entry, runs on regular task stack */
<API key>(exc_debug)
{
exc_debug_user(regs, <API key>());
}
#else
/* 32 bit does not have separate entry points. */
DEFINE_IDTENTRY_RAW(exc_debug)
{
unsigned long dr6 = <API key>();
if (user_mode(regs))
exc_debug_user(regs, dr6);
else
exc_debug_kernel(regs, dr6);
}
#endif
/*
* Note that we play around with the 'TS' bit in an attempt to get
* the correct behaviour even in the presence of the asynchronous
* IRQ13 behaviour
*/
static void math_error(struct pt_regs *regs, int trapnr)
{
struct task_struct *task = current;
struct fpu *fpu = &task->thread.fpu;
int si_code;
char *str = (trapnr == X86_TRAP_MF) ? "fpu exception" :
"simd exception";
<API key>(regs);
if (!user_mode(regs)) {
if (fixup_exception(regs, trapnr, 0, 0))
goto exit;
task->thread.error_code = 0;
task->thread.trap_nr = trapnr;
if (notify_die(DIE_TRAP, str, regs, 0, trapnr,
SIGFPE) != NOTIFY_STOP)
die(str, regs, 0);
goto exit;
}
/*
* Save the info for the exception handler and clear the error.
*/
fpu__save(fpu);
task->thread.trap_nr = trapnr;
task->thread.error_code = 0;
si_code = fpu__exception_code(fpu, trapnr);
/* Retry when we get spurious exceptions: */
if (!si_code)
goto exit;
force_sig_fault(SIGFPE, si_code,
(void __user *)<API key>(regs));
exit:
<API key>(regs);
}
DEFINE_IDTENTRY(<API key>)
{
math_error(regs, X86_TRAP_MF);
}
DEFINE_IDTENTRY(<API key>)
{
if (IS_ENABLED(CONFIG_X86_INVD_BUG)) {
/* AMD 486 bug: INVD in CPL 0 raises #XF instead of #GP */
if (!static_cpu_has(X86_FEATURE_XMM)) {
<API key>(regs, 0);
return;
}
}
math_error(regs, X86_TRAP_XF);
}
DEFINE_IDTENTRY(<API key>)
{
/*
* This addresses a Pentium Pro Erratum:
*
* PROBLEM: If the APIC subsystem is configured in mixed mode with
* Virtual Wire mode implemented through the local APIC, an
* interrupt vector of 0Fh (Intel reserved encoding) may be
* generated by the local APIC (Int 15). This vector may be
* generated upon receipt of a spurious interrupt (an interrupt
* which is removed before the system receives the INTA sequence)
* instead of the programmed 8259 spurious interrupt vector.
*
* IMPLICATION: The spurious interrupt vector programmed in the
* 8259 is normally handled by an operating system's spurious
* interrupt handler. However, a vector of 0Fh is unknown to some
* operating systems, which would crash if this erratum occurred.
*
* In theory this could be limited to 32bit, but the handler is not
* hurting and who knows which other CPUs suffer from this.
*/
}
DEFINE_IDTENTRY(<API key>)
{
unsigned long cr0 = read_cr0();
#ifdef <API key>
if (!boot_cpu_has(X86_FEATURE_FPU) && (cr0 & X86_CR0_EM)) {
struct math_emu_info info = { };
<API key>(regs);
info.regs = regs;
math_emulate(&info);
<API key>(regs);
return;
}
#endif
/* This should not happen. */
if (WARN(cr0 & X86_CR0_TS, "CR0.TS was set")) {
/* Try to fix it up and carry on. */
write_cr0(cr0 & ~X86_CR0_TS);
} else {
/*
* Something terrible happened, and we're better off trying
* to kill the task than getting stuck in a never-ending
* loop of #NM faults.
*/
die("unexpected #NM exception", regs, 0);
}
}
#ifdef CONFIG_X86_32
DEFINE_IDTENTRY_SW(iret_error)
{
local_irq_enable();
if (notify_die(DIE_TRAP, "iret exception", regs, 0,
X86_TRAP_IRET, SIGILL) != NOTIFY_STOP) {
do_trap(X86_TRAP_IRET, SIGILL, "iret exception", regs, 0,
ILL_BADSTK, (void __user *)NULL);
}
local_irq_disable();
}
#endif
void __init trap_init(void)
{
/* Init cpu_entry_area before IST entries are set up */
<API key>();
/* Init GHCB memory pages when running as an SEV-ES guest */
<API key>();
idt_setup_traps();
/*
* Should be a barrier for any external CPU state:
*/
cpu_init();
idt_setup_ist_traps();
} |
#coding=utf-8
#!/usr/bin/env python
# A small script to analyze all the funds data
# Author :xin xin from "python"
import pandas as pd
import numpy as np
file='fund3.1.csv'
df=pd.read_csv(file)
print("head
print(len(df))
print(df.head())
print("fund_id to index
df=df.set_index(df['fund_id'])
print(df.head())
#remove NA row
print("remove NA row
df_no_NA=df.dropna()
print('dropna column',len(df_no_NA))
df_no_name=df_no_NA.drop(['fund_name','fund_id'],axis=1)
print(df_no_name.head())
#del the '%',then we can sort
print("del the '%',then we can sort
def clean_num_in_column(column):
return column.apply(drop_percent_sign)
def drop_percent_sign(state):
if state.endswith('%'):
return float(state.replace('%',''))
df_drop_percent=df_no_name.apply(clean_num_in_column)
print(df_drop_percent.head())
# get max item in each column ,check the max item info
print("get max item in each column ,check the max item info
def get_large_in_column(column):
return column.sort_values(ascending=False).iloc[0]
print(df_drop_percent.apply(get_large_in_column))
range=100
print("sort the top 100 funds by 'from_start'
print(df_drop_percent.sort_values(by=['from_start'],ascending=False).head(range))
fs_index=df_drop_percent.sort_values(by=['from_start'], ascending=False).head(range).index
#print(fs_index)
#sort the funds by 'three_year'
print("sort the top 100 funds by 'three_year'
print(df_drop_percent.sort_values(by=['three_year'],ascending=False).head(range))
y3_index=df_drop_percent.sort_values(by=['three_year'],ascending=False).head(range).index
#sort the funds by 'one_year'
print("sort the top 100 funds by 'one_year'
y1_index=df_drop_percent.sort_values(by=['one_year'],ascending=False).head(range).index
#sort the funds by 'six_month'
print("sort the top 100 funds by 'six_month'
m6_index=df_drop_percent.sort_values(by=['six_month'],ascending=False).head(range).index
#sort the funds by the 'three_month'
print("sort the top 100 funds by the 'three_month'
m3_index=df_drop_percent.sort_values(by=['three_month'],ascending=False).head(range).index
#sort the funds by 'one_month'
print("sort the top 100 funds by 'one_month'
m1_index=df_drop_percent.sort_values(by=['one_month'],ascending=False).head(range).index
fs_index_set=set(fs_index)
y3_index_set=set(y3_index)
y1_index_set=set(y1_index)
m6_index_set=set(m6_index)
m3_index_set=set(m3_index)
m1_index_set=set(m1_index)
#check the mix one during 6 columns
print("check the mix one during 6 columns
mix_6c=fs_index_set&y3_index_set&y1_index_set&m6_index_set&m3_index_set&m1_index_set
print('mix 6c:',mix_6c)
#check the mix one during 5 columns
print("check the mix one during 5 columns
mix_5c=y3_index_set&y1_index_set&m6_index_set&m3_index_set&m1_index_set
print('mix 5c:',mix_5c)
#check the mix one during 4 columns
print("check the mix one during 4 columns
mix_4c=y1_index_set&m6_index_set&m3_index_set&m1_index_set
print('mix 4c:',mix_4c)
#check the mix one during 3 columns
print("check the mix one during 3 columns
mix_3c=m6_index_set&m3_index_set&m1_index_set
print('mix 3c:',mix_3c)
#check the mix one during 2 columns
print("check the mix one during 2 columns
mix_2c=m3_index_set&m1_index_set
print('mix 2c:',mix_2c)
#check the mix one during 1 columns
print("check the mix one during 1 columns
mix_1c=m1_index_set
print('mix 1c:',mix_1c)
#check the detailed info aboout the mix_4c
print("check the detailed info aboout the mix_4c
df_drop_percent=df_drop_percent.drop(['from_start','three_year'],axis=1)
for each in mix_4c:
fund_id=df_drop_percent[df_drop_percent.index==each].sum(axis=1).index[0]
fund_total_rate=df_drop_percent[df_drop_percent.index==each].sum(axis=1).values[0]
print(fund_id,fund_total_rate)
# 5 c with fund_name
#df_no_NA = df_no_NA.sort_values(by=['fund_id'], ascending=True).head()
#a = pd.DataFrame(df_no_NA, index=mix_5c)
#print(a)
#print(Index)
#a = df_no_NA[(df_no_NA.BoolCol==3)&(df_no_NA.attr==22)].mix_5c.tolist()
#print(a)
#print(df_no_NA.head())
#print()
#print(df_no_NA.head(['fund_id'], mix_5c))
#for x in mix_5c:
# print(x)
# print(df_no_NA.at[x, "fund_id"])
print("output the complete info of mix_5c
#print(list(mix_5c))
#print(df_no_NA['fund_id'].isin(list(mix_5c)))
#print(df_no_NA.at(list(mix_5c)[0], 'fund_id'))
print("store mix to mongodb
import time
from pymongo import MongoClient
conn = MongoClient('mongodb://127.0.0.1:27017', 28017)#MongoClient()
db = conn.fund #fund
date = time.strftime('%Y-%m-%d',time.localtime(time.time()))
print(date)
chosen_fund_set = db.chosen_fund_set #fund_set
#fund_set = db[date] #'YYYY-MM-DD HH:MM'
row = {"date":date,
"mix6":str(mix_6c),
"mix5":str(mix_5c),
"mix4":str(mix_4c),
"mix3":str(mix_3c),
"mix2":str(mix_2c),
"mix1":str(mix_1c)}
chosen_fund_set.insert_one(row) |
package com.tutorialspoint.springframework.webmvcframework.mvcform;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
/**
* @author daniel
* Daniel-Dos
* daniel.dias.analistati@gmail.com
*/
@Controller
public class StudentController {
@RequestMapping(value = "/student", method = RequestMethod.GET)
public ModelAndView student() {
return new ModelAndView("student", "command", new Student());
}
@RequestMapping(value = "/addStudent", method = RequestMethod.POST)
public String addStudent(@ModelAttribute("SpringWeb") Student student, ModelMap model) {
model.addAttribute("name", student.getName());
model.addAttribute("age", student.getAge());
model.addAttribute("id", student.getId());
return "result";
}
} |
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/wait.h>
#include <linux/spi/spi.h>
#include <linux/interrupt.h>
#include <linux/sched.h>
#include <linux/spi/spidev.h>
#include <linux/module.h>
#include <linux/device.h>
#include <linux/platform_device.h>
#include <linux/dmaengine.h>
#include <linux/pch_dma.h>
/* Register offsets */
#define PCH_SPCR 0x00 /* SPI control register */
#define PCH_SPBRR 0x04 /* SPI baud rate register */
#define PCH_SPSR 0x08 /* SPI status register */
#define PCH_SPDWR 0x0C /* SPI write data register */
#define PCH_SPDRR 0x10 /* SPI read data register */
#define PCH_SSNXCR 0x18 /* SSN Expand Control Register */
#define PCH_SRST 0x1C /* SPI reset register */
#define PCH_ADDRESS_SIZE 0x20
#define PCH_SPSR_TFD 0x000007C0
#define PCH_SPSR_RFD 0x0000F800
#define PCH_READABLE(x) (((x) & PCH_SPSR_RFD)>>11)
#define PCH_WRITABLE(x) (((x) & PCH_SPSR_TFD)>>6)
#define PCH_RX_THOLD 7
#define PCH_RX_THOLD_MAX 15
#define PCH_TX_THOLD 2
#define PCH_MAX_BAUDRATE 5000000
#define PCH_MAX_FIFO_DEPTH 16
#define STATUS_RUNNING 1
#define STATUS_EXITING 2
#define PCH_SLEEP_TIME 10
#define SSN_LOW 0x02U
#define SSN_HIGH 0x03U
#define SSN_NO_CONTROL 0x00U
#define PCH_MAX_CS 0xFF
#define <API key> 0x8816
#define SPCR_SPE_BIT (1 << 0)
#define SPCR_MSTR_BIT (1 << 1)
#define SPCR_LSBF_BIT (1 << 4)
#define SPCR_CPHA_BIT (1 << 5)
#define SPCR_CPOL_BIT (1 << 6)
#define SPCR_TFIE_BIT (1 << 8)
#define SPCR_RFIE_BIT (1 << 9)
#define SPCR_FIE_BIT (1 << 10)
#define SPCR_ORIE_BIT (1 << 11)
#define SPCR_MDFIE_BIT (1 << 12)
#define SPCR_FICLR_BIT (1 << 24)
#define SPSR_TFI_BIT (1 << 0)
#define SPSR_RFI_BIT (1 << 1)
#define SPSR_FI_BIT (1 << 2)
#define SPSR_ORF_BIT (1 << 3)
#define SPBRR_SIZE_BIT (1 << 10)
#define PCH_ALL (SPCR_TFIE_BIT|SPCR_RFIE_BIT|SPCR_FIE_BIT|\
SPCR_ORIE_BIT|SPCR_MDFIE_BIT)
#define SPCR_RFIC_FIELD 20
#define SPCR_TFIC_FIELD 16
#define <API key> ((1 << 10) - 1)
#define MASK_RFIC_SPCR_BITS (0xf << SPCR_RFIC_FIELD)
#define MASK_TFIC_SPCR_BITS (0xf << SPCR_TFIC_FIELD)
#define PCH_CLOCK_HZ 50000000
#define PCH_MAX_SPBR 1023
/* Definition for ML7213/ML7223/ML7831 by LAPIS Semiconductor */
#define PCI_VENDOR_ID_ROHM 0x10DB
#define <API key> 0x802c
#define <API key> 0x800F
#define <API key> 0x8816
/*
* Set the number of SPI instance max
* Intel EG20T PCH : 1ch
* LAPIS Semiconductor ML7213 IOH : 2ch
* LAPIS Semiconductor ML7223 IOH : 1ch
* LAPIS Semiconductor ML7831 IOH : 1ch
*/
#define PCH_SPI_MAX_DEV 2
#define PCH_BUF_SIZE 4096
#define PCH_DMA_TRANS_SIZE 12
static int use_dma = 1;
struct pch_spi_dma_ctrl {
struct <API key> *desc_tx;
struct <API key> *desc_rx;
struct pch_dma_slave param_tx;
struct pch_dma_slave param_rx;
struct dma_chan *chan_tx;
struct dma_chan *chan_rx;
struct scatterlist *sg_tx_p;
struct scatterlist *sg_rx_p;
struct scatterlist sg_tx;
struct scatterlist sg_rx;
int nent;
void *tx_buf_virt;
void *rx_buf_virt;
dma_addr_t tx_buf_dma;
dma_addr_t rx_buf_dma;
};
/**
* struct pch_spi_data - Holds the SPI channel specific details
* @io_remap_addr: The remapped PCI base address
* @master: Pointer to the SPI master structure
* @work: Reference to work queue handler
* @wk: Workqueue for carrying out execution of the
* requests
* @wait: Wait queue for waking up upon receiving an
* interrupt.
* @transfer_complete: Status of SPI Transfer
* @<API key>: Status flag for message processing
* @lock: Lock for protecting this structure
* @queue: SPI Message queue
* @status: Status of the SPI driver
* @bpw_len: Length of data to be transferred in bits per
* word
* @transfer_active: Flag showing active transfer
* @tx_index: Transmit data count; for bookkeeping during
* transfer
* @rx_index: Receive data count; for bookkeeping during
* transfer
* @tx_buff: Buffer for data to be transmitted
* @rx_index: Buffer for Received data
* @n_curnt_chip: The chip number that this SPI driver currently
* operates on
* @current_chip: Reference to the current chip that this SPI
* driver currently operates on
* @current_msg: The current message that this SPI driver is
* handling
* @cur_trans: The current transfer that this SPI driver is
* handling
* @board_dat: Reference to the SPI device data structure
* @plat_dev: platform_device structure
* @ch: SPI channel number
* @irq_reg_sts: Status of IRQ registration
*/
struct pch_spi_data {
void __iomem *io_remap_addr;
unsigned long io_base_addr;
struct spi_master *master;
struct work_struct work;
struct workqueue_struct *wk;
wait_queue_head_t wait;
u8 transfer_complete;
u8 <API key>;
spinlock_t lock;
struct list_head queue;
u8 status;
u32 bpw_len;
u8 transfer_active;
u32 tx_index;
u32 rx_index;
u16 *pkt_tx_buff;
u16 *pkt_rx_buff;
u8 n_curnt_chip;
struct spi_device *current_chip;
struct spi_message *current_msg;
struct spi_transfer *cur_trans;
struct pch_spi_board_data *board_dat;
struct platform_device *plat_dev;
int ch;
struct pch_spi_dma_ctrl dma;
int use_dma;
u8 irq_reg_sts;
};
/**
* struct pch_spi_board_data - Holds the SPI device specific details
* @pdev: Pointer to the PCI device
* @suspend_sts: Status of suspend
* @num: The number of SPI device instance
*/
struct pch_spi_board_data {
struct pci_dev *pdev;
u8 suspend_sts;
int num;
};
struct pch_pd_dev_save {
int num;
struct platform_device *pd_save[PCH_SPI_MAX_DEV];
struct pch_spi_board_data *board_dat;
};
static struct pci_device_id pch_spi_pcidev_id[] = {
{ PCI_VDEVICE(INTEL, <API key>), 1, },
{ PCI_VDEVICE(ROHM, <API key>), 2, },
{ PCI_VDEVICE(ROHM, <API key>), 1, },
{ PCI_VDEVICE(ROHM, <API key>), 1, },
{ }
};
/**
* pch_spi_writereg() - Performs register writes
* @master: Pointer to struct spi_master.
* @idx: Register offset.
* @val: Value to be written to register.
*/
static inline void pch_spi_writereg(struct spi_master *master, int idx, u32 val)
{
struct pch_spi_data *data = <API key>(master);
iowrite32(val, (data->io_remap_addr + idx));
}
/**
* pch_spi_readreg() - Performs register reads
* @master: Pointer to struct spi_master.
* @idx: Register offset.
*/
static inline u32 pch_spi_readreg(struct spi_master *master, int idx)
{
struct pch_spi_data *data = <API key>(master);
return ioread32(data->io_remap_addr + idx);
}
static inline void pch_spi_setclr_reg(struct spi_master *master, int idx,
u32 set, u32 clr)
{
u32 tmp = pch_spi_readreg(master, idx);
tmp = (tmp & ~clr) | set;
pch_spi_writereg(master, idx, tmp);
}
static void <API key>(struct spi_master *master)
{
pch_spi_setclr_reg(master, PCH_SPCR, SPCR_MSTR_BIT, 0);
}
/**
* pch_spi_clear_fifo() - Clears the Transmit and Receive FIFOs
* @master: Pointer to struct spi_master.
*/
static void pch_spi_clear_fifo(struct spi_master *master)
{
pch_spi_setclr_reg(master, PCH_SPCR, SPCR_FICLR_BIT, 0);
pch_spi_setclr_reg(master, PCH_SPCR, 0, SPCR_FICLR_BIT);
}
static void pch_spi_handler_sub(struct pch_spi_data *data, u32 reg_spsr_val,
void __iomem *io_remap_addr)
{
u32 n_read, tx_index, rx_index, bpw_len;
u16 *pkt_rx_buffer, *pkt_tx_buff;
int read_cnt;
u32 reg_spcr_val;
void __iomem *spsr;
void __iomem *spdrr;
void __iomem *spdwr;
spsr = io_remap_addr + PCH_SPSR;
iowrite32(reg_spsr_val, spsr);
if (data->transfer_active) {
rx_index = data->rx_index;
tx_index = data->tx_index;
bpw_len = data->bpw_len;
pkt_rx_buffer = data->pkt_rx_buff;
pkt_tx_buff = data->pkt_tx_buff;
spdrr = io_remap_addr + PCH_SPDRR;
spdwr = io_remap_addr + PCH_SPDWR;
n_read = PCH_READABLE(reg_spsr_val);
for (read_cnt = 0; (read_cnt < n_read); read_cnt++) {
pkt_rx_buffer[rx_index++] = ioread32(spdrr);
if (tx_index < bpw_len)
iowrite32(pkt_tx_buff[tx_index++], spdwr);
}
/* disable RFI if not needed */
if ((bpw_len - rx_index) <= PCH_MAX_FIFO_DEPTH) {
reg_spcr_val = ioread32(io_remap_addr + PCH_SPCR);
reg_spcr_val &= ~SPCR_RFIE_BIT; /* disable RFI */
/* reset rx threshold */
reg_spcr_val &= ~MASK_RFIC_SPCR_BITS;
reg_spcr_val |= (PCH_RX_THOLD_MAX << SPCR_RFIC_FIELD);
iowrite32(reg_spcr_val, (io_remap_addr + PCH_SPCR));
}
/* update counts */
data->tx_index = tx_index;
data->rx_index = rx_index;
}
/* if transfer complete interrupt */
if (reg_spsr_val & SPSR_FI_BIT) {
if ((tx_index == bpw_len) && (rx_index == tx_index)) {
/* disable interrupts */
pch_spi_setclr_reg(data->master, PCH_SPCR, 0, PCH_ALL);
/* transfer is completed;
inform <API key> */
data->transfer_complete = true;
data->transfer_active = false;
wake_up(&data->wait);
} else {
dev_err(&data->master->dev,
"%s : Transfer is not completed", __func__);
}
}
}
/**
* pch_spi_handler() - Interrupt handler
* @irq: The interrupt number.
* @dev_id: Pointer to struct pch_spi_board_data.
*/
static irqreturn_t pch_spi_handler(int irq, void *dev_id)
{
u32 reg_spsr_val;
void __iomem *spsr;
void __iomem *io_remap_addr;
irqreturn_t ret = IRQ_NONE;
struct pch_spi_data *data = dev_id;
struct pch_spi_board_data *board_dat = data->board_dat;
if (board_dat->suspend_sts) {
dev_dbg(&board_dat->pdev->dev,
"%s returning due to suspend\n", __func__);
return IRQ_NONE;
}
io_remap_addr = data->io_remap_addr;
spsr = io_remap_addr + PCH_SPSR;
reg_spsr_val = ioread32(spsr);
if (reg_spsr_val & SPSR_ORF_BIT) {
dev_err(&board_dat->pdev->dev, "%s Over run error\n", __func__);
if (data->current_msg->complete != 0) {
data->transfer_complete = true;
data->current_msg->status = -EIO;
data->current_msg->complete(data->current_msg->context);
data-><API key> = false;
data->current_msg = NULL;
data->cur_trans = NULL;
}
}
if (data->use_dma)
return IRQ_NONE;
/* Check if the interrupt is for SPI device */
if (reg_spsr_val & (SPSR_FI_BIT | SPSR_RFI_BIT)) {
pch_spi_handler_sub(data, reg_spsr_val, io_remap_addr);
ret = IRQ_HANDLED;
}
dev_dbg(&board_dat->pdev->dev, "%s EXIT return value=%d\n",
__func__, ret);
return ret;
}
/**
* <API key>() - Sets SPBR field in SPBRR
* @master: Pointer to struct spi_master.
* @speed_hz: Baud rate.
*/
static void <API key>(struct spi_master *master, u32 speed_hz)
{
u32 n_spbr = PCH_CLOCK_HZ / (speed_hz * 2);
/* if baud rate is less than we can support limit it */
if (n_spbr > PCH_MAX_SPBR)
n_spbr = PCH_MAX_SPBR;
pch_spi_setclr_reg(master, PCH_SPBRR, n_spbr, <API key>);
}
/**
* <API key>() - Sets SIZE field in SPBRR
* @master: Pointer to struct spi_master.
* @bits_per_word: Bits per word for SPI transfer.
*/
static void <API key>(struct spi_master *master,
u8 bits_per_word)
{
if (bits_per_word == 8)
pch_spi_setclr_reg(master, PCH_SPBRR, 0, SPBRR_SIZE_BIT);
else
pch_spi_setclr_reg(master, PCH_SPBRR, SPBRR_SIZE_BIT, 0);
}
/**
* <API key>() - Configures the PCH SPI hardware for transfer
* @spi: Pointer to struct spi_device.
*/
static void <API key>(struct spi_device *spi)
{
u32 flags = 0;
dev_dbg(&spi->dev, "%s SPBRR content =%x setting baud rate=%d\n",
__func__, pch_spi_readreg(spi->master, PCH_SPBRR),
spi->max_speed_hz);
<API key>(spi->master, spi->max_speed_hz);
/* set bits per word */
<API key>(spi->master, spi->bits_per_word);
if (!(spi->mode & SPI_LSB_FIRST))
flags |= SPCR_LSBF_BIT;
if (spi->mode & SPI_CPOL)
flags |= SPCR_CPOL_BIT;
if (spi->mode & SPI_CPHA)
flags |= SPCR_CPHA_BIT;
pch_spi_setclr_reg(spi->master, PCH_SPCR, flags,
(SPCR_LSBF_BIT | SPCR_CPOL_BIT | SPCR_CPHA_BIT));
/* Clear the FIFO by toggling FICLR to 1 and back to 0 */
pch_spi_clear_fifo(spi->master);
}
/**
* pch_spi_reset() - Clears SPI registers
* @master: Pointer to struct spi_master.
*/
static void pch_spi_reset(struct spi_master *master)
{
/* write 1 to reset SPI */
pch_spi_writereg(master, PCH_SRST, 0x1);
/* clear reset */
pch_spi_writereg(master, PCH_SRST, 0x0);
}
static int pch_spi_setup(struct spi_device *pspi)
{
/* check bits per word */
if (pspi->bits_per_word == 0) {
pspi->bits_per_word = 8;
dev_dbg(&pspi->dev, "%s 8 bits per word\n", __func__);
}
if ((pspi->bits_per_word != 8) && (pspi->bits_per_word != 16)) {
dev_err(&pspi->dev, "%s Invalid bits per word\n", __func__);
return -EINVAL;
}
/* Check baud rate setting */
/* if baud rate of chip is greater than
max we can support,return error */
if ((pspi->max_speed_hz) > PCH_MAX_BAUDRATE)
pspi->max_speed_hz = PCH_MAX_BAUDRATE;
dev_dbg(&pspi->dev, "%s MODE = %x\n", __func__,
(pspi->mode) & (SPI_CPOL | SPI_CPHA));
return 0;
}
static int pch_spi_transfer(struct spi_device *pspi, struct spi_message *pmsg)
{
struct spi_transfer *transfer;
struct pch_spi_data *data = <API key>(pspi->master);
int retval;
unsigned long flags;
/* validate spi message and baud rate */
if (unlikely(list_empty(&pmsg->transfers) == 1)) {
dev_err(&pspi->dev, "%s list empty\n", __func__);
retval = -EINVAL;
goto err_out;
}
if (unlikely(pspi->max_speed_hz == 0)) {
dev_err(&pspi->dev, "%s pch_spi_tranfer maxspeed=%d\n",
__func__, pspi->max_speed_hz);
retval = -EINVAL;
goto err_out;
}
dev_dbg(&pspi->dev, "%s Transfer List not empty. "
"Transfer Speed is set.\n", __func__);
spin_lock_irqsave(&data->lock, flags);
/* validate Tx/Rx buffers and Transfer length */
list_for_each_entry(transfer, &pmsg->transfers, transfer_list) {
if (!transfer->tx_buf && !transfer->rx_buf) {
dev_err(&pspi->dev,
"%s Tx and Rx buffer NULL\n", __func__);
retval = -EINVAL;
goto err_return_spinlock;
}
if (!transfer->len) {
dev_err(&pspi->dev, "%s Transfer length invalid\n",
__func__);
retval = -EINVAL;
goto err_return_spinlock;
}
dev_dbg(&pspi->dev, "%s Tx/Rx buffer valid. Transfer length"
" valid\n", __func__);
/* if baud rate has been specified validate the same */
if (transfer->speed_hz > PCH_MAX_BAUDRATE)
transfer->speed_hz = PCH_MAX_BAUDRATE;
/* if bits per word has been specified validate the same */
if (transfer->bits_per_word) {
if ((transfer->bits_per_word != 8)
&& (transfer->bits_per_word != 16)) {
retval = -EINVAL;
dev_err(&pspi->dev,
"%s Invalid bits per word\n", __func__);
goto err_return_spinlock;
}
}
}
<API key>(&data->lock, flags);
/* We won't process any messages if we have been asked to terminate */
if (data->status == STATUS_EXITING) {
dev_err(&pspi->dev, "%s status = STATUS_EXITING.\n", __func__);
retval = -ESHUTDOWN;
goto err_out;
}
/* If suspended ,return -EINVAL */
if (data->board_dat->suspend_sts) {
dev_err(&pspi->dev, "%s suspend; returning EINVAL\n", __func__);
retval = -EINVAL;
goto err_out;
}
/* set status of message */
pmsg->actual_length = 0;
dev_dbg(&pspi->dev, "%s - pmsg->status =%d\n", __func__, pmsg->status);
pmsg->status = -EINPROGRESS;
spin_lock_irqsave(&data->lock, flags);
/* add message to queue */
list_add_tail(&pmsg->queue, &data->queue);
<API key>(&data->lock, flags);
dev_dbg(&pspi->dev, "%s - Invoked list_add_tail\n", __func__);
/* schedule work queue to run */
queue_work(data->wk, &data->work);
dev_dbg(&pspi->dev, "%s - Invoked queue work\n", __func__);
retval = 0;
err_out:
dev_dbg(&pspi->dev, "%s RETURN=%d\n", __func__, retval);
return retval;
err_return_spinlock:
dev_dbg(&pspi->dev, "%s RETURN=%d\n", __func__, retval);
<API key>(&data->lock, flags);
return retval;
}
static inline void pch_spi_select_chip(struct pch_spi_data *data,
struct spi_device *pspi)
{
if (data->current_chip != NULL) {
if (pspi->chip_select != data->n_curnt_chip) {
dev_dbg(&pspi->dev, "%s : different slave\n", __func__);
data->current_chip = NULL;
}
}
data->current_chip = pspi;
data->n_curnt_chip = data->current_chip->chip_select;
dev_dbg(&pspi->dev, "%s :Invoking <API key>\n", __func__);
<API key>(pspi);
}
static void pch_spi_set_tx(struct pch_spi_data *data, int *bpw)
{
int size;
u32 n_writes;
int j;
struct spi_message *pmsg;
const u8 *tx_buf;
const u16 *tx_sbuf;
/* set baud rate if needed */
if (data->cur_trans->speed_hz) {
dev_dbg(&data->master->dev, "%s:setting baud rate\n", __func__);
<API key>(data->master, data->cur_trans->speed_hz);
}
/* set bits per word if needed */
if (data->cur_trans->bits_per_word &&
(data->current_msg->spi->bits_per_word != data->cur_trans->bits_per_word)) {
dev_dbg(&data->master->dev, "%s:set bits per word\n", __func__);
<API key>(data->master,
data->cur_trans->bits_per_word);
*bpw = data->cur_trans->bits_per_word;
} else {
*bpw = data->current_msg->spi->bits_per_word;
}
/* reset Tx/Rx index */
data->tx_index = 0;
data->rx_index = 0;
data->bpw_len = data->cur_trans->len / (*bpw / 8);
/* find alloc size */
size = data->cur_trans->len * sizeof(*data->pkt_tx_buff);
/* allocate memory for pkt_tx_buff & pkt_rx_buffer */
data->pkt_tx_buff = kzalloc(size, GFP_KERNEL);
if (data->pkt_tx_buff != NULL) {
data->pkt_rx_buff = kzalloc(size, GFP_KERNEL);
if (!data->pkt_rx_buff)
kfree(data->pkt_tx_buff);
}
if (!data->pkt_rx_buff) {
/* flush queue and set status of all transfers to -ENOMEM */
dev_err(&data->master->dev, "%s :kzalloc failed\n", __func__);
list_for_each_entry(pmsg, data->queue.next, queue) {
pmsg->status = -ENOMEM;
if (pmsg->complete != 0)
pmsg->complete(pmsg->context);
/* delete from queue */
list_del_init(&pmsg->queue);
}
return;
}
/* copy Tx Data */
if (data->cur_trans->tx_buf != NULL) {
if (*bpw == 8) {
tx_buf = data->cur_trans->tx_buf;
for (j = 0; j < data->bpw_len; j++)
data->pkt_tx_buff[j] = *tx_buf++;
} else {
tx_sbuf = data->cur_trans->tx_buf;
for (j = 0; j < data->bpw_len; j++)
data->pkt_tx_buff[j] = *tx_sbuf++;
}
}
/* if len greater than PCH_MAX_FIFO_DEPTH, write 16,else len bytes */
n_writes = data->bpw_len;
if (n_writes > PCH_MAX_FIFO_DEPTH)
n_writes = PCH_MAX_FIFO_DEPTH;
dev_dbg(&data->master->dev, "\n%s:Pulling down SSN low - writing "
"0x2 to SSNXCR\n", __func__);
pch_spi_writereg(data->master, PCH_SSNXCR, SSN_LOW);
for (j = 0; j < n_writes; j++)
pch_spi_writereg(data->master, PCH_SPDWR, data->pkt_tx_buff[j]);
/* update tx_index */
data->tx_index = j;
/* reset transfer complete flag */
data->transfer_complete = false;
data->transfer_active = true;
}
static void <API key>(struct pch_spi_data *data)
{
struct spi_message *pmsg;
dev_dbg(&data->master->dev, "%s called\n", __func__);
/* Invoke complete callback
* [To the spi core..indicating end of transfer] */
data->current_msg->status = 0;
if (data->current_msg->complete != 0) {
dev_dbg(&data->master->dev,
"%s:Invoking callback of SPI core\n", __func__);
data->current_msg->complete(data->current_msg->context);
}
/* update status in global variable */
data-><API key> = false;
dev_dbg(&data->master->dev,
"%s:data-><API key> = false\n", __func__);
data->current_msg = NULL;
data->cur_trans = NULL;
/* check if we have items in list and not suspending
* return 1 if list empty */
if ((list_empty(&data->queue) == 0) &&
(!data->board_dat->suspend_sts) &&
(data->status != STATUS_EXITING)) {
/* We have some more work to do (either there is more tranint
* bpw;sfer requests in the current message or there are
*more messages)
*/
dev_dbg(&data->master->dev, "%s:Invoke queue_work\n", __func__);
queue_work(data->wk, &data->work);
} else if (data->board_dat->suspend_sts ||
data->status == STATUS_EXITING) {
dev_dbg(&data->master->dev,
"%s suspend/remove initiated, flushing queue\n",
__func__);
list_for_each_entry(pmsg, data->queue.next, queue) {
pmsg->status = -EIO;
if (pmsg->complete)
pmsg->complete(pmsg->context);
/* delete from queue */
list_del_init(&pmsg->queue);
}
}
}
static void pch_spi_set_ir(struct pch_spi_data *data)
{
/* enable interrupts, set threshold, enable SPI */
if ((data->bpw_len) > PCH_MAX_FIFO_DEPTH)
/* set receive threshold to PCH_RX_THOLD */
pch_spi_setclr_reg(data->master, PCH_SPCR,
PCH_RX_THOLD << SPCR_RFIC_FIELD |
SPCR_FIE_BIT | SPCR_RFIE_BIT |
SPCR_ORIE_BIT | SPCR_SPE_BIT,
MASK_RFIC_SPCR_BITS | PCH_ALL);
else
/* set receive threshold to maximum */
pch_spi_setclr_reg(data->master, PCH_SPCR,
PCH_RX_THOLD_MAX << SPCR_RFIC_FIELD |
SPCR_FIE_BIT | SPCR_ORIE_BIT |
SPCR_SPE_BIT,
MASK_RFIC_SPCR_BITS | PCH_ALL);
/* Wait until the transfer completes; go to sleep after
initiating the transfer. */
dev_dbg(&data->master->dev,
"%s:waiting for transfer to get over\n", __func__);
<API key>(data->wait, data->transfer_complete);
/* clear all interrupts */
pch_spi_writereg(data->master, PCH_SPSR,
pch_spi_readreg(data->master, PCH_SPSR));
/* Disable interrupts and SPI transfer */
pch_spi_setclr_reg(data->master, PCH_SPCR, 0, PCH_ALL | SPCR_SPE_BIT);
/* clear FIFO */
pch_spi_clear_fifo(data->master);
}
static void <API key>(struct pch_spi_data *data, int bpw)
{
int j;
u8 *rx_buf;
u16 *rx_sbuf;
/* copy Rx Data */
if (!data->cur_trans->rx_buf)
return;
if (bpw == 8) {
rx_buf = data->cur_trans->rx_buf;
for (j = 0; j < data->bpw_len; j++)
*rx_buf++ = data->pkt_rx_buff[j] & 0xFF;
} else {
rx_sbuf = data->cur_trans->rx_buf;
for (j = 0; j < data->bpw_len; j++)
*rx_sbuf++ = data->pkt_rx_buff[j];
}
}
static void <API key>(struct pch_spi_data *data, int bpw)
{
int j;
u8 *rx_buf;
u16 *rx_sbuf;
const u8 *rx_dma_buf;
const u16 *rx_dma_sbuf;
/* copy Rx Data */
if (!data->cur_trans->rx_buf)
return;
if (bpw == 8) {
rx_buf = data->cur_trans->rx_buf;
rx_dma_buf = data->dma.rx_buf_virt;
for (j = 0; j < data->bpw_len; j++)
*rx_buf++ = *rx_dma_buf++ & 0xFF;
} else {
rx_sbuf = data->cur_trans->rx_buf;
rx_dma_sbuf = data->dma.rx_buf_virt;
for (j = 0; j < data->bpw_len; j++)
*rx_sbuf++ = *rx_dma_sbuf++;
}
}
static int <API key>(struct pch_spi_data *data)
{
struct pch_spi_dma_ctrl *dma;
unsigned long flags;
int rtn;
dma = &data->dma;
spin_lock_irqsave(&data->lock, flags);
/* disable interrupts, SPI set enable */
pch_spi_setclr_reg(data->master, PCH_SPCR, SPCR_SPE_BIT, PCH_ALL);
<API key>(&data->lock, flags);
/* Wait until the transfer completes; go to sleep after
initiating the transfer. */
dev_dbg(&data->master->dev,
"%s:waiting for transfer to get over\n", __func__);
rtn = <API key>(data->wait,
data->transfer_complete,
msecs_to_jiffies(2 * HZ));
dma_sync_sg_for_cpu(&data->master->dev, dma->sg_rx_p, dma->nent,
DMA_FROM_DEVICE);
dma_sync_sg_for_cpu(&data->master->dev, dma->sg_tx_p, dma->nent,
DMA_FROM_DEVICE);
memset(data->dma.tx_buf_virt, 0, PAGE_SIZE);
async_tx_ack(dma->desc_rx);
async_tx_ack(dma->desc_tx);
kfree(dma->sg_tx_p);
kfree(dma->sg_rx_p);
spin_lock_irqsave(&data->lock, flags);
/* clear fifo threshold, disable interrupts, disable SPI transfer */
pch_spi_setclr_reg(data->master, PCH_SPCR, 0,
MASK_RFIC_SPCR_BITS | MASK_TFIC_SPCR_BITS | PCH_ALL |
SPCR_SPE_BIT);
/* clear all interrupts */
pch_spi_writereg(data->master, PCH_SPSR,
pch_spi_readreg(data->master, PCH_SPSR));
/* clear FIFO */
pch_spi_clear_fifo(data->master);
<API key>(&data->lock, flags);
return rtn;
}
static void pch_dma_rx_complete(void *arg)
{
struct pch_spi_data *data = arg;
/* transfer is completed;inform <API key> */
data->transfer_complete = true;
<API key>(&data->wait);
}
static bool pch_spi_filter(struct dma_chan *chan, void *slave)
{
struct pch_dma_slave *param = slave;
if ((chan->chan_id == param->chan_id) &&
(param->dma_dev == chan->device->dev)) {
chan->private = param;
return true;
} else {
return false;
}
}
static void pch_spi_request_dma(struct pch_spi_data *data, int bpw)
{
dma_cap_mask_t mask;
struct dma_chan *chan;
struct pci_dev *dma_dev;
struct pch_dma_slave *param;
struct pch_spi_dma_ctrl *dma;
unsigned int width;
if (bpw == 8)
width = <API key>;
else
width = <API key>;
dma = &data->dma;
dma_cap_zero(mask);
dma_cap_set(DMA_SLAVE, mask);
/* Get DMA's dev information */
dma_dev = <API key>(2, PCI_DEVFN(12, 0));
/* Set Tx DMA */
param = &dma->param_tx;
param->dma_dev = &dma_dev->dev;
param->chan_id = data->master->bus_num * 2; /* Tx = 0, 2 */
param->tx_reg = data->io_base_addr + PCH_SPDWR;
param->width = width;
chan = dma_request_channel(mask, pch_spi_filter, param);
if (!chan) {
dev_err(&data->master->dev,
"ERROR: dma_request_channel FAILS(Tx)\n");
data->use_dma = 0;
return;
}
dma->chan_tx = chan;
/* Set Rx DMA */
param = &dma->param_rx;
param->dma_dev = &dma_dev->dev;
param->chan_id = data->master->bus_num * 2 + 1; /* Rx = Tx + 1 */
param->rx_reg = data->io_base_addr + PCH_SPDRR;
param->width = width;
chan = dma_request_channel(mask, pch_spi_filter, param);
if (!chan) {
dev_err(&data->master->dev,
"ERROR: dma_request_channel FAILS(Rx)\n");
dma_release_channel(dma->chan_tx);
dma->chan_tx = NULL;
data->use_dma = 0;
return;
}
dma->chan_rx = chan;
}
static void pch_spi_release_dma(struct pch_spi_data *data)
{
struct pch_spi_dma_ctrl *dma;
dma = &data->dma;
if (dma->chan_tx) {
dma_release_channel(dma->chan_tx);
dma->chan_tx = NULL;
}
if (dma->chan_rx) {
dma_release_channel(dma->chan_rx);
dma->chan_rx = NULL;
}
return;
}
static void pch_spi_handle_dma(struct pch_spi_data *data, int *bpw)
{
const u8 *tx_buf;
const u16 *tx_sbuf;
u8 *tx_dma_buf;
u16 *tx_dma_sbuf;
struct scatterlist *sg;
struct <API key> *desc_tx;
struct <API key> *desc_rx;
int num;
int i;
int size;
int rem;
unsigned long flags;
struct pch_spi_dma_ctrl *dma;
dma = &data->dma;
/* set baud rate if needed */
if (data->cur_trans->speed_hz) {
dev_dbg(&data->master->dev, "%s:setting baud rate\n", __func__);
spin_lock_irqsave(&data->lock, flags);
<API key>(data->master, data->cur_trans->speed_hz);
<API key>(&data->lock, flags);
}
/* set bits per word if needed */
if (data->cur_trans->bits_per_word &&
(data->current_msg->spi->bits_per_word !=
data->cur_trans->bits_per_word)) {
dev_dbg(&data->master->dev, "%s:set bits per word\n", __func__);
spin_lock_irqsave(&data->lock, flags);
<API key>(data->master,
data->cur_trans->bits_per_word);
<API key>(&data->lock, flags);
*bpw = data->cur_trans->bits_per_word;
} else {
*bpw = data->current_msg->spi->bits_per_word;
}
data->bpw_len = data->cur_trans->len / (*bpw / 8);
/* copy Tx Data */
if (data->cur_trans->tx_buf != NULL) {
if (*bpw == 8) {
tx_buf = data->cur_trans->tx_buf;
tx_dma_buf = dma->tx_buf_virt;
for (i = 0; i < data->bpw_len; i++)
*tx_dma_buf++ = *tx_buf++;
} else {
tx_sbuf = data->cur_trans->tx_buf;
tx_dma_sbuf = dma->tx_buf_virt;
for (i = 0; i < data->bpw_len; i++)
*tx_dma_sbuf++ = *tx_sbuf++;
}
}
if (data->bpw_len > PCH_DMA_TRANS_SIZE) {
num = data->bpw_len / PCH_DMA_TRANS_SIZE + 1;
size = PCH_DMA_TRANS_SIZE;
rem = data->bpw_len % PCH_DMA_TRANS_SIZE;
} else {
num = 1;
size = data->bpw_len;
rem = data->bpw_len;
}
dev_dbg(&data->master->dev, "%s num=%d size=%d rem=%d\n",
__func__, num, size, rem);
spin_lock_irqsave(&data->lock, flags);
/* set receive fifo threshold and transmit fifo threshold */
pch_spi_setclr_reg(data->master, PCH_SPCR,
((size - 1) << SPCR_RFIC_FIELD) |
(PCH_TX_THOLD << SPCR_TFIC_FIELD),
MASK_RFIC_SPCR_BITS | MASK_TFIC_SPCR_BITS);
<API key>(&data->lock, flags);
dma->sg_rx_p = kzalloc(sizeof(struct scatterlist)*num, GFP_ATOMIC);
sg_init_table(dma->sg_rx_p, num); /* Initialize SG table */
/* offset, length setting */
sg = dma->sg_rx_p;
for (i = 0; i < num; i++, sg++) {
if (i == (num - 2)) {
sg->offset = size * i;
sg->offset = sg->offset * (*bpw / 8);
sg_set_page(sg, virt_to_page(dma->rx_buf_virt), rem,
sg->offset);
sg_dma_len(sg) = rem;
} else if (i == (num - 1)) {
sg->offset = size * (i - 1) + rem;
sg->offset = sg->offset * (*bpw / 8);
sg_set_page(sg, virt_to_page(dma->rx_buf_virt), size,
sg->offset);
sg_dma_len(sg) = size;
} else {
sg->offset = size * i;
sg->offset = sg->offset * (*bpw / 8);
sg_set_page(sg, virt_to_page(dma->rx_buf_virt), size,
sg->offset);
sg_dma_len(sg) = size;
}
sg_dma_address(sg) = dma->rx_buf_dma + sg->offset;
}
sg = dma->sg_rx_p;
desc_rx = <API key>(dma->chan_rx, sg,
num, DMA_DEV_TO_MEM,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc_rx) {
dev_err(&data->master->dev, "%s:<API key> Failed\n",
__func__);
return;
}
<API key>(&data->master->dev, sg, num, DMA_FROM_DEVICE);
desc_rx->callback = pch_dma_rx_complete;
desc_rx->callback_param = data;
dma->nent = num;
dma->desc_rx = desc_rx;
if (data->bpw_len > PCH_DMA_TRANS_SIZE) {
num = data->bpw_len / PCH_DMA_TRANS_SIZE;
size = PCH_DMA_TRANS_SIZE;
rem = 16;
} else {
num = 1;
size = data->bpw_len;
rem = data->bpw_len;
}
dma->sg_tx_p = kzalloc(sizeof(struct scatterlist)*num, GFP_ATOMIC);
sg_init_table(dma->sg_tx_p, num); /* Initialize SG table */
/* offset, length setting */
sg = dma->sg_tx_p;
for (i = 0; i < num; i++, sg++) {
if (i == 0) {
sg->offset = 0;
sg_set_page(sg, virt_to_page(dma->tx_buf_virt), rem,
sg->offset);
sg_dma_len(sg) = rem;
} else {
sg->offset = rem + size * (i - 1);
sg->offset = sg->offset * (*bpw / 8);
sg_set_page(sg, virt_to_page(dma->tx_buf_virt), size,
sg->offset);
sg_dma_len(sg) = size;
}
sg_dma_address(sg) = dma->tx_buf_dma + sg->offset;
}
sg = dma->sg_tx_p;
desc_tx = <API key>(dma->chan_tx,
sg, num, DMA_MEM_TO_DEV,
DMA_PREP_INTERRUPT | DMA_CTRL_ACK);
if (!desc_tx) {
dev_err(&data->master->dev, "%s:<API key> Failed\n",
__func__);
return;
}
<API key>(&data->master->dev, sg, num, DMA_TO_DEVICE);
desc_tx->callback = NULL;
desc_tx->callback_param = data;
dma->nent = num;
dma->desc_tx = desc_tx;
dev_dbg(&data->master->dev, "\n%s:Pulling down SSN low - writing "
"0x2 to SSNXCR\n", __func__);
spin_lock_irqsave(&data->lock, flags);
pch_spi_writereg(data->master, PCH_SSNXCR, SSN_LOW);
desc_rx->tx_submit(desc_rx);
desc_tx->tx_submit(desc_tx);
<API key>(&data->lock, flags);
/* reset transfer complete flag */
data->transfer_complete = false;
}
static void <API key>(struct work_struct *pwork)
{
struct spi_message *pmsg;
struct pch_spi_data *data;
int bpw;
data = container_of(pwork, struct pch_spi_data, work);
dev_dbg(&data->master->dev, "%s data initialized\n", __func__);
spin_lock(&data->lock);
/* check if suspend has been initiated;if yes flush queue */
if (data->board_dat->suspend_sts || (data->status == STATUS_EXITING)) {
dev_dbg(&data->master->dev, "%s suspend/remove initiated,"
"flushing queue\n", __func__);
list_for_each_entry(pmsg, data->queue.next, queue) {
pmsg->status = -EIO;
if (pmsg->complete != 0) {
spin_unlock(&data->lock);
pmsg->complete(pmsg->context);
spin_lock(&data->lock);
}
/* delete from queue */
list_del_init(&pmsg->queue);
}
spin_unlock(&data->lock);
return;
}
data-><API key> = true;
dev_dbg(&data->master->dev,
"%s Set data-><API key>= true\n", __func__);
/* Get the message from the queue and delete it from there. */
data->current_msg = list_entry(data->queue.next, struct spi_message,
queue);
list_del_init(&data->current_msg->queue);
data->current_msg->status = 0;
pch_spi_select_chip(data, data->current_msg->spi);
spin_unlock(&data->lock);
if (data->use_dma)
pch_spi_request_dma(data,
data->current_msg->spi->bits_per_word);
pch_spi_writereg(data->master, PCH_SSNXCR, SSN_NO_CONTROL);
do {
/* If we are already processing a message get the next
transfer structure from the message otherwise retrieve
the 1st transfer request from the message. */
spin_lock(&data->lock);
if (data->cur_trans == NULL) {
data->cur_trans =
list_entry(data->current_msg->transfers.next,
struct spi_transfer, transfer_list);
dev_dbg(&data->master->dev, "%s "
":Getting 1st transfer message\n", __func__);
} else {
data->cur_trans =
list_entry(data->cur_trans->transfer_list.next,
struct spi_transfer, transfer_list);
dev_dbg(&data->master->dev, "%s "
":Getting next transfer message\n", __func__);
}
spin_unlock(&data->lock);
if (data->use_dma) {
pch_spi_handle_dma(data, &bpw);
if (!<API key>(data))
goto out;
<API key>(data, bpw);
} else {
pch_spi_set_tx(data, &bpw);
pch_spi_set_ir(data);
<API key>(data, bpw);
kfree(data->pkt_rx_buff);
data->pkt_rx_buff = NULL;
kfree(data->pkt_tx_buff);
data->pkt_tx_buff = NULL;
}
/* increment message count */
data->current_msg->actual_length += data->cur_trans->len;
dev_dbg(&data->master->dev,
"%s:data->current_msg->actual_length=%d\n",
__func__, data->current_msg->actual_length);
/* check for delay */
if (data->cur_trans->delay_usecs) {
dev_dbg(&data->master->dev, "%s:"
"delay in usec=%d\n", __func__,
data->cur_trans->delay_usecs);
udelay(data->cur_trans->delay_usecs);
}
spin_lock(&data->lock);
/* No more transfer in this message. */
if ((data->cur_trans->transfer_list.next) ==
&(data->current_msg->transfers)) {
<API key>(data);
}
spin_unlock(&data->lock);
} while (data->cur_trans != NULL);
out:
pch_spi_writereg(data->master, PCH_SSNXCR, SSN_HIGH);
if (data->use_dma)
pch_spi_release_dma(data);
}
static void <API key>(struct pch_spi_board_data *board_dat,
struct pch_spi_data *data)
{
dev_dbg(&board_dat->pdev->dev, "%s ENTRY\n", __func__);
/* free workqueue */
if (data->wk != NULL) {
destroy_workqueue(data->wk);
data->wk = NULL;
dev_dbg(&board_dat->pdev->dev,
"%s destroy_workqueue invoked successfully\n",
__func__);
}
}
static int <API key>(struct pch_spi_board_data *board_dat,
struct pch_spi_data *data)
{
int retval = 0;
dev_dbg(&board_dat->pdev->dev, "%s ENTRY\n", __func__);
/* create workqueue */
data->wk = <API key>(KBUILD_MODNAME);
if (!data->wk) {
dev_err(&board_dat->pdev->dev,
"%s create_singlet hread_workqueue failed\n", __func__);
retval = -EBUSY;
goto err_return;
}
/* reset PCH SPI h/w */
pch_spi_reset(data->master);
dev_dbg(&board_dat->pdev->dev,
"%s pch_spi_reset invoked successfully\n", __func__);
dev_dbg(&board_dat->pdev->dev, "%s data->irq_reg_sts=true\n", __func__);
err_return:
if (retval != 0) {
dev_err(&board_dat->pdev->dev,
"%s FAIL:invoking <API key>\n", __func__);
<API key>(board_dat, data);
}
dev_dbg(&board_dat->pdev->dev, "%s Return=%d\n", __func__, retval);
return retval;
}
static void pch_free_dma_buf(struct pch_spi_board_data *board_dat,
struct pch_spi_data *data)
{
struct pch_spi_dma_ctrl *dma;
dma = &data->dma;
if (dma->tx_buf_dma)
dma_free_coherent(&board_dat->pdev->dev, PCH_BUF_SIZE,
dma->tx_buf_virt, dma->tx_buf_dma);
if (dma->rx_buf_dma)
dma_free_coherent(&board_dat->pdev->dev, PCH_BUF_SIZE,
dma->rx_buf_virt, dma->rx_buf_dma);
return;
}
static void pch_alloc_dma_buf(struct pch_spi_board_data *board_dat,
struct pch_spi_data *data)
{
struct pch_spi_dma_ctrl *dma;
dma = &data->dma;
/* Get Consistent memory for Tx DMA */
dma->tx_buf_virt = dma_alloc_coherent(&board_dat->pdev->dev,
PCH_BUF_SIZE, &dma->tx_buf_dma, GFP_KERNEL);
/* Get Consistent memory for Rx DMA */
dma->rx_buf_virt = dma_alloc_coherent(&board_dat->pdev->dev,
PCH_BUF_SIZE, &dma->rx_buf_dma, GFP_KERNEL);
}
static int __devinit pch_spi_pd_probe(struct platform_device *plat_dev)
{
int ret;
struct spi_master *master;
struct pch_spi_board_data *board_dat = dev_get_platdata(&plat_dev->dev);
struct pch_spi_data *data;
dev_dbg(&plat_dev->dev, "%s:debug\n", __func__);
master = spi_alloc_master(&board_dat->pdev->dev,
sizeof(struct pch_spi_data));
if (!master) {
dev_err(&plat_dev->dev, "spi_alloc_master[%d] failed.\n",
plat_dev->id);
return -ENOMEM;
}
data = <API key>(master);
data->master = master;
<API key>(plat_dev, data);
/* baseaddress + address offset) */
data->io_base_addr = pci_resource_start(board_dat->pdev, 1) +
PCH_ADDRESS_SIZE * plat_dev->id;
data->io_remap_addr = pci_iomap(board_dat->pdev, 1, 0) +
PCH_ADDRESS_SIZE * plat_dev->id;
if (!data->io_remap_addr) {
dev_err(&plat_dev->dev, "%s pci_iomap failed\n", __func__);
ret = -ENOMEM;
goto err_pci_iomap;
}
dev_dbg(&plat_dev->dev, "[ch%d] remap_addr=%p\n",
plat_dev->id, data->io_remap_addr);
/* initialize members of SPI master */
master->bus_num = -1;
master->num_chipselect = PCH_MAX_CS;
master->setup = pch_spi_setup;
master->transfer = pch_spi_transfer;
data->board_dat = board_dat;
data->plat_dev = plat_dev;
data->n_curnt_chip = 255;
data->status = STATUS_RUNNING;
data->ch = plat_dev->id;
data->use_dma = use_dma;
INIT_LIST_HEAD(&data->queue);
spin_lock_init(&data->lock);
INIT_WORK(&data->work, <API key>);
init_waitqueue_head(&data->wait);
ret = <API key>(board_dat, data);
if (ret) {
dev_err(&plat_dev->dev, "%s fail(retval=%d)\n", __func__, ret);
goto <API key>;
}
ret = request_irq(board_dat->pdev->irq, pch_spi_handler,
IRQF_SHARED, KBUILD_MODNAME, data);
if (ret) {
dev_err(&plat_dev->dev,
"%s request_irq failed\n", __func__);
goto err_request_irq;
}
data->irq_reg_sts = true;
<API key>(master);
ret = spi_register_master(master);
if (ret != 0) {
dev_err(&plat_dev->dev,
"%s spi_register_master FAILED\n", __func__);
goto <API key>;
}
if (use_dma) {
dev_info(&plat_dev->dev, "Use DMA for data transfers\n");
pch_alloc_dma_buf(board_dat, data);
}
return 0;
<API key>:
free_irq(board_dat->pdev->irq, board_dat);
err_request_irq:
<API key>(board_dat, data);
<API key>:
pci_iounmap(board_dat->pdev, data->io_remap_addr);
err_pci_iomap:
spi_master_put(master);
return ret;
}
static int __devexit pch_spi_pd_remove(struct platform_device *plat_dev)
{
struct pch_spi_board_data *board_dat = dev_get_platdata(&plat_dev->dev);
struct pch_spi_data *data = <API key>(plat_dev);
int count;
unsigned long flags;
dev_dbg(&plat_dev->dev, "%s:[ch%d] irq=%d\n",
__func__, plat_dev->id, board_dat->pdev->irq);
if (use_dma)
pch_free_dma_buf(board_dat, data);
/* check for any pending messages; no action is taken if the queue
* is still full; but at least we tried. Unload anyway */
count = 500;
spin_lock_irqsave(&data->lock, flags);
data->status = STATUS_EXITING;
while ((list_empty(&data->queue) == 0) && --count) {
dev_dbg(&board_dat->pdev->dev, "%s :queue not empty\n",
__func__);
<API key>(&data->lock, flags);
msleep(PCH_SLEEP_TIME);
spin_lock_irqsave(&data->lock, flags);
}
<API key>(&data->lock, flags);
<API key>(board_dat, data);
/* disable interrupts & free IRQ */
if (data->irq_reg_sts) {
/* disable interrupts */
pch_spi_setclr_reg(data->master, PCH_SPCR, 0, PCH_ALL);
data->irq_reg_sts = false;
free_irq(board_dat->pdev->irq, data);
}
pci_iounmap(board_dat->pdev, data->io_remap_addr);
<API key>(data->master);
spi_master_put(data->master);
<API key>(plat_dev, NULL);
return 0;
}
#ifdef CONFIG_PM
static int pch_spi_pd_suspend(struct platform_device *pd_dev,
pm_message_t state)
{
u8 count;
struct pch_spi_board_data *board_dat = dev_get_platdata(&pd_dev->dev);
struct pch_spi_data *data = <API key>(pd_dev);
dev_dbg(&pd_dev->dev, "%s ENTRY\n", __func__);
if (!board_dat) {
dev_err(&pd_dev->dev,
"%s pci_get_drvdata returned NULL\n", __func__);
return -EFAULT;
}
/* check if the current message is processed:
Only after thats done the transfer will be suspended */
count = 255;
while ((--count) > 0) {
if (!(data-><API key>))
break;
msleep(PCH_SLEEP_TIME);
}
/* Free IRQ */
if (data->irq_reg_sts) {
/* disable all interrupts */
pch_spi_setclr_reg(data->master, PCH_SPCR, 0, PCH_ALL);
pch_spi_reset(data->master);
free_irq(board_dat->pdev->irq, data);
data->irq_reg_sts = false;
dev_dbg(&pd_dev->dev,
"%s free_irq invoked successfully.\n", __func__);
}
return 0;
}
static int pch_spi_pd_resume(struct platform_device *pd_dev)
{
struct pch_spi_board_data *board_dat = dev_get_platdata(&pd_dev->dev);
struct pch_spi_data *data = <API key>(pd_dev);
int retval;
if (!board_dat) {
dev_err(&pd_dev->dev,
"%s pci_get_drvdata returned NULL\n", __func__);
return -EFAULT;
}
if (!data->irq_reg_sts) {
/* register IRQ */
retval = request_irq(board_dat->pdev->irq, pch_spi_handler,
IRQF_SHARED, KBUILD_MODNAME, data);
if (retval < 0) {
dev_err(&pd_dev->dev,
"%s request_irq failed\n", __func__);
return retval;
}
/* reset PCH SPI h/w */
pch_spi_reset(data->master);
<API key>(data->master);
data->irq_reg_sts = true;
}
return 0;
}
#else
#define pch_spi_pd_suspend NULL
#define pch_spi_pd_resume NULL
#endif
static struct platform_driver pch_spi_pd_driver = {
.driver = {
.name = "pch-spi",
.owner = THIS_MODULE,
},
.probe = pch_spi_pd_probe,
.remove = __devexit_p(pch_spi_pd_remove),
.suspend = pch_spi_pd_suspend,
.resume = pch_spi_pd_resume
};
static int __devinit pch_spi_probe(struct pci_dev *pdev,
const struct pci_device_id *id)
{
struct pch_spi_board_data *board_dat;
struct platform_device *pd_dev = NULL;
int retval;
int i;
struct pch_pd_dev_save *pd_dev_save;
pd_dev_save = kzalloc(sizeof(struct pch_pd_dev_save), GFP_KERNEL);
if (!pd_dev_save) {
dev_err(&pdev->dev, "%s Can't allocate pd_dev_sav\n", __func__);
return -ENOMEM;
}
board_dat = kzalloc(sizeof(struct pch_spi_board_data), GFP_KERNEL);
if (!board_dat) {
dev_err(&pdev->dev, "%s Can't allocate board_dat\n", __func__);
retval = -ENOMEM;
goto err_no_mem;
}
retval = pci_request_regions(pdev, KBUILD_MODNAME);
if (retval) {
dev_err(&pdev->dev, "%s request_region failed\n", __func__);
goto pci_request_regions;
}
board_dat->pdev = pdev;
board_dat->num = id->driver_data;
pd_dev_save->num = id->driver_data;
pd_dev_save->board_dat = board_dat;
retval = pci_enable_device(pdev);
if (retval) {
dev_err(&pdev->dev, "%s pci_enable_device failed\n", __func__);
goto pci_enable_device;
}
for (i = 0; i < board_dat->num; i++) {
pd_dev = <API key>("pch-spi", i);
if (!pd_dev) {
dev_err(&pdev->dev, "<API key> failed\n");
goto err_platform_device;
}
pd_dev_save->pd_save[i] = pd_dev;
pd_dev->dev.parent = &pdev->dev;
retval = <API key>(pd_dev, board_dat,
sizeof(*board_dat));
if (retval) {
dev_err(&pdev->dev,
"<API key> failed\n");
platform_device_put(pd_dev);
goto err_platform_device;
}
retval = platform_device_add(pd_dev);
if (retval) {
dev_err(&pdev->dev, "platform_device_add failed\n");
platform_device_put(pd_dev);
goto err_platform_device;
}
}
pci_set_drvdata(pdev, pd_dev_save);
return 0;
err_platform_device:
pci_disable_device(pdev);
pci_enable_device:
pci_release_regions(pdev);
pci_request_regions:
kfree(board_dat);
err_no_mem:
kfree(pd_dev_save);
return retval;
}
static void __devexit pch_spi_remove(struct pci_dev *pdev)
{
int i;
struct pch_pd_dev_save *pd_dev_save = pci_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s ENTRY:pdev=%p\n", __func__, pdev);
for (i = 0; i < pd_dev_save->num; i++)
<API key>(pd_dev_save->pd_save[i]);
pci_disable_device(pdev);
pci_release_regions(pdev);
kfree(pd_dev_save->board_dat);
kfree(pd_dev_save);
}
#ifdef CONFIG_PM
static int pch_spi_suspend(struct pci_dev *pdev, pm_message_t state)
{
int retval;
struct pch_pd_dev_save *pd_dev_save = pci_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s ENTRY\n", __func__);
pd_dev_save->board_dat->suspend_sts = true;
/* save config space */
retval = pci_save_state(pdev);
if (retval == 0) {
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_disable_device(pdev);
pci_set_power_state(pdev, PCI_D3hot);
} else {
dev_err(&pdev->dev, "%s pci_save_state failed\n", __func__);
}
return retval;
}
static int pch_spi_resume(struct pci_dev *pdev)
{
int retval;
struct pch_pd_dev_save *pd_dev_save = pci_get_drvdata(pdev);
dev_dbg(&pdev->dev, "%s ENTRY\n", __func__);
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
retval = pci_enable_device(pdev);
if (retval < 0) {
dev_err(&pdev->dev,
"%s pci_enable_device failed\n", __func__);
} else {
pci_enable_wake(pdev, PCI_D3hot, 0);
/* set suspend status to false */
pd_dev_save->board_dat->suspend_sts = false;
}
return retval;
}
#else
#define pch_spi_suspend NULL
#define pch_spi_resume NULL
#endif
static struct pci_driver pch_spi_pcidev = {
.name = "pch_spi",
.id_table = pch_spi_pcidev_id,
.probe = pch_spi_probe,
.remove = pch_spi_remove,
.suspend = pch_spi_suspend,
.resume = pch_spi_resume,
};
static int __init pch_spi_init(void)
{
int ret;
ret = <API key>(&pch_spi_pd_driver);
if (ret)
return ret;
ret = pci_register_driver(&pch_spi_pcidev);
if (ret)
return ret;
return 0;
}
module_init(pch_spi_init);
static void __exit pch_spi_exit(void)
{
<API key>(&pch_spi_pcidev);
<API key>(&pch_spi_pd_driver);
}
module_exit(pch_spi_exit);
module_param(use_dma, int, 0644);
MODULE_PARM_DESC(use_dma,
"to use DMA for data transfers pass 1 else 0; default 1");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Intel EG20T PCH/LAPIS Semiconductor ML7xxx IOH SPI Driver"); |
<?php
/**
* Elgg Message board: add message action
*
* @package ElggMessageBoard
*/
$message_content = get_input('comentario');
$owner_guid = get_input("foto");
$owner = get_entity($owner_guid);
$user = <API key>();
if ($owner && !empty($message_content)) {
$result = comentario_foto_add($user, $owner, $message_content, ACCESS_PUBLIC);
if ($result) {
$options = array(
'annotation_name' => 'comentario_foto',
'guid' => $owner_guid,
'wheres' => " n_table.entity_guid=$owner_guid",
'reverse_order_by' => true,
'limit' => 1,
);
$mensaje = "";
if ($user->guid != $owner->guid) {
if ($owner->type == "group") {
if ($owner->subtype = "grupo_investigacion") {
$options_integrantes = array(
'relationship' => 'es_miembro_de',
'relationship_guid' => $owner->guid,
'<API key>' => true);
$entities = <API key>($options_integrantes);
foreach ($entities as $entity) {
if ($entity->guid != $user->guid) {
$site_url = elgg_get_site_url();
$urlUser = "<a href='{$site_url}profile/{$user->username}'>{$user->name}</a>";
$urlGrupo = "<a href='{$site_url}grupo_investigacion/ver/{$owner->guid}'>{$owner->name}</a>";
$urlResult = "{$site_url}live_notifications/{$result}";
$mensaje = "<div id='item-notification' name='{$urlResult}' style='z-index:100'>{$urlUser} ha publicado en el muro del grupo {$owner->name}: {$message_content}</div>";
<API key>($entity->guid, $user->guid, "post", $result, $mensaje);
}
}
}
} else {
$site_url = elgg_get_site_url();
$urlResult = "{$site_url}live_notifications/{$result}";
$urlUser = "<a href='{$site_url}profile/{$user->username}'>{$user->name}</a>";
$mensaje = "<div id='item-notification' name='{$urlResult}'>{$urlUser} ha publicado tú muro: {$message_content}</div>";
<API key>($owner->guid, $user->guid, "post", $result, $mensaje);
}
}
$output = <API key>($options, false);
echo $output;
} else {
echo "error";
}
} |
#include "../include/config.h"
#include "../include/comments.h"
#include "../include/common.h"
#include "../include/statusdata.h"
#include "../include/downtime.h"
#include "../include/macros.h"
#include "../include/icinga.h"
#include "../include/broker.h"
#include "../include/perfdata.h"
/*#define DEBUG_CHECKS*/
/*#define DEBUG_HOST_CHECKS 1*/
#ifdef EMBEDDEDPERL
#include "../include/epn_icinga.h"
#endif
#ifdef USE_EVENT_BROKER
#include "../include/neberrors.h"
#endif
extern int sigshutdown;
extern int sigrestart;
extern char *temp_file;
extern char *temp_path;
extern char *check_result_path;
extern int interval_length;
extern int <API key>;
extern int log_initial_states;
extern int log_passive_checks;
extern int log_host_retries;
extern int <API key>;
extern int host_check_timeout;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern unsigned long <API key>;
extern unsigned long <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int execute_host_checks;
extern int <API key>;
extern int obsess_over_hosts;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern int <API key>;
extern time_t last_program_stop;
extern time_t program_start;
extern time_t event_start;
extern timed_event *event_list_low;
extern timed_event *event_list_low_tail;
extern host *host_list;
extern service *service_list;
extern servicedependency *<API key>;
extern hostdependency *hostdependency_list;
extern unsigned long next_event_id;
extern unsigned long next_problem_id;
extern check_result check_result_info;
extern check_result *check_result_list;
extern pthread_t worker_threads[<API key>];
extern unsigned long max_debug_file_size;
#ifdef EMBEDDEDPERL
extern int use_embedded_perl;
#endif
int dummy; /* reduce compiler warnings */
/* extract check result */
static void <API key>(FILE *fp, dbuf *checkresult_dbuf) {
char output_buffer[MAX_INPUT_BUFFER] = "";
char *temp_buffer;
/* initialize buffer */
strcpy(output_buffer, "");
/* get all lines of plugin output - escape newlines */
while (fgets(output_buffer, sizeof(output_buffer) - 1, fp)) {
temp_buffer = escape_newlines(output_buffer);
dbuf_strcat(checkresult_dbuf, temp_buffer);
my_free(temp_buffer);
}
}
/* convert a command line to an array of arguments, suitable for exec* functions */
static int parse_command_line(char *cmd, char *argv[MAX_CMD_ARGS]) {
unsigned int argc = 0;
char *parsed_cmd;
/* Skip initial white-space characters. */
for (parsed_cmd = cmd; isspace(*cmd); ++cmd)
;
/* Parse command line. */
while (*cmd && (argc < MAX_CMD_ARGS - 1)) {
argv[argc++] = parsed_cmd;
switch (*cmd) {
case '\'':
while ((*cmd) && (*cmd != '\''))
*(parsed_cmd++) = *(cmd++);
if (*cmd)
++cmd;
break;
case '"':
while ((*cmd) && (*cmd != '"')) {
if ((*cmd == '\\') && cmd[1] && strchr("\"\\\n", cmd[1]))
++cmd;
*(parsed_cmd++) = *(cmd++);
}
if (*cmd)
++cmd;
break;
default:
while ((*cmd) && !isspace(*cmd)) {
if ((*cmd == '\\') && cmd[1])
++cmd;
*(parsed_cmd++) = *(cmd++);
}
}
while (isspace(*cmd))
++cmd;
if (argc >= MAX_CMD_ARGS - 1) {
logit(<API key>, TRUE, "overlimit args for command %s\n", argv[0]);
_exit(STATE_UNKNOWN);
} else
*(parsed_cmd++) = '\0';
}
argv[argc] = NULL;
return OK;
}
/* run a check */
static int run_check(char *processed_command, dbuf *checkresult_dbuf) {
char *argv[MAX_CMD_ARGS];
FILE *fp;
pid_t pid;
int pipefds[2];
int retval;
/* check for check execution method (shell or execvp) */
if (!has_shell_metachars(processed_command)) {
if (pipe(pipefds) < 0) {
logit(<API key>, TRUE, "error creating pipe: %s\n", strerror(errno));
_exit(STATE_UNKNOWN);
}
if ((pid = fork()) < 0) {
logit(<API key>, TRUE, "fork error\n");
_exit(STATE_UNKNOWN);
} else if (!pid) {
/* child replaces stdout/stderr with output of the pipe */
if ((dup2(pipefds[1], STDOUT_FILENO) < 0) || (dup2(pipefds[1], STDERR_FILENO) < 0)) {
logit(<API key>, TRUE, "dup2 error\n");
_exit(STATE_UNKNOWN);
}
/* close unused half of pipe */
close(pipefds[1]);
/* extract command args for execv */
parse_command_line(processed_command, argv);
if (!argv[0]) {
logit(<API key>, TRUE, "plugin command definition empty\n");
_exit(STATE_UNKNOWN);
}
log_debug_info(DEBUGL_CHECKS, 0, "running command %s via execvp\n", processed_command);
if (execvp(argv[0], argv) < 0) { /* execvp only returns in case of an error */
logit(<API key>, TRUE, "error executing command '%s': %s. Make sure that the file actually exists (in PATH, if set) and is executable!\n", processed_command, strerror(errno));
_exit(STATE_UNKNOWN);
}
_exit(STATE_UNKNOWN);
}
/* prepare pipe reading */
close(pipefds[1]);
fp = fdopen(pipefds[0], "r");
if (!fp) {
logit(<API key>, TRUE, "fdopen error\n");
_exit(STATE_UNKNOWN);
}
/* extract check result */
<API key>(fp, checkresult_dbuf);
/* close the process */
fclose(fp);
close(pipefds[0]);
if (waitpid(pid, &retval, 0) != pid)
retval = -1;
} else {
log_debug_info(DEBUGL_CHECKS, 0, "running command %s via popen\n", processed_command);
fp = popen(processed_command, "r");
if (fp == NULL)
_exit(STATE_UNKNOWN);
/* extract check result */
<API key>(fp, checkresult_dbuf);
/* close the process */
retval = pclose(fp);
}
return retval;
}
/* reaps host and service check results */
int reap_check_results(void) {
check_result *queued_check_result = NULL;
service *temp_service = NULL;
host *temp_host = NULL;
time_t current_time = 0L;
time_t reaper_start_time = 0L;
int reaped_checks = 0;
log_debug_info(DEBUGL_FUNCTIONS, 0, "reap_check_results() start\n");
log_debug_info(DEBUGL_CHECKS, 0, "Starting to reap check results.\n");
/* get the start time */
time(&reaper_start_time);
/* process files in the check result queue */
<API key>(check_result_path);
/* read all check results that have come in... */
while ((queued_check_result = read_check_result())) {
reaped_checks++;
log_debug_info(DEBUGL_CHECKS, 2, "Found a check result (#%d) to handle...\n", reaped_checks);
/* service check */
if (queued_check_result->object_check_type == SERVICE_CHECK) {
/* make sure the service exists */
if ((temp_service = find_service(queued_check_result->host_name, queued_check_result->service_description)) == NULL) {
logit(<API key>, TRUE, "Warning: Check result queue contained results for service '%s' on host '%s', but the service could not be found! Perhaps you forgot to define the service in your config files?\n", queued_check_result->service_description, queued_check_result->host_name);
/* free memory */
free_check_result(queued_check_result);
my_free(queued_check_result);
/* TODO - add new service definition automatically */
continue;
}
log_debug_info(DEBUGL_CHECKS, 1, "Handling check result for service '%s' on host '%s'...\n", temp_service->description, temp_service->host_name);
/* process the check result */
<API key>(temp_service, queued_check_result);
}
/* host check */
else {
if ((temp_host = find_host(queued_check_result->host_name)) == NULL) {
/* make sure the host exists */
logit(<API key>, TRUE, "Warning: Check result queue contained results for host '%s', but the host could not be found! Perhaps you forgot to define the host in your config files?\n", queued_check_result->host_name);
/* free memory */
free_check_result(queued_check_result);
my_free(queued_check_result);
/* TODO - add new host definition automatically */
continue;
}
log_debug_info(DEBUGL_CHECKS, 1, "Handling check result for host '%s'...\n", temp_host->name);
/* process the check result */
<API key>(temp_host, queued_check_result);
}
log_debug_info(DEBUGL_CHECKS | DEBUGL_IPC, 1, "Deleted check result file '%s'\n", queued_check_result->output_file);
/* free allocated memory */
free_check_result(queued_check_result);
my_free(queued_check_result);
/* break out if we've been here too long (<API key> seconds) */
time(¤t_time);
if ((int)(current_time - reaper_start_time) > <API key>) {
log_debug_info(DEBUGL_CHECKS, 0, "Breaking out of check result reaper: max reaper time exceeded\n");
break;
}
/* bail out if we encountered a signal */
if (sigshutdown == TRUE || sigrestart == TRUE) {
log_debug_info(DEBUGL_CHECKS, 0, "Breaking out of check result reaper: signal encountered\n");
break;
}
}
log_debug_info(DEBUGL_CHECKS, 0, "Finished reaping %d check results\n", reaped_checks);
log_debug_info(DEBUGL_FUNCTIONS, 0, "reap_check_results() end\n");
return OK;
}
/* executes a scheduled service check */
int <API key>(service *svc, int check_options, double latency) {
int result = OK;
time_t current_time = 0L;
time_t preferred_time = 0L;
time_t next_valid_time = 0L;
int time_is_valid = TRUE;
if (svc == NULL)
return ERROR;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>() start\n");
log_debug_info(DEBUGL_CHECKS, 0, "Attempting to run scheduled check of service '%s' on host '%s': check options=%d, latency=%lf\n", svc->description, svc->host_name, check_options, latency);
/*
* reset the next_check_event so we know it's
* no longer in the scheduling queue
* and can't conflict
*/
svc->next_check_event = NULL;
/* attempt to run the check */
result = <API key>(svc, check_options, latency, TRUE, TRUE, &time_is_valid, &preferred_time);
/* an error occurred, so reschedule the check */
if (result == ERROR) {
log_debug_info(DEBUGL_CHECKS, 1, "Unable to run scheduled service check at this time\n");
/* only attempt to (re)schedule checks that should get checked... */
if (svc->should_be_scheduled == TRUE) {
/* get current time */
time(¤t_time);
/* determine next time we should check the service if needed */
/* if service has no check interval, schedule it again for 5 minutes from now */
if (current_time >= preferred_time)
preferred_time = current_time + ((svc->check_interval <= 0) ? 300 : (svc->check_interval * interval_length));
/* make sure we rescheduled the next service check at a valid time */
get_next_valid_time(preferred_time, &next_valid_time, svc->check_period_ptr);
/*
logit(<API key>,TRUE,"Warning: Service '%s' on host '%s' timeperiod check failed...\n",svc->description,svc->host_name);
logit(<API key>,TRUE,"Current time: %s",ctime(¤t_time));
logit(<API key>,TRUE,"Preferred time: %s",ctime(&preferred_time));
logit(<API key>,TRUE,"Next valid time: %s",ctime(&next_valid_time));
*/
/* the service could not be rescheduled properly - set the next check time for next week */
/*if(time_is_valid==FALSE && next_valid_time==preferred_time){*/
/* UPDATED 08/12/09 EG to reflect proper timeperod check logic */
if (time_is_valid == FALSE && <API key>(next_valid_time, svc->check_period_ptr) == ERROR) {
/*
svc->next_check=(time_t)(next_valid_time+(60*60*24*365));
svc->should_be_scheduled=FALSE;
*/
svc->next_check = (time_t)(next_valid_time + (60 * 60 * 24 * 7));
logit(<API key>, TRUE, "Warning: Check of service '%s' on host '%s' could not be rescheduled properly. Scheduling check for next week...\n", svc->description, svc->host_name);
log_debug_info(DEBUGL_CHECKS, 1, "Unable to find any valid times to reschedule the next service check!\n");
}
/* this service could be rescheduled... */
else {
svc->next_check = next_valid_time;
svc->should_be_scheduled = TRUE;
log_debug_info(DEBUGL_CHECKS, 1, "Rescheduled next service check for %s", ctime(&next_valid_time));
}
}
/* reschedule the next service check - unless we couldn't find a valid next check time */
/* 10/19/07 EG - keep original check options */
if (svc->should_be_scheduled == TRUE)
<API key>(svc, svc->next_check, check_options);
/* update the status log */
<API key>(svc, FALSE);
return ERROR;
}
return OK;
}
/* forks a child process to run a service check, but does not wait for the service check result */
int <API key>(service *svc, int check_options, double latency, int scheduled_check, int reschedule_check, int *time_is_valid, time_t *preferred_time) {
icinga_macros mac;
char *raw_command = NULL;
char *processed_command = NULL;
struct timeval start_time, end_time;
pid_t pid = 0;
int fork_error = FALSE;
int wait_result = 0;
host *temp_host = NULL;
int pclose_result = 0;
mode_t new_umask = 077;
mode_t old_umask;
char *output_file = NULL;
double old_latency = 0.0;
dbuf checkresult_dbuf;
int dbuf_chunk = 1024;
FILE *fp;
#ifdef USE_EVENT_BROKER
int neb_result = OK;
#endif
#ifdef EMBEDDEDPERL
char fname[512] = "";
char *args[5] = {"", DO_CLEAN, "", "", NULL };
char *perl_plugin_output = NULL;
char *temp_buffer = NULL;
char *args3 = NULL;
SV *plugin_hndlr_cr = NULL; /* perl.h holds typedef struct */
STRLEN n_a;
int count;
int use_epn = FALSE;
#ifdef aTHX
dTHX;
#endif
dSP;
#endif
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have something */
if (svc == NULL)
return ERROR;
/* is the service check viable at this time? */
if (<API key>(svc, check_options, time_is_valid, preferred_time) == ERROR)
return ERROR;
/* find the host associated with this service */
if ((temp_host = svc->host_ptr) == NULL)
return ERROR;
#ifdef USE_EVENT_BROKER
/* initialize start/end times */
start_time.tv_sec = 0L;
start_time.tv_usec = 0L;
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
/* send data to event broker */
neb_result = <API key>(<API key>, NEBFLAG_NONE, NEBATTR_NONE, svc, <API key>, start_time, end_time, svc-><API key>, svc->latency, 0.0, 0, FALSE, 0, NULL, NULL);
/* neb module wants to cancel the service check - the check will be rescheduled for a later time by the scheduling logic */
if (neb_result == <API key>) {
if (preferred_time)
*preferred_time += (svc->check_interval * interval_length);
return ERROR;
}
/* neb module wants to override (or cancel) the service check - perhaps it will check the service itself */
/* NOTE: if a module does this, it has to do a lot of the stuff found below to make sure things don't get whacked out of shape! */
/* NOTE: if would be easier for modules to override checks when the <API key> event is called (later) */
if (neb_result == <API key>)
return OK;
#endif
log_debug_info(DEBUGL_CHECKS, 0, "Checking service '%s' on host '%s'...\n", svc->description, svc->host_name);
/* clear check options - we don't want old check options retained */
/* only clear check options for scheduled checks - ondemand checks shouldn't affected retained check options */
if (scheduled_check == TRUE)
svc->check_options = CHECK_OPTION_NONE;
/* update latency for macros, event broker, save old value for later */
old_latency = svc->latency;
svc->latency = latency;
/* grab the host and service macro variables */
memset(&mac, 0, sizeof(mac));
grab_host_macros_r(&mac, temp_host);
<API key>(&mac, svc);
/* get the raw command line */
<API key>(&mac, svc->check_command_ptr, svc-><API key>, &raw_command, 0);
if (raw_command == NULL) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 0, "Raw check command for service '%s' on host '%s' was NULL - aborting.\n", svc->description, svc->host_name);
if (preferred_time)
*preferred_time += (svc->check_interval * interval_length);
svc->latency = old_latency;
return ERROR;
}
/* process any macros contained in the argument */
process_macros_r(&mac, raw_command, &processed_command, 0);
if (processed_command == NULL) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 0, "Processed check command for service '%s' on host '%s' was NULL - aborting.\n", svc->description, svc->host_name);
if (preferred_time)
*preferred_time += (svc->check_interval * interval_length);
svc->latency = old_latency;
my_free(raw_command);
return ERROR;
}
/* get the command start time */
gettimeofday(&start_time, NULL);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
neb_result = <API key>(<API key>, NEBFLAG_NONE, NEBATTR_NONE, svc, <API key>, start_time, end_time, svc-><API key>, svc->latency, 0.0, <API key>, FALSE, 0, processed_command, NULL);
my_free(svc->processed_command);
svc->processed_command = strdup(processed_command);
/* neb module wants to override the service check - perhaps it will check the service itself */
if (neb_result == <API key>) {
<API key>(&mac);
svc->latency = old_latency;
my_free(processed_command);
my_free(raw_command);
return OK;
}
#endif
/* increment number of service checks that are currently running... */
<API key>++;
/* set the execution flag */
svc->is_executing = TRUE;
/* start save check info */
check_result_info.object_check_type = SERVICE_CHECK;
check_result_info.check_type = <API key>;
check_result_info.check_options = check_options;
check_result_info.scheduled_check = scheduled_check;
check_result_info.reschedule_check = reschedule_check;
check_result_info.start_time = start_time;
check_result_info.finish_time = start_time;
check_result_info.early_timeout = FALSE;
check_result_info.exited_ok = TRUE;
check_result_info.return_code = STATE_OK;
check_result_info.output = NULL;
/* open a temp file for storing check output */
old_umask = umask(new_umask);
dummy = asprintf(&output_file, "%s/checkXXXXXX", temp_path);
check_result_info.output_file_fd = mkstemp(output_file);
if (check_result_info.output_file_fd >= 0)
check_result_info.output_file_fp = fdopen(check_result_info.output_file_fd, "w");
else {
check_result_info.output_file_fp = NULL;
check_result_info.output_file_fd = -1;
}
umask(old_umask);
log_debug_info(DEBUGL_CHECKS | DEBUGL_IPC, 1, "Check result output will be written to '%s' (fd=%d)\n", output_file, check_result_info.output_file_fd);
/* finish save check info */
check_result_info.host_name = (char *)strdup(svc->host_name);
check_result_info.service_description = (char *)strdup(svc->description);
check_result_info.output_file = (check_result_info.output_file_fd < 0 || output_file == NULL) ? NULL : strdup(output_file);
/* free memory */
my_free(output_file);
/* write start of check result file */
/* if things go really bad later on down the line, the user will at least have a partial file to help debug missing output results */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "
fprintf(check_result_info.output_file_fp, "file_time=%lu\n", (unsigned long)check_result_info.start_time.tv_sec);
fprintf(check_result_info.output_file_fp, "\n");
fprintf(check_result_info.output_file_fp, "
fprintf(check_result_info.output_file_fp, "# Time: %s", ctime(&check_result_info.start_time.tv_sec));
fprintf(check_result_info.output_file_fp, "host_name=%s\n", check_result_info.host_name);
fprintf(check_result_info.output_file_fp, "service_description=%s\n", check_result_info.service_description);
fprintf(check_result_info.output_file_fp, "check_type=%d\n", check_result_info.check_type);
fprintf(check_result_info.output_file_fp, "check_options=%d\n", check_result_info.check_options);
fprintf(check_result_info.output_file_fp, "scheduled_check=%d\n", check_result_info.scheduled_check);
fprintf(check_result_info.output_file_fp, "reschedule_check=%d\n", check_result_info.reschedule_check);
fprintf(check_result_info.output_file_fp, "latency=%f\n", svc->latency);
fprintf(check_result_info.output_file_fp, "start_time=%lu.%lu\n", check_result_info.start_time.tv_sec, check_result_info.start_time.tv_usec);
/* flush output or it'll get written again when we fork() */
fflush(check_result_info.output_file_fp);
}
/* initialize dynamic buffer for storing plugin output */
dbuf_init(&checkresult_dbuf, dbuf_chunk);
/* reset latency (permanent value will be set later) */
svc->latency = old_latency;
/* update check statistics */
update_check_stats((scheduled_check == TRUE) ? <API key> : <API key>, start_time.tv_sec);
#ifdef EMBEDDEDPERL
/* get"filename" component of command */
strncpy(fname, processed_command, strcspn(processed_command, " "));
fname[strcspn(processed_command, " ")] = '\x0';
/* should we use the embedded Perl interpreter to run this script? */
use_epn = <API key>(fname);
/* if yes, do some initialization */
if (use_epn == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "** Using Embedded Perl interpreter to run service check...\n");
args[0] = fname;
args[2] = "";
if (strchr(processed_command, ' ') == NULL) {
args[3] = "";
} else {
/* make sure to strip leading whitespaces from args */
args3 = processed_command + strlen(fname) + 1;
for (; isspace(*args3); args3++);
args[3] = args3;
}
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(args[0], 0)));
XPUSHs(sv_2mortal(newSVpv(args[1], 0)));
XPUSHs(sv_2mortal(newSVpv(args[2], 0)));
XPUSHs(sv_2mortal(newSVpv(args[3], 0)));
PUTBACK;
/* call our perl interpreter to compile and optionally cache the command */
call_pv("Embed::Persistent::eval_file", G_SCALAR | G_EVAL);
SPAGAIN ;
if (SvTRUE(ERRSV)) {
/*
* if SvTRUE(ERRSV)
* write failure to IPC pipe
* return
*/
/* remove the top element of the Perl stack (undef) */
(void) POPs ;
pclose_result = STATE_UNKNOWN;
perl_plugin_output = SvPVX(ERRSV);
log_debug_info(DEBUGL_CHECKS, 0, "Embedded Perl failed to compile %s, compile error %s - skipping plugin\n", fname, perl_plugin_output);
/* save plugin output */
if (perl_plugin_output != NULL) {
temp_buffer = escape_newlines(perl_plugin_output);
dbuf_strcat(&checkresult_dbuf, temp_buffer);
my_free(temp_buffer);
}
/* get the check finish time */
gettimeofday(&end_time, NULL);
/* record check result info */
check_result_info.exited_ok = FALSE;
check_result_info.return_code = pclose_result;
check_result_info.finish_time = end_time;
/* write check result to file */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(check_result_info.output_file_fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(check_result_info.output_file_fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(check_result_info.output_file_fp, "return_code=%d\n", check_result_info.return_code);
fprintf(check_result_info.output_file_fp, "output=%s\n", (checkresult_dbuf.buf == NULL) ? "(null)" : checkresult_dbuf.buf);
/* close the temp file */
fclose(check_result_info.output_file_fp);
/* move check result to queue directory */
<API key>(check_result_info.output_file);
}
/* free memory */
dbuf_free(&checkresult_dbuf);
/* free check result memory */
free_check_result(&check_result_info);
return OK;
} else {
plugin_hndlr_cr = newSVsv(POPs);
log_debug_info(DEBUGL_CHECKS, 1, "Embedded Perl successfully compiled %s and returned code ref to plugin handler\n", fname);
PUTBACK ;
FREETMPS ;
LEAVE ;
}
}
#endif
/* plugin is a C plugin or a Perl plugin _without_ compilation errors */
/* fork a child process */
pid = fork();
/* an error occurred while trying to fork */
if (pid == -1) {
fork_error = TRUE;
logit(<API key>, TRUE, "Warning: The check of service '%s' on host '%s' could not be performed due to a fork() error: '%s'. The check will be rescheduled.\n", svc->description, svc->host_name, strerror(errno));
log_debug_info(DEBUGL_CHECKS, 0, "Check of service '%s' on host '%s' could not be performed due to a fork() error: '%s'!\n", svc->description, svc->host_name, strerror(errno));
}
/* if we are in the child process... */
else if (pid == 0) {
/* set environment variables */
<API key>(&mac, TRUE);
/* ADDED 11/12/07 EG */
/* close external command file and shut down worker thread */
close_command_file();
/* fork again if we're not in a large installation */
if (<API key> == TRUE) {
/* fork again... */
pid = fork();
/* an error occurred while trying to fork again */
if (pid == -1)
exit(STATE_UNKNOWN);
}
/* the grandchild (or child if large install tweaks are enabled) process should run the service check... */
if (pid == 0 || <API key> == FALSE) {
/* reset signal handling */
reset_sighandler();
/* become the process group leader */
setpgid(0, 0);
/* exit on term signals at this process level */
signal(SIGTERM, SIG_DFL);
/* catch plugins that don't finish in a timely manner */
signal(SIGALRM, <API key>);
alarm(<API key>);
/* disable rotation of the debug file */
max_debug_file_size = 0L;
#ifdef EMBEDDEDPERL
if (use_epn == TRUE) {
/* execute our previously compiled script - from call_pv("Embed::Persistent::eval_file",..) */
/* NB. args[2] is _now_ a code ref (to the Perl subroutine corresp to the plugin) returned by eval_file() */
ENTER;
SAVETMPS;
PUSHMARK(SP);
XPUSHs(sv_2mortal(newSVpv(args[0], 0)));
XPUSHs(sv_2mortal(newSVpv(args[1], 0)));
XPUSHs(plugin_hndlr_cr);
XPUSHs(sv_2mortal(newSVpv(args[3], 0)));
PUTBACK;
count = call_pv("Embed::Persistent::run_package", G_ARRAY);
SPAGAIN;
perl_plugin_output = POPpx ;
pclose_result = POPi ;
/* NOTE: 07/16/07 This has to be done before FREETMPS statement below, or the POPpx pointer will be invalid (Hendrik B.) */
/* get perl plugin output - escape newlines */
if (perl_plugin_output != NULL) {
temp_buffer = escape_newlines(perl_plugin_output);
dbuf_strcat(&checkresult_dbuf, temp_buffer);
my_free(temp_buffer);
}
PUTBACK;
FREETMPS;
LEAVE;
log_debug_info(DEBUGL_CHECKS, 1, "Embedded Perl ran %s: return code=%d, plugin output=%s\n", fname, pclose_result, (perl_plugin_output == NULL) ? "NULL" : checkresult_dbuf.buf);
/* reset the alarm */
alarm(0);
/* get the check finish time */
gettimeofday(&end_time, NULL);
/* record check result info */
check_result_info.return_code = pclose_result;
check_result_info.finish_time = end_time;
/* write check result to file */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(check_result_info.output_file_fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(check_result_info.output_file_fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(check_result_info.output_file_fp, "return_code=%d\n", check_result_info.return_code);
fprintf(check_result_info.output_file_fp, "output=%s\n", (checkresult_dbuf.buf == NULL) ? "(null)" : checkresult_dbuf.buf);
/* close the temp file */
fclose(check_result_info.output_file_fp);
/* move check result to queue directory */
<API key>(check_result_info.output_file);
}
/* free memory */
dbuf_free(&checkresult_dbuf);
/* free check result memory */
free_check_result(&check_result_info);
/* return with plugin exit status - not really necessary... */
_exit(pclose_result);
}
#endif
/* run the plugin check command */
pclose_result = run_check(processed_command, &checkresult_dbuf);
/* reset the alarm and ignore SIGALRM */
signal(SIGALRM, SIG_IGN);
alarm(0);
/* get the check finish time */
gettimeofday(&end_time, NULL);
/* record check result info */
check_result_info.finish_time = end_time;
check_result_info.early_timeout = FALSE;
/* test for execution error */
if (pclose_result == -1) {
pclose_result = STATE_UNKNOWN;
check_result_info.return_code = STATE_CRITICAL;
check_result_info.exited_ok = FALSE;
} else {
if (WEXITSTATUS(pclose_result) == 0 && WIFSIGNALED(pclose_result))
check_result_info.return_code = 128 + WTERMSIG(pclose_result);
else
check_result_info.return_code = WEXITSTATUS(pclose_result);
}
/* write check result to file */
if (check_result_info.output_file_fp) {
/* avoid races with signal handling */
fp = check_result_info.output_file_fp;
check_result_info.output_file_fp = NULL;
fprintf(fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(fp, "return_code=%d\n", check_result_info.return_code);
fprintf(fp, "output=%s\n", (checkresult_dbuf.buf == NULL) ? "(null)" : checkresult_dbuf.buf);
/* close the temp file */
fclose(fp);
/* move check result to queue directory */
<API key>(check_result_info.output_file);
}
/* free memory */
dbuf_free(&checkresult_dbuf);
my_free(raw_command);
my_free(processed_command);
/* free check result memory */
free_check_result(&check_result_info);
/* return with plugin exit status - not really necessary... */
_exit(pclose_result);
}
/* NOTE: this code is never reached if large install tweaks are enabled... */
/* unset environment variables */
<API key>(&mac, FALSE);
/* free allocated memory */
/* this needs to be done last, so we don't free memory for variables before they're used above */
if (<API key> == TRUE)
free_memory(&mac);
/* parent exits immediately - grandchild process is inherited by the INIT process, so we have no zombie problem... */
_exit(STATE_OK);
}
/* else the parent should wait for the first child to return... */
else if (pid > 0) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 2, "Service check is executing in child process (pid=%lu)\n", (unsigned long)pid);
/* parent should close output file */
if (check_result_info.output_file_fp)
fclose(check_result_info.output_file_fp);
/* should this be done in first child process (after spawning grandchild) as well? */
/* free memory allocated for IPC functionality */
free_check_result(&check_result_info);
/* free memory */
my_free(raw_command);
my_free(processed_command);
/* wait for the first child to return */
/* don't do this if large install tweaks are enabled - we'll clean up children in event loop */
if (<API key> == TRUE)
wait_result = waitpid(pid, NULL, 0);
}
/* see if we were able to run the check... */
if (fork_error == TRUE)
return ERROR;
return OK;
}
/* handles asynchronous service check results */
int <API key>(service *temp_service, check_result *queued_check_result) {
host *temp_host = NULL;
time_t next_service_check = 0L;
time_t preferred_time = 0L;
time_t next_valid_time = 0L;
int reschedule_check = FALSE;
int state_change = FALSE;
int hard_state_change = FALSE;
int <API key> = FALSE;
int route_result = HOST_UP;
time_t current_time = 0L;
int state_was_logged = FALSE;
char *old_plugin_output = NULL;
char *temp_plugin_output = NULL;
char *temp_ptr = NULL;
servicedependency *temp_dependency = NULL;
objectlist *check_servicelist = NULL;
objectlist *servicelist_item = NULL;
service *master_service = NULL;
int run_async_check = TRUE;
int <API key> = TRUE; /* TODO - 09/23/07 move this to a global variable */
int flapping_check_done = FALSE;
void *ptr = NULL;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have what we need */
if (temp_service == NULL || queued_check_result == NULL)
return ERROR;
/* get the current time */
time(¤t_time);
log_debug_info(DEBUGL_CHECKS, 0, "** Handling check result for service '%s' on host '%s'...\n", temp_service->description, temp_service->host_name);
log_debug_info(DEBUGL_CHECKS, 1, "HOST: %s, SERVICE: %s, CHECK TYPE: %s, OPTIONS: %d, SCHEDULED: %s, RESCHEDULE: %s, EXITED OK: %s, RETURN CODE: %d, OUTPUT: %s\n", temp_service->host_name, temp_service->description, (queued_check_result->check_type == <API key>) ? "Active" : "Passive", queued_check_result->check_options, (queued_check_result->scheduled_check == TRUE) ? "Yes" : "No", (queued_check_result->reschedule_check == TRUE) ? "Yes" : "No", (queued_check_result->exited_ok == TRUE) ? "Yes" : "No", queued_check_result->return_code, queued_check_result->output);
/* decrement the number of service checks still out there... */
if (queued_check_result->check_type == <API key> && <API key> > 0)
<API key>
/* skip this service check results if its passive and we aren't accepting passive check results */
if (queued_check_result->check_type == <API key>) {
if (<API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding passive service check result because passive service checks are disabled globally.\n");
return ERROR;
}
if (temp_service-><API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding passive service check result because passive checks are disabled for this service.\n");
return ERROR;
}
}
/* clear the freshening flag (it would have been set if this service was determined to be stale) */
if (queued_check_result->check_options & <API key>)
temp_service->is_being_freshened = FALSE;
/* clear the execution flag if this was an active check */
if (queued_check_result->check_type == <API key>)
temp_service->is_executing = FALSE;
/* DISCARD INVALID FRESHNESS CHECK RESULTS */
/* If a services goes stale, Icinga will initiate a forced check in order to freshen it. There is a race condition whereby a passive check
could arrive between the 1) initiation of the forced check and 2) the time when the forced check result is processed here. This would
make the service fresh again, so we do a quick check to make sure the service is still stale before we accept the check result. */
if ((queued_check_result->check_options & <API key>) && <API key>(temp_service, current_time, FALSE) == TRUE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding service freshness check result because the service is currently fresh (race condition avoided).\n");
return OK;
}
/* check latency is passed to us */
temp_service->latency = queued_check_result->latency;
/* update the execution time for this check (millisecond resolution) */
temp_service->execution_time = (double)((double)(queued_check_result->finish_time.tv_sec - queued_check_result->start_time.tv_sec) + (double)((queued_check_result->finish_time.tv_usec - queued_check_result->start_time.tv_usec) / 1000.0) / 1000.0);
if (temp_service->execution_time < 0.0)
temp_service->execution_time = 0.0;
/* get the last check time */
temp_service->last_check = queued_check_result->start_time.tv_sec;
/* was this check passive or active? */
temp_service->check_type = (queued_check_result->check_type == <API key>) ? <API key> : <API key>;
/* update check statistics for passive checks */
if (queued_check_result->check_type == <API key>)
update_check_stats(<API key>, queued_check_result->start_time.tv_sec);
/* should we reschedule the next service check? NOTE: This may be overridden later... */
reschedule_check = queued_check_result->reschedule_check;
/* save the old service status info */
temp_service->last_state = temp_service->current_state;
/* save old plugin output */
if (temp_service->plugin_output)
old_plugin_output = (char *)strdup(temp_service->plugin_output);
/* clear the old plugin output and perf data buffers */
my_free(temp_service->plugin_output);
my_free(temp_service->long_plugin_output);
my_free(temp_service->perf_data);
/* if there was some error running the command, just skip it (this shouldn't be happening) */
if (queued_check_result->exited_ok == FALSE) {
logit(<API key>, TRUE, "Warning: Check of service '%s' on host '%s' did not exit properly!\n", temp_service->description, temp_service->host_name);
temp_service->plugin_output = (char *)strdup("(Service check did not exit properly)");
temp_service->current_state = STATE_CRITICAL;
}
/* make sure the return code is within bounds */
else if (queued_check_result->return_code < 0 || queued_check_result->return_code > 3) {
if (queued_check_result->return_code == 126) {
dummy = asprintf(&temp_service->plugin_output, "The command defined for service %s is not an executable\n", queued_check_result->service_description);
} else if (queued_check_result->return_code == 127) {
dummy = asprintf(&temp_service->plugin_output, "The command defined for service %s does not exist\n", queued_check_result->service_description);
} else {
dummy = asprintf(&temp_service->plugin_output, "Return code of %d is out of bounds", queued_check_result->return_code);
}
logit(<API key>, TRUE, "%s", temp_service->plugin_output);
temp_service->current_state = STATE_CRITICAL;
}
/* else the return code is okay... */
else {
/* parse check output to get: (1) short output, (2) long output, (3) perf data */
parse_check_output(queued_check_result->output, &temp_service->plugin_output, &temp_service->long_plugin_output, &temp_service->perf_data, TRUE, TRUE);
/* make sure the plugin output isn't null */
if (temp_service->plugin_output == NULL)
temp_service->plugin_output = (char *)strdup("(No output returned from plugin)");
/* replace semicolons in plugin output (but not performance data) with colons */
else if ((temp_ptr = temp_service->plugin_output)) {
while ((temp_ptr = strchr(temp_ptr, ';')))
* temp_ptr = ':';
}
log_debug_info(DEBUGL_CHECKS, 2, "Parsing check output...\n");
log_debug_info(DEBUGL_CHECKS, 2, "Short Output: %s\n", (temp_service->plugin_output == NULL) ? "NULL" : temp_service->plugin_output);
log_debug_info(DEBUGL_CHECKS, 2, "Long Output: %s\n", (temp_service->long_plugin_output == NULL) ? "NULL" : temp_service->long_plugin_output);
log_debug_info(DEBUGL_CHECKS, 2, "Perf Data: %s\n", (temp_service->perf_data == NULL) ? "NULL" : temp_service->perf_data);
/* grab the return code */
temp_service->current_state = queued_check_result->return_code;
}
/* record the last state time */
switch (temp_service->current_state) {
case STATE_OK:
temp_service->last_time_ok = temp_service->last_check;
break;
case STATE_WARNING:
temp_service->last_time_warning = temp_service->last_check;
break;
case STATE_UNKNOWN:
temp_service->last_time_unknown = temp_service->last_check;
break;
case STATE_CRITICAL:
temp_service->last_time_critical = temp_service->last_check;
break;
default:
break;
}
/* log passive checks - we need to do this here, as some my bypass external commands by getting dropped in checkresults dir */
if (temp_service->check_type == <API key>) {
if (log_passive_checks == TRUE)
logit(NSLOG_PASSIVE_CHECK, FALSE, "PASSIVE SERVICE CHECK: %s;%s;%d;%s\n", temp_service->host_name, temp_service->description, temp_service->current_state, temp_service->plugin_output);
}
/* get the host that this service runs on */
temp_host = (host *)temp_service->host_ptr;
/* if the service check was okay... */
if (temp_service->current_state == STATE_OK) {
/* if the host has never been checked before, verify its status */
/* only do this if 1) the initial state was set to non-UP or 2) the host is not scheduled to be checked soon (next 5 minutes) */
if (temp_host->has_been_checked == FALSE && (temp_host->initial_state != HOST_UP || (unsigned long)temp_host->next_check == 0L || (unsigned long)(temp_host->next_check - current_time) > 300)) {
/* set a flag to remember that we launched a check */
<API key> = TRUE;
/* 08/04/07 EG launch an async (parallel) host check unless aggressive host checking is enabled */
/* previous logic was to simply run a sync (serial) host check */
/* do NOT allow cached check results to happen here - we need the host to be checked for real... */
if (<API key> == TRUE)
<API key>(temp_host, NULL, CHECK_OPTION_NONE, FALSE, 0L);
else
<API key>(temp_host, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
}
}
/* increment the current attempt number if this is a soft state (service was rechecked) */
if (temp_service->state_type == SOFT_STATE && (temp_service->current_attempt < temp_service->max_attempts))
temp_service->current_attempt = temp_service->current_attempt + 1;
log_debug_info(DEBUGL_CHECKS, 2, "SERVICE: ST (state_type): %s CA (current_attempt): %d MA (max_attempt): %d CS (current_state): %d LS (last_state): %d LHS (last_hard_state): %d\n", (temp_service->state_type == SOFT_STATE) ? "SOFT" : "HARD", temp_service->current_attempt, temp_service->max_attempts, temp_service->current_state, temp_service->last_state, temp_service->last_hard_state);
/* check for a state change (either soft or hard) */
if (temp_service->current_state != temp_service->last_state) {
log_debug_info(DEBUGL_CHECKS, 2, "Service has changed state since last check!\n");
state_change = TRUE;
}
/* checks for a hard state change where host was down at last service check */
/* this occurs in the case where host goes down and service current attempt gets reset to 1 */
/* if this check is not made, the service recovery looks like a soft recovery instead of a hard one */
if (temp_service-><API key> == TRUE && temp_service->current_state == STATE_OK) {
log_debug_info(DEBUGL_CHECKS, 2, "Service had a HARD STATE CHANGE!!\n");
hard_state_change = TRUE;
}
/* check for a "normal" hard state change where max check attempts is reached */
if (temp_service->current_attempt >= temp_service->max_attempts && temp_service->current_state != temp_service->last_hard_state) {
log_debug_info(DEBUGL_CHECKS, 2, "Service had a HARD STATE CHANGE!!\n");
hard_state_change = TRUE;
}
/* a state change occurred... */
/* reset last and next notification times and acknowledgement flag if necessary, misc other stuff */
if (state_change == TRUE || hard_state_change == TRUE) {
/* reschedule the service check */
reschedule_check = TRUE;
/* reset notification times */
temp_service->last_notification = (time_t)0;
temp_service->next_notification = (time_t)0;
/* reset notification suppression option */
temp_service-><API key> = FALSE;
if (temp_service-><API key> == <API key> && (state_change == TRUE || hard_state_change == FALSE)) {
temp_service-><API key> = FALSE;
temp_service-><API key> = <API key>;
/* remove any non-persistant comments associated with the ack */
<API key>(temp_service);
} else if (temp_service-><API key> == <API key> && temp_service->current_state == STATE_OK) {
temp_service-><API key> = FALSE;
temp_service-><API key> = <API key>;
/* remove any non-persistant comments associated with the ack */
<API key>(temp_service);
}
/* do NOT reset current notification number!!! */
/* hard changes between non-OK states should continue to be escalated, so don't reset current notification number */
/*temp_service-><API key>=0;*/
}
/* initialize the last host and service state change times if necessary */
if (temp_service->last_state_change == (time_t)0)
temp_service->last_state_change = temp_service->last_check;
if (temp_service-><API key> == (time_t)0)
temp_service-><API key> = temp_service->last_check;
if (temp_host->last_state_change == (time_t)0)
temp_host->last_state_change = temp_service->last_check;
if (temp_host-><API key> == (time_t)0)
temp_host-><API key> = temp_service->last_check;
/* update last service state change times */
if (state_change == TRUE)
temp_service->last_state_change = temp_service->last_check;
if (hard_state_change == TRUE)
temp_service-><API key> = temp_service->last_check;
/* update the event and problem ids */
if (state_change == TRUE) {
/* always update the event id on a state change */
temp_service->last_event_id = temp_service->current_event_id;
temp_service->current_event_id = next_event_id;
next_event_id++;
/* update the problem id when transitioning to a problem state */
if (temp_service->last_state == STATE_OK) {
/* don't reset last problem id, or it will be zero the next time a problem is encountered */
/* temp_service->last_problem_id=temp_service->current_problem_id;*/
temp_service->current_problem_id = next_problem_id;
next_problem_id++;
}
/* clear the problem id when transitioning from a problem state to an OK state */
if (temp_service->current_state == STATE_OK) {
temp_service->last_problem_id = temp_service->current_problem_id;
temp_service->current_problem_id = 0L;
}
}
/* if the service is up and running OK... */
if (temp_service->current_state == STATE_OK) {
log_debug_info(DEBUGL_CHECKS, 1, "Service is OK.\n");
/* reset the acknowledgement flag (this should already have been done, but just in case...) */
temp_service-><API key> = FALSE;
temp_service-><API key> = <API key>;
/* verify the route to the host and send out host recovery notifications */
if (temp_host->current_state != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Host is NOT UP, so we'll check it to see if it recovered...\n");
/* 08/04/07 EG launch an async (parallel) host check (possibly cached) unless aggressive host checking is enabled */
/* previous logic was to simply run a sync (serial) host check */
if (<API key> == TRUE)
<API key>(temp_host, NULL, CHECK_OPTION_NONE, TRUE, <API key>);
/* 09/23/07 EG don't launch a new host check if we already did so earlier */
else if (<API key> == TRUE)
log_debug_info(DEBUGL_CHECKS, 1, "First host check was already initiated, so we'll skip a new host check.\n");
else {
/* can we use the last cached host state? */
/* usually only use cached host state if no service state change has occurred */
if ((state_change == FALSE || <API key> == TRUE) && temp_host->has_been_checked == TRUE && ((current_time - temp_host->last_check) <= <API key>)) {
log_debug_info(DEBUGL_CHECKS, 1, "* Using cached host state: %d\n", temp_host->current_state);
update_check_stats(<API key>, current_time);
update_check_stats(<API key>, current_time);
}
/* else launch an async (parallel) check of the host */
else
<API key>(temp_host, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
}
}
/* if a hard service recovery has occurred... */
if (hard_state_change == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "Service experienced a HARD RECOVERY.\n");
/* set the state type macro */
temp_service->state_type = HARD_STATE;
/* log the service recovery */
log_service_event(temp_service);
state_was_logged = TRUE;
/* 10/04/07 check to see if the service and/or associate host is flapping */
/* this should be done before a notification is sent out to ensure the host didn't just start flapping */
<API key>(temp_service, TRUE, TRUE);
<API key>(temp_host, TRUE, FALSE, TRUE);
flapping_check_done = TRUE;
/* notify contacts about the service recovery */
<API key>(temp_service, NOTIFICATION_NORMAL, NULL, NULL, <API key>);
/* run the service event handler to handle the hard state change */
<API key>(temp_service);
}
/* else if a soft service recovery has occurred... */
else if (state_change == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "Service experienced a SOFT RECOVERY.\n");
/* this is a soft recovery */
temp_service->state_type = SOFT_STATE;
/* log the soft recovery */
log_service_event(temp_service);
state_was_logged = TRUE;
/* run the service event handler to handle the soft state change */
<API key>(temp_service);
}
/* else no service state change has occurred... */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Service did not change state.\n");
}
/* should we obsessive over service checks? */
if (<API key> == TRUE)
<API key>(temp_service);
/* reset all service variables because its okay now... */
temp_service-><API key> = FALSE;
temp_service->current_attempt = 1;
temp_service->state_type = HARD_STATE;
temp_service->last_hard_state = STATE_OK;
temp_service->last_notification = (time_t)0;
temp_service->next_notification = (time_t)0;
temp_service-><API key> = 0;
#ifdef <API key>
temp_service-><API key> = 0;
temp_service-><API key> = 0;
temp_service-><API key> = 0;
#endif
temp_service-><API key> = FALSE;
temp_service-><API key> = <API key>;
temp_service->notified_on_unknown = FALSE;
temp_service->notified_on_warning = FALSE;
temp_service-><API key> = FALSE;
temp_service-><API key> = FALSE;
if (reschedule_check == TRUE)
next_service_check = (time_t)(temp_service->last_check + (temp_service->check_interval * interval_length));
}
/* hey, something's not working quite like it should... */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Service is in a non-OK state!\n");
/* check the route to the host if its up right now... */
if (temp_host->current_state == HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Host is currently UP, so we'll recheck its state to make sure...\n");
/* 08/04/07 EG launch an async (parallel) host check (possibly cached) unless aggressive host checking is enabled */
/* previous logic was to simply run a sync (serial) host check */
if (<API key> == TRUE)
<API key>(temp_host, &route_result, CHECK_OPTION_NONE, TRUE, <API key>);
else {
/* can we use the last cached host state? */
/* only use cached host state if no service state change has occurred */
if ((state_change == FALSE || <API key> == TRUE) && temp_host->has_been_checked == TRUE && ((current_time - temp_host->last_check) <= <API key>)) {
/* use current host state as route result */
route_result = temp_host->current_state;
log_debug_info(DEBUGL_CHECKS, 1, "* Using cached host state: %d\n", temp_host->current_state);
update_check_stats(<API key>, current_time);
update_check_stats(<API key>, current_time);
}
/* else launch an async (parallel) check of the host */
/* CHANGED 02/15/08 only if service changed state since service was last checked */
else if (state_change == TRUE) {
/* use current host state as route result */
route_result = temp_host->current_state;
<API key>(temp_host, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
}
/* ADDED 02/15/08 */
/* else assume same host state */
else {
route_result = temp_host->current_state;
log_debug_info(DEBUGL_CHECKS, 1, "* Using last known host state: %d\n", temp_host->current_state);
update_check_stats(<API key>, current_time);
update_check_stats(<API key>, current_time);
}
}
}
/* else the host is either down or unreachable, so recheck it if necessary */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Host is currently DOWN/UNREACHABLE.\n");
/* we're using aggressive host checking, so really do recheck the host... */
if (<API key> == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "Agressive host checking is enabled, so we'll recheck the host state...\n");
<API key>(temp_host, &route_result, CHECK_OPTION_NONE, TRUE, <API key>);
}
/* the service wobbled between non-OK states, so check the host... */
else if ((state_change == TRUE && <API key> == FALSE) && temp_service->last_hard_state != STATE_OK) {
log_debug_info(DEBUGL_CHECKS, 1, "Service wobbled between non-OK states, so we'll recheck the host state...\n");
/* 08/04/07 EG launch an async (parallel) host check unless aggressive host checking is enabled */
/* previous logic was to simply run a sync (serial) host check */
/* use current host state as route result */
route_result = temp_host->current_state;
<API key>(temp_host, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
/*<API key>(temp_host,&route_result,CHECK_OPTION_NONE,TRUE,<API key>);*/
}
/* else fake the host check, but (possibly) resend host notifications to contacts... */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Assuming host is in same state as before...\n");
/* if the host has never been checked before, set the checked flag and last check time */
/* 03/11/06 EG Note: This probably never evaluates to FALSE, present for historical reasons only, can probably be removed in the future */
if (temp_host->has_been_checked == FALSE) {
temp_host->has_been_checked = TRUE;
temp_host->last_check = temp_service->last_check;
}
/* fake the route check result */
route_result = temp_host->current_state;
/* possibly re-send host notifications... */
host_notification(temp_host, NOTIFICATION_NORMAL, NULL, NULL, <API key>);
}
}
/* if the host is down or unreachable ... */
/* 05/29/2007 NOTE: The host might be in a SOFT problem state due to host check retries/caching. Not sure if we should take that into account and do something different or not... */
if (route_result != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 2, "Host is not UP, so we mark state changes if appropriate\n");
/* "fake" a hard state change for the service - well, its not really fake, but it didn't get caught earlier... */
if (temp_service->last_hard_state != temp_service->current_state)
hard_state_change = TRUE;
/* update last state change times */
if (state_change == TRUE || hard_state_change == TRUE)
temp_service->last_state_change = temp_service->last_check;
if (hard_state_change == TRUE) {
temp_service-><API key> = temp_service->last_check;
temp_service->state_type = HARD_STATE;
temp_service->last_hard_state = temp_service->current_state;
}
/* put service into a hard state without attempting check retries and don't send out notifications about it */
temp_service-><API key> = TRUE;
temp_service->state_type = HARD_STATE;
temp_service->last_hard_state = temp_service->current_state;
temp_service->current_attempt = 1;
}
/* the host is up - it recovered since the last time the service was checked... */
else if (temp_service-><API key> == TRUE) {
/* next time the service is checked we shouldn't get into this same case... */
temp_service-><API key> = FALSE;
/* reset the current check counter, so we give the service a chance */
/* this helps prevent the case where service has N max check attempts, N-1 of which have already occurred. */
/* if we didn't do this, the next check might fail and result in a hard problem - we should really give it more time */
/* ADDED IF STATEMENT 01-17-05 EG */
/* 01-17-05: Services in hard problem states before hosts went down would sometimes come back as soft problem states after */
/* the hosts recovered. This caused problems, so hopefully this will fix it */
if (temp_service->state_type == SOFT_STATE)
temp_service->current_attempt = 1;
}
log_debug_info(DEBUGL_CHECKS, 1, "Current/Max Attempt(s): %d/%d\n", temp_service->current_attempt, temp_service->max_attempts);
/* if we should retry the service check, do so (except it the host is down or unreachable!) */
if (temp_service->current_attempt < temp_service->max_attempts) {
/* the host is down or unreachable, so don't attempt to retry the service check */
if (route_result != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Host isn't UP, so we won't retry the service check...\n");
/* the host is not up, so reschedule the next service check at regular interval */
if (reschedule_check == TRUE)
next_service_check = (time_t)(temp_service->last_check + (temp_service->check_interval * interval_length));
/* log the problem as a hard state if the host just went down */
if (hard_state_change == TRUE) {
log_service_event(temp_service);
state_was_logged = TRUE;
/* run the service event handler to handle the hard state */
<API key>(temp_service);
}
}
/* the host is up, so continue to retry the service check */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Host is UP, so we'll retry the service check...\n");
/* this is a soft state */
if (temp_service->current_attempt < temp_service->max_attempts) {
temp_service->state_type = SOFT_STATE;
}
/* log the service check retry */
log_service_event(temp_service);
state_was_logged = TRUE;
/* run the service event handler to handle the soft state */
<API key>(temp_service);
if (reschedule_check == TRUE)
next_service_check = (time_t)(temp_service->last_check + (temp_service->retry_interval * interval_length));
}
/* perform dependency checks on the second to last check of the service */
if (<API key> == TRUE && temp_service->current_attempt == (temp_service->max_attempts - 1)) {
log_debug_info(DEBUGL_CHECKS, 1, "Looking for services to check for predictive dependency checks...\n");
/* check services that THIS ONE depends on for notification AND execution */
/* we do this because we might be sending out a notification soon and we want the dependency logic to be accurate */
for (temp_dependency = <API key>(temp_service->host_name, temp_service->description, &ptr); temp_dependency != NULL; temp_dependency = <API key>(temp_service->host_name, temp_service->description, &ptr)) {
if (temp_dependency-><API key> == temp_service && temp_dependency->master_service_ptr != NULL) {
master_service = (service *)temp_dependency->master_service_ptr;
log_debug_info(DEBUGL_CHECKS, 2, "Predictive check of service '%s' on host '%s' queued.\n", master_service->description, master_service->host_name);
<API key>(&check_servicelist, (void *)master_service);
}
}
}
}
/* we've reached the maximum number of service rechecks, so handle the error */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Service has reached max number of rechecks, so we'll handle the error...\n");
/* this is a hard state */
temp_service->state_type = HARD_STATE;
/* if we've hard a hard state change... */
if (hard_state_change == TRUE) {
/* log the service problem (even if host is not up, which is new in 0.0.5) */
log_service_event(temp_service);
state_was_logged = TRUE;
}
/* else log the problem (again) if this service is flagged as being volatile */
else if (temp_service->is_volatile != FALSE) {
log_service_event(temp_service);
state_was_logged = TRUE;
}
/* check for start of flexible (non-fixed) scheduled downtime if we just had a hard/soft error */
/* 2011-02-21 MF: we need to check for both, state_change (SOFT) and hard_state_change (HARD) values */
if ((hard_state_change == TRUE || state_change == TRUE) && temp_service-><API key> > 0)
<API key>(temp_service);
/* 10/04/07 check to see if the service and/or associate host is flapping */
/* this should be done before a notification is sent out to ensure the host didn't just start flapping */
<API key>(temp_service, TRUE, TRUE);
<API key>(temp_host, TRUE, FALSE, TRUE);
flapping_check_done = TRUE;
#ifdef <API key>
if (hard_state_change == TRUE) {
temp_service-><API key> = 0;
temp_service-><API key> = 0;
temp_service-><API key> = 0;
}
#endif
/* (re)send notifications out about this service problem if the host is up (and was at last check also) and the dependencies were okay... */
<API key>(temp_service, NOTIFICATION_NORMAL, NULL, NULL, <API key>);
/* run the service event handler if we changed state from the last hard state or if this service is flagged as being volatile */
if (hard_state_change == TRUE || temp_service->is_volatile != FALSE)
<API key>(temp_service);
/* save the last hard state */
temp_service->last_hard_state = temp_service->current_state;
/* reschedule the next check at the regular interval */
if (reschedule_check == TRUE)
next_service_check = (time_t)(temp_service->last_check + (temp_service->check_interval * interval_length));
}
/* should we obsessive over service checks? */
if (<API key> == TRUE)
<API key>(temp_service);
}
/* reschedule the next service check ONLY for active, scheduled checks */
if (reschedule_check == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "Rescheduling next check of service at %s", ctime(&next_service_check));
/* default is to reschedule service check unless a test below fails... */
temp_service->should_be_scheduled = TRUE;
/* next check time was calculated above */
temp_service->next_check = next_service_check;
/* make sure we don't get ourselves into too much trouble... */
if (current_time > temp_service->next_check)
temp_service->next_check = current_time;
/* make sure we rescheduled the next service check at a valid time */
preferred_time = temp_service->next_check;
get_next_valid_time(preferred_time, &next_valid_time, temp_service->check_period_ptr);
temp_service->next_check = next_valid_time;
/* services with non-recurring intervals do not get rescheduled */
if (temp_service->check_interval == 0)
temp_service->should_be_scheduled = FALSE;
/* services with active checks disabled do not get rescheduled */
if (temp_service->checks_enabled == FALSE)
temp_service->should_be_scheduled = FALSE;
/* schedule a non-forced check if we can */
if (temp_service->should_be_scheduled == TRUE)
<API key>(temp_service, temp_service->next_check, CHECK_OPTION_NONE);
}
/* STALKING
* if we're stalking this state type and state was
* not already logged AND the plugin output changed
* since last check, log it or run event handlers or
* notify now..
*/
if (temp_service->state_type == HARD_STATE && state_change == FALSE && state_was_logged == FALSE && compare_strings(old_plugin_output, temp_service->plugin_output)) {
if ((temp_service->current_state == STATE_OK && temp_service->stalk_on_ok == TRUE)) {
log_service_event(temp_service);
/* should we run event handlers ? */
if (<API key> == TRUE)
<API key>(temp_service);
/* should we notify all contacts ? */
if (<API key> == TRUE)
<API key>(temp_service, <API key>, NULL, NULL, <API key>);
/* WARNING */
} else if ((temp_service->current_state == STATE_WARNING && temp_service->stalk_on_warning == TRUE)) {
log_service_event(temp_service);
/* should we run event handlers ? */
if (<API key> == TRUE)
<API key>(temp_service);
/* should we notify all contacts ? */
if (<API key> == TRUE)
<API key>(temp_service, <API key>, NULL, NULL, <API key>);
/* UNKNOWN */
} else if ((temp_service->current_state == STATE_UNKNOWN && temp_service->stalk_on_unknown == TRUE)) {
log_service_event(temp_service);
/* should we run event handlers ? */
if (<API key> == TRUE)
<API key>(temp_service);
/* should we notify all contacts ? */
if (<API key> == TRUE)
<API key>(temp_service, <API key>, NULL, NULL, <API key>);
/* CRITICAL */
} else if ((temp_service->current_state == STATE_CRITICAL && temp_service->stalk_on_critical == TRUE)) {
log_service_event(temp_service);
/* should we run event handlers ? */
if (<API key> == TRUE)
<API key>(temp_service);
/* should we notify all contacts ? */
if (<API key> == TRUE)
<API key>(temp_service, <API key>, NULL, NULL, <API key>);
}
}
#ifdef USE_EVENT_BROKER
/* send data to event broker */
<API key>(<API key>, NEBFLAG_NONE, NEBATTR_NONE, temp_service, temp_service->check_type, queued_check_result->start_time, queued_check_result->finish_time, temp_service-><API key>, temp_service->latency, temp_service->execution_time, <API key>, queued_check_result->early_timeout, queued_check_result->return_code, temp_service->processed_command, NULL);
#endif
/* set the checked flag */
temp_service->has_been_checked = TRUE;
/* update the current service status log */
<API key>(temp_service, FALSE);
/* check to see if the service and/or associate host is flapping */
if (flapping_check_done == FALSE) {
<API key>(temp_service, TRUE, TRUE);
<API key>(temp_host, TRUE, FALSE, TRUE);
}
/* update service performance info */
<API key>(temp_service);
/* free allocated memory */
my_free(temp_plugin_output);
my_free(old_plugin_output);
/* run async checks of all services we added above */
/* don't run a check if one is already executing or we can get by with a cached state */
for (servicelist_item = check_servicelist; servicelist_item != NULL; servicelist_item = servicelist_item->next) {
run_async_check = TRUE;
temp_service = (service *)servicelist_item->object_ptr;
/* we can get by with a cached state, so don't check the service */
if ((current_time - temp_service->last_check) <= <API key>) {
run_async_check = FALSE;
/* update check statistics */
update_check_stats(<API key>, current_time);
}
if (temp_service->is_executing == TRUE)
run_async_check = FALSE;
if (run_async_check == TRUE)
<API key>(temp_service, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
}
free_objectlist(&check_servicelist);
return OK;
}
/* schedules an immediate or delayed service check */
void <API key>(service *svc, time_t check_time, int options) {
timed_event *temp_event = NULL;
timed_event *new_event = NULL;
int use_original_event = TRUE;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
if (svc == NULL)
return;
log_debug_info(DEBUGL_CHECKS, 0, "Scheduling a %s, active check of service '%s' on host '%s' @ %s", (options & <API key>) ? "forced" : "non-forced", svc->description, svc->host_name, ctime(&check_time));
/* don't schedule a check if active checks of this service are disabled */
if (svc->checks_enabled == FALSE && !(options & <API key>)) {
log_debug_info(DEBUGL_CHECKS, 0, "Active checks of this service are disabled.\n");
return;
}
/* allocate memory for a new event item */
new_event = (timed_event *)malloc(sizeof(timed_event));
if (new_event == NULL) {
logit(<API key>, TRUE, "Warning: Could not reschedule check of service '%s' on host '%s'!\n", svc->description, svc->host_name);
return;
}
/* default is to use the new event */
use_original_event = FALSE;
/* fetch possible saved next check event */
temp_event = (timed_event *)svc->next_check_event;
/*
* if the service already has a check scheduled
* we need to decide wether the original or the
* new event will be used
*/
if (temp_event != NULL) {
log_debug_info(DEBUGL_CHECKS, 2, "Found another service check event for this service @ %s", ctime(&temp_event->run_time));
/* use the originally scheduled check unless we decide otherwise */
use_original_event = TRUE;
/* the original event is a forced check... */
if ((temp_event->event_options & <API key>)) {
/* the new event is also forced and its execution time is earlier than the original, so use it instead */
if ((options & <API key>) && (check_time < temp_event->run_time)) {
use_original_event = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "New service check event is forced and occurs before the existing event, so the new event will be used instead.\n");
}
}
/* the original event is not a forced check... */
else {
/* the new event is a forced check, so use it instead */
if ((options & <API key>)) {
use_original_event = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "New service check event is forced, so it will be used instead of the existing event.\n");
}
/* the new event is not forced either and its execution time is earlier than the original, so use it instead */
else if (check_time < temp_event->run_time) {
use_original_event = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "New service check event occurs before the existing (older) event, so it will be used instead.\n");
}
/* the new event is older, so override the existing one */
else {
log_debug_info(DEBUGL_CHECKS, 2, "New service check event occurs after the existing event, so we'll ignore it.\n");
}
}
/* the originally queued event won the battle, so keep it */
if (use_original_event == TRUE) {
my_free(new_event);
}
/* else we're using the new event, so remove the old one */
else {
remove_event(temp_event, &event_list_low, &event_list_low_tail);
/* save new event for later */
svc->next_check_event = new_event;
my_free(temp_event);
}
}
/* save check options for retention purposes */
svc->check_options = options;
/* schedule a new event */
if (use_original_event == FALSE) {
log_debug_info(DEBUGL_CHECKS, 2, "Scheduling new service check event.\n");
/* set the next service check time */
svc->next_check = check_time;
/* place the new event in the event queue */
new_event->event_type = EVENT_SERVICE_CHECK;
new_event->event_data = (void *)svc;
new_event->event_args = (void *)NULL;
new_event->event_options = options;
new_event->run_time = svc->next_check;
new_event->recurring = FALSE;
new_event->event_interval = 0L;
new_event->timing_func = NULL;
new_event-><API key> = TRUE;
reschedule_event(new_event, &event_list_low, &event_list_low_tail);
}
else {
/* reset the next check time (it may be out of sync) */
if (temp_event != NULL)
svc->next_check = temp_event->run_time;
log_debug_info(DEBUGL_CHECKS, 2, "Keeping original service check event (ignoring the new one).\n");
}
return;
}
/* checks viability of performing a service check */
int <API key>(service *svc, int check_options, int *time_is_valid, time_t *new_time) {
int result = OK;
int perform_check = TRUE;
time_t current_time = 0L;
time_t preferred_time = 0L;
int check_interval = 0;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have a service */
if (svc == NULL)
return ERROR;
/* get the check interval to use if we need to reschedule the check */
if (svc->state_type == SOFT_STATE && svc->current_state != STATE_OK)
check_interval = (svc->retry_interval * interval_length);
else
check_interval = (svc->check_interval * interval_length);
/* get the current time */
time(¤t_time);
/* initialize the next preferred check time */
preferred_time = current_time;
/* can we check the host right now? */
if (!(check_options & <API key>)) {
/* if checks of the service are currently disabled... */
if (svc->checks_enabled == FALSE) {
preferred_time = current_time + check_interval;
perform_check = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "Active checks of the service are currently disabled.\n");
}
/* make sure this is a valid time to check the service */
if (<API key>((unsigned long)current_time, svc->check_period_ptr) == ERROR) {
preferred_time = current_time;
if (time_is_valid)
*time_is_valid = FALSE;
perform_check = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "This is not a valid time for this service to be actively checked.\n");
}
/* check service dependencies for execution */
if (<API key>(svc, <API key>) == DEPENDENCIES_FAILED) {
preferred_time = current_time + check_interval;
perform_check = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "Execution dependencies for this service failed, so it will not be actively checked.\n");
}
}
/* pass back the next viable check time */
if (new_time)
*new_time = preferred_time;
result = (perform_check == TRUE) ? OK : ERROR;
return result;
}
/* checks service dependencies */
int <API key>(service *svc, int dependency_type) {
servicedependency *temp_dependency = NULL;
service *temp_service = NULL;
int state = STATE_OK;
time_t current_time = 0L;
void *ptr = NULL;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* check all dependencies... */
for (temp_dependency = <API key>(svc->host_name, svc->description, &ptr); temp_dependency != NULL; temp_dependency = <API key>(svc->host_name, svc->description, &ptr)) {
/* only check dependencies of the desired type (notification or execution) */
if (temp_dependency->dependency_type != dependency_type)
continue;
/* find the service we depend on... */
if ((temp_service = temp_dependency->master_service_ptr) == NULL)
continue;
/* skip this dependency if it has a timeperiod and the current time isn't valid */
time(¤t_time);
if (temp_dependency->dependency_period != NULL && <API key>(current_time, temp_dependency-><API key>) == ERROR)
return FALSE;
/* get the status to use (use last hard state if its currently in a soft state) */
if (temp_service->state_type == SOFT_STATE && <API key> == FALSE)
state = temp_service->last_hard_state;
else
state = temp_service->current_state;
/* is the service we depend on in state that fails the dependency tests? */
if (state == STATE_OK && temp_dependency->fail_on_ok == TRUE)
return DEPENDENCIES_FAILED;
if (state == STATE_WARNING && temp_dependency->fail_on_warning == TRUE)
return DEPENDENCIES_FAILED;
if (state == STATE_UNKNOWN && temp_dependency->fail_on_unknown == TRUE)
return DEPENDENCIES_FAILED;
if (state == STATE_CRITICAL && temp_dependency->fail_on_critical == TRUE)
return DEPENDENCIES_FAILED;
if ((state == STATE_OK && temp_service->has_been_checked == FALSE) && temp_dependency->fail_on_pending == TRUE)
return DEPENDENCIES_FAILED;
/* immediate dependencies ok at this point - check parent dependencies if necessary */
if (temp_dependency->inherits_parent == TRUE) {
if (<API key>(temp_service, dependency_type) != DEPENDENCIES_OK)
return DEPENDENCIES_FAILED;
}
}
return DEPENDENCIES_OK;
}
/* check for services that never returned from a check... */
void <API key>(void) {
service *temp_service = NULL;
time_t current_time = 0L;
time_t expected_time = 0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* get the current time */
time(¤t_time);
/* check all services... */
for (temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) {
/* skip services that are not currently executing */
if (temp_service->is_executing == FALSE)
continue;
/* determine the time at which the check results should have come in (allow 10 minutes slack time) */
expected_time = (time_t)(temp_service->next_check + temp_service->latency + <API key> + <API key> + 600);
/* this service was supposed to have executed a while ago, but for some reason the results haven't come back in... */
if (expected_time < current_time) {
/* log a warning */
logit(<API key>, TRUE, "Warning: The check of service '%s' on host '%s' looks like it was orphaned (results never came back). I'm scheduling an immediate check of the service...\n", temp_service->description, temp_service->host_name);
log_debug_info(DEBUGL_CHECKS, 1, "Service '%s' on host '%s' was orphaned, so we're scheduling an immediate check...\n", temp_service->description, temp_service->host_name);
/* decrement the number of running service checks */
if (<API key> > 0)
<API key>
/* disable the executing flag */
temp_service->is_executing = FALSE;
/* schedule an immediate check of the service */
<API key>(temp_service, current_time, <API key>);
}
}
return;
}
/* check freshness of service results */
void <API key>(void) {
service *temp_service = NULL;
time_t current_time = 0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
log_debug_info(DEBUGL_CHECKS, 1, "Checking the freshness of service check results...\n");
/* bail out if we're not supposed to be checking freshness */
if (<API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 1, "Service freshness checking is disabled.\n");
return;
}
/* get the current time */
time(¤t_time);
/* check all services... */
for (temp_service = service_list; temp_service != NULL; temp_service = temp_service->next) {
/* skip services we shouldn't be checking for freshness */
if (temp_service->check_freshness == FALSE)
continue;
/* skip services that are currently executing (problems here will be caught by orphaned service check) */
if (temp_service->is_executing == TRUE)
continue;
/* skip services that have both active and passive checks disabled */
if (temp_service->checks_enabled == FALSE && temp_service-><API key> == FALSE)
continue;
/* skip services that are already being freshened */
if (temp_service->is_being_freshened == TRUE)
continue;
/* see if the time is right... */
if (<API key>(current_time, temp_service->check_period_ptr) == ERROR)
continue;
/* EXCEPTION */
/* don't check freshness of services without regular check intervals if we're using auto-freshness threshold */
if (temp_service->check_interval == 0 && temp_service->freshness_threshold == 0)
continue;
/* the results for the last check of this service are stale! */
if (<API key>(temp_service, current_time, TRUE) == FALSE) {
/* set the freshen flag */
temp_service->is_being_freshened = TRUE;
/* schedule an immediate forced check of the service */
<API key>(temp_service, current_time, <API key> | <API key>);
}
}
return;
}
/* tests whether or not a service's check results are fresh */
int <API key>(service *temp_service, time_t current_time, int log_this) {
int freshness_threshold = 0;
time_t expiration_time = 0L;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int tdays = 0;
int thours = 0;
int tminutes = 0;
int tseconds = 0;
log_debug_info(DEBUGL_CHECKS, 2, "Checking freshness of service '%s' on host '%s'...\n", temp_service->description, temp_service->host_name);
/* use user-supplied freshness threshold or auto-calculate a freshness threshold to use? */
if (temp_service->freshness_threshold == 0) {
if (temp_service->state_type == HARD_STATE || temp_service->current_state == STATE_OK)
freshness_threshold = (temp_service->check_interval * interval_length) + temp_service->latency + <API key>;
else
freshness_threshold = (temp_service->retry_interval * interval_length) + temp_service->latency + <API key>;
} else
freshness_threshold = temp_service->freshness_threshold;
log_debug_info(DEBUGL_CHECKS, 2, "Freshness thresholds: service=%d, use=%d\n", temp_service->freshness_threshold, freshness_threshold);
/* calculate expiration time */
/*
* CHANGED 11/10/05 EG
* program start is only used in expiration time calculation
* if > last check AND active checks are enabled, so active checks
* can become stale immediately upon program startup
*/
/*
* CHANGED 02/25/06 SG
* passive checks also become stale, so remove dependence on active
* check logic
*/
if (temp_service->has_been_checked == FALSE)
expiration_time = (time_t)(event_start + freshness_threshold);
/*
* CHANGED 06/19/07 EG
* Per Ton's suggestion (and user requests), only use program start
* time over last check if no specific threshold has been set by user.
* Otheriwse use it. Problems can occur if Icinga is restarted more
* frequently that freshness threshold intervals (services never go stale).
*/
/*
* CHANGED 10/07/07 EG
* Only match next condition for services that have active checks
* enabled...
*/
/*
* CHANGED 10/07/07 EG
* Added <API key> to expiration time as suggested
* by Altinity
*/
else if (temp_service->checks_enabled == TRUE && event_start > temp_service->last_check && temp_service->freshness_threshold == 0)
expiration_time = (time_t)(event_start + freshness_threshold + (<API key> * interval_length));
else
expiration_time = (time_t)(temp_service->last_check + freshness_threshold);
log_debug_info(DEBUGL_CHECKS, 2, "SERVICE: HBC (has_been_checked): %d, PS (program_start): %lu, ES (event_start): %lu, LC (last_check): %lu, CT (current_time): %lu, ET (expiration_time): %lu\n", temp_service->has_been_checked, (unsigned long)program_start, (unsigned long)event_start, (unsigned long)temp_service->last_check, (unsigned long)current_time, (unsigned long)expiration_time);
/* the results for the last check of this service are stale */
if (expiration_time < current_time) {
get_time_breakdown((current_time - expiration_time), &days, &hours, &minutes, &seconds);
get_time_breakdown(freshness_threshold, &tdays, &thours, &tminutes, &tseconds);
/* log a warning */
if (log_this == TRUE)
logit(<API key>, TRUE, "Warning: The results of service '%s' on host '%s' are stale by %dd %dh %dm %ds (threshold=%dd %dh %dm %ds). I'm forcing an immediate check of the service.\n", temp_service->description, temp_service->host_name, days, hours, minutes, seconds, tdays, thours, tminutes, tseconds);
log_debug_info(DEBUGL_CHECKS, 1, "Check results for service '%s' on host '%s' are stale by %dd %dh %dm %ds (threshold=%dd %dh %dm %ds). Forcing an immediate check of the service...\n", temp_service->description, temp_service->host_name, days, hours, minutes, seconds, tdays, thours, tminutes, tseconds);
return FALSE;
}
log_debug_info(DEBUGL_CHECKS, 1, "Check results for service '%s' on host '%s' are fresh.\n", temp_service->description, temp_service->host_name);
return TRUE;
}
/* execute an on-demand check */
int <API key>(host *hst, int *check_return_code, int check_options, int use_cached_result, unsigned long <API key>) {
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
<API key>(hst, check_return_code, check_options, use_cached_result, <API key>);
return OK;
}
/* execute a scheduled host check using either the 2.x or 3.x logic */
int <API key>(host *hst, int check_options, double latency) {
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
<API key>(hst, check_options, latency);
return OK;
}
/* schedules an immediate or delayed host check */
void schedule_host_check(host *hst, time_t check_time, int options) {
timed_event *temp_event = NULL;
timed_event *new_event = NULL;
int use_original_event = TRUE;
log_debug_info(DEBUGL_FUNCTIONS, 0, "schedule_host_check()\n");
if (hst == NULL)
return;
log_debug_info(DEBUGL_CHECKS, 0, "Scheduling a %s, active check of host '%s' @ %s", (options & <API key>) ? "forced" : "non-forced", hst->name, ctime(&check_time));
/* don't schedule a check if active checks of this host are disabled */
if (hst->checks_enabled == FALSE && !(options & <API key>)) {
log_debug_info(DEBUGL_CHECKS, 0, "Active checks are disabled for this host.\n");
return;
}
/* allocate memory for a new event item */
if ((new_event = (timed_event *)malloc(sizeof(timed_event))) == NULL) {
logit(<API key>, TRUE, "Warning: Could not reschedule check of host '%s'!\n", hst->name);
return;
}
/* default is to use the new event */
use_original_event = FALSE;
/* fetch possible saved next check event */
temp_event = (timed_event *)hst->next_check_event;
/*
* if the service already has a check scheduled
* we need to decide wether the original or the
* new event will be used
*/
if (temp_event != NULL) {
log_debug_info(DEBUGL_CHECKS, 2, "Found another host check event for this host @ %s", ctime(&temp_event->run_time));
/* use the originally scheduled check unless we decide otherwise */
use_original_event = TRUE;
/* the original event is a forced check... */
if ((temp_event->event_options & <API key>)) {
/* the new event is also forced and its execution time is earlier than the original, so use it instead */
if ((options & <API key>) && (check_time < temp_event->run_time)) {
log_debug_info(DEBUGL_CHECKS, 2, "New host check event is forced and occurs before the existing event, so the new event be used instead.\n");
use_original_event = FALSE;
}
}
/* the original event is not a forced check... */
else {
/* the new event is a forced check, so use it instead */
if ((options & <API key>)) {
use_original_event = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "New host check event is forced, so it will be used instead of the existing event.\n");
}
/* the new event is not forced either and its execution time is earlier than the original, so use it instead */
else if (check_time < temp_event->run_time) {
use_original_event = FALSE;
log_debug_info(DEBUGL_CHECKS, 2, "New host check event occurs before the existing (older) event, so it will be used instead.\n");
}
/* the new event is older, so override the existing one */
else {
log_debug_info(DEBUGL_CHECKS, 2, "New host check event occurs after the existing event, so we'll ignore it.\n");
}
}
/* the originally queued event won the battle, so keep it */
if (use_original_event == TRUE) {
my_free(new_event);
}
/* else use the new event, so remove the old */
else {
remove_event(temp_event, &event_list_low, &event_list_low_tail);
/* save new event for later */
hst->next_check_event = new_event;
my_free(temp_event);
}
}
/* save check options for retention purposes */
hst->check_options = options;
/* use the new event */
if (use_original_event == FALSE) {
log_debug_info(DEBUGL_CHECKS, 2, "Scheduling new host check event.\n");
/* set the next host check time */
hst->next_check = check_time;
/* place the new event in the event queue */
new_event->event_type = EVENT_HOST_CHECK;
new_event->event_data = (void *)hst;
new_event->event_args = (void *)NULL;
new_event->event_options = options;
new_event->run_time = hst->next_check;
new_event->recurring = FALSE;
new_event->event_interval = 0L;
new_event->timing_func = NULL;
new_event-><API key> = TRUE;
reschedule_event(new_event, &event_list_low, &event_list_low_tail);
}
else {
/* reset the next check time (it may be out of sync) */
if (temp_event != NULL)
hst->next_check = temp_event->run_time;
log_debug_info(DEBUGL_CHECKS, 2, "Keeping original host check event (ignoring the new one).\n");
}
return;
}
/* checks host dependencies */
int <API key>(host *hst, int dependency_type) {
hostdependency *temp_dependency = NULL;
host *temp_host = NULL;
int state = HOST_UP;
time_t current_time = 0L;
void *ptr = NULL;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* check all dependencies... */
for (temp_dependency = <API key>(hst->name, &ptr); temp_dependency != NULL; temp_dependency = <API key>(hst->name, &ptr)) {
/* only check dependencies of the desired type (notification or execution) */
if (temp_dependency->dependency_type != dependency_type)
continue;
/* find the host we depend on... */
if ((temp_host = temp_dependency->master_host_ptr) == NULL)
continue;
/* skip this dependency if it has a timeperiod and the current time isn't valid */
time(¤t_time);
if (temp_dependency->dependency_period != NULL && <API key>(current_time, temp_dependency-><API key>) == ERROR)
return FALSE;
/* get the status to use (use last hard state if its currently in a soft state) */
if (temp_host->state_type == SOFT_STATE && <API key> == FALSE)
state = temp_host->last_hard_state;
else
state = temp_host->current_state;
/* is the host we depend on in state that fails the dependency tests? */
if (state == HOST_UP && temp_dependency->fail_on_up == TRUE)
return DEPENDENCIES_FAILED;
if (state == HOST_DOWN && temp_dependency->fail_on_down == TRUE)
return DEPENDENCIES_FAILED;
if (state == HOST_UNREACHABLE && temp_dependency->fail_on_unreachable == TRUE)
return DEPENDENCIES_FAILED;
if ((state == HOST_UP && temp_host->has_been_checked == FALSE) && temp_dependency->fail_on_pending == TRUE)
return DEPENDENCIES_FAILED;
/* immediate dependencies ok at this point - check parent dependencies if necessary */
if (temp_dependency->inherits_parent == TRUE) {
if (<API key>(temp_host, dependency_type) != DEPENDENCIES_OK)
return DEPENDENCIES_FAILED;
}
}
return DEPENDENCIES_OK;
}
/* check for hosts that never returned from a check... */
void <API key>(void) {
host *temp_host = NULL;
time_t current_time = 0L;
time_t expected_time = 0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* get the current time */
time(¤t_time);
/* check all hosts... */
for (temp_host = host_list; temp_host != NULL; temp_host = temp_host->next) {
/* skip hosts that don't have a set check interval (on-demand checks are missed by the orphan logic) */
if (temp_host->next_check == (time_t)0L)
continue;
/* skip hosts that are not currently executing */
if (temp_host->is_executing == FALSE)
continue;
/* determine the time at which the check results should have come in (allow 10 minutes slack time) */
expected_time = (time_t)(temp_host->next_check + temp_host->latency + host_check_timeout + <API key> + 600);
/* this host was supposed to have executed a while ago, but for some reason the results haven't come back in... */
if (expected_time < current_time) {
/* log a warning */
logit(<API key>, TRUE, "Warning: The check of host '%s' looks like it was orphaned (results never came back). I'm scheduling an immediate check of the host...\n", temp_host->name);
log_debug_info(DEBUGL_CHECKS, 1, "Host '%s' was orphaned, so we're scheduling an immediate check...\n", temp_host->name);
/* decrement the number of running host checks */
if (<API key> > 0)
<API key>
/* disable the executing flag */
temp_host->is_executing = FALSE;
/* schedule an immediate check of the host */
schedule_host_check(temp_host, current_time, <API key>);
}
}
return;
}
/* check freshness of host results */
void <API key>(void) {
host *temp_host = NULL;
time_t current_time = 0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
log_debug_info(DEBUGL_CHECKS, 2, "Attempting to check the freshness of host check results...\n");
/* bail out if we're not supposed to be checking freshness */
if (<API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 2, "Host freshness checking is disabled.\n");
return;
}
/* get the current time */
time(¤t_time);
/* check all hosts... */
for (temp_host = host_list; temp_host != NULL; temp_host = temp_host->next) {
/* skip hosts we shouldn't be checking for freshness */
if (temp_host->check_freshness == FALSE)
continue;
/* skip hosts that have both active and passive checks disabled */
if (temp_host->checks_enabled == FALSE && temp_host-><API key> == FALSE)
continue;
/* skip hosts that are currently executing (problems here will be caught by orphaned host check) */
if (temp_host->is_executing == TRUE)
continue;
/* skip hosts that are already being freshened */
if (temp_host->is_being_freshened == TRUE)
continue;
/* see if the time is right... */
if (<API key>(current_time, temp_host->check_period_ptr) == ERROR)
continue;
/* the results for the last check of this host are stale */
if (<API key>(temp_host, current_time, TRUE) == FALSE) {
/* set the freshen flag */
temp_host->is_being_freshened = TRUE;
/* schedule an immediate forced check of the host */
schedule_host_check(temp_host, current_time, <API key> | <API key>);
}
}
return;
}
/* checks to see if a hosts's check results are fresh */
int <API key>(host *temp_host, time_t current_time, int log_this) {
time_t expiration_time = 0L;
int freshness_threshold = 0;
int days = 0;
int hours = 0;
int minutes = 0;
int seconds = 0;
int tdays = 0;
int thours = 0;
int tminutes = 0;
int tseconds = 0;
log_debug_info(DEBUGL_CHECKS, 2, "Checking freshness of host '%s'...\n", temp_host->name);
/* use user-supplied freshness threshold or auto-calculate a freshness threshold to use? */
if (temp_host->freshness_threshold == 0)
if (temp_host->state_type == HARD_STATE || temp_host->current_state == STATE_OK)
freshness_threshold = (temp_host->check_interval * interval_length) + temp_host->latency + <API key>;
else
freshness_threshold = (temp_host->retry_interval * interval_length) + temp_host->latency + <API key>;
else
freshness_threshold = temp_host->freshness_threshold;
log_debug_info(DEBUGL_CHECKS, 2, "Freshness thresholds: host=%d, use=%d\n", temp_host->freshness_threshold, freshness_threshold);
/* calculate expiration time */
/*
* CHANGED 11/10/05 EG
* program start is only used in expiration time calculation
* if > last check AND active checks are enabled, so active checks
* can become stale immediately upon program startup
*/
if (temp_host->has_been_checked == FALSE)
expiration_time = (time_t)(event_start + freshness_threshold);
/*
* CHANGED 06/19/07 EG
* Per Ton's suggestion (and user requests), only use program start
* time over last check if no specific threshold has been set by user.
* Otheriwse use it. Problems can occur if Icinga is restarted more
* frequently that freshness threshold intervals (hosts never go stale).
*/
/*
* CHANGED 10/07/07 EG
* Added <API key> to expiration time as suggested by
* Altinity
*/
else if (temp_host->checks_enabled == TRUE && event_start > temp_host->last_check && temp_host->freshness_threshold == 0)
expiration_time = (time_t)(event_start + freshness_threshold + (<API key> * interval_length));
else
expiration_time = (time_t)(temp_host->last_check + freshness_threshold);
log_debug_info(DEBUGL_CHECKS, 2, "HOST: HBC (has_been_checked): %d, PS (program_start): %lu, ES (event_start): %lu, LC (last_check): %lu, CT (current_time): %lu, ET (expiration_time): %lu\n", temp_host->has_been_checked, (unsigned long)program_start, (unsigned long)event_start, (unsigned long)temp_host->last_check, (unsigned long)current_time, (unsigned long)expiration_time);
/* the results for the last check of this host are stale */
if (expiration_time < current_time) {
get_time_breakdown((current_time - expiration_time), &days, &hours, &minutes, &seconds);
get_time_breakdown(freshness_threshold, &tdays, &thours, &tminutes, &tseconds);
/* log a warning */
if (log_this == TRUE)
logit(<API key>, TRUE, "Warning: The results of host '%s' are stale by %dd %dh %dm %ds (threshold=%dd %dh %dm %ds). I'm forcing an immediate check of the host.\n", temp_host->name, days, hours, minutes, seconds, tdays, thours, tminutes, tseconds);
log_debug_info(DEBUGL_CHECKS, 1, "Check results for host '%s' are stale by %dd %dh %dm %ds (threshold=%dd %dh %dm %ds). Forcing an immediate check of the host...\n", temp_host->name, days, hours, minutes, seconds, tdays, thours, tminutes, tseconds);
return FALSE;
} else
log_debug_info(DEBUGL_CHECKS, 1, "Check results for host '%s' are fresh.\n", temp_host->name);
return TRUE;
}
/*** ON-DEMAND HOST CHECKS USE THIS FUNCTION ***/
/* check to see if we can reach the host */
int <API key>(host *hst, int *check_result_code, int check_options, int use_cached_result, unsigned long <API key>) {
int result = OK;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have a host */
if (hst == NULL)
return ERROR;
log_debug_info(DEBUGL_CHECKS, 0, "** On-demand check for host '%s'...\n", hst->name);
/* check the status of the host */
result = <API key>(hst, check_result_code, check_options, use_cached_result, <API key>);
return result;
}
/* perform a synchronous check of a host */
/* on-demand host checks will use this... */
int <API key>(host *hst, int *check_result_code, int check_options, int use_cached_result, unsigned long <API key>) {
int result = OK;
time_t current_time = 0L;
int host_result = HOST_UP;
char *old_plugin_output = NULL;
struct timeval start_time;
struct timeval end_time;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have a host */
if (hst == NULL)
return ERROR;
log_debug_info(DEBUGL_CHECKS, 0, "** Run sync check of host '%s'...\n", hst->name);
/* is the host check viable at this time? */
/* if not, return current state and bail out */
if (<API key>(hst, check_options, NULL, NULL) == ERROR) {
if (check_result_code)
*check_result_code = hst->current_state;
log_debug_info(DEBUGL_CHECKS, 0, "Host check is not viable at this time.\n");
return OK;
}
/* get the current time */
time(¤t_time);
/* high resolution start time for event broker */
gettimeofday(&start_time, NULL);
/* can we use the last cached host state? */
if (use_cached_result == TRUE && !(check_options & <API key>)) {
/* we can used the cached result, so return it and get out of here... */
if (hst->has_been_checked == TRUE && ((current_time - hst->last_check) <= <API key>)) {
if (check_result_code)
*check_result_code = hst->current_state;
log_debug_info(DEBUGL_CHECKS, 1, "* Using cached host state: %d\n", hst->current_state);
/* update check statistics */
update_check_stats(<API key>, current_time);
update_check_stats(<API key>, current_time);
return OK;
}
}
log_debug_info(DEBUGL_CHECKS, 1, "* Running actual host check: old state=%d\n", hst->current_state);
/* update check statistics */
update_check_stats(<API key>, current_time);
update_check_stats(<API key>, start_time.tv_sec);
/* reset host check latency, since on-demand checks have none */
hst->latency = 0.0;
/* adjust host check attempt */
<API key>(hst, TRUE);
/* save old host state */
hst->last_state = hst->current_state;
if (hst->state_type == HARD_STATE)
hst->last_hard_state = hst->current_state;
/* save old plugin output for state stalking */
if (hst->plugin_output)
old_plugin_output = (char *)strdup(hst->plugin_output);
/* set the checked flag */
hst->has_been_checked = TRUE;
/* clear the freshness flag */
hst->is_being_freshened = FALSE;
/* clear check options - we don't want old check options retained */
hst->check_options = CHECK_OPTION_NONE;
/* set the check type */
hst->check_type = HOST_CHECK_ACTIVE;
#ifdef USE_EVENT_BROKER
/* send data to event broker */
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, hst->current_state, hst->state_type, start_time, end_time, hst->host_check_command, hst->latency, 0.0, host_check_timeout, FALSE, 0, NULL, NULL, NULL, NULL, NULL);
#endif
/* execute the host check */
host_result = <API key>(hst);
/* process the host check result */
<API key>(hst, host_result, old_plugin_output, check_options, FALSE, use_cached_result, <API key>);
/* free memory */
my_free(old_plugin_output);
log_debug_info(DEBUGL_CHECKS, 1, "* Sync host check done: new state=%d\n", hst->current_state);
/* high resolution end time for event broker */
gettimeofday(&end_time, NULL);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, hst->current_state, hst->state_type, start_time, end_time, hst->host_check_command, hst->latency, hst->execution_time, host_check_timeout, FALSE, hst->current_state, hst->processed_command, hst->plugin_output, hst->long_plugin_output, hst->perf_data, NULL);
#endif
return result;
}
/* run an "alive" check on a host */
/* on-demand host checks will use this... */
int <API key>(host *hst) {
icinga_macros mac;
int result = STATE_OK;
int return_result = HOST_UP;
char *processed_command = NULL;
char *raw_command = NULL;
struct timeval start_time;
struct timeval end_time;
char *temp_ptr;
int early_timeout = FALSE;
double exectime;
char *temp_plugin_output = NULL;
#ifdef USE_EVENT_BROKER
int neb_result = OK;
#endif
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
if (hst == NULL)
return HOST_DOWN;
log_debug_info(DEBUGL_CHECKS, 0, "** Executing sync check of host '%s'...\n", hst->name);
#ifdef USE_EVENT_BROKER
/* initialize start/end times */
start_time.tv_sec = 0L;
start_time.tv_usec = 0L;
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
/* send data to event broker */
neb_result = broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, hst->current_state, hst->state_type, start_time, end_time, hst->host_check_command, hst->latency, 0.0, host_check_timeout, FALSE, 0, NULL, NULL, NULL, NULL, NULL);
/* neb module wants to cancel the host check - return the current state of the host */
if (neb_result == <API key>)
return hst->current_state;
/* neb module wants to override the host check - perhaps it will check the host itself */
/* NOTE: if a module does this, it must check the status of the host and populate the data structures BEFORE it returns from the callback! */
if (neb_result == <API key>)
return hst->current_state;
#endif
/* grab the host macros */
memset(&mac, 0, sizeof(mac));
grab_host_macros_r(&mac, hst);
/* high resolution start time for event broker */
gettimeofday(&start_time, NULL);
/* get the last host check time */
time(&hst->last_check);
/* get the raw command line */
<API key>(&mac, hst->check_command_ptr, hst->host_check_command, &raw_command, 0);
if (raw_command == NULL) {
<API key>(&mac);
return ERROR;
}
/* process any macros contained in the argument */
process_macros_r(&mac, raw_command, &processed_command, 0);
if (processed_command == NULL) {
<API key>(&mac);
return ERROR;
}
my_free(hst->processed_command);
hst->processed_command = strdup(processed_command);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, return_result, hst->state_type, start_time, end_time, hst->host_check_command, 0.0, 0.0, host_check_timeout, early_timeout, result, processed_command, hst->plugin_output, hst->long_plugin_output, hst->perf_data, NULL);
#endif
log_debug_info(DEBUGL_COMMANDS, 1, "Raw host check command: %s\n", raw_command);
log_debug_info(DEBUGL_COMMANDS, 0, "Processed host check ommand: %s\n", processed_command);
/* clear plugin output and performance data buffers */
my_free(hst->plugin_output);
my_free(hst->long_plugin_output);
my_free(hst->perf_data);
/* run the host check command */
result = my_system_r(&mac, processed_command, host_check_timeout, &early_timeout, &exectime, &temp_plugin_output, <API key>);
<API key>(&mac);
/* if the check timed out, report an error */
if (early_timeout == TRUE) {
my_free(temp_plugin_output);
dummy = asprintf(&temp_plugin_output, "Host check timed out after %d seconds\n", host_check_timeout);
/* log the timeout */
logit(<API key>, TRUE, "Warning: Host check command '%s' for host '%s' timed out after %d seconds\n", processed_command, hst->name, host_check_timeout);
}
/* calculate total execution time */
hst->execution_time = exectime;
/* record check type */
hst->check_type = HOST_CHECK_ACTIVE;
/* parse the output: short and long output, and perf data */
parse_check_output(temp_plugin_output, &hst->plugin_output, &hst->long_plugin_output, &hst->perf_data, TRUE, TRUE);
/* free memory */
my_free(temp_plugin_output);
my_free(raw_command);
my_free(processed_command);
/* a NULL host check command means we should assume the host is UP */
if (hst->host_check_command == NULL) {
my_free(hst->plugin_output);
hst->plugin_output = (char *)strdup("(Host assumed to be UP)");
result = STATE_OK;
}
/* make sure we have some data */
if (hst->plugin_output == NULL || !strcmp(hst->plugin_output, "")) {
my_free(hst->plugin_output);
hst->plugin_output = (char *)strdup("(No output returned from host check)");
}
/* replace semicolons in plugin output (but not performance data) with colons */
if ((temp_ptr = hst->plugin_output)) {
while ((temp_ptr = strchr(temp_ptr, ';')))
* temp_ptr = ':';
}
/* if we're not doing aggressive host checking, let WARNING states indicate the host is up (fake the result to be STATE_OK) */
if (<API key> == FALSE && result == STATE_WARNING)
result = STATE_OK;
if (result == STATE_OK)
return_result = HOST_UP;
else
return_result = HOST_DOWN;
/* high resolution end time for event broker */
gettimeofday(&end_time, NULL);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, return_result, hst->state_type, start_time, end_time, hst->host_check_command, 0.0, exectime, host_check_timeout, early_timeout, result, processed_command, hst->plugin_output, hst->long_plugin_output, hst->perf_data, NULL);
#endif
log_debug_info(DEBUGL_CHECKS, 0, "** Sync host check done: state=%d\n", return_result);
return return_result;
}
/* run a scheduled host check asynchronously */
int <API key>(host *hst, int check_options, double latency) {
int result = OK;
time_t current_time = 0L;
time_t preferred_time = 0L;
time_t next_valid_time = 0L;
int time_is_valid = TRUE;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
if (hst == NULL)
return ERROR;
log_debug_info(DEBUGL_CHECKS, 0, "Attempting to run scheduled check of host '%s': check options=%d, latency=%lf\n", hst->name, check_options, latency);
/*
* reset the next_check_event so we know it's
* no longer in the scheduling queue
* and can't conflict
*/
hst->next_check_event = NULL;
/* attempt to run the check */
result = <API key>(hst, check_options, latency, TRUE, TRUE, &time_is_valid, &preferred_time);
/* an error occurred, so reschedule the check */
if (result == ERROR) {
log_debug_info(DEBUGL_CHECKS, 1, "Unable to run scheduled host check at this time\n");
/* only attempt to (re)schedule checks that should get checked... */
if (hst->should_be_scheduled == TRUE) {
/* get current time */
time(¤t_time);
/* determine next time we should check the host if needed */
/* if host has no check interval, schedule it again for 5 minutes from now */
if (current_time >= preferred_time)
preferred_time = current_time + ((hst->check_interval <= 0) ? 300 : (hst->check_interval * interval_length));
/* make sure we rescheduled the next host check at a valid time */
get_next_valid_time(preferred_time, &next_valid_time, hst->check_period_ptr);
/* the host could not be rescheduled properly - set the next check time for next week */
if (time_is_valid == FALSE && next_valid_time == preferred_time) {
/*
hst->next_check=(time_t)(next_valid_time+(60*60*24*365));
hst->should_be_scheduled=FALSE;
*/
hst->next_check = (time_t)(next_valid_time + (60 * 60 * 24 * 7));
logit(<API key>, TRUE, "Warning: Check of host '%s' could not be rescheduled properly. Scheduling check for next week...\n", hst->name);
log_debug_info(DEBUGL_CHECKS, 1, "Unable to find any valid times to reschedule the next host check!\n");
}
/* this service could be rescheduled... */
else {
hst->next_check = next_valid_time;
hst->should_be_scheduled = TRUE;
log_debug_info(DEBUGL_CHECKS, 1, "Rescheduled next host check for %s", ctime(&next_valid_time));
}
}
/* update the status log */
update_host_status(hst, FALSE);
/* reschedule the next host check - unless we couldn't find a valid next check time */
/* 10/19/07 EG - keep original check options */
if (hst->should_be_scheduled == TRUE)
schedule_host_check(hst, hst->next_check, check_options);
return ERROR;
}
return OK;
}
/* perform an asynchronous check of a host */
/* scheduled host checks will use this, as will some checks that result from on-demand checks... */
int <API key>(host *hst, int check_options, double latency, int scheduled_check, int reschedule_check, int *time_is_valid, time_t *preferred_time) {
icinga_macros mac;
char *raw_command = NULL;
char *processed_command = NULL;
struct timeval start_time, end_time;
pid_t pid = 0;
int fork_error = FALSE;
int wait_result = 0;
int pclose_result = 0;
mode_t new_umask = 077;
mode_t old_umask;
char *output_file = NULL;
double old_latency = 0.0;
dbuf checkresult_dbuf;
int dbuf_chunk = 1024;
FILE *fp;
#ifdef USE_EVENT_BROKER
int neb_result = OK;
#endif
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have a host */
if (hst == NULL)
return ERROR;
log_debug_info(DEBUGL_CHECKS, 0, "** Running async check of host '%s'...\n", hst->name);
/* is the host check viable at this time? */
if (<API key>(hst, check_options, time_is_valid, preferred_time) == ERROR)
return ERROR;
/* 08/04/07 EG don't execute a new host check if one is already running */
if (hst->is_executing == TRUE && !(check_options & <API key>)) {
log_debug_info(DEBUGL_CHECKS, 1, "A check of this host is already being executed, so we'll pass for the moment...\n");
return ERROR;
}
#ifdef USE_EVENT_BROKER
/* initialize start/end times */
start_time.tv_sec = 0L;
start_time.tv_usec = 0L;
end_time.tv_sec = 0L;
end_time.tv_usec = 0L;
/* send data to event broker */
neb_result = broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, hst->current_state, hst->state_type, start_time, end_time, hst->host_check_command, hst->latency, 0.0, host_check_timeout, FALSE, 0, NULL, NULL, NULL, NULL, NULL);
/* neb module wants to cancel the host check - the check will be rescheduled for a later time by the scheduling logic */
if (neb_result == <API key>)
return ERROR;
/* neb module wants to override the host check - perhaps it will check the host itself */
/* NOTE: if a module does this, it has to do a lot of the stuff found below to make sure things don't get whacked out of shape! */
if (neb_result == <API key>)
return OK;
#endif
log_debug_info(DEBUGL_CHECKS, 0, "Checking host '%s'...\n", hst->name);
/* clear check options - we don't want old check options retained */
/* only clear options if this was a scheduled check - on demand check options shouldn't affect retained info */
if (scheduled_check == TRUE)
hst->check_options = CHECK_OPTION_NONE;
/* adjust host check attempt */
<API key>(hst, TRUE);
/* set latency (temporarily) for macros and event broker */
old_latency = hst->latency;
hst->latency = latency;
/* grab the host macro variables */
memset(&mac, 0, sizeof(mac));
grab_host_macros_r(&mac, hst);
/* get the raw command line */
<API key>(&mac, hst->check_command_ptr, hst->host_check_command, &raw_command, 0);
if (raw_command == NULL) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 0, "Raw check command for host '%s' was NULL - aborting.\n", hst->name);
return ERROR;
}
/* process any macros contained in the argument */
process_macros_r(&mac, raw_command, &processed_command, 0);
if (processed_command == NULL) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 0, "Processed check command for host '%s' was NULL - aborting.\n", hst->name);
return ERROR;
}
my_free(hst->processed_command);
hst->processed_command = strdup(processed_command);
/* get the command start time */
gettimeofday(&start_time, NULL);
/* set check time for on-demand checks, so they're not incorrectly detected as being orphaned - Luke Ross 5/16/08 */
/* NOTE: 06/23/08 EG not sure if there will be side effects to this or not.... */
if (scheduled_check == FALSE)
hst->next_check = start_time.tv_sec;
/* increment number of host checks that are currently running... */
<API key>++;
/* set the execution flag */
hst->is_executing = TRUE;
/* open a temp file for storing check output */
old_umask = umask(new_umask);
dummy = asprintf(&output_file, "%s/checkXXXXXX", temp_path);
check_result_info.output_file_fd = mkstemp(output_file);
if (check_result_info.output_file_fd >= 0)
check_result_info.output_file_fp = fdopen(check_result_info.output_file_fd, "w");
else {
check_result_info.output_file_fp = NULL;
check_result_info.output_file_fd = -1;
}
umask(old_umask);
log_debug_info(DEBUGL_CHECKS | DEBUGL_IPC, 1, "Check result output will be written to '%s' (fd=%d)\n", output_file, check_result_info.output_file_fd);
/* save check info */
check_result_info.object_check_type = HOST_CHECK;
check_result_info.host_name = (char *)strdup(hst->name);
check_result_info.service_description = NULL;
check_result_info.check_type = HOST_CHECK_ACTIVE;
check_result_info.check_options = check_options;
check_result_info.scheduled_check = scheduled_check;
check_result_info.reschedule_check = reschedule_check;
check_result_info.output_file = (check_result_info.output_file_fd < 0 || output_file == NULL) ? NULL : strdup(output_file);
check_result_info.latency = latency;
check_result_info.start_time = start_time;
check_result_info.finish_time = start_time;
check_result_info.early_timeout = FALSE;
check_result_info.exited_ok = TRUE;
check_result_info.return_code = STATE_OK;
check_result_info.output = NULL;
/* free memory */
my_free(output_file);
/* write initial check info to file */
/* if things go bad later on, the user will at least have something to go on when debugging... */
if (check_result_info.output_file_fp) {
fprintf(check_result_info.output_file_fp, "
fprintf(check_result_info.output_file_fp, "file_time=%lu\n", (unsigned long)check_result_info.start_time.tv_sec);
fprintf(check_result_info.output_file_fp, "\n");
fprintf(check_result_info.output_file_fp, "
fprintf(check_result_info.output_file_fp, "# Time: %s", ctime(&check_result_info.start_time.tv_sec));
fprintf(check_result_info.output_file_fp, "host_name=%s\n", check_result_info.host_name);
fprintf(check_result_info.output_file_fp, "check_type=%d\n", check_result_info.check_type);
fprintf(check_result_info.output_file_fp, "check_options=%d\n", check_result_info.check_options);
fprintf(check_result_info.output_file_fp, "scheduled_check=%d\n", check_result_info.scheduled_check);
fprintf(check_result_info.output_file_fp, "reschedule_check=%d\n", check_result_info.reschedule_check);
fprintf(check_result_info.output_file_fp, "latency=%f\n", hst->latency);
fprintf(check_result_info.output_file_fp, "start_time=%lu.%lu\n", check_result_info.start_time.tv_sec, check_result_info.start_time.tv_usec);
/* flush buffer or we'll end up writing twice when we fork() */
fflush(check_result_info.output_file_fp);
}
/* initialize dynamic buffer for storing plugin output */
dbuf_init(&checkresult_dbuf, dbuf_chunk);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, hst, HOST_CHECK_ACTIVE, hst->current_state, hst->state_type, start_time, end_time, hst->host_check_command, hst->latency, 0.0, host_check_timeout, FALSE, 0, processed_command, NULL, NULL, NULL, NULL);
#endif
/* reset latency (permanent value for this check will get set later) */
hst->latency = old_latency;
/* update check statistics */
update_check_stats((scheduled_check == TRUE) ? <API key> : <API key>, start_time.tv_sec);
update_check_stats(<API key>, start_time.tv_sec);
/* fork a child process */
pid = fork();
/* an error occurred while trying to fork */
if (pid == -1) {
fork_error = TRUE;
/* log an error */
logit(<API key>, TRUE, "Warning: The check of host '%s' could not be performed due to a fork() error: '%s'.\n", hst->name, strerror(errno));
log_debug_info(DEBUGL_CHECKS, 0, "Check of host '%s' could not be performed due to a fork() error: '%s'!\n", hst->name, strerror(errno));
}
/* if we are in the child process... */
else if (pid == 0) {
/* set environment variables */
<API key>(&mac, TRUE);
/* ADDED 11/12/07 EG */
/* close external command file and shut down worker thread */
close_command_file();
/* fork again if we're not in a large installation */
if (<API key> == TRUE) {
/* fork again... */
pid = fork();
/* an error occurred while trying to fork again */
if (pid == -1)
exit(STATE_UNKNOWN);
}
/* the grandchild (or child if large install tweaks are enabled) process should run the host check... */
if (pid == 0 || <API key> == FALSE) {
/* reset signal handling */
reset_sighandler();
/* become the process group leader */
setpgid(0, 0);
/* exit on term signals at this process level */
signal(SIGTERM, SIG_DFL);
/* catch plugins that don't finish in a timely manner */
signal(SIGALRM, <API key>);
alarm(host_check_timeout);
/* disable rotation of the debug file */
max_debug_file_size = 0L;
/* run the plugin check command */
pclose_result = run_check(processed_command, &checkresult_dbuf);
/* reset the alarm and signal handling here */
signal(SIGALRM, SIG_IGN);
alarm(0);
/* get the check finish time */
gettimeofday(&end_time, NULL);
/* record check result info */
check_result_info.finish_time = end_time;
check_result_info.early_timeout = FALSE;
/* test for execution error */
if (pclose_result == -1) {
pclose_result = STATE_UNKNOWN;
check_result_info.return_code = STATE_CRITICAL;
check_result_info.exited_ok = FALSE;
} else {
if (WEXITSTATUS(pclose_result) == 0 && WIFSIGNALED(pclose_result))
check_result_info.return_code = 128 + WTERMSIG(pclose_result);
else
check_result_info.return_code = WEXITSTATUS(pclose_result);
}
/* write check result to file */
if (check_result_info.output_file_fp) {
/* protect against signal races */
fp = check_result_info.output_file_fp;
check_result_info.output_file_fp = NULL;
fprintf(fp, "finish_time=%lu.%lu\n", check_result_info.finish_time.tv_sec, check_result_info.finish_time.tv_usec);
fprintf(fp, "early_timeout=%d\n", check_result_info.early_timeout);
fprintf(fp, "exited_ok=%d\n", check_result_info.exited_ok);
fprintf(fp, "return_code=%d\n", check_result_info.return_code);
fprintf(fp, "output=%s\n", (checkresult_dbuf.buf == NULL) ? "(null)" : checkresult_dbuf.buf);
/* close the temp file */
fclose(fp);
/* move check result to queue directory */
<API key>(check_result_info.output_file);
}
/* free memory */
dbuf_free(&checkresult_dbuf);
my_free(raw_command);
my_free(processed_command);
/* free check result memory */
free_check_result(&check_result_info);
/* return with plugin exit status - not really necessary... */
_exit(pclose_result);
}
/* NOTE: this code is never reached if large install tweaks are enabled... */
/* unset environment variables */
<API key>(&mac, FALSE);
/* free allocated memory */
/* this needs to be done last, so we don't free memory for variables before they're used above */
if (<API key> == TRUE)
free_memory(&mac);
/* parent exits immediately - grandchild process is inherited by the INIT process, so we have no zombie problem... */
_exit(STATE_OK);
}
/* else the parent should wait for the first child to return... */
else if (pid > 0) {
<API key>(&mac);
log_debug_info(DEBUGL_CHECKS, 2, "Host check is executing in child process (pid=%lu)\n", (unsigned long)pid);
/* parent should close output file */
if (check_result_info.output_file_fp)
fclose(check_result_info.output_file_fp);
/* should this be done in first child process (after spawning grandchild) as well? */
/* free memory allocated for IPC functionality */
free_check_result(&check_result_info);
/* free memory */
my_free(raw_command);
my_free(processed_command);
/* wait for the first child to return */
/* if large install tweaks are enabled, we'll clean up the zombie process later */
if (<API key> == TRUE)
wait_result = waitpid(pid, NULL, 0);
}
/* see if we were able to run the check... */
if (fork_error == TRUE)
return ERROR;
return OK;
}
/* process results of an asynchronous host check */
int <API key>(host *temp_host, check_result *queued_check_result) {
time_t current_time;
int result = STATE_OK;
int reschedule_check = FALSE;
char *old_plugin_output = NULL;
char *temp_ptr = NULL;
struct timeval start_time_hires;
struct timeval end_time_hires;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have what we need */
if (temp_host == NULL || queued_check_result == NULL)
return ERROR;
time(¤t_time);
log_debug_info(DEBUGL_CHECKS, 1, "** Handling async check result for host '%s'...\n", temp_host->name);
log_debug_info(DEBUGL_CHECKS, 2, "\tCheck Type: %s\n", (queued_check_result->check_type == HOST_CHECK_ACTIVE) ? "Active" : "Passive");
log_debug_info(DEBUGL_CHECKS, 2, "\tCheck Options: %d\n", queued_check_result->check_options);
log_debug_info(DEBUGL_CHECKS, 2, "\tScheduled Check?: %s\n", (queued_check_result->scheduled_check == TRUE) ? "Yes" : "No");
log_debug_info(DEBUGL_CHECKS, 2, "\tReschedule Check?: %s\n", (queued_check_result->reschedule_check == TRUE) ? "Yes" : "No");
log_debug_info(DEBUGL_CHECKS, 2, "\tExited OK?: %s\n", (queued_check_result->exited_ok == TRUE) ? "Yes" : "No");
log_debug_info(DEBUGL_CHECKS, 2, "\tExec Time: %.3f\n", temp_host->execution_time);
log_debug_info(DEBUGL_CHECKS, 2, "\tLatency: %.3f\n", temp_host->latency);
log_debug_info(DEBUGL_CHECKS, 2, "\tReturn Status: %d\n", queued_check_result->return_code);
log_debug_info(DEBUGL_CHECKS, 2, "\tOutput: %s\n", (queued_check_result == NULL) ? "NULL" : queued_check_result->output);
/* decrement the number of host checks still out there... */
if (queued_check_result->check_type == HOST_CHECK_ACTIVE && <API key> > 0)
<API key>
/* skip this host check results if its passive and we aren't accepting passive check results */
if (queued_check_result->check_type == HOST_CHECK_PASSIVE) {
if (<API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding passive host check result because passive host checks are disabled globally.\n");
return ERROR;
}
if (temp_host-><API key> == FALSE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding passive host check result because passive checks are disabled for this host.\n");
return ERROR;
}
}
/* clear the freshening flag (it would have been set if this host was determined to be stale) */
if (queued_check_result->check_options & <API key>)
temp_host->is_being_freshened = FALSE;
/* DISCARD INVALID FRESHNESS CHECK RESULTS */
/* If a host goes stale, Icinga will initiate a forced check in order to freshen it. There is a race condition whereby a passive check
could arrive between the 1) initiation of the forced check and 2) the time when the forced check result is processed here. This would
make the host fresh again, so we do a quick check to make sure the host is still stale before we accept the check result. */
if ((queued_check_result->check_options & <API key>) && <API key>(temp_host, current_time, FALSE) == TRUE) {
log_debug_info(DEBUGL_CHECKS, 0, "Discarding host freshness check result because the host is currently fresh (race condition avoided).\n");
return OK;
}
/* was this check passive or active? */
temp_host->check_type = (queued_check_result->check_type == HOST_CHECK_ACTIVE) ? HOST_CHECK_ACTIVE : HOST_CHECK_PASSIVE;
/* update check statistics for passive results */
if (queued_check_result->check_type == HOST_CHECK_PASSIVE)
update_check_stats(<API key>, queued_check_result->start_time.tv_sec);
/* should we reschedule the next check of the host? NOTE: this might be overridden later... */
reschedule_check = queued_check_result->reschedule_check;
/* check latency is passed to us for both active and passive checks */
temp_host->latency = queued_check_result->latency;
/* update the execution time for this check (millisecond resolution) */
temp_host->execution_time = (double)((double)(queued_check_result->finish_time.tv_sec - queued_check_result->start_time.tv_sec) + (double)((queued_check_result->finish_time.tv_usec - queued_check_result->start_time.tv_usec) / 1000.0) / 1000.0);
if (temp_host->execution_time < 0.0)
temp_host->execution_time = 0.0;
/* set the checked flag */
temp_host->has_been_checked = TRUE;
/* clear the execution flag if this was an active check */
if (queued_check_result->check_type == HOST_CHECK_ACTIVE)
temp_host->is_executing = FALSE;
/* get the last check time */
temp_host->last_check = queued_check_result->start_time.tv_sec;
/* was this check passive or active? */
temp_host->check_type = (queued_check_result->check_type == HOST_CHECK_ACTIVE) ? HOST_CHECK_ACTIVE : HOST_CHECK_PASSIVE;
/* save the old host state */
temp_host->last_state = temp_host->current_state;
if (temp_host->state_type == HARD_STATE)
temp_host->last_hard_state = temp_host->current_state;
/* save old plugin output */
if (temp_host->plugin_output)
old_plugin_output = (char *)strdup(temp_host->plugin_output);
/* clear the old plugin output and perf data buffers */
my_free(temp_host->plugin_output);
my_free(temp_host->long_plugin_output);
my_free(temp_host->perf_data);
/* parse check output to get: (1) short output, (2) long output, (3) perf data */
parse_check_output(queued_check_result->output, &temp_host->plugin_output, &temp_host->long_plugin_output, &temp_host->perf_data, TRUE, TRUE);
/* make sure we have some data */
if (temp_host->plugin_output == NULL || !strcmp(temp_host->plugin_output, "")) {
my_free(temp_host->plugin_output);
temp_host->plugin_output = (char *)strdup("(No output returned from host check)");
}
/* replace semicolons in plugin output (but not performance data) with colons */
if ((temp_ptr = temp_host->plugin_output)) {
while ((temp_ptr = strchr(temp_ptr, ';')))
* temp_ptr = ':';
}
log_debug_info(DEBUGL_CHECKS, 2, "Parsing check output...\n");
log_debug_info(DEBUGL_CHECKS, 2, "Short Output: %s\n", (temp_host->plugin_output == NULL) ? "NULL" : temp_host->plugin_output);
log_debug_info(DEBUGL_CHECKS, 2, "Long Output: %s\n", (temp_host->long_plugin_output == NULL) ? "NULL" : temp_host->long_plugin_output);
log_debug_info(DEBUGL_CHECKS, 2, "Perf Data: %s\n", (temp_host->perf_data == NULL) ? "NULL" : temp_host->perf_data);
/* get the unprocessed return code */
/* NOTE: for passive checks, this is the final/processed state */
result = queued_check_result->return_code;
/* adjust return code (active checks only) */
if (queued_check_result->check_type == HOST_CHECK_ACTIVE) {
/* if there was some error running the command, just skip it (this shouldn't be happening) */
if (queued_check_result->exited_ok == FALSE) {
logit(<API key>, TRUE, "Warning: Check of host '%s' did not exit properly!\n", temp_host->name);
my_free(temp_host->plugin_output);
my_free(temp_host->long_plugin_output);
my_free(temp_host->perf_data);
temp_host->plugin_output = (char *)strdup("(Host check did not exit properly)");
result = STATE_CRITICAL;
}
/* make sure the return code is within bounds */
else if (queued_check_result->return_code < 0 || queued_check_result->return_code > 3) {
logit(<API key>, TRUE, "Warning: Return code of %d for check of host '%s' was out of bounds.%s\n", queued_check_result->return_code, temp_host->name, (queued_check_result->return_code == 126 || queued_check_result->return_code == 127) ? " Make sure the plugin you're trying to run actually exists." : "");
my_free(temp_host->plugin_output);
my_free(temp_host->long_plugin_output);
my_free(temp_host->perf_data);
dummy = asprintf(&temp_host->plugin_output, "(Return code of %d is out of bounds%s)", queued_check_result->return_code, (queued_check_result->return_code == 126 || queued_check_result->return_code == 127) ? " - plugin may be missing" : "");
result = STATE_CRITICAL;
}
/* a NULL host check command means we should assume the host is UP */
if (temp_host->host_check_command == NULL) {
my_free(temp_host->plugin_output);
temp_host->plugin_output = (char *)strdup("(Host assumed to be UP)");
result = STATE_OK;
}
}
/* translate return code to basic UP/DOWN state - the DOWN/UNREACHABLE state determination is made later */
/* NOTE: only do this for active checks - passive check results already have the final state */
if (queued_check_result->check_type == HOST_CHECK_ACTIVE) {
/* if we're not doing aggressive host checking, let WARNING states indicate the host is up (fake the result to be STATE_OK) */
if (<API key> == FALSE && result == STATE_WARNING)
result = STATE_OK;
/* OK states means the host is UP */
if (result == STATE_OK)
result = HOST_UP;
/* any problem state indicates the host is not UP */
else
result = HOST_DOWN;
}
/* process the host check result */
<API key>(temp_host, result, old_plugin_output, CHECK_OPTION_NONE, reschedule_check, TRUE, <API key>);
/* free memory */
my_free(old_plugin_output);
log_debug_info(DEBUGL_CHECKS, 1, "** Async check result for host '%s' handled: new state=%d\n", temp_host->name, temp_host->current_state);
/* high resolution start time for event broker */
start_time_hires = queued_check_result->start_time;
/* high resolution end time for event broker */
gettimeofday(&end_time_hires, NULL);
#ifdef USE_EVENT_BROKER
/* send data to event broker */
broker_host_check(<API key>, NEBFLAG_NONE, NEBATTR_NONE, temp_host, temp_host->check_type, temp_host->current_state, temp_host->state_type, start_time_hires, end_time_hires, temp_host->host_check_command, temp_host->latency, temp_host->execution_time, host_check_timeout, queued_check_result->early_timeout, queued_check_result->return_code, temp_host->processed_command, temp_host->plugin_output, temp_host->long_plugin_output, temp_host->perf_data, NULL);
#endif
return OK;
}
/* processes the result of a synchronous or asynchronous host check */
int <API key>(host *hst, int new_state, char *old_plugin_output, int check_options, int reschedule_check, int use_cached_result, unsigned long <API key>) {
hostsmember *temp_hostsmember = NULL;
host *child_host = NULL;
host *parent_host = NULL;
host *master_host = NULL;
host *temp_host = NULL;
hostdependency *temp_dependency = NULL;
objectlist *check_hostlist = NULL;
objectlist *hostlist_item = NULL;
int parent_state = HOST_UP;
time_t current_time = 0L;
time_t next_check = 0L;
time_t preferred_time = 0L;
time_t next_valid_time = 0L;
int run_async_check = TRUE;
void *ptr = NULL;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
log_debug_info(DEBUGL_CHECKS, 1, "HOST: %s, ATTEMPT=%d/%d, CHECK TYPE=%s, STATE TYPE=%s, OLD STATE=%d, NEW STATE=%d\n", hst->name, hst->current_attempt, hst->max_attempts, (hst->check_type == HOST_CHECK_ACTIVE) ? "ACTIVE" : "PASSIVE", (hst->state_type == HARD_STATE) ? "HARD" : "SOFT", hst->current_state, new_state);
/* get the current time */
time(¤t_time);
/* default next check time */
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
/* we have to adjust current attempt # for passive checks, as it isn't done elsewhere */
if (hst->check_type == HOST_CHECK_PASSIVE && <API key> == TRUE)
<API key>(hst, FALSE);
/* log passive checks - we need to do this here, as some my bypass external commands by getting dropped in checkresults dir */
if (hst->check_type == HOST_CHECK_PASSIVE) {
if (log_passive_checks == TRUE)
logit(NSLOG_PASSIVE_CHECK, FALSE, "PASSIVE HOST CHECK: %s;%d;%s\n", hst->name, new_state, hst->plugin_output);
}
if (hst->current_state != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Host was DOWN/UNREACHABLE.\n");
/* the host just recovered! */
if (new_state == HOST_UP) {
/* set the current state */
hst->current_state = HOST_UP;
/* set the state type */
/* set state type to HARD for passive checks and active checks that were previously in a HARD STATE */
if (hst->state_type == HARD_STATE || (hst->check_type == HOST_CHECK_PASSIVE && <API key> == FALSE))
hst->state_type = HARD_STATE;
else
hst->state_type = SOFT_STATE;
log_debug_info(DEBUGL_CHECKS, 1, "Host experienced a %s recovery (it's now UP).\n", (hst->state_type == HARD_STATE) ? "HARD" : "SOFT");
/* reschedule the next check of the host at the normal interval */
reschedule_check = TRUE;
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
/* propagate checks to immediate parents if they are not already UP */
/* we do this because a parent host (or grandparent) may have recovered somewhere and we should catch the recovery as soon as possible */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating checks to parent host(s)...\n");
for (temp_hostsmember = hst->parent_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((parent_host = temp_hostsmember->host_ptr) == NULL)
continue;
if (parent_host->current_state != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Check of parent host '%s' queued.\n", parent_host->name);
<API key>(&check_hostlist, (void *)parent_host);
}
}
/* propagate checks to immediate children if they are not already UP */
/* we do this because children may currently be UNREACHABLE, but may (as a result of this recovery) switch to UP or DOWN states */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating checks to child host(s)...\n");
for (temp_hostsmember = hst->child_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((child_host = temp_hostsmember->host_ptr) == NULL)
continue;
if (child_host->current_state != HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Check of child host '%s' queued.\n", child_host->name);
<API key>(&check_hostlist, (void *)child_host);
}
}
}
/* we're still in a problem state... */
else {
log_debug_info(DEBUGL_CHECKS, 1, "Host is still DOWN/UNREACHABLE.\n");
/* passive checks are treated as HARD states by default... */
if (hst->check_type == HOST_CHECK_PASSIVE && <API key> == FALSE) {
/* set the state type */
hst->state_type = HARD_STATE;
/* reset the current attempt */
hst->current_attempt = 1;
}
/* active checks and passive checks (treated as SOFT states) */
else {
/* set the state type */
/* we've maxed out on the retries */
if (hst->current_attempt == hst->max_attempts)
hst->state_type = HARD_STATE;
/* the host was in a hard problem state before, so it still is now */
else if (hst->current_attempt == 1)
hst->state_type = HARD_STATE;
/* the host is in a soft state and the check will be retried */
else
hst->state_type = SOFT_STATE;
}
/* make a determination of the host's state */
/* translate host state between DOWN/UNREACHABLE (only for passive checks if enabled) */
hst->current_state = new_state;
if (hst->check_type == HOST_CHECK_ACTIVE || <API key> == TRUE)
hst->current_state = <API key>(hst);
/* reschedule the next check if the host state changed */
if (hst->last_state != hst->current_state || hst->last_hard_state != hst->current_state) {
reschedule_check = TRUE;
/* schedule a re-check of the host at the retry interval because we can't determine its final state yet... */
if (hst->state_type == SOFT_STATE)
next_check = (unsigned long)(current_time + (hst->retry_interval * interval_length));
/* host has maxed out on retries (or was previously in a hard problem state), so reschedule the next check at the normal interval */
else
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
}
}
}
else {
log_debug_info(DEBUGL_CHECKS, 1, "Host was UP.\n");
/* either the host never went down since last check */
if (new_state == HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Host is still UP.\n");
/* set the current state */
hst->current_state = HOST_UP;
/* set the state type */
hst->state_type = HARD_STATE;
/* reschedule the next check at the normal interval */
if (reschedule_check == TRUE)
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
}
else {
log_debug_info(DEBUGL_CHECKS, 1, "Host is now DOWN/UNREACHABLE.\n");
if (hst->max_attempts == 1) {
log_debug_info(DEBUGL_CHECKS, 1, "Max attempts = 1!.\n");
/* set the state type */
hst->state_type = HARD_STATE;
/* host has maxed out on retries, so reschedule the next check at the normal interval */
reschedule_check = TRUE;
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
/* we need to run SYNCHRONOUS checks of all parent hosts to accurately determine the state of this host */
/* this is extremely inefficient (reminiscent of Icinga 2.x logic), but there's no other good way around it */
/* check all parent hosts to see if we're DOWN or UNREACHABLE */
/* only do this for ACTIVE checks, as PASSIVE checks contain a pre-determined state */
if (hst->check_type == HOST_CHECK_ACTIVE) {
log_debug_info(DEBUGL_CHECKS, 1, "** WARNING: Max attempts = 1, so we have to run serial checks of all parent hosts!\n");
for (temp_hostsmember = hst->parent_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((parent_host = temp_hostsmember->host_ptr) == NULL)
continue;
log_debug_info(DEBUGL_CHECKS, 1, "Running serial check parent host '%s'...\n", parent_host->name);
/* run an immediate check of the parent host */
<API key>(parent_host, &parent_state, check_options, use_cached_result, <API key>);
/* bail out as soon as we find one parent host that is UP */
if (parent_state == HOST_UP) {
log_debug_info(DEBUGL_CHECKS, 1, "Parent host is UP, so this one is DOWN.\n");
/* set the current state */
hst->current_state = HOST_DOWN;
break;
}
}
if (temp_hostsmember == NULL) {
/* host has no parents, so its up */
if (hst->parent_hosts == NULL) {
log_debug_info(DEBUGL_CHECKS, 1, "Host has no parents, so it's DOWN.\n");
hst->current_state = HOST_DOWN;
} else {
/* no parents were up, so this host is UNREACHABLE */
log_debug_info(DEBUGL_CHECKS, 1, "No parents were UP, so this host is UNREACHABLE.\n");
hst->current_state = HOST_UNREACHABLE;
}
}
}
/* set the host state for passive checks */
else {
/* set the state */
hst->current_state = new_state;
/* translate host state between DOWN/UNREACHABLE for passive checks (if enabled) */
/* make a determination of the host's state */
if (<API key> == TRUE)
hst->current_state = <API key>(hst);
}
/* propagate checks to immediate children if they are not UNREACHABLE */
/* we do this because we may now be blocking the route to child hosts */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating check to immediate non-UNREACHABLE child hosts...\n");
for (temp_hostsmember = hst->child_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((child_host = temp_hostsmember->host_ptr) == NULL)
continue;
if (child_host->current_state != HOST_UNREACHABLE) {
log_debug_info(DEBUGL_CHECKS, 1, "Check of child host '%s' queued.\n", child_host->name);
<API key>(&check_hostlist, (void *)child_host);
}
}
}
else {
/* active and (in some cases) passive check results are treated as SOFT states */
if (hst->check_type == HOST_CHECK_ACTIVE || <API key> == TRUE) {
/* set the state type */
hst->state_type = SOFT_STATE;
}
/* by default, passive check results are treated as HARD states */
else {
/* set the state type */
hst->state_type = HARD_STATE;
/* reset the current attempt */
hst->current_attempt = 1;
}
/* make a (in some cases) preliminary determination of the host's state */
/* translate host state between DOWN/UNREACHABLE (for passive checks only if enabled) */
hst->current_state = new_state;
if (hst->check_type == HOST_CHECK_ACTIVE || <API key> == TRUE)
hst->current_state = <API key>(hst);
/* reschedule a check of the host */
reschedule_check = TRUE;
/* schedule a re-check of the host at the retry interval because we can't determine its final state yet... */
if (hst->check_type == HOST_CHECK_ACTIVE || <API key> == TRUE)
next_check = (unsigned long)(current_time + (hst->retry_interval * interval_length));
/* schedule a re-check of the host at the normal interval */
else
next_check = (unsigned long)(current_time + (hst->check_interval * interval_length));
/* propagate checks to immediate parents if they are UP */
/* we do this because a parent host (or grandparent) may have gone down and blocked our route */
/* checking the parents ASAP will allow us to better determine the final state (DOWN/UNREACHABLE) of this host later */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating checks to immediate parent hosts that are UP...\n");
for (temp_hostsmember = hst->parent_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((parent_host = temp_hostsmember->host_ptr) == NULL)
continue;
if (parent_host->current_state == HOST_UP) {
<API key>(&check_hostlist, (void *)parent_host);
log_debug_info(DEBUGL_CHECKS, 1, "Check of host '%s' queued.\n", parent_host->name);
}
}
/* propagate checks to immediate children if they are not UNREACHABLE */
/* we do this because we may now be blocking the route to child hosts */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating checks to immediate non-UNREACHABLE child hosts...\n");
for (temp_hostsmember = hst->child_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((child_host = temp_hostsmember->host_ptr) == NULL)
continue;
if (child_host->current_state != HOST_UNREACHABLE) {
log_debug_info(DEBUGL_CHECKS, 1, "Check of child host '%s' queued.\n", child_host->name);
<API key>(&check_hostlist, (void *)child_host);
}
}
/* check dependencies on second to last host check */
if (<API key> == TRUE && hst->current_attempt == (hst->max_attempts - 1)) {
/* propagate checks to hosts that THIS ONE depends on for notifications AND execution */
/* we do to help ensure that the dependency checks are accurate before it comes time to notify */
log_debug_info(DEBUGL_CHECKS, 1, "Propagating predictive dependency checks to hosts this one depends on...\n");
for (temp_dependency = <API key>(hst->name, &ptr); temp_dependency != NULL; temp_dependency = <API key>(hst->name, &ptr)) {
if (temp_dependency->dependent_host_ptr == hst && temp_dependency->master_host_ptr != NULL) {
master_host = (host *)temp_dependency->master_host_ptr;
log_debug_info(DEBUGL_CHECKS, 1, "Check of host '%s' queued.\n", master_host->name);
<API key>(&check_hostlist, (void *)master_host);
}
}
}
}
}
}
log_debug_info(DEBUGL_CHECKS, 1, "<API key>() Host: %s, Attempt=%d/%d, Type=%s, Final State=%d\n", hst->name, hst->current_attempt, hst->max_attempts, (hst->state_type == HARD_STATE) ? "HARD" : "SOFT", hst->current_state);
/* handle the host state */
handle_host_state(hst);
log_debug_info(DEBUGL_CHECKS, 1, "<API key>() Host: %s, Attempt=%d/%d, Type=%s, Final State=%d\n", hst->name, hst->current_attempt, hst->max_attempts, (hst->state_type == HARD_STATE) ? "HARD" : "SOFT", hst->current_state);
/* STALKING
* if we're stalking this state type and state was
* not already logged AND the plugin output changed
* since last check, log it or run event handlers or
* notify now..
*/
if (hst->last_state == hst->current_state && compare_strings(old_plugin_output, hst->plugin_output)) {
if (hst->current_state == HOST_UP && hst->stalk_on_up == TRUE) {
log_host_event(hst);
/* should we run event handlers ? */
if (<API key> == TRUE)
handle_host_event(hst);
/* should we notify all contacts ? */
if (<API key> == TRUE)
host_notification(hst, <API key>, NULL, NULL, <API key>);
/* DOWN */
} else if (hst->current_state == HOST_DOWN && hst->stalk_on_down == TRUE) {
log_host_event(hst);
/* should we run event handlers ? */
if (<API key> == TRUE)
handle_host_event(hst);
/* should we notify all contacts ? */
if (<API key> == TRUE)
host_notification(hst, <API key>, NULL, NULL, <API key>);
/* UNREACHABLE */
} else if (hst->current_state == HOST_UNREACHABLE && hst-><API key> == TRUE) {
log_host_event(hst);
/* should we run event handlers ? */
if (<API key> == TRUE)
handle_host_event(hst);
/* should we notify all contacts ? */
if (<API key> == TRUE)
host_notification(hst, <API key>, NULL, NULL, <API key>);
}
}
/* check to see if the associated host is flapping */
<API key>(hst, TRUE, TRUE, TRUE);
/* reschedule the next check of the host (usually ONLY for scheduled, active checks, unless overridden above) */
if (reschedule_check == TRUE) {
log_debug_info(DEBUGL_CHECKS, 1, "Rescheduling next check of host at %s", ctime(&next_check));
/* default is to reschedule host check unless a test below fails... */
hst->should_be_scheduled = TRUE;
/* get the new current time */
time(¤t_time);
/* make sure we don't get ourselves into too much trouble... */
if (current_time > next_check)
hst->next_check = current_time;
else
hst->next_check = next_check;
/* make sure we rescheduled the next service check at a valid time */
preferred_time = hst->next_check;
get_next_valid_time(preferred_time, &next_valid_time, hst->check_period_ptr);
hst->next_check = next_valid_time;
/* hosts with non-recurring intervals do not get rescheduled if we're in a HARD or UP state */
if (hst->check_interval == 0 && (hst->state_type == HARD_STATE || hst->current_state == HOST_UP))
hst->should_be_scheduled = FALSE;
/* host with active checks disabled do not get rescheduled */
if (hst->checks_enabled == FALSE)
hst->should_be_scheduled = FALSE;
/* schedule a non-forced check if we can */
if (hst->should_be_scheduled == TRUE) {
schedule_host_check(hst, hst->next_check, CHECK_OPTION_NONE);
}
}
/* update host status - for both active (scheduled) and passive (non-scheduled) hosts */
update_host_status(hst, FALSE);
/* run async checks of all hosts we added above */
/* don't run a check if one is already executing or we can get by with a cached state */
for (hostlist_item = check_hostlist; hostlist_item != NULL; hostlist_item = hostlist_item->next) {
run_async_check = TRUE;
temp_host = (host *)hostlist_item->object_ptr;
log_debug_info(DEBUGL_CHECKS, 2, "ASYNC CHECK OF HOST: %s, CURRENTTIME: %lu, LASTHOSTCHECK: %lu, CACHEDTIMEHORIZON: %lu, USECACHEDRESULT: %d, ISEXECUTING: %d\n", temp_host->name, current_time, temp_host->last_check, <API key>, use_cached_result, temp_host->is_executing);
if (use_cached_result == TRUE && ((current_time - temp_host->last_check) <= <API key>))
run_async_check = FALSE;
if (temp_host->is_executing == TRUE)
run_async_check = FALSE;
if (run_async_check == TRUE)
<API key>(temp_host, CHECK_OPTION_NONE, 0.0, FALSE, FALSE, NULL, NULL);
}
free_objectlist(&check_hostlist);
return OK;
}
/* checks viability of performing a host check */
int <API key>(host *hst, int check_options, int *time_is_valid, time_t *new_time) {
int result = OK;
int perform_check = TRUE;
time_t current_time = 0L;
time_t preferred_time = 0L;
int check_interval = 0;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
/* make sure we have a host */
if (hst == NULL)
return ERROR;
/* get the check interval to use if we need to reschedule the check */
if (hst->state_type == SOFT_STATE && hst->current_state != HOST_UP)
check_interval = (hst->retry_interval * interval_length);
else
check_interval = (hst->check_interval * interval_length);
/* make sure check interval is positive - otherwise use 5 minutes out for next check */
if (check_interval <= 0)
check_interval = 300;
/* get the current time */
time(¤t_time);
/* initialize the next preferred check time */
preferred_time = current_time;
/* can we check the host right now? */
if (!(check_options & <API key>)) {
/* if checks of the host are currently disabled... */
if (hst->checks_enabled == FALSE) {
preferred_time = current_time + check_interval;
perform_check = FALSE;
}
/* make sure this is a valid time to check the host */
if (<API key>((unsigned long)current_time, hst->check_period_ptr) == ERROR) {
preferred_time = current_time;
if (time_is_valid)
*time_is_valid = FALSE;
perform_check = FALSE;
}
/* check host dependencies for execution */
if (<API key>(hst, <API key>) == DEPENDENCIES_FAILED) {
preferred_time = current_time + check_interval;
perform_check = FALSE;
}
}
/* pass back the next viable check time */
if (new_time)
*new_time = preferred_time;
result = (perform_check == TRUE) ? OK : ERROR;
return result;
}
/* adjusts current host check attempt before a new check is performed */
int <API key>(host *hst, int is_active) {
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
if (hst == NULL)
return ERROR;
log_debug_info(DEBUGL_CHECKS, 2, "Adjusting check attempt number for host '%s': current attempt=%d/%d, state=%d, state type=%d\n", hst->name, hst->current_attempt, hst->max_attempts, hst->current_state, hst->state_type);
/* if host is in a hard state, reset current attempt number */
if (hst->state_type == HARD_STATE)
hst->current_attempt = 1;
/* if host is in a soft UP state, reset current attempt number (active checks only) */
else if (is_active == TRUE && hst->state_type == SOFT_STATE && hst->current_state == HOST_UP)
hst->current_attempt = 1;
/* increment current attempt number */
else if (hst->current_attempt < hst->max_attempts)
hst->current_attempt++;
log_debug_info(DEBUGL_CHECKS, 2, "New check attempt number = %d\n", hst->current_attempt);
return OK;
}
/* determination of the host's state based on route availability*/
/* used only to determine difference between DOWN and UNREACHABLE states */
int <API key>(host *hst) {
int state = HOST_DOWN;
host *parent_host = NULL;
hostsmember *temp_hostsmember = NULL;
log_debug_info(DEBUGL_FUNCTIONS, 0, "<API key>()\n");
if (hst == NULL)
return HOST_DOWN;
log_debug_info(DEBUGL_CHECKS, 2, "Determining state of host '%s': current state=%d\n", hst->name, hst->current_state);
/* host is UP - no translation needed */
if (hst->current_state == HOST_UP) {
state = HOST_UP;
log_debug_info(DEBUGL_CHECKS, 2, "Host is UP, no state translation needed.\n");
}
/* host has no parents, so it is DOWN */
else if (hst->parent_hosts == NULL) {
state = HOST_DOWN;
log_debug_info(DEBUGL_CHECKS, 2, "Host has no parents, so it is DOWN.\n");
}
/* check all parent hosts to see if we're DOWN or UNREACHABLE */
else {
for (temp_hostsmember = hst->parent_hosts; temp_hostsmember != NULL; temp_hostsmember = temp_hostsmember->next) {
if ((parent_host = temp_hostsmember->host_ptr) == NULL)
continue;
/* bail out as soon as we find one parent host that is UP */
if (parent_host->current_state == HOST_UP) {
/* set the current state */
state = HOST_DOWN;
log_debug_info(DEBUGL_CHECKS, 2, "At least one parent (%s) is up, so host is DOWN.\n", parent_host->name);
break;
}
}
/* no parents were up, so this host is UNREACHABLE */
if (temp_hostsmember == NULL) {
state = HOST_UNREACHABLE;
log_debug_info(DEBUGL_CHECKS, 2, "No parents were up, so host is UNREACHABLE.\n");
}
}
return state;
}
/* top level host state handler - occurs after every host check (soft/hard and active/passive) */
int handle_host_state(host *hst) {
int state_change = FALSE;
int hard_state_change = FALSE;
time_t current_time = 0L;
log_debug_info(DEBUGL_FUNCTIONS, 0, "handle_host_state()\n");
/* get current time */
time(¤t_time);
/* obsess over this host check */
<API key>(hst);
/* update performance data */
<API key>(hst);
/* record latest time for current state */
switch (hst->current_state) {
case HOST_UP:
hst->last_time_up = current_time;
break;
case HOST_DOWN:
hst->last_time_down = current_time;
break;
case HOST_UNREACHABLE:
hst-><API key> = current_time;
break;
default:
break;
}
/* has the host state changed? */
if (hst->last_state != hst->current_state || (hst->current_state == HOST_UP && hst->state_type == SOFT_STATE))
state_change = TRUE;
if (hst->current_attempt >= hst->max_attempts && hst->last_hard_state != hst->current_state)
hard_state_change = TRUE;
/* if the host state has changed... */
if (state_change == TRUE || hard_state_change == TRUE) {
/* reset the next and last notification times */
hst-><API key> = (time_t)0;
hst-><API key> = (time_t)0;
/* reset notification suppression option */
hst-><API key> = FALSE;
/* reset the acknowledgement flag if necessary */
if (hst-><API key> == <API key> && (state_change == TRUE || hard_state_change == FALSE)) {
hst-><API key> = FALSE;
hst-><API key> = <API key>;
/* remove any non-persistant comments associated with the ack */
<API key>(hst);
} else if (hst-><API key> == <API key> && hst->current_state == HOST_UP) {
hst-><API key> = FALSE;
hst-><API key> = <API key>;
/* remove any non-persistant comments associated with the ack */
<API key>(hst);
}
}
/* Not sure about this, but is old behaviour */
if (hst->last_hard_state != hst->current_state)
hard_state_change = TRUE;
if (state_change == TRUE || hard_state_change == TRUE) {
/* update last state change times */
hst->last_state_change = current_time;
if (hst->state_type == HARD_STATE)
hst-><API key> = current_time;
/* update the event id */
hst->last_event_id = hst->current_event_id;
hst->current_event_id = next_event_id;
next_event_id++;
/* update the problem id when transitioning to a problem state */
if (hst->last_state == HOST_UP) {
/* don't reset last problem id, or it will be zero the next time a problem is encountered */
/*hst->last_problem_id=hst->current_problem_id;*/
hst->current_problem_id = next_problem_id;
next_problem_id++;
}
/* clear the problem id when transitioning from a problem state to an UP state */
if (hst->current_state == HOST_UP) {
hst->last_problem_id = hst->current_problem_id;
hst->current_problem_id = 0L;
}
/* write the host state change to the main log file */
if (hst->state_type == HARD_STATE || (hst->state_type == SOFT_STATE && log_host_retries == TRUE))
log_host_event(hst);
/* check for start of flexible (non-fixed) scheduled downtime */
/* CHANGED 08-05-2010 EG flex downtime can now start on soft states */
/*if(hst->state_type==HARD_STATE)*/
<API key>(hst);
/* notify contacts about the recovery or problem if its a "hard" state */
if (hst->state_type == HARD_STATE) {
#ifdef <API key>
hst-><API key> = 0;
hst-><API key> = 0;
#endif
host_notification(hst, NOTIFICATION_NORMAL, NULL, NULL, <API key>);
}
/* handle the host state change */
handle_host_event(hst);
/* the host just recovered, so reset the current host attempt */
if (hst->current_state == HOST_UP)
hst->current_attempt = 1;
/* the host recovered, so reset the current notification number and state flags (after the recovery notification has gone out) */
if (hst->current_state == HOST_UP) {
hst-><API key> = 0;
hst->notified_on_down = FALSE;
hst-><API key> = FALSE;
}
}
/* else the host state has not changed */
else {
/* notify contacts if host is still down or unreachable */
if (hst->current_state != HOST_UP && hst->state_type == HARD_STATE)
host_notification(hst, NOTIFICATION_NORMAL, NULL, NULL, <API key>);
/* if we're in a soft state and we should log host retries, do so now... */
if (hst->state_type == SOFT_STATE && log_host_retries == TRUE)
log_host_event(hst);
}
return OK;
}
/* parse raw plugin output and return: short and long output, perf data */
int parse_check_output(char *buf, char **short_output, char **long_output, char **perf_data, int <API key>, int <API key>) {
int current_line = 0;
int found_newline = FALSE;
int eof = FALSE;
int used_buf = 0;
int dbuf_chunk = 1024;
dbuf db1;
dbuf db2;
char *ptr = NULL;
int in_perf_data = FALSE;
char *tempbuf = NULL;
register int x = 0;
register int y = 0;
/* initialize values */
if (short_output)
*short_output = NULL;
if (long_output)
*long_output = NULL;
if (perf_data)
*perf_data = NULL;
/* nothing to do */
if (buf == NULL || !strcmp(buf, ""))
return OK;
used_buf = strlen(buf) + 1;
/* initialize dynamic buffers (1KB chunk size) */
dbuf_init(&db1, dbuf_chunk);
dbuf_init(&db2, dbuf_chunk);
/* unescape newlines and escaped backslashes first */
if (<API key> == TRUE) {
for (x = 0, y = 0; buf[x] != '\x0'; x++) {
if (buf[x] == '\\' && buf[x+1] == '\\') {
x++;
buf[y++] = buf[x];
} else if (buf[x] == '\\' && buf[x+1] == 'n') {
x++;
buf[y++] = '\n';
} else
buf[y++] = buf[x];
}
buf[y] = '\x0';
}
/* process each line of input */
for (x = 0; eof == FALSE; x++) {
/* we found the end of a line */
if (buf[x] == '\n')
found_newline = TRUE;
else if (buf[x] == '\\' && buf[x+1] == 'n' && <API key> == TRUE) {
found_newline = TRUE;
buf[x] = '\x0';
x++;
} else if (buf[x] == '\x0') {
found_newline = TRUE;
eof = TRUE;
} else
found_newline = FALSE;
if (found_newline == TRUE) {
current_line++;
/* handle this line of input */
buf[x] = '\x0';
if ((tempbuf = (char *)strdup(buf))) {
/* first line contains short plugin output and optional perf data */
if (current_line == 1) {
/* get the short plugin output */
if ((ptr = strtok(tempbuf, "|"))) {
if (short_output)
*short_output = (char *)strdup(ptr);
/* get the optional perf data */
if ((ptr = strtok(NULL, "\n")))
dbuf_strcat(&db2, ptr);
}
}
/* additional lines contain long plugin output and optional perf data */
else {
/* rest of the output is perf data */
if (in_perf_data == TRUE) {
dbuf_strcat(&db2, tempbuf);
dbuf_strcat(&db2, " ");
}
/* we're still in long output */
else {
/* perf data separator has been found */
if (strstr(tempbuf, "|")) {
/* NOTE: strtok() causes problems if first character of tempbuf='|', so use my_strtok() instead */
/* get the remaining long plugin output */
if ((ptr = my_strtok(tempbuf, "|"))) {
if (current_line > 2)
dbuf_strcat(&db1, "\n");
dbuf_strcat(&db1, ptr);
/* get the perf data */
if ((ptr = my_strtok(NULL, "\n"))) {
dbuf_strcat(&db2, ptr);
dbuf_strcat(&db2, " ");
}
}
/* set the perf data flag */
in_perf_data = TRUE;
}
/* just long output */
else {
if (current_line > 2)
dbuf_strcat(&db1, "\n");
dbuf_strcat(&db1, tempbuf);
}
}
}
my_free(tempbuf);
tempbuf = NULL;
}
/* shift data back to front of buffer and adjust counters */
memmove((void *)&buf[0], (void *)&buf[x+1], (size_t)((int)used_buf - x - 1));
used_buf -= (x + 1);
buf[used_buf] = '\x0';
x = -1;
}
}
/* save long output */
if (long_output && (db1.buf && strcmp(db1.buf, ""))) {
if (<API key> == FALSE)
*long_output = (char *)strdup(db1.buf);
else {
/* escape newlines (and backslashes) in long output */
if ((tempbuf = (char *)malloc((strlen(db1.buf) * 2) + 1))) {
for (x = 0, y = 0; db1.buf[x] != '\x0'; x++) {
if (db1.buf[x] == '\n') {
tempbuf[y++] = '\\';
tempbuf[y++] = 'n';
} else if (db1.buf[x] == '\\') {
tempbuf[y++] = '\\';
tempbuf[y++] = '\\';
} else
tempbuf[y++] = db1.buf[x];
}
tempbuf[y] = '\x0';
*long_output = (char *)strdup(tempbuf);
my_free(tempbuf);
}
}
}
/* save perf data */
if (perf_data && (db2.buf && strcmp(db2.buf, "")))
*perf_data = (char *)strdup(db2.buf);
/* strip short output and perf data */
if (short_output)
strip(*short_output);
if (perf_data)
strip(*perf_data);
/* free dynamic buffers */
dbuf_free(&db1);
dbuf_free(&db2);
return OK;
} |
#pragma once
#include <vector>
#include "KFTracker.h"
#include "Solver.h"
class FilterManager
{
public:
FilterManager(KFArgument args);
~FilterManager();
void reset();
void getCorrectedResult(SolverResultList *results);
private:
KFTracker *currentTracker;
KFArgument args;
bool blInit;
void destructor();
SolverResult* <API key>(SolverResultList results);
void correctResult(SolverResult *result);
bool initFilterInfo(SolverResultList *result);
SolverResult* processNextStep(SolverResultList *results);
}; |
class Robot
attr_accessor :orientation
#setter method
def face_to new_orient
self.orientation = new_orient if valid_orientation?(new_orient)
end
def turn direction
self.orientation = if direction == :left
{ east: :north, south: :east, west: :south, north: :west }[self.orientation]
else
{ east: :south, south: :west, west: :north, north: :east }[self.orientation]
end
end
def move_forward
{east: [x:1, y:0], south: [x:0 , y:-1], west: [x:-1, y:0], north: [x:0, y:1]}[self.orientation]
end
private
def valid_orientation?(new_orient)
[:east, :south, :west, :north].include?(new_orient)
end
end |
#ifndef HostWindow_h
#define HostWindow_h
#include "Widget.h"
namespace WebCore {
class Cursor;
class HostWindow {
<API key>(HostWindow); <API key>;
public:
HostWindow() { }
virtual ~HostWindow() { }
// Requests the host invalidate the root view, not the contents.
virtual void invalidateRootView(const IntRect& updateRect) = 0;
// Requests the host invalidate the contents and the root view.
virtual void <API key>(const IntRect& updateRect) = 0;
// Requests the host scroll backingstore by the specified delta, rect to scroll, and clip rect.
virtual void scroll(const IntSize& scrollDelta, const IntRect& rectToScroll, const IntRect& clipRect) = 0;
// Requests the host invalidate the contents, not the root view. This is the slow path for scrolling.
virtual void <API key>(const IntRect& updateRect) = 0;
#if USE(<API key>)
// Requests the host to do the actual scrolling. This is only used in combination with a tiled backing store.
virtual void <API key>(const IntPoint& scrollPoint) = 0;
#endif
// Methods for doing coordinate conversions to and from screen coordinates.
virtual IntPoint screenToRootView(const IntPoint&) const = 0;
virtual IntRect rootViewToScreen(const IntRect&) const = 0;
#if PLATFORM(IOS)
virtual IntPoint <API key>(const IntPoint&) const = 0;
virtual IntRect <API key>(const IntRect&) const = 0;
#endif
// Method for retrieving the native client of the page.
virtual PlatformPageClient platformPageClient() const = 0;
// To notify WebKit of scrollbar mode changes.
virtual void <API key>() const = 0;
// Request that the cursor change.
virtual void setCursor(const Cursor&) = 0;
virtual void <API key>(bool) = 0;
#if ENABLE(<API key>)
virtual void scheduleAnimation() = 0;
#endif
virtual PlatformDisplayID displayID() const = 0;
virtual void <API key>(PlatformDisplayID) = 0;
virtual FloatSize screenSize() const = 0;
virtual FloatSize availableScreenSize() const = 0;
};
} // namespace WebCore
#endif // HostWindow_h |
#ifndef <API key>
#define <API key>
#include "base/basictypes.h"
#include "base/memory/scoped_ptr.h"
#include "ui/aura/root_window.h"
namespace base {
class MessageLoopForUI;
}
namespace gfx {
class SurfaceFactoryOzone;
}
namespace ui {
class InputMethod;
class <API key>;
}
namespace aura {
class TestScreen;
namespace client {
class <API key>;
class <API key>;
class FocusClient;
}
namespace test {
class <API key>;
class AuraTestHelper {
public:
explicit AuraTestHelper(base::MessageLoopForUI* message_loop);
~AuraTestHelper();
void SetUp();
void TearDown();
void <API key>();
Window* root_window() { return root_window_->window(); }
RootWindow* dispatcher() { return root_window_.get(); }
TestScreen* test_screen() { return test_screen_.get(); }
private:
base::MessageLoopForUI* message_loop_;
bool setup_called_;
bool teardown_called_;
bool owns_root_window_;
scoped_ptr<RootWindow> root_window_;
scoped_ptr<<API key>> stacking_client_;
scoped_ptr<client::<API key>> activation_client_;
scoped_ptr<client::<API key>> capture_client_;
scoped_ptr<ui::InputMethod> test_input_method_;
scoped_ptr<client::FocusClient> focus_client_;
scoped_ptr<TestScreen> test_screen_;
scoped_ptr<ui::<API key>> zero_duration_mode_;
#if defined(USE_OZONE)
scoped_ptr<gfx::SurfaceFactoryOzone> surface_factory_;
#endif
<API key>(AuraTestHelper);
};
}
}
#endif |
package com.Abhijay.webhunter;
import com.Abhijay.webhunter.R;
public class HomepageVariables {
public static final String HEAD = "<!DOCTYPE html><html xmlns=\"http:
+ "<head>"
+ "<meta content=\"en-us\" http-equiv=\"Content-Language\" />"
+ "<meta content=\"text/html; charset=utf-8\" http-equiv=\"Content-Type\" />"
+ "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"
+ "<title>"
+ BrowserApp.getAppContext().getString(R.string.home)
+ "</title>"
+ "</head>"
+ "<style>body{background:#f2f2f2;text-align:center;margin:0px;}#search_input{height:35px; "
+ "width:100%;outline:none;border:none;font-size: 16px;background-color:transparent;}"
+ "span { display: block; overflow: hidden; padding-left:5px;vertical-align:middle;}"
+ ".search_bar{display:table;vertical-align:middle;width:90%;height:35px;max-width:500px;margin:0 auto;background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );"
+ "font-family: Arial;color: #444;-moz-border-radius: 2px;-<API key>: 2px;border-radius: 2px;}"
+ "#search_submit{outline:none;height:37px;float:right;color:#404040;font-size:16px;font-weight:bold;border:none;"
+ "background-color:transparent;}.outer { display: table; position: absolute; height: 100%; width: 100%;}"
+ ".middle { display: table-cell; vertical-align: middle;}.inner { margin-left: auto; margin-right: auto; "
+ "margin-bottom:10%; <!-->maybe bad for small screens</!--> width: 100%;}img.smaller{width:50%;max-width:300px;}"
+ ".box { vertical-align:middle;position:relative; display: block; margin: 10px;padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px;"
+ " background-color:#fff;box-shadow: 0px 3px rgba( 0, 0, 0, 0.1 );font-family: Arial;color: #444;"
+ "font-size: 12px;-moz-border-radius: 2px;-<API key>: 2px;"
+ "border-radius: 2px;}</style><body> <div class=\"outer\"><div class=\"middle\"><div class=\"inner\"><img class=\"smaller\" src=\"";
public static final String MIDDLE = "\" ></br></br><form onsubmit=\"return search()\" class=\"search_bar\">"
+ "<input type=\"submit\" id=\"search_submit\" value=\"Search\" ><span><input class=\"search\" type=\"text\" value=\"\" id=\"search_input\" >"
+ "</span></form></br></br></div></div></div><script type=\"text/javascript\">function search(){if(document.getElementById(\"search_input\").value != \"\"){window.location.href = \"";
public static final String END = "\" + document.getElementById(\"search_input\").value;document.getElementById(\"search_input\").value = \"\";}return false;}</script></body></html>";
} |
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "pmapi.h"
/* Block of real mode code we will eventually call */
static unsigned char realModeCode[] = {
0x93, /* xchg ax,bx */
0x87, 0xCA, /* xchg cx,dx */
0xCB /* retf */
};
int main(void)
{
RMREGS regs;
RMSREGS sregs;
uchar *p;
unsigned r_seg,r_off;
/* Allocate a the block of real mode memory */
if ((p = PM_allocRealSeg(sizeof(realModeCode), &r_seg, &r_off)) == NULL) {
printf("Unable to allocate real mode memory!\n");
exit(1);
}
/* Copy the real mode code */
memcpy(p,realModeCode,sizeof(realModeCode));
/* Now call the real mode code */
regs.x.ax = 1;
regs.x.bx = 2;
regs.x.cx = 3;
regs.x.dx = 4;
regs.x.si = 5;
regs.x.di = 6;
sregs.es = 7;
sregs.ds = 8;
PM_callRealMode(r_seg,r_off,®s,&sregs);
if (regs.x.ax != 2 || regs.x.bx != 1 || regs.x.cx != 4 || regs.x.dx != 3
|| regs.x.si != 5 || regs.x.di != 6 || sregs.es != 7
|| sregs.ds != 8) {
printf("Real mode call failed!\n");
printf("\n");
printf("ax = %04X, bx = %04X, cx = %04X, dx = %04X\n",
regs.x.ax,regs.x.bx,regs.x.cx,regs.x.dx);
printf("si = %04X, di = %04X, es = %04X, ds = %04X\n",
regs.x.si,regs.x.di,sregs.es,sregs.ds);
}
else
printf("Real mode call succeeded!\n");
/* Free the memory we allocated */
PM_freeRealSeg(p);
return 0;
} |
# generated from catkin/cmake/template/pkg.context.pc.in
<API key> = ""
<API key> = "".split(';') if "" != "" else []
<API key> = "roscpp;rospy;std_msgs".replace(';', ' ')
<API key> = "-lscarab_quad".split(';') if "-lscarab_quad" != "" else []
PROJECT_NAME = "scarab_quad"
PROJECT_SPACE_DIR = "/home/monroe/catkin_ws/install"
PROJECT_VERSION = "0.0.0" |
#include "sharp_public.hpp"
#include "qcommon/qcommon.h"
#include <mono/jit/jit.h>
#include <mono/metadata/assembly.h>
#include <mono/metadata/mono-config.h>
#include <mono/metadata/threads.h>
#include <unordered_set>
static MonoDomain * domain = nullptr;
void Sharp_Init() {
mono_config_parse (nullptr);
domain = <API key>("JAOWNT", "v4.0");
if (!domain) Com_Error(ERR_FATAL, "Mono Scripting Engine failed to initialize!\n");
}
void Sharp_Shutdown() {
if (domain) {
mono_jit_cleanup(domain);
domain = nullptr;
}
}
struct mono_scriptcon {
MonoDomain * domain;
MonoAssembly * assembly;
MonoImage * image;
};
std::unordered_set<mono_scriptcon *> active_contexts;
sharp_handle Sharp_Create (char const * assemblyLocation) {
mono_scriptcon * sc = new mono_scriptcon;
fileHandle_t fh;
int len = FS_SV_FOpenFileRead(va("sharp/%s", assemblyLocation), &fh);
if (!fh) {
Com_Printf("ERROR: <API key>: could not find assembly file!");
return nullptr;
}
sc->domain = <API key>(va("%s", assemblyLocation), nullptr);
mono_domain_set(sc->domain, true);
void * asmBuf = S_Malloc(len);
FS_Read(asmBuf, len, fh);
MonoImageOpenStatus mis;
sc->image = <API key>( reinterpret_cast<char *>(asmBuf), len, true, &mis);
if (mis != MONO_IMAGE_OK) {
Com_Error(ERR_FATAL, "Invalid assembly requested!");
}
sc->assembly = <API key>(sc->image, assemblyLocation, &mis);
if (mis != MONO_IMAGE_OK) {
Com_Error(ERR_FATAL, "Assembly could not be created from image!");
}
FS_FCloseFile(fh);
active_contexts.insert(sc);
return sc;
}
void Sharp_Destroy (sharp_handle sh) {
mono_scriptcon * sc = reinterpret_cast<mono_scriptcon *>(sh);
if (active_contexts.erase(sc)) {
mono_domain_set(domain, true);
mono_domain_unload(sc->domain);
delete sc;
}
}
sharp_class Sharp_Resolve_Class (sharp_handle sh, char const * name_space, char const * name) {
return <API key>(reinterpret_cast<mono_scriptcon *>(sh)->image, name_space, name);
}
sharp_method <API key> (sharp_class ch, char const * name, int arg_c) {
return <API key>(reinterpret_cast<MonoClass *>(ch), name, arg_c);
}
void * Sharp_Invoke (sharp_handle sh, sharp_method mh, void * * arg, std::string & err) {
MonoMethod * mm = reinterpret_cast<MonoMethod *>(mh);
MonoObject * exc;
MonoObject * ret = mono_runtime_invoke(mm, nullptr, arg, &exc);
if (exc) {
char * dat = mono_string_to_utf8(<API key>(exc, NULL));
err = dat;
//mono_free(dat);
return nullptr;
}
if (!mono_type_is_void(<API key>(<API key>(mm)))) {
return mono_object_unbox(ret);
}
return nullptr;
}
void <API key>(sharp_handle sh, char const * name, void * call) {
<API key>(name, call);
}
void Sharp_Bind(sharp_handle sh) {
mono_scriptcon * sc = reinterpret_cast<mono_scriptcon *>(sh);
mono_domain_set(sc->domain, true);
}
sharp_string Sharp_Create_String(sharp_handle sh, char const * chars) {
return mono_string_new(reinterpret_cast<mono_scriptcon *>(sh)->domain, chars);
}
std::string Sharp_Unbox_String(sharp_string strh) {
std::string str;
char * nstr = mono_string_to_utf8(reinterpret_cast<MonoString *>(strh));
str = nstr;
mono_free(nstr);
return str;
}
sharp_array <API key>(sharp_handle sh, void * * elements, size_t count) {
MonoArray * arry = mono_array_new(reinterpret_cast<mono_scriptcon *>(sh)->domain, <API key>(), count);
for (size_t i = 0; i < count; i++)
mono_array_set(arry, void *, i, elements[i]);
return arry;
} |
#ifndef __ASM_ARM_CPUTYPE_H
#define __ASM_ARM_CPUTYPE_H
/*
* L4Linux: on v6 CPUs, read_cpuid_*() are used in arch/arm/mm/mmap.c for
* every mmap operation and thus trap _very_ often, to avoid we
* modify here. It is not strictly necessary...
*/
#include <linux/stringify.h>
#include <linux/kernel.h>
#ifdef CONFIG_L4
#include <asm/generic/setup.h>
#include <asm/generic/smp.h>
#endif
#define CPUID_ID 0
#define CPUID_CACHETYPE 1
#define CPUID_TCM 2
#define CPUID_TLBTYPE 3
#define CPUID_MPUIR 4
#define CPUID_MPIDR 5
#ifdef CONFIG_CPU_V7M
#define CPUID_EXT_PFR0 0x40
#define CPUID_EXT_PFR1 0x44
#define CPUID_EXT_DFR0 0x48
#define CPUID_EXT_AFR0 0x4c
#define CPUID_EXT_MMFR0 0x50
#define CPUID_EXT_MMFR1 0x54
#define CPUID_EXT_MMFR2 0x58
#define CPUID_EXT_MMFR3 0x5c
#define CPUID_EXT_ISAR0 0x60
#define CPUID_EXT_ISAR1 0x64
#define CPUID_EXT_ISAR2 0x68
#define CPUID_EXT_ISAR3 0x6c
#define CPUID_EXT_ISAR4 0x70
#define CPUID_EXT_ISAR5 0x74
#else
#define CPUID_EXT_PFR0 "c1, 0"
#define CPUID_EXT_PFR1 "c1, 1"
#define CPUID_EXT_DFR0 "c1, 2"
#define CPUID_EXT_AFR0 "c1, 3"
#define CPUID_EXT_MMFR0 "c1, 4"
#define CPUID_EXT_MMFR1 "c1, 5"
#define CPUID_EXT_MMFR2 "c1, 6"
#define CPUID_EXT_MMFR3 "c1, 7"
#define CPUID_EXT_ISAR0 "c2, 0"
#define CPUID_EXT_ISAR1 "c2, 1"
#define CPUID_EXT_ISAR2 "c2, 2"
#define CPUID_EXT_ISAR3 "c2, 3"
#define CPUID_EXT_ISAR4 "c2, 4"
#define CPUID_EXT_ISAR5 "c2, 5"
#endif
#define MPIDR_SMP_BITMASK (0x3 << 30)
#define MPIDR_SMP_VALUE (0x2 << 30)
#define MPIDR_MT_BITMASK (0x1 << 24)
#define MPIDR_HWID_BITMASK 0xFFFFFF
#define MPIDR_INVALID (~MPIDR_HWID_BITMASK)
#define MPIDR_LEVEL_BITS 8
#define MPIDR_LEVEL_MASK ((1 << MPIDR_LEVEL_BITS) - 1)
#define <API key>(mpidr, level) \
((mpidr >> (MPIDR_LEVEL_BITS * level)) & MPIDR_LEVEL_MASK)
#define ARM_CPU_IMP_ARM 0x41
#define ARM_CPU_IMP_INTEL 0x69
#define <API key> 0xB360
#define <API key> 0xB560
#define <API key> 0xB760
#define <API key> 0xB020
#define <API key> 0xC080
#define <API key> 0xC090
#define <API key> 0xC050
#define <API key> 0xC0F0
#define <API key> 0xC070
#define <API key> 0xe000
#define <API key> 0x2000
#define <API key> 0x4000
#define <API key> 0x6000
extern unsigned int processor_id;
#ifdef CONFIG_CPU_CP15
#define read_cpuid(reg) \
({ \
unsigned int __val; \
asm("mrc p15, 0, %0, c0, c0, " __stringify(reg) \
: "=r" (__val) \
: \
: "cc"); \
__val; \
})
/*
* The memory clobber prevents gcc 4.5 from reordering the mrc before
* any is_smp() tests, which can cause undefined instruction aborts on
* ARM1136 r0 due to the missing extended CP15 registers.
*/
#define read_cpuid_ext(ext_reg) \
({ \
unsigned int __val; \
asm("mrc p15, 0, %0, c0, " ext_reg \
: "=r" (__val) \
: \
: "memory"); \
__val; \
})
#elif defined(CONFIG_CPU_V7M)
#include <asm/io.h>
#include <asm/v7m.h>
#define read_cpuid(reg) \
({ \
WARN_ON_ONCE(1); \
0; \
})
static inline unsigned int __attribute_const__ read_cpuid_ext(unsigned offset)
{
return readl(BASEADDR_V7M_SCB + offset);
}
#else /* ifdef CONFIG_CPU_CP15 / elif defined (CONFIG_CPU_V7M) */
/*
* read_cpuid and read_cpuid_ext should only ever be called on machines that
* have cp15 so warn on other usages.
*/
#define read_cpuid(reg) \
({ \
WARN_ON_ONCE(1); \
0; \
})
#define read_cpuid_ext(reg) read_cpuid(reg)
#endif /* ifdef CONFIG_CPU_CP15 / else */
#ifdef CONFIG_CPU_CP15
/*
* The CPU ID never changes at run time, so we might as well tell the
* compiler that it's constant. Use this function to read the CPU ID
* rather than directly reading processor_id or read_cpuid() directly.
*/
static inline unsigned int __attribute_const__ read_cpuid_id(void)
{
#ifdef CONFIG_L4
return l4lx_kinfo->platform_info.arch.cpuinfo.MIDR;
#else
return read_cpuid(CPUID_ID);
#endif
}
#else /* ifdef CONFIG_CPU_CP15 */
static inline unsigned int __attribute_const__ read_cpuid_id(void)
{
return processor_id;
}
#endif /* ifdef CONFIG_CPU_CP15 / else */
static inline unsigned int __attribute_const__ <API key>(void)
{
return (read_cpuid_id() & 0xFF000000) >> 24;
}
static inline unsigned int __attribute_const__ <API key>(void)
{
return read_cpuid_id() & 0xFFF0;
}
static inline unsigned int __attribute_const__ <API key>(void)
{
return <API key>() & <API key>;
}
static inline unsigned int __attribute_const__ <API key>(void)
{
#ifdef CONFIG_L4
return l4lx_kinfo->platform_info.arch.cpuinfo.CTR;
#else
return read_cpuid(CPUID_CACHETYPE);
#endif
}
static inline unsigned int __attribute_const__ <API key>(void)
{
return read_cpuid(CPUID_TCM);
}
static inline unsigned int __attribute_const__ read_cpuid_mpidr(void)
{
#ifndef CONFIG_L4
return read_cpuid(CPUID_MPIDR);
#else
return (1U << 31) | <API key>(smp_processor_id());
#endif
}
/*
* Intel's XScale3 core supports some v6 features (supersections, L2)
* but advertises itself as v5 as it does not support the v6 ISA. For
* this reason, we need a way to explicitly test for this type of CPU.
*/
#ifndef CONFIG_CPU_XSC3
#define cpu_is_xsc3() 0
#else
static inline int cpu_is_xsc3(void)
{
unsigned int id;
id = read_cpuid_id() & 0xffffe000;
/* It covers both Intel ID and Marvell ID */
if ((id == 0x69056000) || (id == 0x56056000))
return 1;
return 0;
}
#endif
#if !defined(CONFIG_CPU_XSCALE) && !defined(CONFIG_CPU_XSC3)
#define cpu_is_xscale() 0
#else
#define cpu_is_xscale() 1
#endif
#endif |
<?php
require 'vendor/autoload.php';
//$params = array();
//$params['hosts'] = array (
//'192.168.1.1:9200', // IP + Port
//'192.168.1.2', // Just IP
//'mydomain.server.com:9201', // Domain + Port
// 'mydomain2.server.com', // Just Domain
//$params['logging'] = true;
//$params['logPath'] = '/tmp/logs/elasticsearch/elasticsearch.log';
//$params['logLevel'] = Psr\Log\LogLevel::INFO;
$client = new Elasticsearch\Client();
$params['body'] = array(
'id' => 10,
'field_ranjeet_test' => 'new test field',
'title' => 'My New Products',
'price' =>3090,
'type' => 'artilce',
'is_new' => true,
'commerce_store' => 1,
'author' =>1,
'family' => 'jewelery',
'field_tags' => ['2'],
'field_new_field'=> 'New Field Value',
'field_new1_field'=> 'New field value',
'field_new2_field'=> 'new 2 field value',
'field_new4_field'=> 'New4 4',
"search_api_language" => 'und',
'product_id' =>'6',
'created' => '1431511689',
'sku' => 'Sku1',
'nid' => 2,
'vid' => 2,
);
$params['index'] = '<API key>';
$params['type'] = 'new_index';
$params['id'] = 10;
$ret = $client->index($params);
echo 'created document';
/***
'facets' => [
'field_ranjeet_test' => [
'terms' => [
'field' => 'field_ranjeet_test'
]
]
];
$params['facets'] = array(
'field_ranjeet_test' => array(
'terms' => array(
'all_terms' =>false,
'field' => 'field_ranjeet_test',
'size' =>'50')
)
);
"facets": {
"field_ranjeet_test": {
"terms": {
"all_terms": false,
"field": "field_ranjeet_test",
"size": 50
}
},
"_index": "<API key>",
"_type": "new_index",
"_id": "3",
"_score": 1,
"_source": {
"id": 3,
"commerce_store": null,
"created": "1431511689",
"field_store_data": [
"1"
],
"product_id": "3",
"sku": "<API key>",
"title": "Hesstar Table Fan HF-306 Purple",
"type": "product"
*/ |
@keyframes alpha
{
from
{
opacity: 1;
}
to
{
opacity: 0.2;
}
}
@-moz-keyframes alpha
{
from
{
opacity: 1;
}
to
{
opacity: 0.2;
}
}
@-webkit-keyframes alpha
{
from
{
opacity: 1;
}
to
{
opacity: 0.2;
}
}
@keyframes beta
{
from
{
margin: 0em;
opacity: 0;
}
10%
{
opacity: 0.2;
}
50%
{
opacity: 0.5;
}
51%
{
opacity: 0.6;
}
to
{
margin: 1em;
opacity: 1;
}
} |
using UnityEngine;
using System.Collections;
public class ParalaxMove2 : MonoBehaviour {
public GameObject paralaxObjects;
private float speed;
// Use this for initialization
void Start()
{
SetSpeed();
}
void Update()
{
SetSpeed();
}
void SetSpeed()
{
speed = paralaxObjects.GetComponent<ParalaxSettings>().BuildingSet2Speed;
GetComponent<Rigidbody2D>().velocity = new Vector2(0, -speed);
}
} |
gdbexport2xml
==========
.NET C# console program for export tables/feature classes from ArcGIS geodatabase. Works fine with SDE.
ArcCatalog has a tool in featureclass/table context menu 'Export - XML Workspace Document'. This program let you do such export from your scripts.
Links
* http://vasnake.blogspot.ru/2010/08/arccatalog-esri.html
* [Exporting feature datasets, classes, and tables to an export file](http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Exporting%20feature%20datasets,%20classes,%20and%20tables%20to%20an%20export%20file)
* http://forums.esri.com/Thread.asp?c=93&f=1149&t=212981
* http: |
# -*- coding: utf-8 -*-
from config import *
print(Color(
'{autored}[{/red}{autoyellow}+{/yellow}{autored}]{/red} {autocyan} log.py importado.{/cyan}'))
@bot.message_handler(commands=['log'])
def command_log(m):
cid = m.chat.id
uid = m.from_user.id
try:
send_udp('log')
except Exception as e:
bot.send_message(52033876, send_exception(e), parse_mode="Markdown")
if not is_recent(m):
return None
if is_admin(uid):
if extra["log"]:
extra["log"] = False
bot.send_message(cid, "Log desactivado")
else:
extra["log"] = True
bot.send_message(cid, "Log activado")
with open("extra_data/extra.json", "w") as f:
json.dump(extra, f) |
// Registers the Mosaic namespace
Drupal.field_defaults = Drupal.field_defaults || {};
/**
*
* Mosaic forms will check to see if there are
* settings for any form's textfield defaults.
* Should only recieve requests for items that
* implement it. Only implement on pages where
* needed!
*
* These defaults are added via modules and
* themes via whatever hooks they deem fit.
*
* Add new defaults to:
*
* Drupal.settings.mosaic.fieldDefaults:
*
* - fieldDefaults['.selector']['default'] = 'Default text';
*
*/
// Document loaded!
(function($) {
Drupal.behaviors.<API key> = {
attach : function(context, settings) {
try { // use try to ensure that if this breaks/fails, it won't break other stuff.
if (Drupal.settings.field_defaults.textareaDefaults) {
var textareaDefaults = Drupal.settings.field_defaults.textareaDefaults;
for (selector in textareaDefaults) {
var $formElement = $(selector);
//console.log(selector);
for (var index = 0; index < $formElement.length; index++) {
new Drupal.field_defaults.textareaDefault($formElement[index], textareaDefaults[selector]);
}
}
}
}
catch (err) {
console.log('<API key>() reported errors! Error: '+err);
}
}
};
// Mosaic textfieldDefault takes one textfield and ensures it is
// set as it should be according to the specs in textfield_defaults.inc
// @TODO: make this able to handle Form API defaults as well as passed in defaults.
Drupal.field_defaults.textareaDefault = function(formElement, fieldDefaults) {
this.$element = $(formElement);
var textareaDefault = this;
var FieldList = Backbone.View.extend({
// Home
el: this.$element,
// Events
events: {
'focusin': 'focusField',
'focusout': 'blurField'
},
// Init
initialize: function() {
textareaDefault.process(fieldDefaults, 'blur', true);
_.bindAll(this, 'blurField', 'focusField');
},
// Updates
blurField: function() { textareaDefault.process(fieldDefaults, 'blur' ); },
focusField: function() { textareaDefault.process(fieldDefaults, 'focus'); }
});
// Kick start!
new FieldList();
};
// Process each textfield
Drupal.field_defaults.textareaDefault.prototype.process = function(settings, op, init) {
// Runtime baby!
init = init || false;
var id = this.$element.attr('id');
var $elm = this.$element;
var val = $elm.val();
// Field is blurring
if (op == 'blur') {
if (val == settings['default']) { // value is already ok
$elm.addClass('field-default'); // add the default class
}
if (val != settings['default']) { // value is not eq to settings
if (init && $elm.val() == '') { // do we override? yes on initialization of the page
// @TODO: Check and see if what IS there is the default
$elm.val(settings['default']).addClass('field-default');
}
else {
if (val == '') { // they are leaving it blank
$elm.val(settings['default']).addClass('field-default');
}
}
}
}
// User is focusing
if (op == 'focus') {
if (val == settings['default']) { // we only work on it if its in a default state
$elm.val('').removeClass('field-default');
}
else {
$elm.removeClass('field-default');
}
}
};
})(jQuery); |
#awd-mainarea {
margin:0 auto;
font-size:12px;
font-family:Arial, Geneva, sans-serif;
line-height:100% !important;
padding:14px;
background:#F6F6F6;
float:left;
}
#awd-mainarea ul li{
padding-left:0px !important;
background-image:none !important;
}
#awd-mainarea img {
border:none;
}
#awd-mainarea .round {
background-image:none!important;
-moz-border-radius: 5px;
color: #111;
position: relative;
width:95% !important;
height: 50px;
background-color: #F4F8DF;
border-bottom-color: #666666;
overflow:hidden !important;
border:1px solid #BF9BD2;
padding:0px!important;
line-height:normal!important;
}
#awd-mainarea .input_border {
padding: 2px;
font:calibri;
font-size:1.2e;
position: relative;
overflow:hidden !important;
margin-top:5px;
background-image:none!important;
-moz-border-radius:5px 5px 5px 5px;
background-color:#f8e7fd;
border:1px solid #F8E7FD;
color:#222;
}
#awd-mainarea .text_comment{
padding: 2px;
font:calibri;
font-size:1.2e;
background-image:none!important;
-moz-border-radius: 5px;
color: #222;
position: relative;
width: 98%;
height: 50px;
background-color: #f8e7fd;
overflow:hidden !important;
border:1px solid #b987c9;
}
#awd-mainarea form {
margin:0;
padding:0;
}
/* #awd-mainarea a:link {
text-decoration: none;
color: rgb(85, 116, 160);
}
*/
#awd-mainarea a:link {
text-decoration: none;
color: #5574A0;
font-weight:normal;
}
#awd-mainarea .awdfullbox {
border-collapse:separate;
margin:3px 0;
position:relative!important;
display:block;
}
#awd-mainarea .awdfullbox_top {
border-collapse:separate;
margin:3px 0;
position:relative!important;
display:inline-block;
background-color: #E8E8E8;
}
/*roundbox start*/
/* #awd-mainarea .rbroundbox, .rbroundboxleft, .rbroundboxlefttop, .awdfullbox {
background:#E8E8E8;
}
#awd-mainarea .rbroundboxrighttop, .rbroundboxright {
background:#E8E8E8;
} */
#awd-mainarea .rbtop div, .rbtop, .rbbot div, .rbbot {
width: 100%;
height: 7px;
font-size: 1px;
}
#awd-mainarea .tl {
background: url(../images/bor.gif) no-repeat top left;
position:absolute;
top:0;
left:0;
width:7px;
height:6px;
font-size:0;
}
#awd-mainarea .tr {
background: url(../images/bor.gif) no-repeat top right;
position:absolute;
top:0;
right:0;
width:7px;
height:6px;
font-size:0;
}
#awd-mainarea .bl {
background: url(../images/bor.gif) no-repeat bottom left;
position:absolute;
bottom:0;
left:0;
width:7px;
height:6px;
font-size:0;
}
#awd-mainarea .br {
background: url(../images/bor.gif) no-repeat bottom right;
position:absolute;
bottom:0;
right:0;
width:7px;
height:6px;
font-size:0;
}
#awd-mainarea .tl2 {
background: url(../images/bor2.png) no-repeat top left;
position:absolute;
top:0;
left:-7px;
width:14px;
height:6px;
font-size:0;
}
#awd-mainarea .bl2 {
/* background: url(../images/bor2.png) no-repeat bottom left; */
position:absolute;
bottom:0;
left:-7px;
width:14px;
height:6px;
font-size:0;
}
#awd-mainarea .tr2 {
/* background: url(../images/bor2.png) no-repeat top left; */
position:absolute;
top:0;
right:0;
width:7px;
height:6px;
font-size:0;
}
#awd-mainarea .br2 {
/* background: url(../images/bor2.png) no-repeat bottom left; */
position:absolute;
bottom:0;
right:0;
width:7px;
height:6px;
font-size:0;
}
* html #awd-mainarea .tr2 {
right:-1px;
}
* html #awd-mainarea .br2 {
right:-1px;
}
#awd-mainarea .fullboxtop {
margin-top:0;
color:#333;
color:#333333;
float:left;
margin:0;
padding:0;
width:100%;
}
#awd-mainarea .rbcontent {
margin: 0 7px;
font-size:11px !important;
line-height:10px;
color:#333333;
}
#awd-mainarea .rbroundbox {
width: 100%;
margin: 2px auto;
}
#awd-mainarea .rbroundboxleft {
width: 27%;
text-align:center !important;
float:left;
margin-right:25px;
}
#awd-mainarea #msg_content .rbroundboxleft {
margin-right:0px!important;
}
#awd-mainarea #<API key> .rbroundboxleft {
margin-right:0px!important;
}
#awd-mainarea .rbroundboxleft_user {
width: 27%;
text-align:center !important;
float:left;
/*background-color: #E8E8E8;*/
margin-right:25px;
}
#awd-mainarea .rbroundboxright {
width: 70%;
float:right;
position:relative !important;
min-height:85px;
}
#awd-mainarea .rbroundboxrightfull {
width: 100%;
float:right;
position:relative !important;
min-height:20px;
}
#awd-mainarea .rbroundboxrighttop {
width: 69%;
float:left;
position:relative !important;
min-height:615px;
background-color: #E8E8E8;
}
#awd-mainarea .mid_content {
padding:10px;
text-align:center !important;
}
#awd-mainarea .mid_content_top {
text-align:left !important;
/* margin-bottom:10px;
width:100%; */
overflow:hidden;
}
#awd-mainarea .right_mid_content {
padding:14px 1px 4px;
}
* html #awd-mainarea .rbroundboxright {
width: 79.9%;
}
* html #awd-mainarea .rbroundboxrightfull {
width: 99.9%;
}
/*roundbox end*/
#awd-mainarea .search_user {
/* background:#FFFFFF url(../images/s_button.jpg) no-repeat top right; */
border:1px solid #BF9BD2;
height: 22px;
padding:0px !important;
color:#222;
font-size:12px;
width:76%;
background: url(../images/lavender/searchbg.png) no-repeat right;
padding-right:23px !important;
line-height:normal!important;
}
#awd-mainarea .wrap_sm{
background:url(../images/wrap_sm.jpg) no-repeat left top ;
height:24px;
line-height:24px;
display:block;
}
#awd-mainarea .postButton {
background: url(../images/button_sm.jpg) no-repeat right top;
height:24px;
color: #10389f;
border:none;
text-align:center;
line-height:24px;
font-weight:bold;
padding-bottom:5px;
}
#awd-mainarea .wallheading {
background:url(../images/lavender/menu-left.png) top left no-repeat!important;
float:left;
height:48px;
padding-left: 10px;
width:99%;
}
#awd-mainarea .wallheadingRight{
background:url(../images/lavender/menu-right.png) top right no-repeat!important;
height:48px;
padding-right: 10px;
}
#awd-mainarea .searchWall {
float:left;
height:49px;
/*background:url(../images/green/menu-center.png) top right repeat-x!important;
width:20%; */
width: 150px;
text-align:right;
padding:0px 0px 0px 15px;
}
* +html #awd-mainarea .searchWall {
padding-top:0;
}
#awd-mainarea .wallheadingRight ul {
float:left;
text-align: left;
height:48px;
background:url(../images/lavender/menu-center.png) top right repeat-x;
padding:0px;
margin:0px;
width:100%;
}
#awd-mainarea li.logo{
padding:0px 0px 0px 20px;
float:left;
width:24px !important;
}
#awd-mainarea li.logo img{
display:inline;
float:left;
padding-top:3px;
}
#awd-mainarea .wallheadingRight li {
list-style-type: none;
display: inline;
padding:0px 5px;
line-height:42px;
font-size: 12px;
color:#888;
font-weight:bold;
background:none;
height:42px;
padding-top:2px;
float:left;
margin:0px!important;
}
#awd-mainarea .wallheadingRight li.separator, #awd-mainarea .wallheadingRight li.logo{
display:none;
}
#awd-mainarea .wallheadingRight li a {
font-size: 13px!important;
color:#868686;
text-decoration: none;
font-weight:bold;
text-transform:capitalize;
height:42px!important;
line-height:42px!important;
float:left;
padding:0 8px;
}
#awd-mainarea .wallheadingRight li a:hover, #awd-mainarea .wallheadingRight li a.active{
background:url(../images/lavender/menu-center-hover.png) repeat-x left top;
color:#FAF1FA;
}
#awd-mainarea ul.walltowall {
margin:0px;
padding:0px;
font-size: 13px;
}
#awd-mainarea .walltowall li {
font-size: 13px !important;
color:#333 !important;
list-style-type: none;
display: inline;
}
#awd-mainarea .walltowall li a {
color:#308CB6;
text-decoration: none;
font-weight: bold;
font-size: 13px !important;
}
#awd-mainarea .wall_date {
color:#8C8C8C;
}
#awd-mainarea .commentinfo {
padding-top:10px;
/*color:#b3b3b3;*/
color:#666666;
padding-right: 2px;
font-size: 11px;
margin-bottom:3px;
}
#awd-mainarea .commentinfo a, .commentinfo a:visited {
font-size: 11px;
color:#308CB6;
text-decoration: none;
}
#awd-mainarea .whitebox {
background-color:#fff;
width:auto;
font-size:12px;
padding:1px 10px 1px 10px;
margin-top:1px;
}
#awd-mainarea .video{
padding-top:10px;
}
#awd-mainarea .imagebox {
width:36%;
float:left;
color:#9997ac;
font-size: 11px;
}
#awd-mainarea .maincomment {
width:64%;
float:left;
color:#B6B6B6;
line-height:18px;
}
#awd-mainarea .maincomment p {
color:#B6B6B6;
font-size:12px;
word-wrap:break-word;
}
#awd-mainarea .maincomment h3 {
font-weight: bold;
font-size: 12px;
padding:0px;
margin:0px;
color: #ac79bf;
}
#awd-mainarea .subcommentImagebox {
width:14%;
float:left;
text-align: center !important;
color:#ac79bf;
font-size: 11px;
margin-top:7px;
}
#awd-mainarea .subcomment {
width:83%;
float:right;
text-align: left;
color:#000;
font-size: 12px;
line-height:0.9em;
}
#awd-mainarea .subcommentmenu {
width:100%;
margin:10px 0px;
padding:0px;
}
#awd-mainarea a.authorlink {
font-size: 11px;
color:#308CB6;
text-decoration: none;
font-weight: bold;
}
#awd-mainarea .user_place, #awd-mainarea .mid_content_top{
padding:10px 10px 10px 10px;
}
#awd-mainarea .profileLink a, #awd-mainarea .profileLink a:visited {
text-decoration: none;
text-align: left;
color: #5574A0;
font-size:11px;
font-weight: normal;
padding-left:8px;
}
#awd-mainarea .profileStatus {
color: #8C8C8C;
font-size:12px;
font-weight: normal;
padding-top:5px;
padding-bottom:5px;
display:block;
}
#awd-mainarea ul.profileMenu {
margin:0px;
padding:10px 0px;
padding-left:8px;
}
#awd-mainarea ul.profileMenu li {
list-style-type: none;
font-size: 11px;
padding:1px 0 1px 32px !important;
background:#006;
text-align:left !important;
}
#awd-mainarea ul.profileMenu li a, #awd-mainarea ul.profileMenu li a:visited {
font-size: 11px;
color:#3A4563;
text-decoration:none !important;
}
#awd-mainarea ul.tabProfile {
margin:12px 0px 0px 0px;
padding:0px;
}
#awd-mainarea ul.tabProfile li {
display: inline;
list-style-type: none;
font-size: 12px;
color:#475875;
margin:0px 2px;
}
#awd-mainarea ul.tabProfile li a {
padding:3px 7px;
font-size: 12px;
color:#475875;
background-color: #D1E8EA;
-moz-border-radius:5px 5px 5px 5px;
border:1px solid #bd8ccd;
}
#awd-mainarea ul.tabProfile li a:hover, #awd-mainarea ul.tabProfile li.active a {
color:#475875;
background-color:#FFFFFF;
}
#awd-mainarea ul.attach {
margin:17px 0px;
padding:0px;
width:auto!important;
}
#awd-mainarea ul.attach li {
list-style-type: none;
font-weight: bold;
font-size: 12px;
color:#5D6160;
display: inline;
line-height:16px;
padding-right:8px;
float:left;
margin:0px!important;
}
#awd-mainarea .john {
background: url(../images/arrow.jpg) no-repeat right center;
padding-right:10px;
}
* html #awd-mainarea .clearfix {
height: 1%; /* IE5-6 */
}
* +html #awd-mainarea .clearfix {
display: inline-block;
} /* IE7xhtml*/
html[xmlns] #awd-mainarea .clearfix {
display: block;
clear:left;
}
#awd-mainarea .clearfix:after { /* FF, O, etc. */
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
#awd-mainarea .post_msg_btn_list{
padding-top:5px;
float: left;
width:98%;
}
#awd-mainarea .post_msg_btn .postButton_small{
float:right;
margin-top:10px;
}
#awd-mainarea .post_msg_btn_list .postButton_small{
margin-top:0px!important;
}
#awd-mainarea .login_post_text{
font-weight: bold;
color: #D95B51;
}
#awd-mainarea .comment_text{
width: 65%;
}
#awd-mainarea .awd_message{
border:1px solid #CCCCCC;
}
#awd-mainarea .ui-dialog .ui-resizable-se {
float:right;
}
#awd-mainarea .pm_text{
background-color:#FFFFFF;
font-size:11px;
padding-left:10px;
color:red !important;
}
#awd-mainarea .lightblue_box {
background-color:#E8E8E8;
border:1px solid #D8DFEA;
height:15px;
padding:5px;
margin-bottom:10px;
margin-top:5px;
}
#awd-mainarea .lightblue_box a{
color:#BC06EA;
}
/* new css for 1.6.2 */
#awd-mainarea .fullboxnew {
background:none!important;
padding:0px 0 0px 0px;
margin-bottom:15px;
width:99.5%;
float:right;
}
#awd-mainarea .tl2, #awd-mainarea .bl2 {
display:none;
}
#awd-mainarea .fullboxnew .rbroundboxleft_user {
width:14%;
}
#awd-mainarea .fullboxnew .rbroundboxrighttop {
width:86%;
}
#awd-mainarea .subcomment .rbroundbox {
/* background:#262523; */
}
#awd-mainarea .rbroundboxleft {
font-size:11px;
}
#awd-mainarea .rbroundboxleft p {
margin:0px 0;
}
#awd-mainarea .rbroundboxleft a {
color:#2e5888;
text-decoration:none;
}
#awd-mainarea .rbroundboxleft a:hover {
text-decoration: underline;
}
#awd-mainarea ul.profileMenu li {
text-align:left;
line-height:20px;
}
#awd-mainarea .profileName,#awd-mainarea .profileLink {
text-align:left;
}
#awd-mainarea .blog_friend, #awd-mainarea .blog_groups {
text-align:left;
color:#2e5888;
font-weight:normal;
}
#awd-mainarea .blog_content {
background:#fff;
border:1px solid #B783C8;
}
#awd-mainarea .blog_content {
padding:3px 5px;
}
#awd-mainarea .blog_friend .blog_content .column1, #awd-mainarea .blog_friend .blog_content .column2 {
float:left;
width:47px;
margin:2px 0;
}
#awd-mainarea .blog_friend a{
text-decoration:none !important;
}
#awd-mainarea .blog_friend .blog_content .column2 {
float:right!important;
}
#awd-mainarea .blog_friend img {
border:0px solid #a1a19f!important;
max-width:19px;
}
#awd-mainarea .blog_groups img {
/*border:1px solid #a1a19f!important;*/
padding:1px;
width:19px;
/*height:30px;*/
float:left;
margin:3px;
}
#awd-mainarea .about_me {
background:#fff;
padding:2px;
text-align:left;
margin:0 -2px;
border:0px solid #b783c8;
}
/* #awd-mainarea .about_me .about_tr { background: url(../images/ab_tr.jpg) top right no-repeat; height:5px; font-size:0; float:left; width:100%;margin:0 0 0 0;}
#awd-mainarea .about_me .about_tl { background: url(../images/ab_tl.jpg) top left no-repeat; height:5px; width:6px; font-size:0;}
#awd-mainarea .about_me .about_br { background: url(../images/ab_br.jpg) bottom right no-repeat; height:5px; font-size:0; float:left; width:100%;margin:0 0 0 0;}
#awd-mainarea .about_me .about_bl { background: url(../images/ab_bl.jpg) bottom left no-repeat; height:5px; width:6px; font-size:0;}
*/
#awd-mainarea .about_me .about_content {
padding:0 10px;
margin:0;
}
#awd-mainarea .about_me .title {
font-weight:bold;
color:#50655e;
line-height:20px;
background:url(../images/icon_spen.jpg) right center no-repeat;
}
#awd-mainarea .about_me .border {
border-bottom:1px solid #b783c8;
line-height:20px;
color:#ac79bf;
}
#awd-mainarea .about_me .color1 {
color:#6985c6;
}
#awd-mainarea .attach_link {
margin:0 10px 10px 0!important;
padding:5px;
position:relative;
}
#awd-mainarea .attach_link .input {
border:1px solid #c6d7de;
border-top-color:#55758e;
margin:5px 0;
}
#awd-mainarea .attach_link .close {
font-size:17px;
position:absolute;
top:3px !important;
right:10px;
}
#awd-mainarea .attach_link .close a {
color:#333!important;
}
#awd-mainarea .wr_buton_at {
height:33px;
float:left;
line-height:32px!important;
margin-right:10px;
margin-top:-4px;
}
#awd-mainarea .wr_buton_at .button {
border:0;
display:block;
color:#fff;
font-weight:bold;
height:36px!important;
line-height:30px;
margin-top:-4px;
width:146px;
padding-left:16px;
background:url(../images/lavender/button-links.jpg) no-repeat right top;
}
#awd-mainarea .invalid { border-color: #ff0000 !important; }
#awd-mainarea #frm_message p{
margin:0 !important;
padding:0 !important;
}
#awd_video_form {
font-size:11px !important;
}
#awd_video_form ul a{
padding-right: 2px;
padding-left: 2px;
display: block;
text-decoration: none;
color:#777777 !important;
}
#awd_video_form ul{
background-image:none !important;
}
#awd_video_form ul li{
float:left;
background:none !important;
padding-right:5px !important;
line-height:100% !important;
/*list-style-type:none !important;*/
}
#awd-mainarea .maincomment_noimg{
width:100%;
float:right;
color:#333333;
line-height:100%;
}
#awd-mainarea .maincomment_noimg p {
color:#B6B6B6;
font-size: 12px;
line-height:120% !important;
}
#awd-mainarea .maincomment_noimg h3 {
font-weight: bold;
font-size: 12px;
padding:0px;
margin:0px;
color: rgb(61, 90, 150);
}
#awd-mainarea .maincomment_noimg a {
font-weight: bold;
font-size: 12px;
padding:0px;
margin:0px;
color:#ccc;
}
#awd-mainarea #<API key>{
font-size:11px;
clear:both;
float:left;
}
#awd-mainarea dl.profile-right-info {
list-style:none outside none;
margin:10px 0 0;
padding:0;
}
#awd-mainarea dl.profile-right-info dt {
background:none repeat scroll 0 0 transparent;
color:#a5a4a4;
font-size:100%;
line-height:normal;
padding:0;
margin:5px 0 0 0;
}
#awd-mainarea dl.profile-right-info dd {
color:#b783c8;
font-size:100%;
margin:0;
}
#awd_image_form {
font-size:12px !important;
}
#awd_mp3_form {
font-size:12px !important;
}
#awd_link_form {
font-size:12px !important;
}
/* #awd-mainarea .button_cancel {background:url(../images/button_cance_r.png) top right no-repeat; padding-right:6px; float:left; margin-left:10px; height:23px;} */
#awd-mainarea .button_cancel span {
background:url("../images/lavender/buttom.png") no-repeat scroll left top transparent;
color:#FFFFFF;
display:block;
font-size:12px;
font-weight:bold;
height:31px;
line-height:30px;
margin-top:-4px;
text-align:center;
width:90px;
float:left;
}
#awd-mainarea .uploadmp3 { background:url(../images/bl_at_mp3.jpg) no-repeat top left!important;}
#awd-mainarea .uploadvideo {
height:31px!important;
line-height:31px!important;
}
#awd-mainarea .uploadcamera { background:url(../images/bl_at_camera.jpg) no-repeat top left!important;}
#awd-mainarea .uploadfile { background:url(../images/bl_at_file.jpg) no-repeat top left!important;}
#frmUploadAvatar p.submit {
margin-left:100px;
}
#awd-mainarea #frmUploadAvatar p {
width:400px;
}
#awd-mainarea p {
margin-bottom:5px;
margin-top:0;
}
#awd-mainarea #frmUploadAvatar p label {
float:left;
width:100px;
}
#awd-mainarea .add_as_friend a{
color:white !important;height:30px;width:200px;background-color:#AE7BC1 ;padding:3px 10px 3px 10px;
font-weight:bold !important;
-moz-border-radius:5px 5px 5px 5px;
}
#awd-mainarea .deny_friend{
color:#1E86F9 !important;
}
#awd-mainarea .accept_friend{
color:#61BE3C !important;
}
#awd-mainarea #awd_newgroup{
padding:20px;
}
#awd-mainarea #frmNewGroup{
}
#awd-mainarea #frmNewGroup p.submit {
padding-left:100px;
}
#awd-mainarea #frmNewGroup p {
float:left;
clear:both;
}
#awd-mainarea #frmNewGroup p label {
float:left;
width:80px;
text-align:right;
padding-right:10px;
}
#awd-mainarea #awd_ng_header{
padding:10px;
border-bottom:1px solid #EEEEEE;
font-size:16px;
font-weight:bold;
}
#awd-mainarea #awd_ng_header h3{
color:#333333;
}
#awd-mainarea #aw_ng_body{
padding:10px;
min-height:250px!important;
}
#awd-mainarea #frmNewGroup p.awd_ng_type{
width:500px;
}
#awd-mainarea .awd_ng_type span{
float:left;
}
#awd-mainarea .awd_ng_rad_group input{
padding:1px 5px 1px 5px;
background-color:#d0d0d0;
border: 1px;
height:15px;
}
#awd-mainarea #frmNewGroup .submit{
margin-left:100px;
margin-top:10px;
}
#awd-mainarea .postbtn_group_black {
background: url(../images/bg_btn_group.jpg) no-repeat;
width:120px;
height:24px;
color: #000000;
border:none;
text-align:center;
line-height:22px;
font-weight:bold;
padding-bottom:5px;
}
#awd-mainarea #awd_groups{
padding:20px;
background-color:#f6f6f6 !important;
}
/* #awd_grps_cont{
background-color:#fff !important;
} */
#awd_grps_header{
padding:10px;
font-size:16px;
font-weight:bold;
width:95%;
}
#awd-mainarea .awd_grp_ele{
width:32%;
/* height:90px; */
float:left;
margin-left:4px;display:
}
#awd-mainarea .awd_grp_ele img{
float:left;
}
#awd-mainarea .awd_subgrp_ele{
float:left;
height:69px;
width:65%;
padding-top:5px;
padding-left:5px;
}
* +html #awd-mainarea .awd_subgrp_ele{
width:110px;
}
#awd-mainarea .awd_grp_new{
font-size:12px;
font-weight:bold;
float:right;
color:#56AE04;
}
#awd-mainarea .awd_grp_new a{
color:#a876b5!important;
font-size:12px;
font-weight:bold;
}
/* insert css dangcv */
#awd-mainarea .user_place div{
/* background:#E8E8E8; */
}
#awd-mainarea .blog_groups, .blog_friend{
color:#fff;
}
#awd-mainarea .blog_groups a, #awd-mainarea .blog_friend a{
color:#fff;
}
#awd-mainarea #msg_content .awdfullbox{
background:url(../images/lavender/line.png) repeat-x bottom left!important;
padding-bottom:4px;
}
#awd-mainarea #msg_content .rbroundboxleft,#awd-mainarea #msg_content .awdfullbox{
background:#E7EBEE;
}
#list_attach, #awd_video_form, #awd_image_form, #awd_mp3_form, #awd_link_form, #awd_file_form,#awd_trail_form,#awd_pm_form,#awd_article_form,#awd_jing_form,#awd_event_form{
float:left;
width:98%;
}
#awd-mainarea .fullboxnew{
float:left;
}
#awd-mainarea #frm_message{
float:left;
width:100%;
}
#awd-mainarea #awd_attached_file a{
color:#79AF15 !important;
}
#awd-mainarea div.ashare{
float:left;
left:233px;
position:absolute;
top:50px;
width:150px;
z-index:10000;
background:#D0A0DE;
-moz-border-radius:5px 5px 5px 5px;
}
#awd-mainarea .share-top{
/* background:url(../images/bor2.png) no-repeat scroll right top transparent; */
float:left;
height:7px;
width:100%;
}
#awd-mainarea .share-top div{
/* background:url(../images/tl.png) no-repeat scroll left top transparent; */
float:left;
height:7px;
width:100%;
}
#awd-mainarea .share-bottom{
/* background:url(../images/bor2.png) no-repeat scroll right bottom transparent; */
float:left;
height:6px;
width:100%;
}
#awd-mainarea .share-bottom div{
/* background:url(../images/bl.png) no-repeat scroll left top transparent; */
float:left;
height:6px;
width:100%;
}
#awd-mainarea .share-center{
margin:0 10px;
float:left;
}
#awd-mainarea .share-center a{
color:#ADB0B7;
font-size:12px;
font-weight:bold;
line-height:22px;
}
.ac_results{
border:1px solid black;
background:#fff;
width:250px!important;
text-align:left!important;
max-height:160px!important;
overflow-y:hidden!important;
}
.ac_results ul{
margin:0px;
padding:0px;
}
.ac_results ul li{
/*height:40px!important;*/
}
.autotxt{
margin-top:5px;
display:inline-block;
padding-left:10px;
position:absolute;
}
.ac_results ul li a{
color:#AD7BC0;
font-size:14px!important;
font-weight:normal!important
}
.ac_results ul li a:hover{
background: none;
}
.ac_results .ac_even{
background:#fff;
float:left!important;
display:block!important;
margin:0px!important;
padding:0px!important;
height:40px!important;
}
.ac_results .ac_odd{
background:#EEEEEE;
float:left!important;
display:block!important;
margin:0px!important;
padding:0px!important;
height:40px!important;
}
.ac_results .ac_over{
background:#F8E7FD;
}
.ac_loading{
background: white url('../images/peoplesarch.gif') right center no-repeat!important;
}
/* 24-09 */
#awd-mainarea .user_place, .mid_content_top{
float:left;
width:95%;
}
#awd-mainarea .post_msg_btn{
float:left;
width:100%;
}
#awd-mainarea .fix_op{
float:left;
}
#awd-mainarea .awd_grp_ele{
position: relative;
z-index: 1000000;
}
#awd-mainarea .fix_op_tab1{
margin:22px 0px 0px -284px;
width: 670px;
}
#awd-mainarea .fix_op_tab2{
margin:22px 0px 0px 0px!important;
}
#awd-mainarea #tabs .tab3{
width:204px;
}
#awd-mainarea #msg_content{
float:right;
/* width:598px; */
width:99.5%;
}
#awd-mainarea #area {
float:left;
overflow:hidden;
padding:0;
}
#awd-mainarea table.nopad{
width:auto!important;
}
#awd-mainarea .lightblue_box{
float:left;
width:98.5%;
}/* Attach file */
#awd-mainarea .<API key>{
background:#f8e7fd!important;
border:1px solid #b987c9;
display:block;
padding:10px;
overflow:hidden;
-moz-border-radius:6px 6px 6px 6px;
width:96%;
}
#awd-mainarea .<API key> div{
background:#f8e7fd!important;
}
#<API key> h3{
font-size:12px;
font-weight:normal;
margin:0px;
padding:0px;
}
#awd-mainarea .<API key> h3{
border-bottom:1px solid #b987c9;
float:left;
font-size:12px;
padding-bottom:8px;
width:100%;
font-weight:bold;
color:#AD7BC0;
}
.<API key> .<API key>, .<API key> #awd_attached_title, .<API key> #awd_attached_des, .<API key> .<API key>, .<API key> br{
display:block!important;
}
.<API key>, #awd_attached_title, #awd_attached_des, .<API key>, #<API key> br{
display:none;
}
#<API key>{
float:right;
width:80%;
}
#<API key>{
float:left;
width:20%;
font-size:0px;
}
#<API key> img{
width:110px;
float:left;
}
#awd_attached_file{
float:left;
padding:4px 0;
width:100%;
}
#awd-mainarea img.hidden{
display:none;
}
#awd-mainarea .<API key>{
float:left;
width:28%;
}
#awd-mainarea .<API key> img{
width:110px;
}
#awd-mainarea .<API key>{
float:right;
width:68%;
}
#awd-mainarea #count_text{
float: left;
padding-left: 8px;
line-height: 22px;
}
#awd-mainarea .subcommentImagebox img{
width:55%;
}
#awd-mainarea .<API key>{
float:left;
line-height:20px;
padding-top:6px;
}
#awd-mainarea #hidden_img{
clear:both;
display:block;
float:left;
}
#<API key>{
float:left;
width:100%;
}
#awd-mainarea #<API key> h3{
float:left;
}
#awd-mainarea .<API key>{
float:right;
width:82%;
}
#awd-mainarea #awd_attached_file{
padding:0px 0 0 2px;
}
#<API key>{
width:80%;
}
#awd-mainarea .<API key>{
width:80%!important;
}
#awd-mainarea .<API key> #<API key>{
width:78%!important;
}
#awd-mainarea .subcommentImagebox img{
width:32px;
height:auto;
}
/* insert css */
#awd-mainarea #frm_auto_search{
float:left;
width:96%;
/*background:url(../images/lavender/icon-search.png) no-repeat right top;*/
margin-top:9px!important;
}
#awd-mainarea #frm_auto_search input{
float:left;
}
#awd-mainarea .line{
background:url(../images/lavender/line.png) repeat-x top left!important;
line-height:5px !important;
/*border-bottom: 1px solid #DFC5E6;*/
}
#awd-mainarea .wall{
background:url(../images/lavender/line.png) repeat-x bottom left!important;
padding-bottom:8px;
}
#awd-mainarea #awd-mainarea .profileName a{
color: #AD7BC0;
font-size:12px;
font-weight: bold;
text-align:left !important;
/*padding-left:8px;*/
text-transform:capitalize;
}
#awd-mainarea ul.profileMenu li.ppm {
background: url(../images/lavender/icon-news.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.pvideo {
background: url(../images/lavender/icon-videos.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.pimage {
background: url(../images/lavender/icon-images.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.pmessage {
background: url(../images/lavender/icon-message.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.ptrail {
background: url(../images/lavender/icon-trails.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.pjing {
background: url(../images/lavender/icon-jing.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.pevent {
background: url(../images/lavender/icon-event.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.particle {
background: url(../images/lavender/icon-article.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.music {
background: url(../images/lavender/icon-music.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.files {
background: url(../images/lavender/icon-file.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.friend {
background: url(../images/lavender/icon-friends.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.friend {
background: url(../images/lavender/icon-friends.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.groups {
background: url(../images/lavender/icon-groups.png) no-repeat left !important;
}
#awd-mainarea ul.profileMenu li.links {
background: url(../images/lavender/icon-links.png) no-repeat left !important;
}
#awd-mainarea h2.newsFeed {
background: url(../images/lavender/news.png) no-repeat left !important;
line-height:38px;
padding:0px 0px 4px 50px;
margin:0px;
font-size: 16px;
color:#717171;
font-weight: bold;
}
#awd-mainarea .postButton_small {
background: url(../images/lavender/buttom.png) no-repeat!important;
width:91px!important;
height:31px!important;
color: #FFF!important;
border:none!important;
text-align:center!important;
line-height:22px!important;
font-weight:bold!important;
float:right!important;
padding-bottom:5px!important;
box-shadow:none!important;
border-radius:none!important;
}
/*
#awd-mainarea .rbtop div {
background: url(../images/tl.gif) no-repeat top left;
}
#awd-mainarea .rbtop {
background: url(../images/tr.gif) no-repeat top right;
}
#awd-mainarea .rbbot div {
background: url(../images/bl.gif) no-repeat bottom left;
}
#awd-mainarea .rbbot {
background: url(../images/br.gif) no-repeat bottom right;
}
*/
#awd-mainarea .blog_content hr{
border:0px;
}
#awd-mainarea .blog_content span{
text-decoration:underline;
}
#awd-mainarea #submit{
height:30px!important;
line-height:30px!important;
text-align:center!important;
color:#fff!important;
background:url("../images/lavender/button-left.png") no-repeat scroll 0px 1px transparent!important;
border:0px!important;
font-weight:bold!important;
padding-left:5px!important;
margin-top:-1px!important;
}
#awd-mainarea p.submit{
height:30px!important;
line-height:30px!important;
text-align:center!important;
color:#fff!important;
background:url("../images/lavender/button-right.png") no-repeat scroll right top transparent!important;
border:0px!important;
font-weight:bold!important;
padding-right:5px!important;
padding-left:0px!important;
float:left!important;
width:auto!important;
}
#awd-mainarea #frmUploadAvatar p.submit{
padding-right:16px;
}
#awd-mainarea #frmUploadAvatar #submit{
padding-left:16px;
}
#awd-mainarea #frmUploadAvatar, #frmNewGroup{
color:#797979;
}
#awd-mainarea #frmUploadAvatar h3, #frmNewGroup h3{
color:#ac79bf;
}
#awd-mainarea #frmUploadAvatar input, #frmUploadAvatar select, #frmUploadAvatar textarea,
#frmNewGroup input, #frmNewGroup select, #frmNewGroup textarea{
border:1px solid #a876b5;
}
#awd-mainarea #awd_grps_header{
color:#a876b5;
}
#awd-mainarea #awd_grps_body a, #awd_grps_body b{
color:#a876b5;
font-size:12px!important;
}
#awd-mainarea #awd_grps_body li b{
color:#858585;
}
/*div.moduletable, div.module {
margin-bottom: 25px;
float: left;
}
*/#awd-mainarea .uploadvideo .button{
background:url(../images/lavender/button-video.jpg) no-repeat right top;
}
#awd-mainarea .uploadcamera .button{
background:url(../images/lavender/button-image.jpg) no-repeat right top;
}
#awd-mainarea .uploadmp3 .button{
background:url(../images/lavender/button-music.jpg) no-repeat right top;
}
#awd-mainarea .uploadfile .button{
background:url(../images/lavender/button-files.jpg) no-repeat right top;
}
#awd-mainarea .rbroundboxleft .mid_content a img{
max-width:133px;
}
#awd-mainarea .share a{
color:#222!important;
}
#awd-mainarea .title-mus h3{
color:#AD7BC0!important;
}
#awd-mainarea ul{
list-style:none;
}
#awd-mainarea .mid_content p{
text-align:left !important;
padding:1px;
}
#awd-mainarea .mid_content a.mvideo {
background: url(../images/lavender/icon-videos.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea .mid_content a.mphoto {
background: url(../images/lavender/icon-images.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea .mid_content a.minfo {
background: url(../images/lavender/icon-info.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea .mid_content a.mmessage {
background: url(../images/lavender/icon-message.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea .mid_content a.friends {
background: url(../images/lavender/icon-friends.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea .mid_content a.groups {
background: url(../images/lavender/icon-groups.png) no-repeat left !important;
padding-left:28px;
}
#awd-mainarea #dropAlerts {
background: none repeat scroll 0 0 #F5F5F5;
border-color: #E5E5E5;
border-style: solid;
border-width: 1px 1px 1px;
position: absolute;
width: 300px;
z-index: 99999;
font-size:11px;
font-family:Tahoma,Arial,Helvetica,sans-serif;
color:#000000!important;
font-weight:normal!important;
max-height:192px;
min-height:40px;
overflow-y:scroll;
overflow-x:hidden;
}
#awd-mainarea #dropAlerts a{
background: none!important;
cursor:pointer!important;
color:#000000!important;
font-weight:normal!important;
}
#awd-mainarea #dropAlerts a:hover{
background: none!important;
color:#000000!important;
}
#awd-mainarea #dropAlerts .notiItem {
display: block;
margin: 0;
padding: 4px;
float:left;
width:100%;
}
#awd-mainarea #dropAlerts .notiItem:hover {
display: block;
background-color:#F9E7FD;
}
#awd-mainarea .itemThumb30px .thumbWrap {
float: left;
margin: 0;
overflow: hidden;
width: 30px;
}
#awd-mainarea .itemThumb30px .txtWrap {
margin-left: 55px;
margin-right: 5px;
}
#awd-mainarea a.userlink{
font-size:11px!important;
display:inline!important;
height:auto!important;
margin:0px!important;
padding:0px 5px 0px 0px!important;
color:#000000!important;
text-decoration:underline!important;
background: none!important;
cursor:pointer!important;
font-weight:normal!important;
}
#awd-mainarea .wallheadingRight li .txtWrap a.userlink{
line-height:12px!important;
height:12px!important;
}
#awd-mainarea .notiItemsWrap{
border-bottom:1px solid #E5E5E5;
cursor:pointer;
opacity:0.7;
filter:alpha(opacity=70);
float:left;
width:100%;
line-height:normal!important;
}
#awd-mainarea .notiItemsWrapLast{
border-bottom:0px solid #E5E5E5;
cursor:pointer;
opacity:0.7;
filter:alpha(opacity=70);
float:left;
width:100%;
line-height:normal!important;
}
#awd-mainarea .notiItemsWrap:hover{
opacity:1;
filter:alpha(opacity=100);
}
#awd-mainarea .notiItemsWrapLast:hover{
opacity:1;
filter:alpha(opacity=100);
}
#awd-mainarea .removenoticeDiv{
width:10px;
float:right;
}
#awd-mainarea .awdloading{
padding:13px 0px;
}
#awd-mainarea #alertimg
{
margin-top:7px;
}
#awd-mainarea .imglogout
{
margin-top:12px;
}
#awd-mainarea .wallheadingRight li.no a:hover
{
background:none!important;
}
#awd-mainarea .vicons{
float:left;
margin:0px 2px 2px 2px;
padding:0px 2px 0px 2px;
}
#awd-mainarea .likespan{
background-image:url(../images/like.png);
background-repeat:no-repeat;
background-position:left center;
padding-left:20px;
font-size:11px;
}
#awd-mainarea .awdmessagetxt a{
font-weight:normal!important;
}
#awd-mainarea .wallheadingRight li.activenews{
background:url(../images/lavender/menu-center-hover.png) repeat-x center center!important;
margin-top:0px;
}
#awd-mainarea .wallheadingRight li a.newsfeed{
background-image:url(../images/newsfeed.png)!important;
width:35px;
display:block;
background-position:center;
background-repeat:no-repeat;
font-size:0px;
}
#awd-mainarea .wallheadingRight li a.activenews{
background-image:url(../images/hovernewsfeed.png)!important;
width:35px;
display:block;
background-position:center!important;
background-repeat:no-repeat!important;
font-size:0px;
}
#awd-mainarea .wallheadingRight li a.newsfeed:hover{
background-image:url(../images/hovernewsfeed.png)!important;
background-position:center!important;
background-repeat:no-repeat!important;
}
#awd-mainarea tr, #awd-mainarea td {
border:0px!important;
padding:0px!important;
}
#awd-mainarea .wallheadingRight ul ul{
background:none;
}
#awd-mainarea .avtartool{
margin-top:5px;
}
#awd-mainarea table{
border:none !important;
}
#awd-mainarea .wallheadingRight ul li.toolbaravtar a {
font-weight:normal!important;
font-size:11px!important;
}
#awd-mainarea #tabs .ui-tabs-nav a{
font-size:12px !important;
}
#awd-mainarea .button{
box-shadow: none!important;
border-radius:none!important;
}
#awd-mainarea #msg_content .rbroundboxleft{
width:17%!important;
}
#awd-mainarea #msg_content .rbroundboxright{
width:82%!important;
}
.hasDatepicker {
width: 120px !important;
}
#awd-mainarea .form-input1 textarea, #awd-mainarea .form-input1 input[type="text"], #awd-mainarea .form-input1 input[type="password"], #awd-mainarea .form-input1 input[type="email"], #awd-mainarea .form-input1 input[type="url"], #awd-mainarea .form-input1 input[type="date"], #awd-mainarea .form-input1 input[type="number"], #awd-mainarea .form-input1 input[type="time"], #awd-mainarea .form-input1 input[type="date"], #awd-mainarea .form-input1 input.date, #awd-mainarea .form-input1 .selector, #awd-mainarea .form-input1 .uploader, #awd-mainarea .form-input1 .radiogroup, #awd-mainarea .form-input1 .checkgroup {
-moz-appearance: none;
border-radius: 0 0 0 0;
box-shadow: none;
display: block;
line-height: 22px;
width: 100%;
}
#awd-mainarea .form-input1{
display:block;
float:left!important;
width:65%;
margin-bottom:3px!important;
}
input.date, input[type="text"], input[type="password"], input[type="url"], input[type="email"], input[type="date"], input[type="time"], textarea, .uploader span.filename {
border: 1px solid #AAAAAA;
border-radius: 2px 2px 2px 2px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) inset, 0 1px 0 rgba(255, 255, 255, 0.2);
padding: 4px;
font-size:13px!important;
}
input, select, textarea, button, .button, .pagination li a, .toolbar li a {
-moz-box-sizing: border-box;
background-clip: padding-box;
}
input, select {
vertical-align: middle;
} |
<?php
// this file contains the contents of the popup window
?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<title>Insert YouTube Video</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.js"></script>
<script language="javascript" type="text/javascript" src="../../../../../../wp-includes/js/tinymce/tiny_mce_popup.js"></script>
<style type="text/css" src="../../../wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css"></style>
<link rel="stylesheet" href="buttons_tinymce.css" />
<script type="text/javascript">
var ButtonDialog = {
local_ed : 'ed',
init : function(ed) {
ButtonDialog.local_ed = ed;
tinyMCEPopup.resizeToInnerSize();
},
insert : function insertButton(ed) {
// Try and remove existing style / blockquote
//tinyMCEPopup.execCommand('mceRemoveNode', false, null);
// set up variables to contain our input values
var youtube = jQuery('#button-dialog textarea#button-text').val();
var output = '';
// setup the output of our shortcode
output = '[youtube vid="' + youtube + '"]';
tinyMCEPopup.execCommand('mceReplaceContent', false, output);
// Return
tinyMCEPopup.close();
}
};
tinyMCEPopup.onInit.add(ButtonDialog.init, ButtonDialog);
</script>
</head>
<body>
<div id="button-dialog">
<form action="/" method="get" accept-charset="utf-8">
<div>
<label for="button-text">YouTube video ID </br></br><strong>EG. HZwMX6T5Jhk</strong></br></br>Can be found in the videos URL</label>
<textarea name="button-text" value="" id="button-text"></textarea>
</div>
<div>
<a href="javascript:ButtonDialog.insert(ButtonDialog.local_ed)" id="insert" style="display: block; line-height: 24px;">Insert</a>
</div>
</form>
</div>
</body>
</html> |
# ex:ts=4:sw=4:sts=4:et
# -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
# This program is free software; you can redistribute it and/or modify
# published by the Free Software Foundation.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
from wic import msger
from wic.pluginbase import SourcePlugin
from wic.utils.oe.misc import exec_cmd, get_bitbake_var
class RawCopyPlugin(SourcePlugin):
name = 'rawcopy'
@classmethod
def do_install_disk(self, disk, disk_name, cr, workdir, oe_builddir,
bootimg_dir, kernel_dir, native_sysroot):
"""
Called after all partitions have been prepared and assembled into a
disk image. Do nothing.
"""
pass
@classmethod
def <API key>(self, part, source_params, cr, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
native_sysroot):
"""
Called before <API key>(). Possibly prepare
configuration files of some sort.
"""
pass
@classmethod
def <API key>(self, part, source_params, cr, cr_workdir,
oe_builddir, bootimg_dir, kernel_dir,
rootfs_dir, native_sysroot):
"""
Called to do the actual content population for a partition i.e. it
'prepares' the partition to be incorporated into the image.
"""
if not bootimg_dir:
bootimg_dir = get_bitbake_var("DEPLOY_DIR_IMAGE")
if not bootimg_dir:
msger.error("Couldn't find DEPLOY_DIR_IMAGE, exiting\n")
msger.debug('Bootimg dir: %s' % bootimg_dir)
if ('file' not in source_params):
msger.error("No file specified\n")
return
src = os.path.join(bootimg_dir, source_params['file'])
dst = src
if ('skip' in source_params):
dst = os.path.join(cr_workdir, source_params['file'])
dd_cmd = "dd if=%s of=%s ibs=%s skip=1 conv=notrunc" % \
(src, dst, source_params['skip'])
exec_cmd(dd_cmd)
# get the size in the right units for kickstart (kB)
du_cmd = "du -Lbks %s" % dst
out = exec_cmd(du_cmd)
filesize = out.split()[0]
if int(filesize) > int(part.size):
part.size = filesize
part.source_file = dst |
/* This file contains basic routines manipulating call graph
The call-graph is a data structure designed for intra-procedural optimization.
It represents a multi-graph where nodes are functions and edges are call sites. */
#include "config.h"
#include "system.h"
#include "coretypes.h"
#include "tm.h"
#include "hash-set.h"
#include "machmode.h"
#include "vec.h"
#include "double-int.h"
#include "input.h"
#include "alias.h"
#include "symtab.h"
#include "wide-int.h"
#include "inchash.h"
#include "tree.h"
#include "fold-const.h"
#include "varasm.h"
#include "calls.h"
#include "print-tree.h"
#include "tree-inline.h"
#include "langhooks.h"
#include "hashtab.h"
#include "toplev.h"
#include "flags.h"
#include "debug.h"
#include "target.h"
#include "predict.h"
#include "dominance.h"
#include "cfg.h"
#include "basic-block.h"
#include "hash-map.h"
#include "is-a.h"
#include "plugin-api.h"
#include "hard-reg-set.h"
#include "function.h"
#include "ipa-ref.h"
#include "cgraph.h"
#include "intl.h"
#include "tree-ssa-alias.h"
#include "internal-fn.h"
#include "tree-eh.h"
#include "gimple-expr.h"
#include "gimple.h"
#include "gimple-iterator.h"
#include "timevar.h"
#include "dumpfile.h"
#include "gimple-ssa.h"
#include "tree-cfg.h"
#include "tree-ssa.h"
#include "value-prof.h"
#include "except.h"
#include "diagnostic-core.h"
#include "rtl.h"
#include "ipa-utils.h"
#include "lto-streamer.h"
#include "alloc-pool.h"
#include "symbol-summary.h"
#include "ipa-prop.h"
#include "ipa-inline.h"
#include "cfgloop.h"
#include "gimple-pretty-print.h"
#include "statistics.h"
#include "real.h"
#include "fixed-value.h"
#include "insn-config.h"
#include "expmed.h"
#include "dojump.h"
#include "explow.h"
#include "emit-rtl.h"
#include "stmt.h"
#include "expr.h"
#include "tree-dfa.h"
#include "profile.h"
#include "params.h"
#include "tree-chkp.h"
#include "context.h"
/* FIXME: Only for PROP_loops, but cgraph shouldn't have to know about this. */
#include "tree-pass.h"
/* Queue of cgraph nodes scheduled to be lowered. */
symtab_node *<API key>;
#define cgraph_nodes_queue ((cgraph_node *)<API key>)
/* Symbol table global context. */
symbol_table *symtab;
/* List of hooks triggered on cgraph_edge events. */
struct <API key> {
cgraph_edge_hook hook;
void *data;
struct <API key> *next;
};
/* List of hooks triggered on cgraph_node events. */
struct <API key> {
cgraph_node_hook hook;
void *data;
struct <API key> *next;
};
/* List of hooks triggered on events involving two cgraph_edges. */
struct <API key> {
cgraph_2edge_hook hook;
void *data;
struct <API key> *next;
};
/* List of hooks triggered on events involving two cgraph_nodes. */
struct <API key> {
cgraph_2node_hook hook;
void *data;
struct <API key> *next;
};
/* Hash descriptor for <API key>. */
struct <API key> : ggc_hasher<<API key> *>
{
static hashval_t hash (<API key> *);
static bool equal (<API key> *,
<API key> *);
};
/* Map a cgraph_node to <API key> using this htab.
The <API key> has a THIS_NODE field that is the
corresponding cgraph_node.. */
static GTY(()) hash_table<<API key>> *cgraph_fnver_htab = NULL;
/* Hash function for cgraph_fnver_htab. */
hashval_t
<API key>::hash (<API key> *ptr)
{
int uid = ptr->this_node->uid;
return (hashval_t)(uid);
}
/* eq function for cgraph_fnver_htab. */
bool
<API key>::equal (<API key> *n1,
<API key> *n2)
{
return n1->this_node->uid == n2->this_node->uid;
}
/* Mark as GC root all allocated nodes. */
static GTY(()) struct <API key> *
version_info_node = NULL;
/* Get the <API key> node corresponding to node. */
<API key> *
cgraph_node::function_version (void)
{
<API key> key;
key.this_node = this;
if (cgraph_fnver_htab == NULL)
return NULL;
return cgraph_fnver_htab->find (&key);
}
/* Insert a new <API key> node into cgraph_fnver_htab
corresponding to cgraph_node NODE. */
<API key> *
cgraph_node::<API key> (void)
{
version_info_node = NULL;
version_info_node = ggc_cleared_alloc<<API key>> ();
version_info_node->this_node = this;
if (cgraph_fnver_htab == NULL)
cgraph_fnver_htab = hash_table<<API key>>::create_ggc (2);
*cgraph_fnver_htab->find_slot (version_info_node, INSERT)
= version_info_node;
return version_info_node;
}
/* Remove the <API key> and cgraph_node for DECL. This
DECL is a duplicate declaration. */
void
cgraph_node::<API key> (tree decl)
{
cgraph_node *decl_node = cgraph_node::get (decl);
<API key> *decl_v = NULL;
if (decl_node == NULL)
return;
decl_v = decl_node->function_version ();
if (decl_v == NULL)
return;
if (decl_v->prev != NULL)
decl_v->prev->next = decl_v->next;
if (decl_v->next != NULL)
decl_v->next->prev = decl_v->prev;
if (cgraph_fnver_htab != NULL)
cgraph_fnver_htab->remove_elt (decl_v);
decl_node->remove ();
}
/* Record that DECL1 and DECL2 are semantically identical function
versions. */
void
cgraph_node::<API key> (tree decl1, tree decl2)
{
cgraph_node *decl1_node = cgraph_node::get_create (decl1);
cgraph_node *decl2_node = cgraph_node::get_create (decl2);
<API key> *decl1_v = NULL;
<API key> *decl2_v = NULL;
<API key> *before;
<API key> *after;
gcc_assert (decl1_node != NULL && decl2_node != NULL);
decl1_v = decl1_node->function_version ();
decl2_v = decl2_node->function_version ();
if (decl1_v != NULL && decl2_v != NULL)
return;
if (decl1_v == NULL)
decl1_v = decl1_node-><API key> ();
if (decl2_v == NULL)
decl2_v = decl2_node-><API key> ();
/* Chain decl2_v and decl1_v. All semantically identical versions
will be chained together. */
before = decl1_v;
after = decl2_v;
while (before->next != NULL)
before = before->next;
while (after->prev != NULL)
after= after->prev;
before->next = after;
after->prev = before;
}
/* Initialize callgraph dump file. */
void
symbol_table::initialize (void)
{
if (!dump_file)
dump_file = dump_begin (TDI_cgraph, NULL);
}
/* Allocate new callgraph node and insert it into basic data structures. */
cgraph_node *
symbol_table::create_empty (void)
{
cgraph_node *node = <API key> ();
node->type = SYMTAB_FUNCTION;
node->frequency = <API key>;
node-><API key> = REG_BR_PROB_BASE;
cgraph_count++;
return node;
}
/* Register HOOK to be called with DATA on each removed edge. */
<API key> *
symbol_table::<API key> (cgraph_edge_hook hook, void *data)
{
<API key> *entry;
<API key> **ptr = &<API key>;
entry = (<API key> *) xmalloc (sizeof (*entry));
entry->hook = hook;
entry->data = data;
entry->next = NULL;
while (*ptr)
ptr = &(*ptr)->next;
*ptr = entry;
return entry;
}
/* Remove ENTRY from the list of hooks called on removing edges. */
void
symbol_table::<API key> (<API key> *entry)
{
<API key> **ptr = &<API key>;
while (*ptr != entry)
ptr = &(*ptr)->next;
*ptr = entry->next;
free (entry);
}
/* Call all edge removal hooks. */
void
symbol_table::<API key> (cgraph_edge *e)
{
<API key> *entry = <API key>;
while (entry)
{
entry->hook (e, entry->data);
entry = entry->next;
}
}
/* Register HOOK to be called with DATA on each removed node. */
<API key> *
symbol_table::<API key> (cgraph_node_hook hook, void *data)
{
<API key> *entry;
<API key> **ptr = &<API key>;
entry = (<API key> *) xmalloc (sizeof (*entry));
entry->hook = hook;
entry->data = data;
entry->next = NULL;
while (*ptr)
ptr = &(*ptr)->next;
*ptr = entry;
return entry;
}
/* Remove ENTRY from the list of hooks called on removing nodes. */
void
symbol_table::<API key> (<API key> *entry)
{
<API key> **ptr = &<API key>;
while (*ptr != entry)
ptr = &(*ptr)->next;
*ptr = entry->next;
free (entry);
}
/* Call all node removal hooks. */
void
symbol_table::<API key> (cgraph_node *node)
{
<API key> *entry = <API key>;
while (entry)
{
entry->hook (node, entry->data);
entry = entry->next;
}
}
/* Call all node removal hooks. */
void
symbol_table::<API key> (cgraph_node *node)
{
<API key> *entry = <API key>;
while (entry)
{
entry->hook (node, entry->data);
entry = entry->next;
}
}
/* Register HOOK to be called with DATA on each inserted node. */
<API key> *
symbol_table::<API key> (cgraph_node_hook hook, void *data)
{
<API key> *entry;
<API key> **ptr = &<API key>;
entry = (<API key> *) xmalloc (sizeof (*entry));
entry->hook = hook;
entry->data = data;
entry->next = NULL;
while (*ptr)
ptr = &(*ptr)->next;
*ptr = entry;
return entry;
}
/* Remove ENTRY from the list of hooks called on inserted nodes. */
void
symbol_table::<API key> (<API key> *entry)
{
<API key> **ptr = &<API key>;
while (*ptr != entry)
ptr = &(*ptr)->next;
*ptr = entry->next;
free (entry);
}
/* Register HOOK to be called with DATA on each duplicated edge. */
<API key> *
symbol_table::<API key> (cgraph_2edge_hook hook, void *data)
{
<API key> *entry;
<API key> **ptr = &<API key>;
entry = (<API key> *) xmalloc (sizeof (*entry));
entry->hook = hook;
entry->data = data;
entry->next = NULL;
while (*ptr)
ptr = &(*ptr)->next;
*ptr = entry;
return entry;
}
/* Remove ENTRY from the list of hooks called on duplicating edges. */
void
symbol_table::<API key> (<API key> *entry)
{
<API key> **ptr = &<API key>;
while (*ptr != entry)
ptr = &(*ptr)->next;
*ptr = entry->next;
free (entry);
}
/* Call all edge duplication hooks. */
void
symbol_table::<API key> (cgraph_edge *cs1, cgraph_edge *cs2)
{
<API key> *entry = <API key>;
while (entry)
{
entry->hook (cs1, cs2, entry->data);
entry = entry->next;
}
}
/* Register HOOK to be called with DATA on each duplicated node. */
<API key> *
symbol_table::<API key> (cgraph_2node_hook hook, void *data)
{
<API key> *entry;
<API key> **ptr = &<API key>;
entry = (<API key> *) xmalloc (sizeof (*entry));
entry->hook = hook;
entry->data = data;
entry->next = NULL;
while (*ptr)
ptr = &(*ptr)->next;
*ptr = entry;
return entry;
}
/* Remove ENTRY from the list of hooks called on duplicating nodes. */
void
symbol_table::<API key> (<API key> *entry)
{
<API key> **ptr = &<API key>;
while (*ptr != entry)
ptr = &(*ptr)->next;
*ptr = entry->next;
free (entry);
}
/* Call all node duplication hooks. */
void
symbol_table::<API key> (cgraph_node *node,
cgraph_node *node2)
{
<API key> *entry = <API key>;
while (entry)
{
entry->hook (node, node2, entry->data);
entry = entry->next;
}
}
/* Return cgraph node assigned to DECL. Create new one when needed. */
cgraph_node *
cgraph_node::create (tree decl)
{
cgraph_node *node = symtab->create_empty ();
gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
node->decl = decl;
if ((flag_openacc || flag_openmp)
&& lookup_attribute ("omp declare target", DECL_ATTRIBUTES (decl)))
{
node->offloadable = 1;
#ifdef ENABLE_OFFLOADING
g->have_offload = true;
#endif
}
node->register_symbol ();
if (DECL_CONTEXT (decl) && TREE_CODE (DECL_CONTEXT (decl)) == FUNCTION_DECL)
{
node->origin = cgraph_node::get_create (DECL_CONTEXT (decl));
node->next_nested = node->origin->nested;
node->origin->nested = node;
}
return node;
}
/* Try to find a call graph node for declaration DECL and if it does not exist
or if it corresponds to an inline clone, create a new one. */
cgraph_node *
cgraph_node::get_create (tree decl)
{
cgraph_node *first_clone = cgraph_node::get (decl);
if (first_clone && !first_clone->global.inlined_to)
return first_clone;
cgraph_node *node = cgraph_node::create (decl);
if (first_clone)
{
first_clone->clone_of = node;
node->clones = first_clone;
symtab-><API key> (node);
node->decl->decl_with_vis.symtab_node = node;
if (dump_file)
fprintf (dump_file, "Introduced new external node "
"(%s/%i) and turned into root of the clone tree.\n",
node->name (), node->order);
}
else if (dump_file)
fprintf (dump_file, "Introduced new external node "
"(%s/%i).\n", node->name (), node->order);
return node;
}
/* Mark ALIAS as an alias to DECL. DECL_NODE is cgraph node representing
the function body is associated with (not necessarily cgraph_node (DECL). */
cgraph_node *
cgraph_node::create_alias (tree alias, tree target)
{
cgraph_node *alias_node;
gcc_assert (TREE_CODE (target) == FUNCTION_DECL
|| TREE_CODE (target) == IDENTIFIER_NODE);
gcc_assert (TREE_CODE (alias) == FUNCTION_DECL);
alias_node = cgraph_node::get_create (alias);
gcc_assert (!alias_node->definition);
alias_node->alias_target = target;
alias_node->definition = true;
alias_node->alias = true;
if (lookup_attribute ("weakref", DECL_ATTRIBUTES (alias)) != NULL)
alias_node->weakref = true;
return alias_node;
}
/* Attempt to mark ALIAS as an alias to DECL. Return alias node if successful
and NULL otherwise.
Same body aliases are output whenever the body of DECL is output,
and cgraph_node::get (ALIAS) transparently returns
cgraph_node::get (DECL). */
cgraph_node *
cgraph_node::<API key> (tree alias, tree decl)
{
cgraph_node *n;
#ifndef ASM_OUTPUT_DEF
/* If aliases aren't supported by the assembler, fail. */
return NULL;
#endif
/* Langhooks can create same body aliases of symbols not defined.
Those are useless. Drop them on the floor. */
if (symtab->global_info_ready)
return NULL;
n = cgraph_node::create_alias (alias, decl);
n->cpp_implicit_alias = true;
if (symtab-><API key>)
n->resolve_alias (cgraph_node::get (decl));
return n;
}
/* Add thunk alias into callgraph. The alias declaration is ALIAS and it
aliases DECL with an adjustments made into the first parameter.
See comments in thunk_adjust for detail on the parameters. */
cgraph_node *
cgraph_node::create_thunk (tree alias, tree, bool this_adjusting,
HOST_WIDE_INT fixed_offset,
HOST_WIDE_INT virtual_value,
tree virtual_offset,
tree real_alias)
{
cgraph_node *node;
node = cgraph_node::get (alias);
if (node)
node->reset ();
else
node = cgraph_node::create (alias);
gcc_checking_assert (!virtual_offset
|| wi::eq_p (virtual_offset, virtual_value));
node->thunk.fixed_offset = fixed_offset;
node->thunk.this_adjusting = this_adjusting;
node->thunk.virtual_value = virtual_value;
node->thunk.virtual_offset_p = virtual_offset != NULL;
node->thunk.alias = real_alias;
node->thunk.thunk_p = true;
node->definition = true;
return node;
}
/* Return the cgraph node that has ASMNAME for its DECL_ASSEMBLER_NAME.
Return NULL if there's no such node. */
cgraph_node *
cgraph_node::get_for_asmname (tree asmname)
{
/* We do not want to look at inline clones. */
for (symtab_node *node = symtab_node::get_for_asmname (asmname);
node;
node = node-><API key>)
{
cgraph_node *cn = dyn_cast <cgraph_node *> (node);
if (cn && !cn->global.inlined_to)
return cn;
}
return NULL;
}
/* Returns a hash value for X (which really is a cgraph_edge). */
hashval_t
cgraph_edge_hasher::hash (cgraph_edge *e)
{
/* This is a really poor hash function, but it is what htab_hash_pointer
uses. */
return (hashval_t) ((intptr_t)e->call_stmt >> 3);
}
/* Returns a hash value for X (which really is a cgraph_edge). */
hashval_t
cgraph_edge_hasher::hash (gimple call_stmt)
{
/* This is a really poor hash function, but it is what htab_hash_pointer
uses. */
return (hashval_t) ((intptr_t)call_stmt >> 3);
}
/* Return nonzero if the call_stmt of of cgraph_edge X is stmt *Y. */
inline bool
cgraph_edge_hasher::equal (cgraph_edge *x, gimple y)
{
return x->call_stmt == y;
}
/* Add call graph edge E to call site hash of its caller. */
static inline void
<API key> (cgraph_edge *e)
{
gimple call = e->call_stmt;
*e->caller->call_site_hash->find_slot_with_hash
(call, cgraph_edge_hasher::hash (call), INSERT) = e;
}
/* Add call graph edge E to call site hash of its caller. */
static inline void
<API key> (cgraph_edge *e)
{
/* There are two speculative edges for every statement (one direct,
one indirect); always hash the direct one. */
if (e->speculative && e-><API key>)
return;
cgraph_edge **slot = e->caller->call_site_hash->find_slot_with_hash
(e->call_stmt, cgraph_edge_hasher::hash (e->call_stmt), INSERT);
if (*slot)
{
gcc_assert (((cgraph_edge *)*slot)->speculative);
if (e->callee)
*slot = e;
return;
}
gcc_assert (!*slot || e->speculative);
*slot = e;
}
/* Return the callgraph edge representing the GIMPLE_CALL statement
CALL_STMT. */
cgraph_edge *
cgraph_node::get_edge (gimple call_stmt)
{
cgraph_edge *e, *e2;
int n = 0;
if (call_site_hash)
return call_site_hash->find_with_hash
(call_stmt, cgraph_edge_hasher::hash (call_stmt));
/* This loop may turn out to be performance problem. In such case adding
hashtables into call nodes with very many edges is probably best
solution. It is not good idea to add pointer into CALL_EXPR itself
because we want to make possible having multiple cgraph nodes representing
different clones of the same body before the body is actually cloned. */
for (e = callees; e; e = e->next_callee)
{
if (e->call_stmt == call_stmt)
break;
n++;
}
if (!e)
for (e = indirect_calls; e; e = e->next_callee)
{
if (e->call_stmt == call_stmt)
break;
n++;
}
if (n > 100)
{
call_site_hash = hash_table<cgraph_edge_hasher>::create_ggc (120);
for (e2 = callees; e2; e2 = e2->next_callee)
<API key> (e2);
for (e2 = indirect_calls; e2; e2 = e2->next_callee)
<API key> (e2);
}
return e;
}
/* Change field call_stmt of edge to NEW_STMT.
If UPDATE_SPECULATIVE and E is any component of speculative
edge, then update all components. */
void
cgraph_edge::set_call_stmt (gcall *new_stmt, bool update_speculative)
{
tree decl;
/* Speculative edges has three component, update all of them
when asked to. */
if (update_speculative && speculative)
{
cgraph_edge *direct, *indirect;
ipa_ref *ref;
<API key> (direct, indirect, ref);
direct->set_call_stmt (new_stmt, false);
indirect->set_call_stmt (new_stmt, false);
ref->stmt = new_stmt;
return;
}
/* Only direct speculative edges go to call_site_hash. */
if (caller->call_site_hash
&& (!speculative || !<API key>))
{
caller->call_site_hash-><API key>
(call_stmt, cgraph_edge_hasher::hash (call_stmt));
}
cgraph_edge *e = this;
call_stmt = new_stmt;
if (<API key>
&& (decl = gimple_call_fndecl (new_stmt)))
{
/* Constant propagation (and possibly also inlining?) can turn an
indirect call into a direct one. */
cgraph_node *new_callee = cgraph_node::get (decl);
gcc_checking_assert (new_callee);
e = make_direct (new_callee);
}
push_cfun (<API key> (e->caller->decl));
e->can_throw_external = <API key> (new_stmt);
pop_cfun ();
if (e->caller->call_site_hash)
<API key> (e);
}
/* Allocate a cgraph_edge structure and fill it with data according to the
parameters of which only CALLEE can be NULL (when creating an indirect call
edge). */
cgraph_edge *
symbol_table::create_edge (cgraph_node *caller, cgraph_node *callee,
gcall *call_stmt, gcov_type count, int freq,
bool <API key>)
{
cgraph_edge *edge;
/* LTO does not actually have access to the call_stmt since these
have not been loaded yet. */
if (call_stmt)
{
/* This is a rather expensive check possibly triggering
construction of call stmt hashtable. */
#ifdef ENABLE_CHECKING
cgraph_edge *e;
gcc_checking_assert (
!(e = caller->get_edge (call_stmt)) || e->speculative);
#endif
gcc_assert (is_gimple_call (call_stmt));
}
if (free_edges)
{
edge = free_edges;
free_edges = NEXT_FREE_EDGE (edge);
}
else
{
edge = ggc_alloc<cgraph_edge> ();
edge->uid = edges_max_uid++;
}
edges_count++;
edge->aux = NULL;
edge->caller = caller;
edge->callee = callee;
edge->prev_caller = NULL;
edge->next_caller = NULL;
edge->prev_callee = NULL;
edge->next_callee = NULL;
edge->lto_stmt_uid = 0;
edge->count = count;
gcc_assert (count >= 0);
edge->frequency = freq;
gcc_assert (freq >= 0);
gcc_assert (freq <= CGRAPH_FREQ_MAX);
edge->call_stmt = call_stmt;
push_cfun (<API key> (caller->decl));
edge->can_throw_external
= call_stmt ? <API key> (call_stmt) : false;
pop_cfun ();
if (call_stmt
&& callee && callee->decl
&& !<API key> (call_stmt, callee->decl,
false))
edge-><API key> = true;
else
edge-><API key> = false;
edge->indirect_info = NULL;
edge-><API key> = 0;
edge->speculative = false;
edge-><API key> = <API key>;
if (opt_for_fn (edge->caller->decl, flag_devirtualize)
&& call_stmt && <API key> (caller->decl))
edge-><API key>
= <API key> (NULL, NULL, call_stmt,
caller->decl);
else
edge-><API key> = caller->thunk.thunk_p;
if (call_stmt && caller->call_site_hash)
<API key> (edge);
return edge;
}
/* Create edge from a given function to CALLEE in the cgraph. */
cgraph_edge *
cgraph_node::create_edge (cgraph_node *callee,
gcall *call_stmt, gcov_type count, int freq)
{
cgraph_edge *edge = symtab->create_edge (this, callee, call_stmt, count,
freq, false);
<API key> (edge);
edge->next_caller = callee->callers;
if (callee->callers)
callee->callers->prev_caller = edge;
edge->next_callee = callees;
if (callees)
callees->prev_callee = edge;
callees = edge;
callee->callers = edge;
return edge;
}
/* Allocate <API key> and set its fields to default values. */
<API key> *
<API key> (void)
{
<API key> *ii;
ii = ggc_cleared_alloc<<API key>> ();
ii->param_index = -1;
return ii;
}
/* Create an indirect edge with a yet-undetermined callee where the call
statement destination is a formal parameter of the caller with index
PARAM_INDEX. */
cgraph_edge *
cgraph_node::<API key> (gcall *call_stmt, int ecf_flags,
gcov_type count, int freq,
bool <API key>)
{
cgraph_edge *edge = symtab->create_edge (this, NULL, call_stmt,
count, freq, true);
tree target;
<API key> (edge);
edge->indirect_info = <API key> ();
edge->indirect_info->ecf_flags = ecf_flags;
edge->indirect_info->vptr_changed = true;
/* Record polymorphic call info. */
if (<API key>
&& call_stmt
&& (target = gimple_call_fn (call_stmt))
&& <API key> (target))
{
<API key> context (decl, target, call_stmt);
/* Only record types can have virtual calls. */
edge->indirect_info->polymorphic = true;
edge->indirect_info->param_index = -1;
edge->indirect_info->otr_token
= tree_to_uhwi (OBJ_TYPE_REF_TOKEN (target));
edge->indirect_info->otr_type = obj_type_ref_class (target);
gcc_assert (TREE_CODE (edge->indirect_info->otr_type) == RECORD_TYPE);
edge->indirect_info->context = context;
}
edge->next_callee = indirect_calls;
if (indirect_calls)
indirect_calls->prev_callee = edge;
indirect_calls = edge;
return edge;
}
/* Remove the edge from the list of the callees of the caller. */
void
cgraph_edge::remove_caller (void)
{
if (prev_callee)
prev_callee->next_callee = next_callee;
if (next_callee)
next_callee->prev_callee = prev_callee;
if (!prev_callee)
{
if (<API key>)
caller->indirect_calls = next_callee;
else
caller->callees = next_callee;
}
if (caller->call_site_hash)
caller->call_site_hash-><API key>
(call_stmt, cgraph_edge_hasher::hash (call_stmt));
}
/* Put the edge onto the free list. */
void
symbol_table::free_edge (cgraph_edge *e)
{
int uid = e->uid;
if (e->indirect_info)
ggc_free (e->indirect_info);
/* Clear out the edge so we do not dangle pointers. */
memset (e, 0, sizeof (*e));
e->uid = uid;
NEXT_FREE_EDGE (e) = free_edges;
free_edges = e;
edges_count
}
/* Remove the edge in the cgraph. */
void
cgraph_edge::remove (void)
{
/* Call all edge removal hooks. */
symtab-><API key> (this);
if (!<API key>)
/* Remove from callers list of the callee. */
remove_callee ();
/* Remove from callees list of the callers. */
remove_caller ();
/* Put the edge onto the free list. */
symtab->free_edge (this);
}
/* Turn edge into speculative call calling N2. Update
the profile so the direct call is taken COUNT times
with FREQUENCY.
At clone materialization time, the indirect call E will
be expanded as:
if (call_dest == N2)
n2 ();
else
call call_dest
At this time the function just creates the direct call,
the referencd representing the if conditional and attaches
them all to the orginal indirect call statement.
Return direct edge created. */
cgraph_edge *
cgraph_edge::make_speculative (cgraph_node *n2, gcov_type direct_count,
int direct_frequency)
{
cgraph_node *n = caller;
ipa_ref *ref = NULL;
cgraph_edge *e2;
if (dump_file)
{
fprintf (dump_file, "Indirect call -> speculative call"
" %s/%i => %s/%i\n",
xstrdup_for_dump (n->name ()), n->order,
xstrdup_for_dump (n2->name ()), n2->order);
}
speculative = true;
e2 = n->create_edge (n2, call_stmt, direct_count, direct_frequency);
<API key> (e2);
e2->speculative = true;
if (TREE_NOTHROW (n2->decl))
e2->can_throw_external = false;
else
e2->can_throw_external = can_throw_external;
e2->lto_stmt_uid = lto_stmt_uid;
e2-><API key> = <API key>;
count -= e2->count;
frequency -= e2->frequency;
symtab-><API key> (this, e2);
ref = n->create_reference (n2, IPA_REF_ADDR, call_stmt);
ref->lto_stmt_uid = lto_stmt_uid;
ref->speculative = speculative;
n2->mark_address_taken ();
return e2;
}
/* Speculative call consist of three components:
1) an indirect edge representing the original call
2) an direct edge representing the new call
3) ADDR_EXPR reference representing the speculative check.
All three components are attached to single statement (the indirect
call) and if one of them exists, all of them must exist.
Given speculative call edge, return all three components.
*/
void
cgraph_edge::<API key> (cgraph_edge *&direct,
cgraph_edge *&indirect,
ipa_ref *&reference)
{
ipa_ref *ref;
int i;
cgraph_edge *e2;
cgraph_edge *e = this;
if (!e-><API key>)
for (e2 = e->caller->indirect_calls;
e2->call_stmt != e->call_stmt || e2->lto_stmt_uid != e->lto_stmt_uid;
e2 = e2->next_callee)
;
else
{
e2 = e;
/* We can take advantage of the call stmt hash. */
if (e2->call_stmt)
{
e = e->caller->get_edge (e2->call_stmt);
gcc_assert (e->speculative && !e-><API key>);
}
else
for (e = e->caller->callees;
e2->call_stmt != e->call_stmt
|| e2->lto_stmt_uid != e->lto_stmt_uid;
e = e->next_callee)
;
}
gcc_assert (e->speculative && e2->speculative);
direct = e;
indirect = e2;
reference = NULL;
for (i = 0; e->caller->iterate_reference (i, ref); i++)
if (ref->speculative
&& ((ref->stmt && ref->stmt == e->call_stmt)
|| (!ref->stmt && ref->lto_stmt_uid == e->lto_stmt_uid)))
{
reference = ref;
break;
}
/* Speculative edge always consist of all three components - direct edge,
indirect and reference. */
gcc_assert (e && e2 && ref);
}
/* Speculative call edge turned out to be direct call to CALLE_DECL.
Remove the speculative call sequence and return edge representing the call.
It is up to caller to redirect the call as appropriate. */
cgraph_edge *
cgraph_edge::resolve_speculation (tree callee_decl)
{
cgraph_edge *edge = this;
cgraph_edge *e2;
ipa_ref *ref;
gcc_assert (edge->speculative);
edge-><API key> (e2, edge, ref);
if (!callee_decl
|| !ref->referred-><API key>
(symtab_node::get (callee_decl)))
{
if (dump_file)
{
if (callee_decl)
{
fprintf (dump_file, "Speculative indirect call %s/%i => %s/%i has "
"turned out to have contradicting known target ",
xstrdup_for_dump (edge->caller->name ()),
edge->caller->order,
xstrdup_for_dump (e2->callee->name ()),
e2->callee->order);
print_generic_expr (dump_file, callee_decl, 0);
fprintf (dump_file, "\n");
}
else
{
fprintf (dump_file, "Removing speculative call %s/%i => %s/%i\n",
xstrdup_for_dump (edge->caller->name ()),
edge->caller->order,
xstrdup_for_dump (e2->callee->name ()),
e2->callee->order);
}
}
}
else
{
cgraph_edge *tmp = edge;
if (dump_file)
fprintf (dump_file, "Speculative call turned into direct call.\n");
edge = e2;
e2 = tmp;
/* FIXME: If EDGE is inlined, we should scale up the frequencies and counts
in the functions inlined through it. */
}
edge->count += e2->count;
edge->frequency += e2->frequency;
if (edge->frequency > CGRAPH_FREQ_MAX)
edge->frequency = CGRAPH_FREQ_MAX;
edge->speculative = false;
e2->speculative = false;
ref->remove_reference ();
if (e2-><API key> || e2->inline_failed)
e2->remove ();
else
e2->callee-><API key> ();
if (edge->caller->call_site_hash)
<API key> (edge);
return edge;
}
/* Make an indirect edge with an unknown callee an ordinary edge leading to
CALLEE. DELTA is an integer constant that is to be added to the this
pointer (first parameter) to compensate for skipping a thunk adjustment. */
cgraph_edge *
cgraph_edge::make_direct (cgraph_node *callee)
{
cgraph_edge *edge = this;
gcc_assert (<API key>);
/* If we are redirecting speculative call, make it non-speculative. */
if (<API key> && speculative)
{
edge = edge->resolve_speculation (callee->decl);
/* On successful speculation just return the pre existing direct edge. */
if (!<API key>)
return edge;
}
<API key> = 0;
ggc_free (indirect_info);
indirect_info = NULL;
/* Get the edge out of the indirect edge list. */
if (prev_callee)
prev_callee->next_callee = next_callee;
if (next_callee)
next_callee->prev_callee = prev_callee;
if (!prev_callee)
caller->indirect_calls = next_callee;
/* Put it into the normal callee list */
prev_callee = NULL;
next_callee = caller->callees;
if (caller->callees)
caller->callees->prev_callee = edge;
caller->callees = edge;
/* Insert to callers list of the new callee. */
edge->set_callee (callee);
if (call_stmt)
<API key>
= !<API key> (call_stmt, callee->decl,
false);
/* We need to re-determine the inlining status of the edge. */
<API key> (edge);
return edge;
}
/* If necessary, change the function declaration in the call statement
associated with E so that it corresponds to the edge callee. */
gimple
cgraph_edge::<API key> (void)
{
cgraph_edge *e = this;
tree decl = gimple_call_fndecl (e->call_stmt);
tree lhs = gimple_call_lhs (e->call_stmt);
gcall *new_stmt;
<API key> gsi;
#ifdef ENABLE_CHECKING
cgraph_node *node;
#endif
if (e->speculative)
{
cgraph_edge *e2;
gcall *new_stmt;
ipa_ref *ref;
e-><API key> (e, e2, ref);
/* If there already is an direct call (i.e. as a result of inliner's
substitution), forget about speculating. */
if (decl)
e = e->resolve_speculation (decl);
/* If types do not match, speculation was likely wrong.
The direct edge was posisbly redirected to the clone with a different
signature. We did not update the call statement yet, so compare it
with the reference that still points to the proper type. */
else if (!<API key> (e->call_stmt,
ref->referred->decl,
true))
{
if (dump_file)
fprintf (dump_file, "Not expanding speculative call of %s/%i -> %s/%i\n"
"Type mismatch.\n",
xstrdup_for_dump (e->caller->name ()),
e->caller->order,
xstrdup_for_dump (e->callee->name ()),
e->callee->order);
e = e->resolve_speculation ();
/* We are producing the final function body and will throw away the
callgraph edges really soon. Reset the counts/frequencies to
keep verifier happy in the case of roundoff errors. */
e->count = gimple_bb (e->call_stmt)->count;
e->frequency = <API key>
(e->caller->decl, gimple_bb (e->call_stmt));
}
/* Expand speculation into GIMPLE code. */
else
{
if (dump_file)
fprintf (dump_file,
"Expanding speculative call of %s/%i -> %s/%i count:"
"%"PRId64"\n",
xstrdup_for_dump (e->caller->name ()),
e->caller->order,
xstrdup_for_dump (e->callee->name ()),
e->callee->order,
(int64_t)e->count);
gcc_assert (e2->speculative);
push_cfun (<API key> (e->caller->decl));
new_stmt = gimple_ic (e->call_stmt,
dyn_cast<cgraph_node *> (ref->referred),
e->count || e2->count
? RDIV (e->count * REG_BR_PROB_BASE,
e->count + e2->count)
: e->frequency || e2->frequency
? RDIV (e->frequency * REG_BR_PROB_BASE,
e->frequency + e2->frequency)
: REG_BR_PROB_BASE / 2,
e->count, e->count + e2->count);
e->speculative = false;
e->caller-><API key> (e->call_stmt, new_stmt,
false);
/* Fix edges for <API key> calls attached to the
processed call stmt. */
if (<API key> (new_stmt)
&& gimple_call_lhs (new_stmt)
&& <API key> (gimple_call_lhs (e2->call_stmt)))
{
tree dresult = gimple_call_lhs (new_stmt);
tree iresult = gimple_call_lhs (e2->call_stmt);
gcall *dbndret = <API key> (dresult);
gcall *ibndret = <API key> (iresult);
struct cgraph_edge *iedge
= e2->caller->cgraph_node::get_edge (ibndret);
struct cgraph_edge *dedge;
if (dbndret)
{
dedge = iedge->caller->create_edge (iedge->callee,
dbndret, e->count,
e->frequency);
dedge->frequency = <API key>
(dedge->caller->decl, gimple_bb (dedge->call_stmt));
}
iedge->frequency = <API key>
(iedge->caller->decl, gimple_bb (iedge->call_stmt));
}
e->frequency = <API key>
(e->caller->decl, gimple_bb (e->call_stmt));
e2->frequency = <API key>
(e2->caller->decl, gimple_bb (e2->call_stmt));
e2->speculative = false;
ref->speculative = false;
ref->stmt = NULL;
/* Indirect edges are not both in the call site hash.
get it updated. */
if (e->caller->call_site_hash)
<API key> (e2);
pop_cfun ();
/* Continue redirecting E to proper target. */
}
}
if (e-><API key>
|| decl == e->callee->decl)
return e->call_stmt;
#ifdef ENABLE_CHECKING
if (decl)
{
node = cgraph_node::get (decl);
gcc_assert (!node || !node->clone.<API key>);
}
#endif
if (symtab->dump_file)
{
fprintf (symtab->dump_file, "updating call of %s/%i -> %s/%i: ",
xstrdup_for_dump (e->caller->name ()), e->caller->order,
xstrdup_for_dump (e->callee->name ()), e->callee->order);
print_gimple_stmt (symtab->dump_file, e->call_stmt, 0, dump_flags);
if (e->callee->clone.<API key>)
{
fprintf (symtab->dump_file, " combined args to skip: ");
dump_bitmap (symtab->dump_file,
e->callee->clone.<API key>);
}
}
if (e->callee->clone.<API key>)
{
int lp_nr;
new_stmt
= <API key> (e->call_stmt,
e->callee->clone.<API key>);
<API key> (new_stmt, e->callee->decl);
<API key> (new_stmt, gimple_call_fntype (e->call_stmt));
if (gimple_vdef (new_stmt)
&& TREE_CODE (gimple_vdef (new_stmt)) == SSA_NAME)
SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
gsi = gsi_for_stmt (e->call_stmt);
gsi_replace (&gsi, new_stmt, false);
/* We need to defer cleaning EH info on the new statement to
fixup-cfg. We may not have dominator information at this point
and thus would end up with unreachable blocks and have no way
to communicate that we need to run CFG cleanup then. */
lp_nr = lookup_stmt_eh_lp (e->call_stmt);
if (lp_nr != 0)
{
<API key> (e->call_stmt);
add_stmt_to_eh_lp (new_stmt, lp_nr);
}
}
else
{
new_stmt = e->call_stmt;
<API key> (new_stmt, e->callee->decl);
update_stmt_fn (<API key> (e->caller->decl), new_stmt);
}
/* If the call becomes noreturn, remove the lhs. */
if (lhs && (gimple_call_flags (new_stmt) & ECF_NORETURN))
{
if (TREE_CODE (lhs) == SSA_NAME)
{
tree var = create_tmp_reg_fn (<API key> (e->caller->decl),
TREE_TYPE (lhs), NULL);
var = <API key>
(<API key> (e->caller->decl), var);
gimple set_stmt = gimple_build_assign (lhs, var);
gsi = gsi_for_stmt (new_stmt);
<API key> (&gsi, set_stmt, GSI_SAME_STMT);
update_stmt_fn (<API key> (e->caller->decl), set_stmt);
}
gimple_call_set_lhs (new_stmt, NULL_TREE);
update_stmt_fn (<API key> (e->caller->decl), new_stmt);
}
/* If new callee has no static chain, remove it. */
if (gimple_call_chain (new_stmt) && !DECL_STATIC_CHAIN (e->callee->decl))
{
<API key> (new_stmt, NULL);
update_stmt_fn (<API key> (e->caller->decl), new_stmt);
}
<API key> (<API key> (e->caller->decl),
new_stmt);
e->caller-><API key> (e->call_stmt, new_stmt, false);
if (symtab->dump_file)
{
fprintf (symtab->dump_file, " updated to:");
print_gimple_stmt (symtab->dump_file, e->call_stmt, 0, dump_flags);
}
return new_stmt;
}
/* Update or remove the corresponding cgraph edge if a GIMPLE_CALL
OLD_STMT changed into NEW_STMT. OLD_CALL is gimple_call_fndecl
of OLD_STMT if it was previously call statement.
If NEW_STMT is NULL, the call has been dropped without any
replacement. */
static void
<API key> (cgraph_node *node,
gimple old_stmt, tree old_call,
gimple new_stmt)
{
tree new_call = (new_stmt && is_gimple_call (new_stmt))
? gimple_call_fndecl (new_stmt) : 0;
/* We are seeing indirect calls, then there is nothing to update. */
if (!new_call && !old_call)
return;
/* See if we turned indirect call into direct call or folded call to one builtin
into different builtin. */
if (old_call != new_call)
{
cgraph_edge *e = node->get_edge (old_stmt);
cgraph_edge *ne = NULL;
gcov_type count;
int frequency;
if (e)
{
/* See if the edge is already there and has the correct callee. It
might be so because of indirect inlining has already updated
it. We also might've cloned and redirected the edge. */
if (new_call && e->callee)
{
cgraph_node *callee = e->callee;
while (callee)
{
if (callee->decl == new_call
|| callee->former_clone_of == new_call)
{
e->set_call_stmt (as_a <gcall *> (new_stmt));
return;
}
callee = callee->clone_of;
}
}
/* Otherwise remove edge and create new one; we can't simply redirect
since function has changed, so inline plan and other information
attached to edge is invalid. */
count = e->count;
frequency = e->frequency;
if (e-><API key> || e->inline_failed)
e->remove ();
else
e->callee-><API key> ();
}
else if (new_call)
{
/* We are seeing new direct call; compute profile info based on BB. */
basic_block bb = gimple_bb (new_stmt);
count = bb->count;
frequency = <API key> (<API key>,
bb);
}
if (new_call)
{
ne = node->create_edge (cgraph_node::get_create (new_call),
as_a <gcall *> (new_stmt), count,
frequency);
gcc_assert (ne->inline_failed);
}
}
/* We only updated the call stmt; update pointer in cgraph edge.. */
else if (old_stmt != new_stmt)
node->get_edge (old_stmt)->set_call_stmt (as_a <gcall *> (new_stmt));
}
/* Update or remove the corresponding cgraph edge if a GIMPLE_CALL
OLD_STMT changed into NEW_STMT. OLD_DECL is gimple_call_fndecl
of OLD_STMT before it was updated (updating can happen inplace). */
void
<API key> (gimple old_stmt, tree old_decl, gimple new_stmt)
{
cgraph_node *orig = cgraph_node::get (cfun->decl);
cgraph_node *node;
gcc_checking_assert (orig);
<API key> (orig, old_stmt, old_decl, new_stmt);
if (orig->clones)
for (node = orig->clones; node != orig;)
{
<API key> (node, old_stmt, old_decl, new_stmt);
if (node->clones)
node = node->clones;
else if (node->next_sibling_clone)
node = node->next_sibling_clone;
else
{
while (node != orig && !node->next_sibling_clone)
node = node->clone_of;
if (node != orig)
node = node->next_sibling_clone;
}
}
}
/* Remove all callees from the node. */
void
cgraph_node::remove_callees (void)
{
cgraph_edge *e, *f;
/* It is sufficient to remove the edges from the lists of callers of
the callees. The callee list of the node can be zapped with one
assignment. */
for (e = callees; e; e = f)
{
f = e->next_callee;
symtab-><API key> (e);
if (!e-><API key>)
e->remove_callee ();
symtab->free_edge (e);
}
for (e = indirect_calls; e; e = f)
{
f = e->next_callee;
symtab-><API key> (e);
if (!e-><API key>)
e->remove_callee ();
symtab->free_edge (e);
}
indirect_calls = NULL;
callees = NULL;
if (call_site_hash)
{
call_site_hash->empty ();
call_site_hash = NULL;
}
}
/* Remove all callers from the node. */
void
cgraph_node::remove_callers (void)
{
cgraph_edge *e, *f;
/* It is sufficient to remove the edges from the lists of callees of
the callers. The caller list of the node can be zapped with one
assignment. */
for (e = callers; e; e = f)
{
f = e->next_caller;
symtab-><API key> (e);
e->remove_caller ();
symtab->free_edge (e);
}
callers = NULL;
}
/* Helper function for <API key> and free_lang_data.
It releases body from function DECL without having to inspect its
possibly non-existent symtab node. */
void
<API key> (tree decl)
{
if (<API key> (decl))
{
if (<API key> (decl)->cfg
|| <API key> (decl)->gimple_df)
{
push_cfun (<API key> (decl));
if (cfun->cfg
&& current_loops)
{
cfun->curr_properties &= ~PROP_loops;
<API key> ();
}
if (cfun->gimple_df)
{
delete_tree_ssa ();
<API key> ();
cfun->eh = NULL;
}
if (cfun->cfg)
{
gcc_assert (!<API key> (CDI_DOMINATORS));
gcc_assert (!<API key> (CDI_POST_DOMINATORS));
clear_edges ();
cfun->cfg = NULL;
}
if (cfun->value_histograms)
free_histograms ();
pop_cfun ();
}
gimple_set_body (decl, NULL);
/* Struct function hangs a lot of data that would leak if we didn't
removed all pointers to it. */
ggc_free (<API key> (decl));
<API key> (decl) = NULL;
}
DECL_SAVED_TREE (decl) = NULL;
}
/* Release memory used to represent body of function.
Use this only for functions that are released before being translated to
target code (i.e. RTL). Functions that are compiled to RTL and beyond
are free'd in final.c via <API key>().
KEEP_ARGUMENTS are useful only if you want to rebuild body as thunk. */
void
cgraph_node::release_body (bool keep_arguments)
{
<API key>.release ();
if (!<API key> && symtab->state != PARSING)
{
DECL_RESULT (decl) = NULL;
if (!keep_arguments)
DECL_ARGUMENTS (decl) = NULL;
}
/* If the node is abstract and needed, then do not clear DECL_INITIAL
of its associated function function declaration because it's
needed to emit debug info later. */
if (!<API key> && DECL_INITIAL (decl))
DECL_INITIAL (decl) = error_mark_node;
<API key> (decl);
if (lto_file_data)
{
<API key> (this);
lto_file_data = NULL;
}
}
/* Remove function from symbol table. */
void
cgraph_node::remove (void)
{
cgraph_node *n;
int uid = this->uid;
symtab-><API key> (this);
remove_callers ();
remove_callees ();
<API key>.release ();
/* Incremental inlining access removed nodes stored in the postorder list.
*/
force_output = false;
forced_by_abi = false;
for (n = nested; n; n = n->next_nested)
n->origin = NULL;
nested = NULL;
if (origin)
{
cgraph_node **node2 = &origin->nested;
while (*node2 != this)
node2 = &(*node2)->next_nested;
*node2 = next_nested;
}
unregister ();
if (prev_sibling_clone)
prev_sibling_clone->next_sibling_clone = next_sibling_clone;
else if (clone_of)
clone_of->clones = next_sibling_clone;
if (next_sibling_clone)
next_sibling_clone->prev_sibling_clone = prev_sibling_clone;
if (clones)
{
cgraph_node *n, *next;
if (clone_of)
{
for (n = clones; n->next_sibling_clone; n = n->next_sibling_clone)
n->clone_of = clone_of;
n->clone_of = clone_of;
n->next_sibling_clone = clone_of->clones;
if (clone_of->clones)
clone_of->clones->prev_sibling_clone = n;
clone_of->clones = clones;
}
else
{
/* We are removing node with clones. This makes clones inconsistent,
but assume they will be removed subsequently and just keep clone
tree intact. This can happen in unreachable function removal since
we remove unreachable functions in random order, not by bottom-up
walk of clone trees. */
for (n = clones; n; n = next)
{
next = n->next_sibling_clone;
n->next_sibling_clone = NULL;
n->prev_sibling_clone = NULL;
n->clone_of = NULL;
}
}
}
/* While all the clones are removed after being proceeded, the function
itself is kept in the cgraph even after it is compiled. Check whether
we are done with this body and reclaim it proactively if this is the case.
*/
if (symtab->state != LTO_STREAMING)
{
n = cgraph_node::get (decl);
if (!n
|| (!n->clones && !n->clone_of && !n->global.inlined_to
&& ((symtab->global_info_ready || in_lto_p)
&& (TREE_ASM_WRITTEN (n->decl)
|| DECL_EXTERNAL (n->decl)
|| !n->analyzed
|| (!flag_wpa && n->in_other_partition)))))
release_body ();
}
else
{
<API key> (this);
lto_file_data = NULL;
}
decl = NULL;
if (call_site_hash)
{
call_site_hash->empty ();
call_site_hash = NULL;
}
if (<API key>)
{
<API key>-><API key> = NULL;
<API key> = NULL;
}
symtab->release_symbol (this, uid);
}
/* Likewise indicate that a node is having address taken. */
void
cgraph_node::mark_address_taken (void)
{
/* Indirect inlining can figure out that all uses of the address are
inlined. */
if (global.inlined_to)
{
gcc_assert (cfun->after_inlining);
gcc_assert (callers-><API key>);
return;
}
/* FIXME: address_taken flag is used both as a shortcut for testing whether
IPA_REF_ADDR reference exists (and thus it should be set on node
representing alias we take address of) and as a test whether address
of the object was taken (and thus it should be set on node alias is
referring to). We should remove the first use and the remove the
following set. */
address_taken = 1;
cgraph_node *node = <API key> ();
node->address_taken = 1;
}
/* Return local info for the compiled function. */
cgraph_local_info *
cgraph_node::local_info (tree decl)
{
gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
cgraph_node *node = get (decl);
if (!node)
return NULL;
return &node-><API key> ()->local;
}
/* Return local info for the compiled function. */
cgraph_rtl_info *
cgraph_node::rtl_info (tree decl)
{
gcc_assert (TREE_CODE (decl) == FUNCTION_DECL);
cgraph_node *node = get (decl);
if (!node)
return NULL;
node = node-><API key> ();
if (node->decl != <API key>
&& !TREE_ASM_WRITTEN (node->decl))
return NULL;
return &node-><API key> ()->rtl;
}
/* Return a string describing the failure REASON. */
const char*
<API key> (<API key> reason)
{
#undef DEFCIFCODE
#define DEFCIFCODE(code, type, string) string,
static const char *cif_string_table[CIF_N_REASONS] = {
#include "cif-code.def"
};
/* Signedness of an enum type is implementation defined, so cast it
to unsigned before testing. */
gcc_assert ((unsigned) reason < CIF_N_REASONS);
return cif_string_table[reason];
}
/* Return a type describing the failure REASON. */
<API key>
<API key> (<API key> reason)
{
#undef DEFCIFCODE
#define DEFCIFCODE(code, type, string) type,
static <API key> cif_type_table[CIF_N_REASONS] = {
#include "cif-code.def"
};
/* Signedness of an enum type is implementation defined, so cast it
to unsigned before testing. */
gcc_assert ((unsigned) reason < CIF_N_REASONS);
return cif_type_table[reason];
}
/* Names used to print out the availability enum. */
const char * const <API key>[] =
{"unset", "not_available", "overwritable", "available", "local"};
/* Output flags of edge to a file F. */
void
cgraph_edge::dump_edge_flags (FILE *f)
{
if (speculative)
fprintf (f, "(speculative) ");
if (!inline_failed)
fprintf (f, "(inlined) ");
if (<API key>)
fprintf (f, "(indirect_inlining) ");
if (count)
fprintf (f, "(%"PRId64"x) ", (int64_t)count);
if (frequency)
fprintf (f, "(%.2f per call) ", frequency / (double)CGRAPH_FREQ_BASE);
if (can_throw_external)
fprintf (f, "(can throw external) ");
}
/* Dump call graph node to file F. */
void
cgraph_node::dump (FILE *f)
{
cgraph_edge *edge;
dump_base (f);
if (global.inlined_to)
fprintf (f, " Function %s/%i is inline copy in %s/%i\n",
xstrdup_for_dump (name ()),
order,
xstrdup_for_dump (global.inlined_to->name ()),
global.inlined_to->order);
if (clone_of)
fprintf (f, " Clone of %s/%i\n",
clone_of->asm_name (),
clone_of->order);
if (symtab-><API key>)
fprintf (f, " Availability: %s\n",
<API key> [get_availability ()]);
if (profile_id)
fprintf (f, " Profile id: %i\n",
profile_id);
fprintf (f, " First run: %i\n", tp_first_run);
fprintf (f, " Function flags:");
if (count)
fprintf (f, " executed %"PRId64"x",
(int64_t)count);
if (origin)
fprintf (f, " nested in: %s", origin->asm_name ());
if (gimple_has_body_p (decl))
fprintf (f, " body");
if (process)
fprintf (f, " process");
if (local.local)
fprintf (f, " local");
if (local.<API key>)
fprintf (f, " <API key>");
if (<API key>)
fprintf (f, " <API key>");
if (only_called_at_exit)
fprintf (f, " only_called_at_exit");
if (tm_clone)
fprintf (f, " tm_clone");
if (icf_merged)
fprintf (f, " icf_merged");
if (nonfreeing_fn)
fprintf (f, " nonfreeing_fn");
if (<API key> (decl))
fprintf (f," static_constructor (priority:%i)", get_init_priority ());
if (<API key> (decl))
fprintf (f," static_destructor (priority:%i)", get_fini_priority ());
if (frequency == NODE_FREQUENCY_HOT)
fprintf (f, " hot");
if (frequency == <API key>)
fprintf (f, " unlikely_executed");
if (frequency == <API key>)
fprintf (f, " executed_once");
if (<API key>)
fprintf (f, " <API key>");
if (only_called_at_exit)
fprintf (f, " only_called_at_exit");
if (opt_for_fn (decl, optimize_size))
fprintf (f, " optimize_size");
if (<API key>)
fprintf (f, " <API key>");
fprintf (f, "\n");
if (thunk.thunk_p)
{
fprintf (f, " Thunk");
if (thunk.alias)
fprintf (f, " of %s (asm: %s)",
lang_hooks.decl_printable_name (thunk.alias, 2),
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk.alias)));
fprintf (f, " fixed offset %i virtual value %i has "
"virtual offset %i)\n",
(int)thunk.fixed_offset,
(int)thunk.virtual_value,
(int)thunk.virtual_offset_p);
}
if (alias && thunk.alias
&& DECL_P (thunk.alias))
{
fprintf (f, " Alias of %s",
lang_hooks.decl_printable_name (thunk.alias, 2));
if (<API key> (thunk.alias))
fprintf (f, " (asm: %s)",
IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (thunk.alias)));
fprintf (f, "\n");
}
fprintf (f, " Called by: ");
for (edge = callers; edge; edge = edge->next_caller)
{
fprintf (f, "%s/%i ", edge->caller->asm_name (),
edge->caller->order);
edge->dump_edge_flags (f);
}
fprintf (f, "\n Calls: ");
for (edge = callees; edge; edge = edge->next_callee)
{
fprintf (f, "%s/%i ", edge->callee->asm_name (),
edge->callee->order);
edge->dump_edge_flags (f);
}
fprintf (f, "\n");
for (edge = indirect_calls; edge; edge = edge->next_callee)
{
if (edge->indirect_info->polymorphic)
{
fprintf (f, " Polymorphic indirect call of type ");
print_generic_expr (f, edge->indirect_info->otr_type, TDF_SLIM);
fprintf (f, " token:%i", (int) edge->indirect_info->otr_token);
}
else
fprintf (f, " Indirect call");
edge->dump_edge_flags (f);
if (edge->indirect_info->param_index != -1)
{
fprintf (f, " of param:%i", edge->indirect_info->param_index);
if (edge->indirect_info->agg_contents)
fprintf (f, " loaded from %s %s at offset %i",
edge->indirect_info->member_ptr ? "member ptr" : "aggregate",
edge->indirect_info->by_ref ? "passed by reference":"",
(int)edge->indirect_info->offset);
if (edge->indirect_info->vptr_changed)
fprintf (f, " (vptr maybe changed)");
}
fprintf (f, "\n");
if (edge->indirect_info->polymorphic)
edge->indirect_info->context.dump (f);
}
if (<API key>)
fprintf (f, " Is instrumented version.\n");
else if (<API key>)
fprintf (f, " Has instrumented version.\n");
}
/* Dump call graph node NODE to stderr. */
DEBUG_FUNCTION void
cgraph_node::debug (void)
{
dump (stderr);
}
/* Dump the callgraph to file F. */
void
cgraph_node::dump_cgraph (FILE *f)
{
cgraph_node *node;
fprintf (f, "callgraph:\n\n");
FOR_EACH_FUNCTION (node)
node->dump (f);
}
/* Return true when the DECL can possibly be inlined. */
bool
<API key> (tree decl)
{
if (!symtab->global_info_ready)
return !DECL_UNINLINABLE (decl);
return <API key> (decl);
}
/* cgraph_node is no longer nested function; update cgraph accordingly. */
void
cgraph_node::unnest (void)
{
cgraph_node **node2 = &origin->nested;
gcc_assert (origin);
while (*node2 != this)
node2 = &(*node2)->next_nested;
*node2 = next_nested;
origin = NULL;
}
/* Return function availability. See cgraph.h for description of individual
return values. */
enum availability
cgraph_node::get_availability (void)
{
enum availability avail;
if (!analyzed)
avail = AVAIL_NOT_AVAILABLE;
else if (local.local)
avail = AVAIL_LOCAL;
else if (alias && weakref)
<API key> (&avail);
else if (lookup_attribute ("ifunc", DECL_ATTRIBUTES (decl)))
avail = AVAIL_INTERPOSABLE;
else if (!externally_visible)
avail = AVAIL_AVAILABLE;
/* Inline functions are safe to be analyzed even if their symbol can
be overwritten at runtime. It is not meaningful to enforce any sane
behaviour on replacing inline function by different body. */
else if (<API key> (decl))
avail = AVAIL_AVAILABLE;
/* If the function can be overwritten, return OVERWRITABLE. Take
care at least of two notable extensions - the COMDAT functions
used to share template instantiations in C++ (this is symmetric
to code <API key> and probably shall be shared and
the inlinability hooks completely eliminated).
??? Does the C++ one definition rule allow us to always return
AVAIL_AVAILABLE here? That would be good reason to preserve this
bit. */
else if (decl_replaceable_p (decl) && !DECL_EXTERNAL (decl))
avail = AVAIL_INTERPOSABLE;
else avail = AVAIL_AVAILABLE;
return avail;
}
/* Worker for <API key>. */
static bool
<API key> (cgraph_node *node, void *)
{
return !(!node->force_output
&& ((DECL_COMDAT (node->decl)
&& !node->forced_by_abi
&& !node-><API key> ()
&& !node->same_comdat_group)
|| !node->externally_visible));
}
/* Return true if cgraph_node can be made local for API change.
Extern inline functions and C++ COMDAT functions can be made local
at the expense of possible code size growth if function is used in multiple
compilation units. */
bool
cgraph_node::can_be_local_p (void)
{
return (!address_taken
&& !<API key> (<API key>,
NULL, true));
}
/* Call callback on cgraph_node, thunks and aliases associated to cgraph_node.
When <API key> is false, overwritable aliases and thunks are
skipped. When <API key> is true, virtual thunks are
skipped. */
bool
cgraph_node::<API key> (bool (*callback)
(cgraph_node *, void *),
void *data,
bool <API key>,
bool <API key>)
{
cgraph_edge *e;
ipa_ref *ref;
if (callback (this, data))
return true;
FOR_EACH_ALIAS (this, ref)
{
cgraph_node *alias = dyn_cast <cgraph_node *> (ref->referring);
if (<API key>
|| alias->get_availability () > AVAIL_INTERPOSABLE)
if (alias-><API key> (callback, data,
<API key>,
<API key>))
return true;
}
for (e = callers; e; e = e->next_caller)
if (e->caller->thunk.thunk_p
&& (<API key>
|| e->caller->get_availability () > AVAIL_INTERPOSABLE)
&& !(<API key>
&& e->caller->thunk.virtual_offset_p))
if (e->caller-><API key> (callback, data,
<API key>,
<API key>))
return true;
return false;
}
/* Worker to bring NODE local. */
bool
cgraph_node::make_local (cgraph_node *node, void *)
{
gcc_checking_assert (node->can_be_local_p ());
if (DECL_COMDAT (node->decl) || DECL_EXTERNAL (node->decl))
{
node->make_decl_local ();
node->set_section (NULL);
node->set_comdat_group (NULL);
node->externally_visible = false;
node->forced_by_abi = false;
node->local.local = true;
node->set_section (NULL);
node->unique_name = (node->resolution == <API key>
|| node->resolution == <API key>);
node->resolution = <API key>;
gcc_assert (node->get_availability () == AVAIL_LOCAL);
}
return false;
}
/* Bring cgraph node local. */
void
cgraph_node::make_local (void)
{
<API key> (cgraph_node::make_local, NULL, true);
}
/* Worker to set nothrow flag. */
static bool
<API key> (cgraph_node *node, void *data)
{
cgraph_edge *e;
TREE_NOTHROW (node->decl) = data != NULL;
if (data != NULL)
for (e = node->callers; e; e = e->next_caller)
e->can_throw_external = false;
return false;
}
/* Set TREE_NOTHROW on NODE's decl and on aliases of NODE
if any to NOTHROW. */
void
cgraph_node::set_nothrow_flag (bool nothrow)
{
<API key> (<API key>,
(void *)(size_t)nothrow, false);
}
/* Worker to set const flag. */
static bool
<API key> (cgraph_node *node, void *data)
{
/* Static constructors and destructors without a side effect can be
optimized out. */
if (data && !((size_t)data & 2))
{
if (<API key> (node->decl))
<API key> (node->decl) = 0;
if (<API key> (node->decl))
<API key> (node->decl) = 0;
}
TREE_READONLY (node->decl) = data != NULL;
<API key> (node->decl) = ((size_t)data & 2) != 0;
return false;
}
/* Set TREE_READONLY on cgraph_node's decl and on aliases of the node
if any to READONLY. */
void
cgraph_node::set_const_flag (bool readonly, bool looping)
{
<API key> (<API key>,
(void *)(size_t)(readonly + (int)looping * 2),
false, true);
}
/* Worker to set pure flag. */
static bool
<API key> (cgraph_node *node, void *data)
{
/* Static constructors and destructors without a side effect can be
optimized out. */
if (data && !((size_t)data & 2))
{
if (<API key> (node->decl))
<API key> (node->decl) = 0;
if (<API key> (node->decl))
<API key> (node->decl) = 0;
}
DECL_PURE_P (node->decl) = data != NULL;
<API key> (node->decl) = ((size_t)data & 2) != 0;
return false;
}
/* Set DECL_PURE_P on cgraph_node's decl and on aliases of the node
if any to PURE. */
void
cgraph_node::set_pure_flag (bool pure, bool looping)
{
<API key> (<API key>,
(void *)(size_t)(pure + (int)looping * 2),
false, true);
}
/* Return true when cgraph_node can not return or throw and thus
it is safe to ignore its side effects for IPA analysis. */
bool
cgraph_node::cannot_return_p (void)
{
int flags = <API key> (decl);
if (!opt_for_fn (decl, flag_exceptions))
return (flags & ECF_NORETURN) != 0;
else
return ((flags & (ECF_NORETURN | ECF_NOTHROW))
== (ECF_NORETURN | ECF_NOTHROW));
}
/* Return true when call of edge can not lead to return from caller
and thus it is safe to ignore its side effects for IPA analysis
when computing side effects of the caller.
FIXME: We could actually mark all edges that have no reaching
patch to the exit block or throw to get better results. */
bool
cgraph_edge::<API key> (void)
{
if (caller->cannot_return_p ())
return true;
if (<API key>)
{
int flags = indirect_info->ecf_flags;
if (!opt_for_fn (caller->decl, flag_exceptions))
return (flags & ECF_NORETURN) != 0;
else
return ((flags & (ECF_NORETURN | ECF_NOTHROW))
== (ECF_NORETURN | ECF_NOTHROW));
}
else
return callee->cannot_return_p ();
}
/* Return true if the call can be hot. */
bool
cgraph_edge::maybe_hot_p (void)
{
/* TODO: Export profile_status from cfun->cfg to cgraph_node. */
if (profile_info
&& opt_for_fn (caller->decl, <API key>)
&& !maybe_hot_count_p (NULL, count))
return false;
if (caller->frequency == <API key>
|| (callee
&& callee->frequency == <API key>))
return false;
if (caller->frequency > <API key>
&& (callee
&& callee->frequency <= <API key>))
return false;
if (opt_for_fn (caller->decl, optimize_size))
return false;
if (caller->frequency == NODE_FREQUENCY_HOT)
return true;
if (caller->frequency == <API key>
&& frequency < CGRAPH_FREQ_BASE * 3 / 2)
return false;
if (opt_for_fn (caller->decl, <API key>))
{
if (PARAM_VALUE (<API key>) == 0
|| frequency <= (CGRAPH_FREQ_BASE
/ PARAM_VALUE (<API key>)))
return false;
}
return true;
}
/* Worker for <API key>. */
static bool
nonremovable_p (cgraph_node *node, void *)
{
return !node-><API key> ();
}
/* Return true if whole comdat group can be removed if there are no direct
calls to THIS. */
bool
cgraph_node::<API key> (bool will_inline)
{
struct ipa_ref *ref;
/* For local symbols or non-comdat group it is the same as
<API key>. */
if (!externally_visible || !same_comdat_group)
{
if (DECL_EXTERNAL (decl))
return true;
if (address_taken)
return false;
return !<API key> (nonremovable_p, NULL, true);
}
if (will_inline && address_taken)
return false;
/* Otheriwse check if we can remove the symbol itself and then verify
that only uses of the comdat groups are direct call to THIS
or its aliases. */
if (!<API key> ())
return false;
/* Check that all refs come from within the comdat group. */
for (int i = 0; iterate_referring (i, ref); i++)
if (ref->referring->get_comdat_group () != get_comdat_group ())
return false;
struct cgraph_node *target = <API key> ();
for (cgraph_node *next = dyn_cast<cgraph_node *> (same_comdat_group);
next != this; next = dyn_cast<cgraph_node *> (next->same_comdat_group))
{
if (!externally_visible)
continue;
if (!next->alias
&& !next-><API key> ())
return false;
/* If we see different symbol than THIS, be sure to check calls. */
if (next-><API key> () != target)
for (cgraph_edge *e = next->callers; e; e = e->next_caller)
if (e->caller->get_comdat_group () != get_comdat_group ()
|| will_inline)
return false;
/* If function is not being inlined, we care only about
references outside of the comdat group. */
if (!will_inline)
for (int i = 0; next->iterate_referring (i, ref); i++)
if (ref->referring->get_comdat_group () != get_comdat_group ())
return false;
}
return true;
}
/* Return true when function cgraph_node can be expected to be removed
from program when direct calls in this compilation unit are removed.
As a special case COMDAT functions are
<API key> while the are not
<API key> (it is possible they are called from other
unit)
This function behaves as <API key> because eliminating
all uses of COMDAT function does not make it necessarily disappear from
the program unless we are compiling whole program or we do LTO. In this
case we know we win since dynamic linking will not really discard the
linkonce section. */
bool
cgraph_node::<API key>
(bool will_inline)
{
gcc_assert (!global.inlined_to);
if (DECL_EXTERNAL (decl))
return true;
if (!in_lto_p && !flag_whole_program)
{
/* If the symbol is in comdat group, we need to verify that whole comdat
group becomes unreachable. Technically we could skip references from
within the group, too. */
if (!<API key> ())
return false;
if (same_comdat_group && externally_visible)
{
struct cgraph_node *target = <API key> ();
if (will_inline && address_taken)
return true;
for (cgraph_node *next = dyn_cast<cgraph_node *> (same_comdat_group);
next != this;
next = dyn_cast<cgraph_node *> (next->same_comdat_group))
{
if (!externally_visible)
continue;
if (!next->alias
&& !next-><API key> ())
return false;
/* If we see different symbol than THIS,
be sure to check calls. */
if (next-><API key> () != target)
for (cgraph_edge *e = next->callers; e; e = e->next_caller)
if (e->caller->get_comdat_group () != get_comdat_group ()
|| will_inline)
return false;
}
}
return true;
}
else
return <API key> (will_inline);
}
/* Worker for <API key>. */
static bool
<API key> (cgraph_node *node, void *)
{
return !node-><API key> ();
}
/* Return true when function cgraph_node and all its aliases are only called
directly.
i.e. it is not externally visible, address was not taken and
it is not used in any other non-standard way. */
bool
cgraph_node::<API key> (void)
{
gcc_assert (<API key> () == this);
return !<API key> (<API key>,
NULL, true);
}
/* Collect all callers of NODE. Worker for <API key>. */
static bool
<API key> (cgraph_node *node, void *data)
{
vec<cgraph_edge *> *redirect_callers = (vec<cgraph_edge *> *)data;
cgraph_edge *cs;
enum availability avail;
node-><API key> (&avail);
if (avail > AVAIL_INTERPOSABLE)
for (cs = node->callers; cs != NULL; cs = cs->next_caller)
if (!cs-><API key>)
redirect_callers->safe_push (cs);
return false;
}
/* Collect all callers of cgraph_node and its aliases that are known to lead to
cgraph_node (i.e. are not overwritable). */
vec<cgraph_edge *>
cgraph_node::collect_callers (void)
{
vec<cgraph_edge *> redirect_callers = vNULL;
<API key> (<API key>,
&redirect_callers, false);
return redirect_callers;
}
/* Return TRUE if NODE2 a clone of NODE or is equivalent to it. */
static bool
clone_of_p (cgraph_node *node, cgraph_node *node2)
{
bool skipped_thunk = false;
node = node-><API key> ();
node2 = node2-><API key> ();
/* There are no virtual clones of thunks so check former_clone_of or if we
might have skipped thunks because this adjustments are no longer
necessary. */
while (node->thunk.thunk_p)
{
if (node2->former_clone_of == node->decl)
return true;
if (!node->thunk.this_adjusting)
return false;
node = node->callees->callee-><API key> ();
skipped_thunk = true;
}
if (skipped_thunk)
{
if (!node2->clone.args_to_skip
|| !bitmap_bit_p (node2->clone.args_to_skip, 0))
return false;
if (node2->former_clone_of == node->decl)
return true;
else if (!node2->clone_of)
return false;
}
while (node != node2 && node2)
node2 = node2->clone_of;
return node2 != NULL;
}
/* Verify edge count and frequency. */
bool
cgraph_edge::<API key> ()
{
bool error_found = false;
if (count < 0)
{
error ("caller edge count is negative");
error_found = true;
}
if (frequency < 0)
{
error ("caller edge frequency is negative");
error_found = true;
}
if (frequency > CGRAPH_FREQ_MAX)
{
error ("caller edge frequency is too large");
error_found = true;
}
if (gimple_has_body_p (caller->decl)
&& !caller->global.inlined_to
&& !speculative
/* FIXME: Inline-analysis sets frequency to 0 when edge is optimized out.
Remove this once edges are actually removed from the function at that time. */
&& (frequency
|| (<API key>.exists ()
&& ((<API key>.length () <= (unsigned) uid)
|| !inline_edge_summary (this)->predicate)))
&& (frequency
!= <API key> (caller->decl,
gimple_bb (call_stmt))))
{
error ("caller edge frequency %i does not match BB frequency %i",
frequency,
<API key> (caller->decl,
gimple_bb (call_stmt)));
error_found = true;
}
return error_found;
}
/* Switch to THIS_CFUN if needed and print STMT to stderr. */
static void
<API key> (function *this_cfun, gimple stmt)
{
bool fndecl_was_null = false;
/* debug_gimple_stmt needs correct cfun */
if (cfun != this_cfun)
set_cfun (this_cfun);
/* ...and an actual <API key> */
if (!<API key>)
{
<API key> = this_cfun->decl;
fndecl_was_null = true;
}
debug_gimple_stmt (stmt);
if (fndecl_was_null)
<API key> = NULL;
}
/* Verify that call graph edge corresponds to DECL from the associated
statement. Return true if the verification should fail. */
bool
cgraph_edge::<API key> (tree decl)
{
cgraph_node *node;
if (!decl || callee->global.inlined_to)
return false;
if (symtab->state == LTO_STREAMING)
return false;
node = cgraph_node::get (decl);
/* We do not know if a node from a different partition is an alias or what it
aliases and therefore cannot do the former_clone_of check reliably. When
body_removed is set, we have lost all information about what was alias or
thunk of and also cannot proceed. */
if (!node
|| node->body_removed
|| node->in_other_partition
|| callee->icf_merged
|| callee->in_other_partition)
return false;
node = node-><API key> ();
/* Optimizers can redirect unreachable calls or calls triggering undefined
behaviour to builtin_unreachable. */
if (DECL_BUILT_IN_CLASS (callee->decl) == BUILT_IN_NORMAL
&& DECL_FUNCTION_CODE (callee->decl) == <API key>)
return false;
if (callee->former_clone_of != node->decl
&& (node != callee-><API key> ())
&& !clone_of_p (node, callee))
return true;
else
return false;
}
/* Verify cgraph nodes of given cgraph node. */
DEBUG_FUNCTION void
cgraph_node::verify_node (void)
{
cgraph_edge *e;
function *this_cfun = <API key> (decl);
basic_block this_block;
<API key> gsi;
bool error_found = false;
if (seen_error ())
return;
timevar_push (TV_CGRAPH_VERIFY);
error_found |= verify_base ();
for (e = callees; e; e = e->next_callee)
if (e->aux)
{
error ("aux field set for edge %s->%s",
<API key> (e->caller->name ()),
<API key> (e->callee->name ()));
error_found = true;
}
if (count < 0)
{
error ("execution count is negative");
error_found = true;
}
if (global.inlined_to && same_comdat_group)
{
error ("inline clone in same comdat group list");
error_found = true;
}
if (!definition && !in_other_partition && local.local)
{
error ("local symbols must be defined");
error_found = true;
}
if (global.inlined_to && externally_visible)
{
error ("externally visible inline clone");
error_found = true;
}
if (global.inlined_to && address_taken)
{
error ("inline clone with address taken");
error_found = true;
}
if (global.inlined_to && force_output)
{
error ("inline clone is forced to output");
error_found = true;
}
for (e = indirect_calls; e; e = e->next_callee)
{
if (e->aux)
{
error ("aux field set for indirect edge from %s",
<API key> (e->caller->name ()));
error_found = true;
}
if (!e-><API key>
|| !e->indirect_info)
{
error ("An indirect edge from %s is not marked as indirect or has "
"associated indirect_info, the corresponding statement is: ",
<API key> (e->caller->name ()));
<API key> (this_cfun, e->call_stmt);
error_found = true;
}
}
bool check_comdat = comdat_local_p ();
for (e = callers; e; e = e->next_caller)
{
if (e-><API key> ())
error_found = true;
if (check_comdat
&& !<API key> (e->caller))
{
error ("comdat-local function called by %s outside its comdat",
<API key> (e->caller->name ()));
error_found = true;
}
if (!e->inline_failed)
{
if (global.inlined_to
!= (e->caller->global.inlined_to
? e->caller->global.inlined_to : e->caller))
{
error ("inlined_to pointer is wrong");
error_found = true;
}
if (callers->next_caller)
{
error ("multiple inline callers");
error_found = true;
}
}
else
if (global.inlined_to)
{
error ("inlined_to pointer set for noninline callers");
error_found = true;
}
}
for (e = indirect_calls; e; e = e->next_callee)
if (e-><API key> ())
error_found = true;
if (!callers && global.inlined_to)
{
error ("inlined_to pointer is set but no predecessors found");
error_found = true;
}
if (global.inlined_to == this)
{
error ("inlined_to pointer refers to itself");
error_found = true;
}
if (clone_of)
{
cgraph_node *n;
for (n = clone_of->clones; n; n = n->next_sibling_clone)
if (n == this)
break;
if (!n)
{
error ("cgraph_node has wrong clone_of");
error_found = true;
}
}
if (clones)
{
cgraph_node *n;
for (n = clones; n; n = n->next_sibling_clone)
if (n->clone_of != this)
break;
if (n)
{
error ("cgraph_node has wrong clone list");
error_found = true;
}
}
if ((prev_sibling_clone || next_sibling_clone) && !clone_of)
{
error ("cgraph_node is in clone list but it is not clone");
error_found = true;
}
if (!prev_sibling_clone && clone_of && clone_of->clones != this)
{
error ("cgraph_node has wrong prev_clone pointer");
error_found = true;
}
if (prev_sibling_clone && prev_sibling_clone->next_sibling_clone != this)
{
error ("double linked list of clones corrupted");
error_found = true;
}
if (analyzed && alias)
{
bool ref_found = false;
int i;
ipa_ref *ref = NULL;
if (callees)
{
error ("Alias has call edges");
error_found = true;
}
for (i = 0; iterate_reference (i, ref); i++)
if (ref->use == IPA_REF_CHKP)
;
else if (ref->use != IPA_REF_ALIAS)
{
error ("Alias has non-alias reference");
error_found = true;
}
else if (ref_found)
{
error ("Alias has more than one alias reference");
error_found = true;
}
else
ref_found = true;
if (!ref_found)
{
error ("Analyzed alias has no reference");
error_found = true;
}
}
/* Check instrumented version reference. */
if (<API key>
&& <API key>-><API key> != this)
{
error ("Instrumentation clone does not reference original node");
error_found = true;
}
/* Cannot have orig_decl for not instrumented nodes. */
if (!<API key> && orig_decl)
{
error ("Not instrumented node has non-NULL original declaration");
error_found = true;
}
/* If original not instrumented node still exists then we may check
original declaration is set properly. */
if (<API key>
&& orig_decl
&& orig_decl != <API key>->decl)
{
error ("Instrumented node has wrong original declaration");
error_found = true;
}
/* Check all nodes have chkp reference to their instrumented versions. */
if (analyzed
&& <API key>
&& !<API key>)
{
bool ref_found = false;
int i;
struct ipa_ref *ref;
for (i = 0; iterate_reference (i, ref); i++)
if (ref->use == IPA_REF_CHKP)
{
if (ref_found)
{
error ("Node has more than one chkp reference");
error_found = true;
}
if (ref->referred != <API key>)
{
error ("Wrong node is referenced with chkp reference");
error_found = true;
}
ref_found = true;
}
if (!ref_found)
{
error ("Analyzed node has no reference to instrumented version");
error_found = true;
}
}
if (analyzed && thunk.thunk_p)
{
if (!callees)
{
error ("No edge out of thunk node");
error_found = true;
}
else if (callees->next_callee)
{
error ("More than one edge out of thunk node");
error_found = true;
}
if (gimple_has_body_p (decl))
{
error ("Thunk is not supposed to have body");
error_found = true;
}
if (thunk.<API key>
&& !<API key>-><API key> (callees->callee))
{
error ("Instrumentation thunk has wrong edge callee");
error_found = true;
}
}
else if (analyzed && gimple_has_body_p (decl)
&& !TREE_ASM_WRITTEN (decl)
&& (!DECL_EXTERNAL (decl) || global.inlined_to)
&& !flag_wpa)
{
if (this_cfun->cfg)
{
hash_set<gimple> stmts;
int i;
ipa_ref *ref = NULL;
/* Reach the trees by walking over the CFG, and note the
enclosing basic-blocks in the call edges. */
FOR_EACH_BB_FN (this_block, this_cfun)
{
for (gsi = gsi_start_phis (this_block);
!gsi_end_p (gsi); gsi_next (&gsi))
stmts.add (gsi_stmt (gsi));
for (gsi = gsi_start_bb (this_block);
!gsi_end_p (gsi);
gsi_next (&gsi))
{
gimple stmt = gsi_stmt (gsi);
stmts.add (stmt);
if (is_gimple_call (stmt))
{
cgraph_edge *e = get_edge (stmt);
tree decl = gimple_call_fndecl (stmt);
if (e)
{
if (e->aux)
{
error ("shared call_stmt:");
<API key> (this_cfun, stmt);
error_found = true;
}
if (!e-><API key>)
{
if (e-><API key> (decl))
{
error ("edge points to wrong declaration:");
debug_tree (e->callee->decl);
fprintf (stderr," Instead of:");
debug_tree (decl);
error_found = true;
}
}
else if (decl)
{
error ("an indirect edge with unknown callee "
"corresponding to a call_stmt with "
"a known declaration:");
error_found = true;
<API key> (this_cfun, e->call_stmt);
}
e->aux = (void *)1;
}
else if (decl)
{
error ("missing callgraph edge for call stmt:");
<API key> (this_cfun, stmt);
error_found = true;
}
}
}
}
for (i = 0; iterate_reference (i, ref); i++)
if (ref->stmt && !stmts.contains (ref->stmt))
{
error ("reference to dead statement");
<API key> (this_cfun, ref->stmt);
error_found = true;
}
}
else
/* No CFG available?! */
gcc_unreachable ();
for (e = callees; e; e = e->next_callee)
{
if (!e->aux)
{
error ("edge %s->%s has no corresponding call_stmt",
<API key> (e->caller->name ()),
<API key> (e->callee->name ()));
<API key> (this_cfun, e->call_stmt);
error_found = true;
}
e->aux = 0;
}
for (e = indirect_calls; e; e = e->next_callee)
{
if (!e->aux && !e->speculative)
{
error ("an indirect edge from %s has no corresponding call_stmt",
<API key> (e->caller->name ()));
<API key> (this_cfun, e->call_stmt);
error_found = true;
}
e->aux = 0;
}
}
if (error_found)
{
dump (stderr);
internal_error ("verify_cgraph_node failed");
}
timevar_pop (TV_CGRAPH_VERIFY);
}
/* Verify whole cgraph structure. */
DEBUG_FUNCTION void
cgraph_node::verify_cgraph_nodes (void)
{
cgraph_node *node;
if (seen_error ())
return;
FOR_EACH_FUNCTION (node)
node->verify ();
}
/* Walk the alias chain to return the function cgraph_node is alias of.
Walk through thunks, too.
When AVAILABILITY is non-NULL, get minimal availability in the chain. */
cgraph_node *
cgraph_node::function_symbol (enum availability *availability)
{
cgraph_node *node = <API key> (availability);
while (node->thunk.thunk_p)
{
node = node->callees->callee;
if (availability)
{
enum availability a;
a = node->get_availability ();
if (a < *availability)
*availability = a;
}
node = node-><API key> (availability);
}
return node;
}
/* Walk the alias chain to return the function cgraph_node is alias of.
Walk through non virtual thunks, too. Thus we return either a function
or a virtual thunk node.
When AVAILABILITY is non-NULL, get minimal availability in the chain. */
cgraph_node *
cgraph_node::<API key>
(enum availability *availability)
{
cgraph_node *node = <API key> (availability);
while (node->thunk.thunk_p && !node->thunk.virtual_offset_p)
{
node = node->callees->callee;
if (availability)
{
enum availability a;
a = node->get_availability ();
if (a < *availability)
*availability = a;
}
node = node-><API key> (availability);
}
return node;
}
/* When doing LTO, read cgraph_node's body from disk if it is not already
present. */
bool
cgraph_node::<API key> (void)
{
lto_file_decl_data *file_data;
const char *data, *name;
size_t len;
tree decl = this->decl;
if (DECL_RESULT (decl))
return false;
gcc_assert (in_lto_p);
timevar_push (<API key>);
file_data = lto_file_data;
name = IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl));
/* We may have renamed the declaration, e.g., a static function. */
name = <API key> (file_data, name);
data = <API key> (file_data, <API key>,
name, &len);
if (!data)
fatal_error (input_location, "%s: section %s is missing",
file_data->file_name,
name);
gcc_assert (<API key> (decl) == NULL);
<API key> (file_data, this, data);
lto_stats.num_function_bodies++;
<API key> (file_data, <API key>, name,
data, len);
<API key> (this);
/* Keep lto file data so ipa-inline-analysis knows about cross module
inlining. */
timevar_pop (<API key>);
return true;
}
/* Prepare function body. When doing LTO, read cgraph_node's body from disk
if it is not already present. When some IPA transformations are scheduled,
apply them. */
bool
cgraph_node::get_body (void)
{
bool updated;
updated = <API key> ();
/* Getting transformed body makes no sense for inline clones;
we should never use this on real clones becuase they are materialized
early.
TODO: Materializing clones here will likely lead to smaller LTRANS
footprint. */
gcc_assert (!global.inlined_to && !clone_of);
if (<API key>.exists ())
{
opt_pass *saved_current_pass = current_pass;
FILE *saved_dump_file = dump_file;
int saved_dump_flags = dump_flags;
push_cfun (<API key> (decl));
<API key> ();
cgraph_edge::rebuild_edges ();
free_dominance_info (CDI_DOMINATORS);
free_dominance_info (CDI_POST_DOMINATORS);
pop_cfun ();
updated = true;
current_pass = saved_current_pass;
dump_file = saved_dump_file;
dump_flags = saved_dump_flags;
}
return updated;
}
/* Return the <API key> of the function. */
struct function *
cgraph_node::get_fun (void)
{
cgraph_node *node = this;
struct function *fun = <API key> (node->decl);
while (!fun && node->clone_of)
{
node = node->clone_of;
fun = <API key> (node->decl);
}
return fun;
}
/* Verify if the type of the argument matches that of the function
declaration. If we cannot verify this or there is a mismatch,
return false. */
static bool
<API key> (gimple stmt, tree fndecl, bool args_count_match)
{
tree parms, p;
unsigned int i, nargs;
/* Calls to internal functions always match their signature. */
if (<API key> (stmt))
return true;
nargs = <API key> (stmt);
/* Get argument types for verification. */
if (fndecl)
parms = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
else
parms = TYPE_ARG_TYPES (gimple_call_fntype (stmt));
/* Verify if the type of the argument matches that of the function
declaration. If we cannot verify this or there is a mismatch,
return false. */
if (fndecl && DECL_ARGUMENTS (fndecl))
{
for (i = 0, p = DECL_ARGUMENTS (fndecl);
i < nargs;
i++, p = DECL_CHAIN (p))
{
tree arg;
/* We cannot distinguish a varargs function from the case
of excess parameters, still deferring the inlining decision
to the callee is possible. */
if (!p)
break;
arg = gimple_call_arg (stmt, i);
if (p == error_mark_node
|| DECL_ARG_TYPE (p) == error_mark_node
|| arg == error_mark_node
|| (!types_compatible_p (DECL_ARG_TYPE (p), TREE_TYPE (arg))
&& !fold_convertible_p (DECL_ARG_TYPE (p), arg)))
return false;
}
if (args_count_match && p)
return false;
}
else if (parms)
{
for (i = 0, p = parms; i < nargs; i++, p = TREE_CHAIN (p))
{
tree arg;
/* If this is a varargs function defer inlining decision
to callee. */
if (!p)
break;
arg = gimple_call_arg (stmt, i);
if (TREE_VALUE (p) == error_mark_node
|| arg == error_mark_node
|| TREE_CODE (TREE_VALUE (p)) == VOID_TYPE
|| (!types_compatible_p (TREE_VALUE (p), TREE_TYPE (arg))
&& !fold_convertible_p (TREE_VALUE (p), arg)))
return false;
}
}
else
{
if (nargs != 0)
return false;
}
return true;
}
/* Verify if the type of the argument and lhs of CALL_STMT matches
that of the function declaration CALLEE. If ARGS_COUNT_MATCH is
true, the arg count needs to be the same.
If we cannot verify this or there is a mismatch, return false. */
bool
<API key> (gimple call_stmt, tree callee,
bool args_count_match)
{
tree lhs;
if ((DECL_RESULT (callee)
&& !DECL_BY_REFERENCE (DECL_RESULT (callee))
&& (lhs = gimple_call_lhs (call_stmt)) != NULL_TREE
&& !<API key> (TREE_TYPE (DECL_RESULT (callee)),
TREE_TYPE (lhs))
&& !fold_convertible_p (TREE_TYPE (DECL_RESULT (callee)), lhs))
|| !<API key> (call_stmt, callee, args_count_match))
return false;
return true;
}
/* Reset all state within cgraph.c so that we can rerun the compiler
within the same process. For use by toplev::finalize. */
void
cgraph_c_finalize (void)
{
symtab = NULL;
<API key> = NULL;
cgraph_fnver_htab = NULL;
version_info_node = NULL;
}
/* A wroker for <API key>. */
bool
cgraph_node::<API key> (bool (*callback) (cgraph_node *,
void *),
void *data,
bool <API key>)
{
ipa_ref *ref;
FOR_EACH_ALIAS (this, ref)
{
cgraph_node *alias = dyn_cast <cgraph_node *> (ref->referring);
if (<API key>
|| alias->get_availability () > AVAIL_INTERPOSABLE)
if (alias-><API key> (callback, data,
<API key>))
return true;
}
return false;
}
/* Return true if NODE has thunk. */
bool
cgraph_node::has_thunk_p (cgraph_node *node, void *)
{
for (cgraph_edge *e = node->callers; e; e = e->next_caller)
if (e->caller->thunk.thunk_p)
return true;
return false;
}
#include "gt-cgraph.h" |
<?php
// Check to ensure this file is included in Joomla!
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport( 'joomla.application.component.view');
/**
* HTML View class for the Registration component
*
* @package Joomla
* @subpackage Registration
* @since 1.0
*/
class <API key> extends JView
{
function display($tpl = null)
{
$mainframe = JFactory::getApplication();
$pathway =& $mainframe->getPathway();
$document =& JFactory::getDocument();
$params = &$mainframe->getParams();
// Page Title
$menus = &JSite::getMenu();
$menu = $menus->getActive();
$is_id = 0;
$cid = JRequest::getVar( 'cid', array(0), '', 'array' );
$msg = JRequest::getVar( 'msg', '', 'get', 'string', JREQUEST_ALLOWRAW );
JArrayHelper::toInteger($cid, array(0));
if($cid[0])
{
$is_id = $cid[0];
}
$db =& JFactory::getDBO();
$tid = JRequest::getVar( 'tid', 0, '', 'int' );
$sid = JRequest::getVar( 'sid', 0, '', 'int' );
/*if($is_id){
$query = "SELECT COUNT(*) FROM #__bl_players as p LEFT JOIN #__bl_positions as bp ON bp.p_id=p.position_id, #__bl_teams as t, #__bl_seasons as s, #__bl_season_teams as st, #__bl_tournament as tr WHERE s.s_id=st.season_id AND st.team_id = t.id AND s.t_id = tr.id AND s.s_id=".$s_id." AND p.team_id = t.id AND p.id = ".$is_id;
$db->setQuery($query);
if(!$db->loadResult()){
JError::raiseError( 403, JText::_('Access Forbidden') );
return;
}
}*/
$row = new JTablePlayer($db);
$row->load($is_id);
$pos = array();
$query = "SELECT * FROM #__bl_positions ORDER BY p_name";
$db->setQuery($query);
$tourn = $db->loadObjectList();
$pos[] = JHTML::_('select.option', 0, JText::_('Select Position'), 'p_id', 'p_name' );
$positions = array_merge($pos,$tourn);
$lists['pos'] = JHTML::_('select.genericlist', $positions, 'position_id', 'class="inputbox" size="1"', 'p_id', 'p_name', $row->position_id );
$query = "SELECT * FROM #__bl_teams ORDER BY t_name";
$db->setQuery($query);
$teams = $db->loadObjectList();
$lists['teams'] = JHTML::_('select.genericlist', $teams, 'team_id', 'class="inputbox" size="1" disabled', 'id', 't_name', $tid );
$query = "SELECT p.ph_name as name,p.id as id,p.ph_filename as filename FROM #__bl_assign_photos as ap, #__bl_photos as p WHERE ap.photo_id = p.id AND cat_type = 1 AND cat_id = ".$row->id."";
$db->setQuery($query);
$lists['photos'] = $db->loadObjectList();
$query = "SELECT t.sport_id FROM #__bl_tournament as t,#__bl_seasons as s, #__bl_season_teams as st WHERE s.t_id=t.id AND st.season_id = s.s_id AND st.team_id = ".$row->team_id." ORDER BY s.s_id LIMIT 1";
$db->setQuery($query);
$sport_id = $db->loadResult();
$query = "SELECT ef.*,ev.fvalue as fvalue FROM #__bl_extra_filds as ef LEFT JOIN #__bl_extra_values as ev ON ef.id=ev.f_id AND ev.uid=".$row->id." WHERE ef.published=1 AND ef.type='0' ORDER BY ef.ordering";
$db->setQuery($query);
$lists['ext_fields'] = $db->loadObjectList();
$this->assignRef('params', $params);
$this->assignRef('lists', $lists);
$this->assignRef('rows', $row);
$this->assignRef('tid', $tid);
$this->assignRef('s_id', $sid);
$this->assignRef('msg', $msg);
parent::display($tpl);
}
} |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Uses of Interface com.sun.jersey.spi.container.<API key> (jersey-bundle 1.19 API)
</TITLE>
<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="Uses of Interface com.sun.jersey.spi.container.<API key> (jersey-bundle 1.19 API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/sun/jersey/spi/container/<API key>.html" title="interface in com.sun.jersey.spi.container"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/sun/jersey/spi/container//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<HR>
<CENTER>
<H2>
<B>Uses of Interface<br>com.sun.jersey.spi.container.<API key></B></H2>
</CENTER>
No usage of com.sun.jersey.spi.container.<API key>
<P>
<HR>
<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="<API key>"></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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/sun/jersey/spi/container/<API key>.html" title="interface in com.sun.jersey.spi.container"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</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">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/sun/jersey/spi/container//<API key>.html" target="_top"><B>FRAMES</B></A>
<A HREF="<API key>.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<HR>
Copyright &
</BODY>
</HTML> |
</div>
<div class="credit">Site built by <a href="https:
<div class="carrots"></div>
<?php wp_footer(); ?>
</body>
</html> |
<?php
/*Template Name: Curator Page
*/
get_header();
$user_id = $_GET['id'];
if(!$user_id) {
wp_redirect( '/curators' ); exit();
}
$user = get_userdata( $user_id );
if ( $user === false ) {
wp_redirect( '/curators' ); exit();
}
$user_posts = count_user_posts($user->ID, 'acme_article');
$args = array(
'post_type' => 'acme_article',
'author' => $user->ID,
'orderby' => 'post_date',
'order' => 'ASC',
'posts_per_page' => -1
);
$posts = get_posts($args);
$curator_profile = get_avatar_url(get_avatar( $user->ID ));
?>
<div class="banner">
<div class="category-search">
<form action="">
<div class="<API key>">
<p></p>
</div>
<select name="" id="country">
<option value="hide">-- --</option>
<option value="india"></option>
<option value="indonesia"></option>
<option value="cambodia"> </option>
<option value="singapore"></option>
<option value="thailand"></option>
<option value="philippines"></option>
<option value="vietnam"></option>
<option value="malaysia"></option>
<option value="china"></option>
<option value="taiwan"></option>
<option value="japan"></option>
<option value="korea"></option>
<option value="hongkong">/</option>
<option value="egypt"></option>
<option value="dubai"></option>
<option value="middleeast"></option>
<option value="usa"></option>
<option value="argentina"></option>
<option value="canada"></option>
<option value="brazil"></option>
<option value="bolivia"></option>
<option value="mexico"></option>
<option value="australia"></option>
<option value="guam"></option>
<option value="saipan"></option>
<option value="hawaii"></option>
<option value="newzealand"></option>
<option value="uk"></option>
<option value="italy"></option>
<option value="austria"></option>
<option value="greece"></option>
<option value="croatia"></option>
<option value="switzerland"></option>
<option value="spain"></option>
<option value="czech-republic"></option>
<option value="germany"></option>
<option value="france"></option>
</select>
<select name="" id="category">
<option value="">-- --</option>
<option value="life"></option>
<option value="fashion"></option>
<option value="gourmet"></option>
<option value="hotel"></option>
<option value="leisure"></option>
</select>
<input type="submit" value="">
</form>
</div>
</div>
<div class="defaultWidth center clear-auto bodycontent bodycontent-index ">
<div class="contentbox">
<div class="breadcrumbs" xmlns:v="http://rdf.data-vocabulary.org/
<?php echo function_exists('custom_breadcrumb') ? custom_breadcrumb() : ''; ?>
</div><!-- .breadcrumb -->';
<div class="curator-detail-wrap">
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-4">
<div class="pointer2"></div>
<?php $profile = getCurrentProfile(array( 'user_id' => $user->ID )); ?>
<?php
$current_user_id = get_current_user_id();
if($current_user_id == $user->ID){
?>
<div class="img-round cur-pic">
<img id="uploaded_image" src="<?php echo $profile; ?>" class="avatar avatar-96 photo " >
<span class="icon-cam-holder">
<img src="<?php echo <API key>().'/images/icons/camera.png'; ?>" id="change-image" class="avatar avatar-96 photo">
</span>
</div>
<?php }else{ ?>
<div class="img-round">
<img id="uploaded_image" src="<?php echo $profile; ?>" class="avatar avatar-96 photo " height="96" width="96" >
</div>
<?php } ?>
</div>
<div class="col-xs-12 col-sm-12 col-md-8">
<div class="article-content">
<div class="labels labels2">
<span class="countrylabel"><b><?php echo $user_posts ?></b> <?php echo $user_posts > 1 ? 'Articles' : 'Article'?></span>
<span class="catlabel"><b><?php echo <API key>($user->ID) ?></b> Favorites </span>
</div>
<div class="curator-info">
<form method="POST" id="edit-custom-form" enctype="multipart/form-data">
<div class="display_details">
<span id="edit-form">
<h4>
<?php echo $user->display_name ?>
</h4>
<p> <?php echo get_the_author_meta( 'description', $user->ID ) ?></p>
</span>
<?php
$current_user = wp_get_current_user();
?>
<?php if(is_user_logged_in() && $current_user->ID == $user->ID) : ?>
<span class="catlabel"><a href="#" class="edit-custom-form">Edit</a> </span>
<?php endif; ?>
</div>
<!-- <div style="display:none;" class="userinfo_section"> -->
<div style="display:none;" class="display_section">
<div class="row">
<div class="form-grp <API key> input-user">
/*
* Ranking article sidebar
* @hook: <API key>
*/
?>
<?php echo do_shortcode( '[ranking_article]' ) ?>
<?php
/*
* Ranking country sidebar
* @hook: <API key>
*/
?>
<?php echo do_shortcode( '[ranking_country]' ) ?>
?>
</div>
</div>
<script type="text/javascript">
</script>
<?php
get_footer(); |
package tuwien.auto.calimero.knxnetip;
import java.net.InetSocketAddress;
import tuwien.auto.calimero.Connection;
import tuwien.auto.calimero.KNXListener;
import tuwien.auto.calimero.KNXTimeoutException;
import tuwien.auto.calimero.cemi.CEMI;
/**
* Interface for working with KNX networks over an IP network connection.
* <p>
* The data exchange (send and receive) is done through {@link CEMI} messages.
* Asynchronous or incoming events are relayed to the registered event listeners.
* <p>
* Point-to-point logical connections:<br>
* Implementations with connectionless protocols, like UDP, shall provide heartbeat
* monitoring as defined by the KNX specification to check the connection state.
* Connection state messages are sent regularly, every 60 seconds, to the connected
* server. If the message is not responded to within a timeout of 10 seconds, it is
* repeated 3 times, and on no response the connection will be terminated.
* <p>
* Log information of this connection is provided using a logger in the namespace "calimero.knxnetip" and the name
* obtained from {@link KNXnetIPConnection#name()}.
*
* @author B. Malinowsky
* @see KNXnetIPTunnel
* @see KNXnetIPDevMgmt
* @see KNXnetIPRouting
* @see KNXListener
* @see CEMI
*/
public interface KNXnetIPConnection extends Connection<CEMI>
{
/**
* Identifier for KNXnet/IP protocol version 1.0.
*/
// same as in KNXnetIPHeader type
int KNXNETIP_VERSION_10 = 0x10;
/**
* KNXnet/IP default transport layer port number (port {@value #DEFAULT_PORT}) used
* for a communication endpoint (besides, this is the fixed port number used for
* discovery and routing).
*/
int DEFAULT_PORT = 3671;
/**
* State of communication: in idle state, no error, ready to send.
*/
int OK = 0;
/**
* State of communication: in closed state, no send possible.
*/
int CLOSED = 1;
/**
* Blocking mode used in {@link KNXnetIPConnection#send(CEMI, KNXnetIPConnection.BlockingMode)}.
*/
enum BlockingMode {
/**
* Send mode without any blocking for a response.
*/
NonBlocking,
/**
* Send mode with waiting for service acknowledgment response.
*/
WaitForAck,
/**
* Send mode with waiting for cEMI confirmation response.
*/
WaitForCon
}
/**
* Adds the specified event listener <code>l</code> to receive events from this
* connection.
* <p>
* If <code>l</code> was already added as listener, no action is performed.
* <p>
* Note: the method {@link KNXListener#frameReceived(tuwien.auto.calimero.FrameEvent)}
* of an added listener will be invoked by the KNXnet/IP receiver, and not in the
* context of the calling thread. Any lengthy processing tasks have to be avoided
* during the notification, and should be moved to dedicated own worker thread.
* Otherwise subsequent listener invocations will suffer from time delays since the
* receiver can not move on.
*
* @param l the listener to add
*/
@Override
void <API key>(KNXListener l);
/**
* Removes the specified event listener <code>l</code>, so it does no longer receive
* events from this connection.
* <p>
* If <code>l</code> was not added in the first place, no action is performed.
*
* @param l the listener to remove
*/
@Override
void <API key>(KNXListener l);
@Override
default void send(final CEMI frame, final Connection.BlockingMode blockingMode)
throws KNXTimeoutException, <API key>, <API key> {
final var mode = blockingMode == Connection.BlockingMode.Confirmation ? BlockingMode.WaitForCon
: blockingMode == Connection.BlockingMode.Ack ? BlockingMode.WaitForAck : BlockingMode.NonBlocking;
send(frame, mode);
}
/**
* Sends a cEMI frame to the remote server communicating with this endpoint.
* <p>
* The particular subtype of the cEMI frame expected might differ according to the
* implementation of the KNXnet/IP connection.<br>
* In blocking mode, all necessary retransmissions of sent frames will be done
* automatically according to the protocol specification (e.g. in case of timeout). <br>
* If a communication failure occurs on the local socket, {@link #close()} is called.
* <br>
* In blocking send mode, on successfully receiving a response, all listeners are
* guaranteed to get notified before this method returns, with the communication state
* (see {@link #getState()}) reset to {@link #OK} after the notifying is done, so to
* prevent another send call from a listener.
*
* @param frame cEMI message to send
* @param mode specifies the behavior in regard to response messages, this parameter
* will be ignored by protocols in case no response is expected at all;<br>
* supply one of the {@link BlockingMode} constants, with following blocking
* behavior in increasing order: {@link BlockingMode#NonBlocking}, {@link BlockingMode#WaitForAck},
* {@link BlockingMode#WaitForCon}
* @throws KNXTimeoutException in a blocking <code>mode</code> if a timeout regarding
* a response message was encountered
* @throws <API key> if no communication was established in the
* first place or communication was closed
* @throws <API key> on thread interrupt
* @throws <API key> if the send is not permitted by the protocol
*/
void send(CEMI frame, BlockingMode mode)
throws KNXTimeoutException, <API key>, <API key>;
/**
* Returns the address (endpoint) this connection endpoint is communicating to.
* <p>
* The address returned is equal to the one used to establish the communication (e.g.,
* the control endpoint address), although internally, different addresses might be
* used.<br>
* If no communication is established, the unspecified (wildcard) address with port
* number 0 is returned.
*
* @return IP address/host and port as {@link InetSocketAddress}
*/
InetSocketAddress getRemoteAddress();
/**
* Returns information about the current KNXnet/IP communication state.
*
* @return state enumeration
*/
int getState();
/**
* Returns the name of this connection, a brief textual representation to identify a
* KNXnet/IP connection.
* <p>
* The name has to be unique at least for connections with different IP addresses for
* the remote control endpoint.<br>
* The returned name is used by this connection for the name of its log service.
*
* @return name for this connection as string
*/
default String getName() { return name(); }
/**
* Ends communication with the remote server/client as specified by the used protocol.
* <p>
* All registered event listeners get notified. The close event is the last event the
* listeners receive. <br>
* If this connection endpoint is already closed, no action is performed.
*/
@Override
void close();
} |
// Added for Ishiiruka by Tino
#pragma once
#include <map>
#include "VideoCommon/NativeVertexFormat.h"
class G_GSAE01_pvt
{
public:
static void Initialize(std::map<u64, <API key>> &pvlmap);
}; |
/* $OpenBSD: getopt.h,v 1.2 2008/06/26 05:42:04 ray Exp $ */
/* $NetBSD: getopt.h,v 1.4 2000/07/07 10:43:54 ad Exp $ */
#ifndef _GETOPT_H_
#define _GETOPT_H_
/*
* GNU-like getopt_long() and 4.4BSD getsubopt()/optreset extensions
*/
#define no_argument 0
#define required_argument 1
#define optional_argument 2
#ifdef __cplusplus
extern "C" {
#endif
struct option {
/* name of long option */
const char *name;
/*
* one of no_argument, required_argument, and optional_argument:
* whether option takes an argument
*/
int has_arg;
/* if not NULL, set *flag to val when option found */
int *flag;
/* if flag not NULL, value to set *flag to; else return value */
int val;
};
int getopt_long(int, char * const *, const char *,
const struct option *, int *);
int getopt_long_only(int, char * const *, const char *,
const struct option *, int *);
#ifndef _GETOPT_DEFINED_
#define _GETOPT_DEFINED_
int getopt(int, char * const *, const char *);
int getsubopt(char **, char * const *, char **);
extern char *optarg; /* getopt(3) external variables */
extern int opterr;
extern int optind;
extern int optopt;
extern int optreset;
extern char *suboptarg; /* getsubopt(3) external variable */
#endif
#ifdef __cplusplus
}
#endif
#endif /* !_GETOPT_H_ */ |
#include "debugmain.h"
#ifdef KEY_DEBUG
DEBUG_HANDLE Debug_Keyboard;
#endif
#ifdef FDC_DEBUG
DEBUG_HANDLE FDC_Debug; /* FDC */
#endif
#ifdef CRTC_DEBUG
DEBUG_HANDLE CRTC_Debug; /* CRTC */
#endif
#ifdef ASIC_DEBUGGING
DEBUG_HANDLE ASIC_Debug; /* ASIC */
#endif
#ifdef AUDIOEVENT_DEBUG
DEBUG_HANDLE AudioEvent_Debug;
#endif
#ifdef TZX_DEBUG
DEBUG_HANDLE TZX_Debug;
#endif
void <API key>(void)
{
#ifdef DEBUG_MODE
#ifdef FDC_DEBUG
FDC_Debug = Debug_Start("fdc-dbg.txt");
Debug_Enable(FDC_Debug,FALSE);
#endif
#ifdef CRTC_DEBUG
CRTC_Debug = Debug_Start("crtc-dbg.txt");
Debug_Enable(CRTC_Debug,FALSE);
#endif
#ifdef ASIC_DEBUGGING
ASIC_Debug = Debug_Start("asic-dbg.txt");
Debug_Enable(ASIC_Debug,FALSE);
#endif
#ifdef AUDIOEVENT_DEBUG
AudioEvent_Debug = Debug_Start("audio-dbg.txt");
Debug_Enable(AudioEvent_Debug,FALSE);
#endif
#ifdef TZX_DEBUG
TZX_Debug = Debug_Start("tzx-dbg.txt");
Debug_Enable(TZX_Debug,FALSE);
#endif
#ifdef KEY_DEBUG
Debug_Keyboard = Debug_Start("key-dbg.txt");
Debug_Enable(Debug_Keyboard, TRUE);
#endif
#endif
}
void DebugMain_Finish(void)
{
#ifdef DEBUG_MODE
#ifdef KEY_DEBUG
Debug_End(Debug_Keyboard);
#endif
#ifdef FDC_DEBUG
Debug_End(FDC_Debug);
#endif
#ifdef CRTC_DEBUG
Debug_End(CRTC_Debug);
#endif
#ifdef ASIC_DEBUGGING
Debug_End(ASIC_Debug);
#endif
#ifdef AUDIOEVENT_DEBUG
Debug_End(AudioEvent_Debug);
#endif
#ifdef TZX_DEBUG
Debug_End(TZX_Debug);
#endif
#endif
} |
<?php
namespace Celest\Zone;
use Celest\ZoneOffset;
class <API key> extends ZoneRulesProvider
{
/**
* SPI method to get the available zone IDs.
* <p>
* This obtains the IDs that this {@code ZoneRulesProvider} provides.
* A provider should provide data for at least one zone ID.
* <p>
* The returned zone IDs remain available and valid for the lifetime of the application.
* A dynamic provider may increase the set of IDs as more data becomes available.
*
* @return string[] the set of zone IDs being provided, not null
* @throws ZoneRulesException if a problem occurs while providing the IDs
*/
protected function provideZoneIds()
{
return ['Europe/Paris', 'Europe/Berlin', 'UTC'];
}
/**
* SPI method to get the rules for the zone ID.
* <p>
* This loads the rules for the specified zone ID.
* The provider implementation must validate that the zone ID is valid and
* available, throwing a {@code ZoneRulesException} if it is not.
* The result of the method in the valid case depends on the caching flag.
* <p>
* If the provider implementation is not dynamic, then the result of the
* method must be the non-null set of rules selected by the ID.
* <p>
* If the provider implementation is dynamic, then the flag gives the option
* of preventing the returned rules from being cached in {@link ZoneId}.
* When the flag is true, the provider is permitted to return null, where
* null will prevent the rules from being cached in {@code ZoneId}.
* When the flag is false, the provider must return non-null rules.
*
* @param string $zoneId the zone ID as defined by {@code ZoneId}, not null
* @param bool $forCaching whether the rules are being queried for caching,
* true if the returned rules will be cached by {@code ZoneId},
* false if they will be returned to the user without being cached in {@code ZoneId}
* @return ZoneRules the rules, null if {@code forCaching} is true and this
* is a dynamic provider that wants to prevent caching in {@code ZoneId},
* otherwise not null
* @throws ZoneRulesException if rules cannot be obtained for the zone ID
*/
protected function provideRules($zoneId, $forCaching)
{
return ZoneRules::ofOffset(ZoneOffset::ofHours(1));
}
/**
* SPI method to get the history of rules for the zone ID.
* <p>
* This returns a map of historical rules keyed by a version string.
* The exact meaning and format of the version is provider specific.
* The version must follow lexicographical order, thus the returned map will
* be order from the oldest known rules to the newest available rules.
* The default 'TZDB' group uses version numbering consisting of the year
* followed by a letter, such as '2009e' or '2012f'.
* <p>
* Implementations must provide a result for each valid zone ID, however
* they do not have to provide a history of rules.
* Thus the map will contain at least one element, and will only contain
* more than one element if historical rule information is available.
* <p>
* The returned versions remain available and valid for the lifetime of the application.
* A dynamic provider may increase the set of versions as more data becomes available.
*
* @param string $zoneId the zone ID as defined by {@code ZoneId}, not null
* @return ZoneRules[] a modifiable copy of the history of the rules for the ID, sorted
* from oldest to newest, not null
* @throws ZoneRulesException if history cannot be obtained for the zone ID
*/
protected function provideVersions($zoneId)
{
// TODO: Implement provideVersions() method.
}
} |
<?php
add_action('init', 'TheShortcodesForVC');
function TheShortcodesForVC() {
if (!class_exists('<API key>')) { // or using plugins path function
return;
}
// Remove Front End
vc_disable_frontend();
// Settings
vc_set_as_theme(true);
// Removing Default shortcodes
vc_remove_element("vc_widget_sidebar");
vc_remove_element("vc_wp_search");
vc_remove_element("vc_wp_meta");
vc_remove_element("<API key>");
vc_remove_element("vc_wp_calendar");
vc_remove_element("vc_wp_pages");
vc_remove_element("vc_wp_tagcloud");
vc_remove_element("vc_wp_custommenu");
vc_remove_element("vc_wp_text");
vc_remove_element("vc_wp_posts");
vc_remove_element("vc_wp_links");
vc_remove_element("vc_wp_categories");
vc_remove_element("vc_wp_archives");
vc_remove_element("vc_wp_rss");
vc_remove_element("vc_teaser_grid");
vc_remove_element("vc_button");
vc_remove_element("vc_button2");
vc_remove_element("vc_cta_button");
vc_remove_element("vc_message");
vc_remove_element("vc_progress_bar");
vc_remove_element("vc_pie");
vc_remove_element("vc_posts_slider");
vc_remove_element("vc_posts_grid");
vc_remove_element("vc_images_carousel");
vc_remove_element("vc_carousel");
vc_remove_element("vc_gallery");
vc_remove_element("vc_single_image");
vc_remove_element("vc_facebook");
vc_remove_element("vc_tweetmeme");
vc_remove_element("vc_googleplus");
vc_remove_element("vc_pinterest");
vc_remove_element("vc_single_image");
vc_remove_element("vc_cta_button2");
vc_remove_element("vc_gmaps");
vc_remove_element("vc_raw_js");
vc_remove_element("vc_flickr");
vc_remove_element("vc_separator");
vc_remove_element("vc_text_separator");
vc_remove_element("vc_empty_space");
vc_remove_element("vc_custom_heading");
add_action( 'admin_head', 'remove_my_meta_box' );
function remove_my_meta_box() {
remove_meta_box("vc_teaser", "portfolio", "side");
remove_meta_box("vc_teaser", "page", "side");
remove_meta_box("vc_teaser", "product", "side");
}
// Adding Extra Shortcodes
require_once(THB_THEME_ROOT_ABS.'/vc_templates/button/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/image/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/styled_header/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/product/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/product_list/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/product_cat/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/post/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/portfolio/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/iconlist/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/iconbox/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/lookbook/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/product_grid/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/counter/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/notification/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/banner/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/progress_bar/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/team_member/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/testimonials/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/clients/shortcode.php');
require_once(THB_THEME_ROOT_ABS.'/vc_templates/gap/shortcode.php');
/* Visual Composer Mappings */
// Adding animation to columns
vc_add_param("vc_column", array(
"type" => "dropdown",
"class" => "",
"heading" => __("Animation"),
"admin_label" => true,
"param_name" => "animation",
"value" => array(
"None" => "",
"Left" => "animation right-to-left",
"Right" => "animation left-to-right",
"Top" => "animation bottom-to-top",
"Bottom" => "animation top-to-bottom",
"Scale" => "animation scale",
"Fade" => "animation fade-in"
),
"description" => ""
));
// Add parameters to rows
vc_add_param("vc_row", array(
"type" => "dropdown",
"class" => "",
"heading" => "Type",
"param_name" => "type",
"value" => array(
"In Container" => "in_container",
"Full Width Background" => "<API key>",
"Full Width Content" => "full_width_content"
)
));
vc_add_param("vc_row", array(
"type" => "checkbox",
"class" => "",
"heading" => __("Enable parallax"),
"param_name" => "enable_parallax",
"value" => array(
"" => "false"
)
));
vc_add_param("vc_row", array(
"type" => "textfield",
"class" => "",
"heading" => __("Parallax Speed"),
"param_name" => "parallax_speed",
"value" => "1",
"dependency" => array(
"element" => "enable_parallax",
"not_empty" => true
),
"description" => __("A value between 0 and 1 is recommended")
));
vc_add_param("vc_row", array(
"type" => "textfield",
"class" => "",
"heading" => __("Video background (mp4)"),
"param_name" => "bg_video_src_mp4",
"value" => "",
"description" => _("You must include the ogv & the mp4 format to render your video with cross browser compatibility. OGV is optional. Video must be in a 16:9 aspect ratio. The row background image will be used as in mobile devices.")
));
vc_add_param("vc_row", array(
"type" => "textfield",
"class" => "",
"heading" => __("Video background (ogv)"),
"param_name" => "bg_video_src_ogv",
"value" => ""
));
vc_add_param("vc_row", array(
"type" => "textfield",
"class" => "",
"heading" => __("Video background (webm)"),
"param_name" => "bg_video_src_webm",
"value" => ""
));
vc_add_param("vc_row", array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Video Overlay Color"),
"param_name" => "<API key>",
"value" => "",
"description" => __("If you want, you can select an overlay color.")
));
// Button shortcode
vc_map( array(
"name" => __("Button"),
"base" => "thb_button",
"icon" => "thb_vc_ico_button",
"class" => "thb_vc_sc_button",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "textfield",
"class" => "",
"heading" => __("Caption"),
"admin_label" => true,
"param_name" => "content",
"value" => "",
"description" => ""
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Link URL"),
"param_name" => "link",
"value" => "",
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Icon"),
"param_name" => "icon",
"value" => <API key>(),
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Open link in"),
"param_name" => "target_blank",
"value" => array(
"Same window" => "",
"New window" => "true"
),
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Style"),
"param_name" => "size",
"value" => array(
"Small button" => "small",
"Medium button" => "medium",
"Big button" => "large"
),
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Button color"),
"param_name" => "color",
"value" => array(
"White" => "white",
"Light Grey" => "grey",
"Black" => "black",
"Blue" => "blue",
"Green" => "green",
"Yellow" => "yellow",
"Orange" => "orange",
"Pink" => "pink",
"Petrol Green" => "petrol",
"Gray" => "darkgrey"
),
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Animation"),
"param_name" => "animation",
"value" => array(
"None" => "",
"Left" => "animation right-to-left",
"Right" => "animation left-to-right",
"Top" => "animation bottom-to-top",
"Bottom" => "animation top-to-bottom",
"Scale" => "animation scale",
"Fade" => "animation fade-in"
),
"description" => ""
)
)
) );
// Image shortcode
vc_map( array(
"name" => __("Image"),
"base" => "thb_image",
"icon" => "thb_vc_ico_image",
"class" => "thb_vc_sc_image",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Select Image"),
"param_name" => "image",
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Animation"),
"param_name" => "animation",
"value" => array(
"None" => "",
"Left" => "animation right-to-left",
"Right" => "animation left-to-right",
"Top" => "animation bottom-to-top",
"Bottom" => "animation top-to-bottom",
"Scale" => "animation scale",
"Fade" => "animation fade-in"
),
"description" => ""
),
array(
"type" => "textfield",
"heading" => __("Image size"),
"param_name" => "img_size",
"description" => __("Enter image size. Example: thumbnail, medium, large, full or other sizes defined by current theme. Alternatively enter image size in pixels: 200x100 (Width x Height). Leave empty to use 'thumbnail' size.")
),
array(
"type" => "dropdown",
"heading" => __("Image alignment"),
"param_name" => "alignment",
"value" => array(__("Align left") => "", __("Align right") => "right", __("Align center") => "center"),
"description" => __("Select image alignment.")
),
array(
"type" => "checkbox",
"class" => "",
"heading" => __("Link to Full-Width Image?"),
"param_name" => "lightbox",
"value" => array(
"" => "true"
)
),
array(
"type" => "textfield",
"heading" => __("Image link"),
"param_name" => "img_link",
"description" => __("Enter url if you want this image to have link."),
"dependency" => Array('element' => "lightbox", 'is_empty' => true)
),
array(
"type" => "dropdown",
"heading" => __("Link Target"),
"param_name" => "img_link_target",
"value" => array(
"Same window" => "",
"New window" => "true"
),
"dependency" => Array('element' => "lightbox", 'is_empty' => true)
)
)
) );
// Styled Header
vc_map( array(
"name" => __("Styled Header"),
"base" => "thb_header",
"icon" => "thb_vc_ico_styled",
"class" => "thb_vc_sc_styled",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "textfield",
"heading" => __("Title"),
"param_name" => "title",
"admin_label" => true,
"description" => __("Title of the header")
),
array(
"type" => "textfield",
"heading" => __("Sub-Title"),
"param_name" => "sub_title",
"description" => __("Sub - Title of the header. It's actually above the title.")
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Icon"),
"param_name" => "icon",
"value" => <API key>(),
"description" => ""
),
array(
"type" => "checkbox",
"class" => "",
"heading" => __("Use image instead of icon?"),
"param_name" => "is_image",
"value" => array(
"" => "true"
),
"description" => __("20px width is recommended (40px) for retina.")
),
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Select Image"),
"param_name" => "image",
"description" => "",
"dependency" => Array('element' => "is_image", 'not_empty' => true)
)
)
) );
// Products
vc_map( array(
"name" => __("Products"),
"base" => "thb_product",
"icon" => "thb_vc_ico_product",
"class" => "thb_vc_sc_product",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"heading" => __("Product Sort"),
"param_name" => "product_sort",
"value" => array(
__('Best Sellers') => "best-sellers",
__('Latest Products') => "latest-products",
__('Featured Products') => "featured-products",
__('Top Rated Products') => "top-rated",
__('Sale Products') => "sale-products",
__('By Category') => "by-category",
__('By Product ID') => "by-id",
),
"description" => __("Select the order of the products you'd like to show.")
),
array(
"type" => "checkbox",
"heading" => __("Product Category"),
"param_name" => "cat",
"value" => <API key>(),
"description" => __("Select the order of the products you'd like to show."),
"dependency" => Array('element' => "product_sort", 'value' => array('by-category'))
),
array(
"type" => "textfield",
"heading" => __("Product IDs"),
"param_name" => "product_ids",
"description" => __("Enter the products IDs you would like to display seperated by comma"),
"dependency" => Array('element' => "product_sort", 'value' => array('by-id'))
),
array(
"type" => "dropdown",
"heading" => __("Carousel"),
"param_name" => "carousel",
"value" => array(
'Yes' => "yes",
'No' => "no",
),
"description" => __("Select yes to display the products in a carousel.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of items"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of products to show."),
"dependency" => Array('element' => "product_sort", 'value' => array('by-category', 'featured-products', 'sale-products', 'top-rated', 'latest-products', 'best-sellers'))
),
array(
"type" => "dropdown",
"heading" => __("Columns"),
"param_name" => "columns",
"admin_label" => true,
"value" => array(
__('Four Columns') => "4",
__('Three Columns') => "3",
__('Two Columns') => "2"
),
"description" => __("Select the layout of the products.")
),
)
) );
// Product List
vc_map( array(
"name" => __("Product List"),
"base" => "thb_product_list",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "textfield",
"class" => "",
"heading" => __("Title"),
"param_name" => "title",
"value" => "",
"admin_label" => true,
"description" => __("Title of the widget")
),
array(
"type" => "dropdown",
"heading" => __("Product Sort"),
"param_name" => "product_sort",
"value" => array(
__('Best Sellers') => "best-sellers",
__('Featured Products') => "featured-products",
__('Latest Products') => "latest-products",
__('Top Rated') => "top-rated",
__('Sale Products') => "sale-products",
__('By Product ID') => "by-id"
),
"admin_label" => true,
"description" => __("Select the order of the products you'd like to show.")
),
array(
"type" => "textfield",
"heading" => __("Product IDs"),
"param_name" => "product_ids",
"description" => __("Enter the products IDs you would like to display seperated by comma"),
"dependency" => Array('element' => "product_sort", 'value' => array('by-id'))
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of items"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of products to show."),
"dependency" => Array('element' => "product_sort", 'value' => array('by-category', 'featured-products', 'sale-products', 'top-rated', 'latest-products', 'best-sellers'))
)
)
) );
// Product Categories
vc_map( array(
"name" => __("Product Categories"),
"base" => "<API key>",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "checkbox",
"heading" => __("Product Category"),
"param_name" => "cat",
"value" => <API key>(),
"description" => __("Select the categories you would like to display")
),
array(
"type" => "dropdown",
"heading" => __("Carousel"),
"param_name" => "carousel",
"value" => array(
'Yes' => "yes",
'No' => "no",
),
"description" => __("Select yes to display the categories in a carousel.")
),
array(
"type" => "dropdown",
"heading" => __("Columns"),
"param_name" => "columns",
"admin_label" => true,
"value" => array(
__('Four Columns') => "4",
__('Three Columns') => "3",
__('Two Columns') => "2"
),
"description" => __("Select the layout of the products.")
),
)
) );
// Posts
vc_map( array(
"name" => __("Posts"),
"base" => "thb_post",
"icon" => "thb_vc_ico_post",
"class" => "thb_vc_sc_post",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"heading" => __("Carousel"),
"param_name" => "carousel",
"value" => array(
'Yes' => "yes",
'No' => "no",
),
"description" => __("Select yes to display the products in a carousel.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of posts"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of posts to show.")
),
array(
"type" => "dropdown",
"heading" => __("Columns"),
"param_name" => "columns",
"admin_label" => true,
"value" => array(
__('Four Columns') => "4",
__('Three Columns') => "3",
__('Two Columns') => "2"
),
"description" => __("Select the layout of the posts.")
),
)
) );
// Portfolio
vc_map( array(
"name" => __("Portfolios"),
"base" => "thb_portfolio",
"icon" => "<API key>",
"class" => "thb_vc_sc_portfolio",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"heading" => __("Carousel"),
"param_name" => "carousel",
"value" => array(
'Yes' => "yes",
'No' => "no",
),
"description" => __("Select yes to display the portfolios in a carousel.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of portfolios"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of portfolios to show.")
),
array(
"type" => "dropdown",
"heading" => __("Columns"),
"param_name" => "columns",
"value" => array(
__('Four Columns') => "4",
__('Three Columns') => "3",
__('Two Columns') => "2"
),
"description" => __("Select the layout of the portfolios.")
),
array(
"type" => "checkbox",
"heading" => __("Categories"),
"param_name" => "categories",
"value" => <API key>(),
"description" => __("Select which categories of portfolios you would like to display.")
),
)
) );
// Icon List shortcode
vc_map( array(
"name" => __("Icon List"),
"base" => "thb_iconlist",
"icon" => "thb_vc_ico_iconlist",
"class" => "thb_vc_sc_iconlist",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Icon"),
"param_name" => "icon",
"value" => <API key>(),
"description" => ""
),
array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Icon color"),
"param_name" => "color",
"value" => "",
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Animation"),
"param_name" => "animation",
"value" => array(
"None" => "",
"Left" => "animation right-to-left",
"Right" => "animation left-to-right",
"Top" => "animation bottom-to-top",
"Bottom" => "animation top-to-bottom",
"Scale" => "animation scale",
"Fade" => "animation fade-in"
),
"description" => ""
),
array(
"type" => "exploded_textarea",
"class" => "",
"heading" => __("List Items"),
"admin_label" => true,
"param_name" => "content",
"value" => "",
"description" => __("Every new line will be treated as a list item")
)
)
) );
// Iconbox shortcode
vc_map( array(
"name" => __("Iconbox"),
"base" => "thb_iconbox",
"icon" => "thb_vc_ico_iconbox",
"class" => "thb_vc_sc_iconbox",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Type"),
"param_name" => "type",
"value" => array(
"Top Icon - Type 1" => "top type1",
"Top Icon - Type 2" => "top type2",
"Top Icon - Type 3" => "top type3",
"Left Icon - Round" => "left type1",
"Left Icon - Square" => "left type2",
"Left Icon - Only Icon" => "left type3",
"Right Icon - Round" => "right type1",
"Right Icon - Square" => "right type2",
"Right Icon - Only Icon" => "right type3"
),
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Icon"),
"param_name" => "icon",
"value" => <API key>(),
"description" => ""
),
array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Color"),
"param_name" => "color",
"value" => "",
"description" => __("Leave empty to use default color")
),
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Image"),
"param_name" => "image",
"description" => __("Use image instead of icon? Image uploaded should be 130*130 or 260*260 for retina. For small icons, 78*78 or 156*156 for retina."),
"dependency" => Array('element' => "type", 'value' => array('top type1', 'top type2', 'top type3', 'left type1', 'left type2', 'right type1', 'right type2'))
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Heading"),
"param_name" => "heading",
"value" => "",
"description" => ""
),
array(
"type" => "textarea",
"class" => "",
"heading" => __("Content"),
"admin_label" => true,
"param_name" => "content",
"value" => "",
"description" => ""
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Animation"),
"param_name" => "animation",
"value" => array(
"None" => "",
"Left" => "animation right-to-left",
"Right" => "animation left-to-right",
"Top" => "animation bottom-to-top",
"Bottom" => "animation top-to-bottom",
"Scale" => "animation scale",
"Fade" => "animation fade-in"
),
"description" => ""
),
array(
"type" => "checkbox",
"class" => "",
"heading" => __("Add Button?"),
"param_name" => "use_btn",
"value" => array(
"" => "true"
),
"description" => __("Check if you want to add a button.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Content"),
"admin_label" => true,
"param_name" => "btn_content",
"value" => "",
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Button Caption"),
"admin_label" => true,
"param_name" => "btn_content",
"value" => "",
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Button Link URL"),
"param_name" => "btn_link",
"value" => "",
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Button Icon"),
"param_name" => "btn_icon",
"value" => <API key>(),
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Button Open link in"),
"param_name" => "btn_target_blank",
"value" => array(
"Same window" => "",
"New window" => "true"
),
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Button Style"),
"param_name" => "btn_size",
"value" => array(
"Small button" => "small",
"Medium button" => "medium",
"Big button" => "big"
),
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Button color"),
"param_name" => "btn_color",
"value" => array(
"White" => "white",
"Light Grey" => "lightgrey",
"Black" => "black",
"Blue" => "blue",
"Green" => "green",
"Yellow" => "yellow",
"Orange" => "orange",
"Pink" => "pink",
"Petrol Green" => "petrol",
"Gray" => "gray"
),
"description" => "",
"dependency" => Array('element' => "use_btn", 'not_empty' => true)
)
)
) );
// Look Book
vc_map( array(
"name" => __("Look Book"),
"base" => "thb_lookbook",
"icon" => "thb_vc_ico_lookbook",
"class" => "thb_vc_sc_lookbook",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "checkbox",
"heading" => __("Product Category"),
"param_name" => "cat",
"value" => <API key>(),
"description" => __("Select the order of the products you'd like to show.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of items"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of products to show.")
),
array(
"type" => "textarea_html",
"class" => "",
"heading" => __("Content"),
"admin_label" => true,
"param_name" => "content",
"value" => "",
"description" => __("Enter a starting content to be displayed before lookbook products.")
)
)
) );
// Product Grid
vc_map( array(
"name" => __("Product Grid"),
"base" => "thb_productgrid",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"heading" => __("Product Sort"),
"param_name" => "product_sort",
"value" => array(
__('Best Sellers') => "best-sellers",
__('Latest Products') => "latest-products",
__('Top Rated') => "top-rated",
__('Sale Products') => "sale-products",
__('By Category') => "by-category",
__('By Product ID') => "by-id",
),
"admin_label" => true,
"description" => __("Select the order of the products you'd like to show.")
),
array(
"type" => "checkbox",
"heading" => __("Product Category"),
"param_name" => "cat",
"value" => <API key>(),
"description" => __("Select the order of the products you'd like to show."),
"dependency" => Array('element' => "product_sort", 'value' => array('by-category'))
),
array(
"type" => "textfield",
"heading" => __("Product IDs"),
"param_name" => "product_ids",
"description" => __("Enter the products IDs you would like to display seperated by comma"),
"dependency" => Array('element' => "product_sort", 'value' => array('by-id'))
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number of items"),
"param_name" => "item_count",
"value" => "4",
"description" => __("The number of products to show.")
)
)
) );
// Counter
vc_map( array(
"name" => __("Counter"),
"base" => "thb_counter",
"icon" => "thb_vc_ico_counter",
"class" => "thb_vc_sc_counter",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Icon"),
"param_name" => "icon",
"value" => <API key>(),
"description" => ""
),
array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Color"),
"param_name" => "color",
"value" => "",
"description" => __("Leave empty to use default color")
),
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Image"),
"param_name" => "image",
"description" => __("Use image instead of icon? Image uploaded should be 70*70 or 140*140 for retina.")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Number to count to"),
"param_name" => "content",
"value" => "",
"description" => ""
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Speed of the counter animation"),
"param_name" => "speed",
"value" => "",
"description" => __("Speed of the counter animation, default 1500")
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Heading"),
"param_name" => "heading",
"value" => "",
"admin_label" => true,
"description" => ""
)
)
) );
// Notification shortcode
vc_map( array(
"name" => __("Notification"),
"base" => "thb_notification",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Type"),
"param_name" => "type",
"value" => array(
"Information" => "information",
"Success" => "success",
"Warning" => "warning",
"Error" => "error",
"Note" => "note"
),
"description" => ""
),
array(
"type" => "textarea",
"class" => "",
"heading" => __("Content"),
"admin_label" => true,
"param_name" => "content",
"value" => "",
"description" => ""
)
)
) );
// Banner shortcode
vc_map( array(
"name" => __("Banner"),
"base" => "thb_banner",
"icon" => "thb_vc_ico_banner",
"class" => "thb_vc_sc_banner",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Background Color"),
"param_name" => "banner_color",
"value" => "",
"description" => __("Select Background Color")
),
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Select Background Image"),
"param_name" => "banner_bg",
"description" => ""
),
array(
"type" => "textfield",
"heading" => __("Banner Height"),
"param_name" => "banner_height",
"description" => __("Enter height of the banner in px.")
),
array(
"type" => "textfield",
"heading" => __("Padding"),
"param_name" => "banner_padding",
"description" => __("Enter padding value of the content. <small>This does not affect border offset values, only the content.</small>")
),
array(
"type" => "dropdown",
"class" => "",
"heading" => __("Banner Type"),
"param_name" => "type",
"value" => array(
"Type - 1 (5px Border with offset)" => "type1",
"Type - 2 (10px Border)" => "type2",
"Type - 3 (Call to Action style without border)" => "type3",
"Type - 4 (Simple no border)" => "type4",
"Type - 5 (With overlay link)" => "type5",
),
"description" => ""
),
array(
"type" => "colorpicker",
"class" => "",
"heading" => __("Border Color"),
"param_name" => "banner_border_color",
"value" => "",
"description" => __("Select Border Color if the banner type supports it"),
"dependency" => array(
"element" => "type",
"value" => array('type1', 'type2')
)
),
array(
"type" => "textfield",
"heading" => __("Title"),
"param_name" => "title",
"dependency" => array(
"element" => "type",
"value" => array('type3')
)
),
array(
"type" => "textfield",
"heading" => __("Sub Title"),
"param_name" => "subtitle",
"dependency" => array(
"element" => "type",
"value" => array('type3')
)
),
array(
"type" => "textfield",
"heading" => __("Button Text"),
"param_name" => "button_text",
"dependency" => array(
"element" => "type",
"value" => array('type3')
)
),
array(
"type" => "textfield",
"heading" => __("Button Link"),
"param_name" => "button_link",
"dependency" => array(
"element" => "type",
"value" => array('type3')
)
),
array(
"type" => "textfield",
"heading" => __("Overlay Link"),
"param_name" => "overlay_link",
"dependency" => array(
"element" => "type",
"value" => array('type5')
)
),
array(
"type" => "checkbox",
"class" => "",
"heading" => __("Enable parallax"),
"param_name" => "enable_parallax",
"value" => array(
"" => "false"
)
),
array(
"type" => "textfield",
"class" => "",
"heading" => __("Parallax Speed"),
"param_name" => "parallax_speed",
"value" => "1",
"dependency" => array(
"element" => "enable_parallax",
"not_empty" => true
),
"description" => __("A value between 0 and 10 is recommended. Lower is faster")
),
array(
"type" => "dropdown",
"heading" => __("Text alignment"),
"param_name" => "alignment",
"value" => array( __("Align center") => "", __("Align left") => "textleft", __("Align right") => "textright" ),
"description" => __("Select text alignment."),
"dependency" => array(
"element" => "type",
"value" => array('type1', 'type2', 'type4', 'type5')
)
),
array(
"type" => "textarea_html",
"class" => "",
"heading" => __("Content"),
"param_name" => "content",
"value" => "",
"admin_label" => true,
"description" => __("Content you would like to place inside the banner"),
"dependency" => array(
"element" => "type",
"value" => array('type1', 'type2', 'type4', 'type5')
)
)
)
) );
// Banner shortcode
vc_map( array(
"name" => __("Gap"),
"base" => "thb_gap",
"icon" => "thb_vc_ico_gap",
"class" => "thb_vc_sc_gap",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "textfield",
"heading" => __("Gap Height"),
"param_name" => "height",
"admin_label" => true,
"description" => __("Enter height of the gap in px.")
)
)
) );
// Progress Bar Shortcode
vc_map( array(
"name" => __("Progress Bar"),
"base" => "thb_progressbar",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "exploded_textarea",
"heading" => __("Graphic values"),
"param_name" => "values",
"description" => __('Input graph values here. Divide values with linebreaks (Enter). Example: 90|Development', 'js_composer'),
"value" => "90|Development,80|Design,70|Marketing"
),
array(
"type" => "dropdown",
"heading" => __("Bar color"),
"param_name" => "bgcolor",
"value" => array(
"Light Grey" => "lightgrey",
"Black" => "black",
"Blue" => "blue",
"Green" => "green",
"Yellow" => "yellow",
"Orange" => "orange",
"Pink" => "pink",
"Petrol Green" => "petrol",
"Gray" => "gray"
),
"description" => __("Select bar background color.")
)
)
) );
// Testimonials Shortcode
vc_map( array(
"name" => __("Testimonials"),
"base" => "thb_testimonials",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "exploded_textarea",
"heading" => __("Testimonials"),
"param_name" => "values",
"admin_label" => true,
"description" => __('Enter testimonials here. Divide values with linebreaks (Enter). Example: Abraham Lincoln|Lorem ipsum ....', 'js_composer'),
"value" => "Abraham Lincoln|Lorem Ipsum is simply dummy text of the printing and typesetting industry,George Bush|Lorem Ipsum is simply dummy text of the printing and typesetting industry."
)
)
) );
// Team Member shortcode
vc_map( array(
"name" => __("Team Member"),
"base" => "thb_teammember",
"icon" => "<API key>",
"class" => "<API key>",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "attach_image", //attach_images
"class" => "",
"heading" => __("Select Team Member Image"),
"param_name" => "image",
"description" => __("Minimum size is 270x270 pixels")
),
array(
"type" => "textfield",
"heading" => __("Name"),
"param_name" => "name",
"admin_label" => true,
"description" => __("Enter name of the team member")
),
array(
"type" => "textfield",
"heading" => __("Position"),
"param_name" => "position",
"description" => __("Enter position/title of the team member")
),
array(
"type" => "textfield",
"heading" => __("Facebook"),
"param_name" => "facebook",
"description" => __("Enter Facebook Link")
),
array(
"type" => "textfield",
"heading" => __("Twitter"),
"param_name" => "twitter",
"description" => __("Enter Twitter Link")
),
array(
"type" => "textfield",
"heading" => __("Google Plus"),
"param_name" => "googleplus",
"description" => __("Enter Google Plus Link")
),
array(
"type" => "textfield",
"heading" => __("Linkedin"),
"param_name" => "linkedin",
"description" => __("Enter Linkedin Link")
)
)
) );
// Clients shortcode
vc_map( array(
"name" => __("Clients"),
"base" => "thb_clients",
"icon" => "thb_vc_ico_clients",
"class" => "thb_vc_sc_clients",
"category" => "by Fuel Themes",
"params" => array(
array(
"type" => "attach_images", //attach_images
"class" => "",
"heading" => __("Select Images"),
"param_name" => "images",
"description" => __("Add as many client images as possible.")
)
)
) );
function <API key>($width) {
switch ( $width ) {
case "1/6" :
$w = "medium-2";
break;
case "1/4" :
$w = "medium-3";
break;
case "1/3" :
$w = "medium-4";
break;
case "2/4" :
$w = "medium-6";
case "1/2" :
$w = "medium-6";
break;
case "4/6" :
$w = "medium-8";
break;
case "2/3" :
$w = "medium-8";
break;
case "3/4" :
$w = "medium-9";
break;
case "10/12" :
$w = "medium-10";
break;
case "5/6" :
$w = "medium-10";
break;
case "1/1" :
$w = "medium-12";
break;
case "1/12" :
$w = "medium-1";
break;
case "2/12" :
$w = "medium-2";
break;
case "5/12" :
$w = "medium-5";
break;
case "7/12" :
$w = "medium-7";
break;
default :
$w = $width;
}
return $w;
}
/* Offsets */
function <API key>($column_offset, $width) {
/* Remove VC */
$column_offset = preg_replace('/vc_col-/', '', $column_offset);
/* Change responsive columns */
$column_offset = preg_replace('/lg/', 'large', $column_offset);
$column_offset = preg_replace('/md/', 'medium', $column_offset);
$column_offset = preg_replace('/sm/', 'small', $column_offset);
$column_offset = preg_replace('/xs/', 'small', $column_offset);
/* Check If no Small setting */
if (!preg_match('/vc_col\-(sm|xs)[^\s]*/', $column_offset)) {
$column_offset = 'small-12 '. $column_offset;
}
/* Change visibility */
$column_offset = preg_replace('/vc_hidden-large/', 'hide-for-large-up', $column_offset);
$column_offset = preg_replace('/vc_hidden-medium/', '<API key>', $column_offset);
$column_offset = preg_replace('/vc_hidden-smallall/', 'hide-for-small-only', $column_offset);
return $width.(empty($column_offset) ? '' : ' '.$column_offset);
}
} |
/* See Documentation/block/row-iosched.txt */
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/blkdev.h>
#include <linux/elevator.h>
#include <linux/bio.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/compiler.h>
#include <linux/blktrace_api.h>
#include <linux/jiffies.h>
/*
* enum row_queue_prio - Priorities of the ROW queues
*
* This enum defines the priorities (and the number of queues)
* the requests will be disptributed to. The higher priority -
* the bigger is the dispatch quantum given to that queue.
* ROWQ_PRIO_HIGH_READ - is the higher priority queue.
*
*/
enum row_queue_prio {
ROWQ_PRIO_HIGH_READ = 0,
ROWQ_PRIO_REG_READ,
<API key>,
<API key>,
ROWQ_PRIO_REG_WRITE,
ROWQ_PRIO_LOW_READ,
<API key>,
ROWQ_MAX_PRIO,
};
/* Flags indicating whether idling is enabled on the queue */
static const bool <API key>[] = {
true, /* ROWQ_PRIO_HIGH_READ */
true, /* ROWQ_PRIO_REG_READ */
false, /* <API key> */
false, /* <API key> */
false, /* ROWQ_PRIO_REG_WRITE */
false, /* ROWQ_PRIO_LOW_READ */
false, /* <API key> */
};
/* Flags indicating whether the queue can notify on urgent requests */
static const bool urgent_queues[] = {
true, /* ROWQ_PRIO_HIGH_READ */
true, /* ROWQ_PRIO_REG_READ */
false, /* <API key> */
false, /* <API key> */
false, /* ROWQ_PRIO_REG_WRITE */
false, /* ROWQ_PRIO_LOW_READ */
false, /* <API key> */
};
/* Default values for row queues quantums in each dispatch cycle */
static const int queue_quantum[] = {
100, /* ROWQ_PRIO_HIGH_READ */
100, /* ROWQ_PRIO_REG_READ */
2, /* <API key> */
1, /* <API key> */
1, /* ROWQ_PRIO_REG_WRITE */
1, /* ROWQ_PRIO_LOW_READ */
1 /* <API key> */
};
/* Default values for idling on read queues */
#define ROW_IDLE_TIME_MSEC 5 /* msec */
#define ROW_READ_FREQ_MSEC 20 /* msec */
/**
* struct rowq_idling_data - parameters for idling on the queue
* @last_insert_time: time the last request was inserted
* to the queue
* @begin_idling: flag indicating wether we should idle
*
*/
struct rowq_idling_data {
ktime_t last_insert_time;
bool begin_idling;
};
/**
* struct row_queue - requests grouping structure
* @rdata: parent row_data structure
* @fifo: fifo of requests
* @prio: queue priority (enum row_queue_prio)
* @nr_dispatched: number of requests already dispatched in
* the current dispatch cycle
* @slice: number of requests to dispatch in a cycle
* @idle_data: data for idling on queues
*
*/
struct row_queue {
struct row_data *rdata;
struct list_head fifo;
enum row_queue_prio prio;
unsigned int nr_dispatched;
unsigned int slice;
/* used only for READ queues */
struct rowq_idling_data idle_data;
};
/**
* struct idling_data - data for idling on empty rqueue
* @idle_time: idling duration (jiffies)
* @freq: min time between two requests that
* triger idling (msec)
* @idle_work: pointer to struct delayed_work
*
*/
struct idling_data {
unsigned long idle_time;
u32 freq;
struct workqueue_struct *idle_workqueue;
struct delayed_work idle_work;
};
/**
* struct row_queue - Per block device rqueue structure
* @dispatch_queue: dispatch rqueue
* @row_queues: array of priority request queues with
* dispatch quantum per rqueue
* @curr_queue: index in the row_queues array of the
* currently serviced rqueue
* @read_idle: data for idling after READ request
* @nr_reqs: nr_reqs[0] holds the number of all READ requests in
* scheduler, nr_reqs[1] holds the number of all WRITE
* requests in scheduler
* @cycle_flags: used for marking unserved queueus
*
*/
struct row_data {
struct request_queue *dispatch_queue;
struct {
struct row_queue rqueue;
int disp_quantum;
} row_queues[ROWQ_MAX_PRIO];
enum row_queue_prio curr_queue;
struct idling_data read_idle;
unsigned int nr_reqs[2];
unsigned int cycle_flags;
};
#define RQ_ROWQ(rq) ((struct row_queue *) ((rq)->elv.priv[0]))
#define row_log(q, fmt, args...) \
blk_add_trace_msg(q, "%s():" fmt , __func__, ##args)
#define row_log_rowq(rdata, rowq_id, fmt, args...) \
blk_add_trace_msg(rdata->dispatch_queue, "rowq%d " fmt, \
rowq_id, ##args)
static inline void <API key>(struct row_data *rd,
enum row_queue_prio qnum)
{
rd->cycle_flags |= (1 << qnum);
}
static inline void <API key>(struct row_data *rd,
enum row_queue_prio qnum)
{
rd->cycle_flags &= ~(1 << qnum);
}
static inline int row_rowq_unserved(struct row_data *rd,
enum row_queue_prio qnum)
{
return rd->cycle_flags & (1 << qnum);
}
/*
* kick_queue() - Wake up device driver queue thread
* @work: pointer to struct work_struct
*
* This is a idling delayed work function. It's purpose is to wake up the
* device driver in order for it to start fetching requests.
*
*/
static void kick_queue(struct work_struct *work)
{
struct delayed_work *idle_work = to_delayed_work(work);
struct idling_data *read_data =
container_of(idle_work, struct idling_data, idle_work);
struct row_data *rd =
container_of(read_data, struct row_data, read_idle);
row_log_rowq(rd, rd->curr_queue, "Performing delayed work");
/* Mark idling process as done */
rd->row_queues[rd->curr_queue].rqueue.idle_data.begin_idling = false;
if (!(rd->nr_reqs[0] + rd->nr_reqs[1]))
row_log(rd->dispatch_queue, "No requests in scheduler");
else {
spin_lock_irq(rd->dispatch_queue->queue_lock);
__blk_run_queue(rd->dispatch_queue);
spin_unlock_irq(rd->dispatch_queue->queue_lock);
}
}
/*
* <API key>() - Restart the dispatch cycle
* @rd: pointer to struct row_data
*
* This function restarts the dispatch cycle by:
* - Setting current queue to ROWQ_PRIO_HIGH_READ
* - For each queue: reset the number of requests dispatched in
* the cycle
*/
static inline void <API key>(struct row_data *rd)
{
int i;
for (i = 0; i < ROWQ_MAX_PRIO; i++)
rd->row_queues[i].rqueue.nr_dispatched = 0;
rd->curr_queue = ROWQ_PRIO_HIGH_READ;
row_log(rd->dispatch_queue, "Restarting cycle");
}
static inline void row_get_next_queue(struct row_data *rd)
{
rd->curr_queue++;
if (rd->curr_queue == ROWQ_MAX_PRIO)
<API key>(rd);
}
/*
* row_add_request() - Add request to the scheduler
* @q: requests queue
* @rq: request to add
*
*/
static void row_add_request(struct request_queue *q,
struct request *rq)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
struct row_queue *rqueue = RQ_ROWQ(rq);
list_add_tail(&rq->queuelist, &rqueue->fifo);
rd->nr_reqs[rq_data_dir(rq)]++;
rq_set_fifo_time(rq, jiffies); /* for statistics*/
if (<API key>[rqueue->prio]) {
if (<API key>(&rd->read_idle.idle_work))
(void)cancel_delayed_work(
&rd->read_idle.idle_work);
if (ktime_to_ms(ktime_sub(ktime_get(),
rqueue->idle_data.last_insert_time)) <
rd->read_idle.freq) {
rqueue->idle_data.begin_idling = true;
row_log_rowq(rd, rqueue->prio, "Enable idling");
} else {
rqueue->idle_data.begin_idling = false;
row_log_rowq(rd, rqueue->prio, "Disable idling");
}
rqueue->idle_data.last_insert_time = ktime_get();
}
if (urgent_queues[rqueue->prio] &&
row_rowq_unserved(rd, rqueue->prio)) {
row_log_rowq(rd, rqueue->prio,
"added urgent req curr_queue = %d",
rd->curr_queue);
} else
row_log_rowq(rd, rqueue->prio, "added request");
}
/**
* row_reinsert_req() - Reinsert request back to the scheduler
* @q: requests queue
* @rq: request to add
*
* Reinsert the given request back to the queue it was
* dispatched from as if it was never dispatched.
*
* Returns 0 on success, error code otherwise
*/
/*static int row_reinsert_req(struct request_queue *q,
struct request *rq)
{
struct row_data *rd = q->elevator->elevator_data;
struct row_queue *rqueue = RQ_ROWQ(rq);
if (rqueue->prio >= ROWQ_MAX_PRIO) {
pr_err("\n\nROW BUG: row_reinsert_req() rqueue->prio = %d\n",
rqueue->prio);
blk_dump_rq_flags(rq, "");
return -EIO;
}
list_add(&rq->queuelist, &rqueue->fifo);
rd->nr_reqs[rq_data_dir(rq)]++;
row_log_rowq(rd, rqueue->prio, "request reinserted");
return 0;
}*/
/**
* row_urgent_pending() - Return TRUE if there is an urgent
* request on scheduler
* @q: requests queue
*/
/*static bool row_urgent_pending(struct request_queue *q)
{
struct row_data *rd = q->elevator->elevator_data;
int i;
for (i = 0; i < ROWQ_MAX_PRIO; i++)
if (urgent_queues[i] && row_rowq_unserved(rd, i) &&
!list_empty(&rd->row_queues[i].rqueue.fifo)) {
row_log_rowq(rd, i,
"Urgent request pending (curr=%i)",
rd->curr_queue);
return true;
}
return false;
}*/
/**
* row_remove_request() - Remove given request from scheduler
* @q: requests queue
* @rq: request to remove
*
*/
static void row_remove_request(struct request_queue *q,
struct request *rq)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
rq_fifo_clear(rq);
rd->nr_reqs[rq_data_dir(rq)]
}
/*
* row_dispatch_insert() - move request to dispatch queue
* @rd: pointer to struct row_data
*
* This function moves the next request to dispatch from
* rd->curr_queue to the dispatch queue
*
*/
static void row_dispatch_insert(struct row_data *rd)
{
struct request *rq;
rq = rq_entry_fifo(rd->row_queues[rd->curr_queue].rqueue.fifo.next);
row_remove_request(rd->dispatch_queue, rq);
<API key>(rd->dispatch_queue, rq);
rd->row_queues[rd->curr_queue].rqueue.nr_dispatched++;
<API key>(rd, rd->curr_queue);
row_log_rowq(rd, rd->curr_queue, " Dispatched request nr_disp = %d",
rd->row_queues[rd->curr_queue].rqueue.nr_dispatched);
}
/*
* row_choose_queue() - choose the next queue to dispatch from
* @rd: pointer to struct row_data
*
* Updates rd->curr_queue. Returns 1 if there are requests to
* dispatch, 0 if there are no requests in scheduler
*
*/
static int row_choose_queue(struct row_data *rd)
{
int prev_curr_queue = rd->curr_queue;
if (!(rd->nr_reqs[0] + rd->nr_reqs[1])) {
row_log(rd->dispatch_queue, "No more requests in scheduler");
return 0;
}
row_get_next_queue(rd);
/*
* Loop over all queues to find the next queue that is not empty.
* Stop when you get back to curr_queue
*/
while (list_empty(&rd->row_queues[rd->curr_queue].rqueue.fifo)
&& rd->curr_queue != prev_curr_queue) {
/* Mark rqueue as unserved */
<API key>(rd, rd->curr_queue);
row_get_next_queue(rd);
}
return 1;
}
/*
* <API key>() - selects the next request to dispatch
* @q: requests queue
* @force: ignored
*
* Return 0 if no requests were moved to the dispatch queue.
* 1 otherwise
*
*/
static int <API key>(struct request_queue *q, int force)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
int ret = 0, currq, i;
currq = rd->curr_queue;
/*
* Find the first unserved queue (with higher priority then currq)
* that is not empty
*/
for (i = 0; i < currq; i++) {
if (row_rowq_unserved(rd, i) &&
!list_empty(&rd->row_queues[i].rqueue.fifo)) {
row_log_rowq(rd, currq,
" Preemting for unserved rowq%d", i);
rd->curr_queue = i;
row_dispatch_insert(rd);
ret = 1;
goto done;
}
}
if (rd->row_queues[currq].rqueue.nr_dispatched >=
rd->row_queues[currq].disp_quantum) {
rd->row_queues[currq].rqueue.nr_dispatched = 0;
row_log_rowq(rd, currq, "Expiring rqueue");
ret = row_choose_queue(rd);
if (ret)
row_dispatch_insert(rd);
goto done;
}
/* Dispatch from curr_queue */
if (list_empty(&rd->row_queues[currq].rqueue.fifo)) {
/* check idling */
if (<API key>(&rd->read_idle.idle_work)) {
if (force) {
(void)cancel_delayed_work(
&rd->read_idle.idle_work);
row_log_rowq(rd, currq,
"Canceled delayed work - forced dispatch");
} else {
row_log_rowq(rd, currq,
"Delayed work pending. Exiting");
goto done;
}
}
if (!force && <API key>[currq] &&
rd->row_queues[currq].rqueue.idle_data.begin_idling) {
if (!queue_delayed_work(rd->read_idle.idle_workqueue,
&rd->read_idle.idle_work,
rd->read_idle.idle_time)) {
row_log_rowq(rd, currq,
"Work already on queue!");
pr_err("ROW_BUG: Work already on queue!");
} else
row_log_rowq(rd, currq,
"Scheduled delayed work. exiting");
goto done;
} else {
row_log_rowq(rd, currq,
"Currq empty. Choose next queue");
ret = row_choose_queue(rd);
if (!ret)
goto done;
}
}
ret = 1;
row_dispatch_insert(rd);
done:
return ret;
}
/*
* row_init_queue() - Init scheduler data structures
* @q: requests queue
*
* Return pointer to struct row_data to be saved in elevator for
* this dispatch queue
*
*/
static void *row_init_queue(struct request_queue *q)
{
struct row_data *rdata;
int i;
rdata = kmalloc_node(sizeof(*rdata),
GFP_KERNEL | __GFP_ZERO, q->node);
if (!rdata)
return NULL;
for (i = 0; i < ROWQ_MAX_PRIO; i++) {
INIT_LIST_HEAD(&rdata->row_queues[i].rqueue.fifo);
rdata->row_queues[i].disp_quantum = queue_quantum[i];
rdata->row_queues[i].rqueue.rdata = rdata;
rdata->row_queues[i].rqueue.prio = i;
rdata->row_queues[i].rqueue.idle_data.begin_idling = false;
rdata->row_queues[i].rqueue.idle_data.last_insert_time =
ktime_set(0, 0);
}
/*
* Currently idling is enabled only for READ queues. If we want to
* enable it for write queues also, note that idling frequency will
* be the same in both cases
*/
rdata->read_idle.idle_time = msecs_to_jiffies(ROW_IDLE_TIME_MSEC);
/* Maybe 0 on some platforms */
if (!rdata->read_idle.idle_time)
rdata->read_idle.idle_time = 1;
rdata->read_idle.freq = ROW_READ_FREQ_MSEC;
rdata->read_idle.idle_workqueue = alloc_workqueue("row_idle_work",
WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
if (!rdata->read_idle.idle_workqueue)
panic("Failed to create idle workqueue\n");
INIT_DELAYED_WORK(&rdata->read_idle.idle_work, kick_queue);
rdata->curr_queue = ROWQ_PRIO_HIGH_READ;
rdata->dispatch_queue = q;
rdata->nr_reqs[READ] = rdata->nr_reqs[WRITE] = 0;
return rdata;
}
/*
* row_exit_queue() - called on unloading the RAW scheduler
* @e: poiner to struct elevator_queue
*
*/
static void row_exit_queue(struct elevator_queue *e)
{
struct row_data *rd = (struct row_data *)e->elevator_data;
int i;
for (i = 0; i < ROWQ_MAX_PRIO; i++)
BUG_ON(!list_empty(&rd->row_queues[i].rqueue.fifo));
(void)<API key>(&rd->read_idle.idle_work);
BUG_ON(<API key>(&rd->read_idle.idle_work));
destroy_workqueue(rd->read_idle.idle_workqueue);
kfree(rd);
}
/*
* row_merged_requests() - Called when 2 requests are merged
* @q: requests queue
* @rq: request the two requests were merged into
* @next: request that was merged
*/
static void row_merged_requests(struct request_queue *q, struct request *rq,
struct request *next)
{
struct row_queue *rqueue = RQ_ROWQ(next);
list_del_init(&next->queuelist);
rqueue->rdata->nr_reqs[rq_data_dir(rq)]
}
/*
* get_queue_type() - Get queue type for a given request
*
* This is a helping function which purpose is to determine what
* ROW queue the given request should be added to (and
* dispatched from leter on)
*
* TODO: Right now only 3 queues are used REG_READ, REG_WRITE
* and REG_SWRITE
*/
static enum row_queue_prio get_queue_type(struct request *rq)
{
const int data_dir = rq_data_dir(rq);
const bool is_sync = rq_is_sync(rq);
if (data_dir == READ)
return ROWQ_PRIO_REG_READ;
else if (is_sync)
return <API key>;
else
return ROWQ_PRIO_REG_WRITE;
}
/*
* row_set_request() - Set ROW data structures associated with this request.
* @q: requests queue
* @rq: pointer to the request
* @gfp_mask: ignored
*
*/
static int
row_set_request(struct request_queue *q, struct request *rq, gfp_t gfp_mask)
{
struct row_data *rd = (struct row_data *)q->elevator->elevator_data;
unsigned long flags;
spin_lock_irqsave(q->queue_lock, flags);
rq->elv.priv[0] =
(void *)(&rd->row_queues[get_queue_type(rq)]);
<API key>(q->queue_lock, flags);
return 0;
}
static ssize_t row_var_show(int var, char *page)
{
return snprintf(page, 100, "%d\n", var);
}
static ssize_t row_var_store(int *var, const char *page, size_t count)
{
int err;
err = kstrtoul(page, 10, (unsigned long *)var);
return count;
}
#define SHOW_FUNCTION(__FUNC, __VAR, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, char *page) \
{ \
struct row_data *rowd = e->elevator_data; \
int __data = __VAR; \
if (__CONV) \
__data = jiffies_to_msecs(__data); \
return row_var_show(__data, (page)); \
}
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_HIGH_READ].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_REG_READ].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_REG_WRITE].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[ROWQ_PRIO_LOW_READ].disp_quantum, 0);
SHOW_FUNCTION(<API key>,
rowd->row_queues[<API key>].disp_quantum, 0);
SHOW_FUNCTION(row_read_idle_show, rowd->read_idle.idle_time, 1);
SHOW_FUNCTION(<API key>, rowd->read_idle.freq, 0);
#undef SHOW_FUNCTION
#define STORE_FUNCTION(__FUNC, __PTR, MIN, MAX, __CONV) \
static ssize_t __FUNC(struct elevator_queue *e, \
const char *page, size_t count) \
{ \
struct row_data *rowd = e->elevator_data; \
int __data; \
int ret = row_var_store(&__data, (page), count); \
if (__CONV) \
__data = (int)msecs_to_jiffies(__data); \
if (__data < (MIN)) \
__data = (MIN); \
else if (__data > (MAX)) \
__data = (MAX); \
*(__PTR) = __data; \
return ret; \
}
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_HIGH_READ].disp_quantum, 1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_REG_READ].disp_quantum,
1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_REG_WRITE].disp_quantum,
1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[ROWQ_PRIO_LOW_READ].disp_quantum,
1, INT_MAX, 0);
STORE_FUNCTION(<API key>,
&rowd->row_queues[<API key>].disp_quantum,
1, INT_MAX, 1);
STORE_FUNCTION(row_read_idle_store, &rowd->read_idle.idle_time, 1, INT_MAX, 1);
STORE_FUNCTION(<API key>, &rowd->read_idle.freq, 1, INT_MAX, 0);
#undef STORE_FUNCTION
#define ROW_ATTR(name) \
__ATTR(name, S_IRUGO|S_IWUSR, row_##name##_show, \
row_##name##_store)
static struct elv_fs_entry row_attrs[] = {
ROW_ATTR(hp_read_quantum),
ROW_ATTR(rp_read_quantum),
ROW_ATTR(hp_swrite_quantum),
ROW_ATTR(rp_swrite_quantum),
ROW_ATTR(rp_write_quantum),
ROW_ATTR(lp_read_quantum),
ROW_ATTR(lp_swrite_quantum),
ROW_ATTR(read_idle),
ROW_ATTR(read_idle_freq),
__ATTR_NULL
};
static struct elevator_type iosched_row = {
.ops = {
.<API key> = row_merged_requests,
.<API key> = <API key>,
.elevator_add_req_fn = row_add_request,
.<API key> = <API key>,
.<API key> = <API key>,
.elevator_set_req_fn = row_set_request,
.elevator_init_fn = row_init_queue,
.elevator_exit_fn = row_exit_queue,
},
.elevator_attrs = row_attrs,
.elevator_name = "row",
.elevator_owner = THIS_MODULE,
};
static int __init row_init(void)
{
elv_register(&iosched_row);
return 0;
}
static void __exit row_exit(void)
{
elv_unregister(&iosched_row);
}
module_init(row_init);
module_exit(row_exit);
MODULE_LICENSE("GPLv2");
MODULE_DESCRIPTION("Read Over Write IO scheduler"); |
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class Hand : MonoBehaviour {
private List<Card> cards = new List<Card>();
[SerializeField]
private Board board;
[SerializeField]
private GameObject cardPrefab;
[SerializeField]
private GridLayoutGroup gridLayout;
[SerializeField]
private Transform selectedCardPanel;
public Card selectedCard;
private bool draggingCard = false;
private int lastTouchCount = 0;
private bool <API key> = false;
void Start () {
}
void Update () {
if(selectedCard != null)
{
if(!draggingCard && selectedCard.pressed)
{
selectedCard.transform.GetComponent<RectTransform>().sizeDelta = selectedCard.transform.GetComponent<RectTransform>().sizeDelta/3f;
draggingCard = true;
}
if(draggingCard)
{
selectedCard.transform.position = Input.mousePosition;
}
if(<API key> == true && !selectedCard.pressed)
{
for(int i=0; i < board.playerCardSlots.Length; i++)
{
if(Vector3.Distance(selectedCard.transform.position, board.playerCardSlots[i].transform.position) < 45f)
{
if(!board.playerCardSlots[i].occupied)
{
selectedCard.transform.SetParent(board.playerCardSlots[i].transform);
selectedCard.transform.localPosition = Vector3.zero;
selectedCard.placed = true;
board.playerCardSlots[i].occupied = true;
break;
}
}
}
draggingCard = false;
if(!selectedCard.placed)
{
selectedCard.transform.SetParent(transform);
selectedCard.transform.SetSiblingIndex(selectedCard.<API key>);
}
selectedCard.selected = false;
selectedCard = null;
<API key> = false;
}
if(selectedCard != null)
{
<API key> = selectedCard.pressed;
}
}
}
public void AddCard(Card card)
{
card.selectedCardPanel = selectedCardPanel;
card.transform.SetSiblingIndex(cards.Count);
card.hand = this;
cards.Add(card);
if(cards.Count > 1)
gridLayout.spacing = new Vector2((1080 - gridLayout.padding.left - gridLayout.padding.right - cards.Count*gridLayout.cellSize.x)/(cards.Count-1), gridLayout.spacing.y);
}
} |
/* if both both DEBUG and DEBUG_TRACE are defined, trace_printk() is used */
#define DEBUG
//#define DEBUG_TRACE
#include <linux/device.h>
#include <linux/gpio/consumer.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/phy/phy.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/<API key>.h>
#include <linux/v4l2-dv-timings.h>
#include <linux/firmware.h>
#include <linux/clk.h>
#include <media/v4l2-async.h>
#include <media/v4l2-ctrls.h>
#include <media/v4l2-event.h>
#include <media/v4l2-subdev.h>
#include <media/v4l2-dv-timings.h>
#include "linux/phy/phy-vphy.h"
#include "xilinx-vip.h"
/* baseline driver includes */
#include "xilinx-hdmi-rx/xv_hdmirxss.h"
/* for the HMAC, using password to decrypt HDCP keys */
#include "phy-xilinx-vphy/xhdcp22_common.h"
#include "phy-xilinx-vphy/aes256.h"
//#include "../hdcp_private_keys.h" //RC: TO BE DELETED
/* select either trace or printk logging */
#ifdef DEBUG_TRACE
#define do_hdmi_dbg(format, ...) do { \
trace_printk("xlnx-hdmi-rxss: " format, ##__VA_ARGS__); \
} while(0)
#else
#define do_hdmi_dbg(format, ...) do { \
printk(KERN_DEBUG "xlnx-hdmi-rxss: " format, ##__VA_ARGS__); \
} while(0)
#endif
/* Use hdmi_dbg to debug control flow.
* Use dev_err() to report errors to user.
* either enable or disable debugging. */
#ifdef DEBUG
# define hdmi_dbg(x...) do_hdmi_dbg(x)
#else
# define hdmi_dbg(x...)
#endif
#define hdmi_mutex_lock(x) mutex_lock(x)
#define hdmi_mutex_unlock(x) mutex_unlock(x)
#define HDMI_MAX_LANES 4
#define EDID_BLOCKS_MAX 10
#define EDID_BLOCK_SIZE 128
/* RX Subsystem Sub-core offsets */
#define RXSS_RX_OFFSET 0x90000u
#define RXSS_HDCP14_OFFSET 0x80000u
#define <API key> 0x00000u
#define RXSS_HDCP22_OFFSET 0x40000u
/* HDCP22 sub-core offsets */
#define <API key> 0x00000u
#define <API key> 0x10000u
#define <API key> 0x20000u
#define <API key> 0x30000u
struct xhdmi_device {
struct device xvip;
struct device *dev;
void __iomem *iomem;
void __iomem *<API key>;
/* clocks */
struct clk *clk;
struct clk *axi_lite_clk;
/* HDMI RXSS interrupt number */
int irq;
/* HDCP interrupt numbers */
int hdcp1x_irq;
int hdcp1x_timer_irq;
int hdcp22_irq;
int hdcp22_timer_irq;
/* status */
bool hdcp_authenticated;
bool hdcp_encrypted;
bool <API key>;
/* delayed work to drive HDCP poll */
struct delayed_work <API key>;
#ifdef DEBUG
struct delayed_work <API key>;
int hdcp_info_counter;
#endif
bool teardown;
struct phy *phy[HDMI_MAX_LANES];
/* mutex to prevent concurrent access to this structure */
struct mutex xhdmi_mutex;
/* protects concurrent access from interrupt context */
spinlock_t irq_lock;
/* schedule (future) work */
struct workqueue_struct *work_queue;
struct delayed_work <API key>;
struct v4l2_subdev subdev;
/* V4L media output pad to construct the video pipeline */
struct media_pad pad;
struct v4l2_mbus_framefmt detected_format;
struct v4l2_dv_timings detected_timings;
const struct xvip_video_format *vip_format;
struct v4l2_ctrl_handler ctrl_handler;
bool cable_is_connected;
bool hdmi_stream_is_up;
/* copy of user specified EDID block, if any */
u8 edid_user[EDID_BLOCKS_MAX * EDID_BLOCK_SIZE];
/* number of actual blocks valid in edid_user */
int edid_user_blocks;
/* number of EDID blocks supported by IP */
int edid_blocks_max;
/* configuration for the baseline subsystem driver instance */
XV_HdmiRxSs_Config config;
/* bookkeeping for the baseline subsystem driver instance */
XV_HdmiRxSs xv_hdmirxss;
/* sub core interrupt status registers */
u32 IntrStatus[7];
/* pointer to xvphy */
XVphy *xvphy;
/* HDCP keys */
u8 hdcp_password[32];
u8 Hdcp22Lc128[16];
u8 Hdcp22PrivateKey[902];
u8 Hdcp14KeyA[328];
u8 Hdcp14KeyB[328];
};
// Xilinx EDID
static const u8 xilinx_edid[] = {
0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x61, 0x98, 0x34, 0x12, 0x78, 0x56, 0x34, 0x12,
0x1F, 0x19, 0x01, 0x03, 0x80, 0x59, 0x32, 0x78, 0x0A, 0xEE, 0x91, 0xA3, 0x54, 0x4C, 0x99, 0x26,
0x0F, 0x50, 0x54, 0x21, 0x08, 0x00, 0x71, 0x4F, 0x81, 0xC0, 0x81, 0x00, 0x81, 0x80, 0x95, 0x00,
0xA9, 0xC0, 0xB3, 0x00, 0x01, 0x01, 0x02, 0x3A, 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40, 0x58, 0x2C,
0x45, 0x00, 0x20, 0xC2, 0x31, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0xFC, 0x00, 0x58, 0x49, 0x4C,
0x49, 0x4E, 0x58, 0x20, 0x48, 0x44, 0x4D, 0x49, 0x0A, 0x20, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x0C,
0x02, 0x03, 0x34, 0x71, 0x57, 0x61, 0x10, 0x1F, 0x04, 0x13, 0x05, 0x14, 0x20, 0x21, 0x22, 0x5D,
0x5E, 0x5F, 0x60, 0x65, 0x66, 0x62, 0x63, 0x64, 0x07, 0x16, 0x03, 0x12, 0x23, 0x09, 0x07, 0x07,
0x67, 0x03, 0x0C, 0x00, 0x10, 0x00, 0x78, 0x3C, 0xE3, 0x0F, 0x01, 0xE0, 0x67, 0xD8, 0x5D, 0xC4,
0x01, 0x78, 0x80, 0x07, 0x02, 0x3A, 0x80, 0x18, 0x71, 0x38, 0x2D, 0x40, 0x58, 0x2C, 0x45, 0x00,
0x20, 0xC2, 0x31, 0x00, 0x00, 0x1E, 0x08, 0xE8, 0x00, 0x30, 0xF2, 0x70, 0x5A, 0x80, 0xB0, 0x58,
0x8A, 0x00, 0x20, 0xC2, 0x31, 0x00, 0x00, 0x1E, 0x04, 0x74, 0x00, 0x30, 0xF2, 0x70, 0x5A, 0x80,
0xB0, 0x58, 0x8A, 0x00, 0x20, 0x52, 0x31, 0x00, 0x00, 0x1E, 0x66, 0x21, 0x56, 0xAA, 0x51, 0x00,
0x1E, 0x30, 0x46, 0x8F, 0x33, 0x00, 0x50, 0x1D, 0x74, 0x00, 0x00, 0x1E, 0x00, 0x00, 0x00, 0x2E
};
static inline struct xhdmi_device *to_xhdmi(struct v4l2_subdev *subdev)
{
return container_of(subdev, struct xhdmi_device, subdev);
}
static const struct v4l2_event xhdmi_ev_fmt = {
.type = <API key>,
.u.src_change.changes = <API key>,
};
static int <API key>(struct v4l2_subdev *sd, struct v4l2_fh *fh, struct <API key> *sub)
{
switch (sub->type) {
case <API key>:
{
int rc;
rc = <API key>(sd, fh, sub);
printk(KERN_INFO "<API key>(<API key>) = %d\n", rc);
return rc;
}
#if 0
case V4L2_EVENT_CTRL:
return <API key>(sd, fh, sub);
#endif
default:
{
printk(KERN_INFO "<API key>() default: -EINVAL\n");
return -EINVAL;
}
}
}
static int xhdmi_s_stream(struct v4l2_subdev *subdev, int enable)
{
/* HDMI does not need to be enabled when we start streaming */
printk(KERN_INFO "xhdmi_s_stream enable = %d\n", enable);
return 0;
}
static struct v4l2_mbus_framefmt *
<API key>(struct xhdmi_device *xhdmi,
struct <API key> *cfg,
unsigned int pad, u32 which)
{
switch (which) {
case <API key>:
hdmi_dbg("<API key>(): <API key>\n");
return <API key>(&xhdmi->subdev, cfg, pad);
case <API key>:
hdmi_dbg("<API key>(): <API key>\n");
hdmi_dbg("detected_format->width = %u\n", xhdmi->detected_format.width);
return &xhdmi->detected_format;
default:
return NULL;
}
}
static int xhdmi_get_format(struct v4l2_subdev *subdev,
struct <API key> *cfg,
struct v4l2_subdev_format *fmt)
{
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
hdmi_dbg("xhdmi_get_format\n");
if (fmt->pad > 0)
return -EINVAL;
/* copy either try or currently-active (i.e. detected) format to caller */
fmt->format = *<API key>(xhdmi, cfg, fmt->pad, fmt->which);
hdmi_dbg("xhdmi_get_format, height = %u\n", fmt->format.height);
return 0;
}
/* we must modify the requested format to match what the hardware can provide */
static int xhdmi_set_format(struct v4l2_subdev *subdev,
struct <API key> *cfg,
struct v4l2_subdev_format *fmt)
{
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
hdmi_dbg("xhdmi_set_format\n");
if (fmt->pad > 0)
return -EINVAL;
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
/* there is nothing we can take from the format requested by the caller,
* by convention we must return the active (i.e. detected) format */
fmt->format = xhdmi->detected_format;
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return 0;
}
static int xhdmi_get_edid(struct v4l2_subdev *subdev, struct v4l2_edid *edid) {
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
int do_copy = 1;
if (edid->pad > 0)
return -EINVAL;
if (edid->start_block != 0)
return -EINVAL;
/* caller is only interested in the size of the EDID? */
if ((edid->start_block == 0) && (edid->blocks == 0)) do_copy = 0;
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
/* user EDID active? */
if (xhdmi->edid_user_blocks) {
if (do_copy)
memcpy(edid->edid, xhdmi->edid_user, 128 * xhdmi->edid_user_blocks);
edid->blocks = xhdmi->edid_user_blocks;
} else {
if (do_copy)
memcpy(edid->edid, &xilinx_edid[0], sizeof(xilinx_edid));
edid->blocks = sizeof(xilinx_edid) / 128;
}
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return 0;
}
static void xhdmi_set_hpd(struct xhdmi_device *xhdmi, int enable)
{
XV_HdmiRxSs *HdmiRxSsPtr;
BUG_ON(!xhdmi);
HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XV_HdmiRx_SetHpd(HdmiRxSsPtr->HdmiRxPtr, enable);
}
static void <API key>(struct work_struct *work)
{
struct delayed_work *dwork = to_delayed_work(work);
struct xhdmi_device *xhdmi = container_of(dwork, struct xhdmi_device,
<API key>);
XV_HdmiRxSs *HdmiRxSsPtr;
BUG_ON(!xhdmi);
HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XV_HdmiRx_SetHpd(HdmiRxSsPtr->HdmiRxPtr, 1);
}
static int xhdmi_set_edid(struct v4l2_subdev *subdev, struct v4l2_edid *edid) {
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
if (edid->pad > 0)
return -EINVAL;
if (edid->start_block != 0)
return -EINVAL;
if (edid->blocks > xhdmi->edid_blocks_max) {
/* notify caller of how many EDID blocks this driver supports */
edid->blocks = xhdmi->edid_blocks_max;
return -E2BIG;
}
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
xhdmi->edid_user_blocks = edid->blocks;
/* Disable hotplug and I2C access to EDID RAM from DDC port */
<API key>(&xhdmi-><API key>);
xhdmi_set_hpd(xhdmi, 0);
if (edid->blocks) {
memcpy(xhdmi->edid_user, edid->edid, 128 * edid->blocks);
<API key>(HdmiRxSsPtr, (u8 *)&xhdmi->edid_user, 128 * xhdmi->edid_user_blocks);
/* enable hotplug after 100 ms */
queue_delayed_work(xhdmi->work_queue,
&xhdmi-><API key>, HZ / 10);
}
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return 0;
}
static int <API key>(struct v4l2_subdev *subdev,
struct <API key> *cfg,
struct <API key> *fse)
{
if (fse->pad > 0)
return -EINVAL;
/* we support a non-discrete set, i.e. contiguous range of frame sizes,
* do not return a discrete set */
return 0;
}
static int <API key>(struct v4l2_subdev *subdev,
struct v4l2_dv_timings_cap *cap)
{
if (cap->pad != 0)
return -EINVAL;
cap->type = V4L2_DV_BT_656_1120;
cap->bt.max_width = 4096;
cap->bt.max_height = 2160;
cap->bt.min_pixelclock = 25000000;
cap->bt.max_pixelclock = 297000000;
cap->bt.standards = <API key> | V4L2_DV_BT_STD_DMT |
V4L2_DV_BT_STD_GTF | V4L2_DV_BT_STD_CVT;
cap->bt.capabilities = <API key> |
<API key> | <API key>;
return 0;
}
static int <API key>(struct v4l2_subdev *subdev,
struct v4l2_dv_timings *timings)
{
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
if (!timings)
return -EINVAL;
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
if (!xhdmi->hdmi_stream_is_up) {
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return -ENOLINK;
}
/* copy detected timings into destination */
*timings = xhdmi->detected_timings;
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return 0;
}
/* struct <API key>.open */
static int xhdmi_open(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh)
{
struct xhdmi_device *xhdmi = to_xhdmi(subdev);
(void)xhdmi;
hdmi_dbg("xhdmi_open\n");
return 0;
}
/* struct <API key>.close */
static int xhdmi_close(struct v4l2_subdev *subdev, struct v4l2_subdev_fh *fh)
{
hdmi_dbg("xhdmi_close\n");
return 0;
}
static int xhdmi_s_ctrl(struct v4l2_ctrl *ctrl)
{
hdmi_dbg("xhdmi_s_ctrl\n");
return 0;
}
static const struct v4l2_ctrl_ops xhdmi_ctrl_ops = {
.s_ctrl = xhdmi_s_ctrl,
};
static struct <API key> xhdmi_core_ops = {
.subscribe_event = <API key>,
.unsubscribe_event = <API key>,
};
static struct <API key> xhdmi_video_ops = {
.s_stream = xhdmi_s_stream,
.query_dv_timings = <API key>,
};
/* If the subdev driver intends to process video and integrate with the media framework,
* it must implement format related functionality using v4l2_subdev_pad_ops instead of
* <API key>. */
static struct v4l2_subdev_pad_ops xhdmi_pad_ops = {
.enum_mbus_code = xvip_enum_mbus_code,
.enum_frame_size = <API key>,
.get_fmt = xhdmi_get_format,
.set_fmt = xhdmi_set_format,
.get_edid = xhdmi_get_edid,
.set_edid = xhdmi_set_edid,
.dv_timings_cap = <API key>,
};
static struct v4l2_subdev_ops xhdmi_ops = {
.core = &xhdmi_core_ops,
.video = &xhdmi_video_ops,
.pad = &xhdmi_pad_ops,
};
static const struct <API key> xhdmi_internal_ops = {
.open = xhdmi_open,
.close = xhdmi_close,
};
static const struct <API key> xhdmi_media_ops = {
.link_validate = <API key>,
};
static int __maybe_unused xhdmi_pm_suspend(struct device *dev)
{
return 0;
}
static int __maybe_unused xhdmi_pm_resume(struct device *dev)
{
return 0;
}
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
void <API key>(XV_HdmiRx *InstancePtr);
static void <API key>(XV_HdmiRxSs *HdmiRxSsPtr)
{
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
}
static void <API key>(XV_HdmiRxSs *HdmiRxSsPtr)
{
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
<API key>(HdmiRxSsPtr->HdmiRxPtr);
}
static irqreturn_t hdmirx_irq_handler(int irq, void *dev_id)
{
struct xhdmi_device *xhdmi;
XV_HdmiRxSs *HdmiRxSsPtr;
unsigned long flags;
BUG_ON(!dev_id);
xhdmi = (struct xhdmi_device *)dev_id;
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr->HdmiRxPtr);
if (HdmiRxSsPtr->IsReady != <API key>) {
printk(KERN_INFO "hdmirx_irq_handler(): HDMI RX SS is not initialized?!\n");
}
/* read status registers */
xhdmi->IntrStatus[0] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[1] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[2] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[3] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[4] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[5] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
xhdmi->IntrStatus[6] = XV_HdmiRx_ReadReg(HdmiRxSsPtr->HdmiRxPtr->Config.BaseAddress, (<API key>)) & (<API key>);
spin_lock_irqsave(&xhdmi->irq_lock, flags);
/* mask interrupt request */
<API key>(HdmiRxSsPtr);
<API key>(&xhdmi->irq_lock, flags);
/* call bottom-half */
return IRQ_WAKE_THREAD;
}
static irqreturn_t hdmirx_irq_thread(int irq, void *dev_id)
{
struct xhdmi_device *xhdmi;
XV_HdmiRxSs *HdmiRxSsPtr;
unsigned long flags;
BUG_ON(!dev_id);
xhdmi = (struct xhdmi_device *)dev_id;
if (xhdmi->teardown) {
printk(KERN_INFO "irq_thread: teardown\n");
return IRQ_HANDLED;
}
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr->HdmiRxPtr);
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
/* call baremetal interrupt handler, this in turn will
* call the registed callbacks functions */
if (xhdmi->IntrStatus[0]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[1]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[2]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[3]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[4]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[5]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
if (xhdmi->IntrStatus[6]) <API key>(HdmiRxSsPtr->HdmiRxPtr);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
spin_lock_irqsave(&xhdmi->irq_lock, flags);
/* unmask interrupt request */
<API key>(HdmiRxSsPtr);
<API key>(&xhdmi->irq_lock, flags);
return IRQ_HANDLED;
}
/* top-half interrupt handler for HDMI RX HDCP */
static irqreturn_t <API key>(int irq, void *dev_id)
{
struct xhdmi_device *xhdmi;
XV_HdmiRxSs *HdmiRxSsPtr;
unsigned long flags;
BUG_ON(!dev_id);
xhdmi = (struct xhdmi_device *)dev_id;
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr->HdmiRxPtr);
spin_lock_irqsave(&xhdmi->irq_lock, flags);
/* mask/disable interrupt requests */
if (irq == xhdmi->hdcp1x_irq) {
XHdcp1x_WriteReg(HdmiRxSsPtr->Hdcp14Ptr->Config.BaseAddress,
<API key>, (u32)0xFFFFFFFFu);
} else if (irq == xhdmi->hdcp1x_timer_irq) {
XTmrCtr_DisableIntr(HdmiRxSsPtr->HdcpTimerPtr->BaseAddress, 0);
} else if (irq == xhdmi->hdcp22_timer_irq) {
XTmrCtr_DisableIntr(HdmiRxSsPtr->Hdcp22Ptr->TimerInst.BaseAddress, 0);
XTmrCtr_DisableIntr(HdmiRxSsPtr->Hdcp22Ptr->TimerInst.BaseAddress, 1);
}
<API key>(&xhdmi->irq_lock, flags);
/* call bottom-half */
return IRQ_WAKE_THREAD;
}
/* HDCP service routine, runs outside of interrupt context and can sleep and takes mutexes */
static irqreturn_t <API key>(int irq, void *dev_id)
{
struct xhdmi_device *xhdmi;
XV_HdmiRxSs *HdmiRxSsPtr;
unsigned long flags;
BUG_ON(!dev_id);
xhdmi = (struct xhdmi_device *)dev_id;
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr->HdmiRxPtr);
/* driver is being torn down, do not process further interrupts */
if (xhdmi->teardown) {
printk(KERN_INFO "irq_thread: teardown\n");
return IRQ_HANDLED;
}
/* invoke the bare-metal interrupt handler under mutex lock */
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
if (irq == xhdmi->hdcp1x_irq) {
<API key>(HdmiRxSsPtr);
} else if (irq == xhdmi->hdcp1x_timer_irq) {
<API key>(HdmiRxSsPtr);
} else if (irq == xhdmi->hdcp22_timer_irq) {
<API key>(HdmiRxSsPtr);
}
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
/* re-enable interrupt requests */
spin_lock_irqsave(&xhdmi->irq_lock, flags);
if (irq == xhdmi->hdcp1x_irq) {
XHdcp1x_WriteReg(HdmiRxSsPtr->Hdcp14Ptr->Config.BaseAddress,
<API key>, (u32)0xFFFFFFFDu);
} else if (irq == xhdmi->hdcp1x_timer_irq) {
XTmrCtr_EnableIntr(HdmiRxSsPtr->HdcpTimerPtr->BaseAddress, 0);
} else if (irq == xhdmi->hdcp22_timer_irq) {
XTmrCtr_EnableIntr(HdmiRxSsPtr->Hdcp22Ptr->TimerInst.BaseAddress, 0);
XTmrCtr_EnableIntr(HdmiRxSsPtr->Hdcp22Ptr->TimerInst.BaseAddress, 1);
}
<API key>(&xhdmi->irq_lock, flags);
return IRQ_HANDLED;
}
/* callbacks from HDMI RX SS interrupt handler
* these are called with the xhdmi->mutex locked and the xvphy_mutex non-locked
* to prevent mutex deadlock, always lock the xhdmi first, then the xvphy mutex */
static void RxConnectCallback(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XVphy *VphyPtr = xhdmi->xvphy;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (!xhdmi || !HdmiRxSsPtr || !VphyPtr) return;
xhdmi->cable_is_connected = !!HdmiRxSsPtr->IsStreamConnected;
hdmi_dbg("RxConnectCallback(): cable is %sconnected.\n", xhdmi->cable_is_connected? "": "dis");
xvphy_mutex_lock(xhdmi->phy[0]);
/* RX cable is connected? */
if (HdmiRxSsPtr->IsStreamConnected) {
XVphy_IBufDsEnable(VphyPtr, 0, XVPHY_DIR_RX, (TRUE));
} else {
/* clear GT RX TMDS clock ratio */
VphyPtr-><API key> = 0;
XVphy_IBufDsEnable(VphyPtr, 0, XVPHY_DIR_RX, (FALSE));
}
xvphy_mutex_unlock(xhdmi->phy[0]);
}
static void RxAuxCallback(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
u8 AuxBuffer[36];
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (!xhdmi || !HdmiRxSsPtr) return;
// Copy the RX packet into the local buffer
memcpy(AuxBuffer, <API key>(HdmiRxSsPtr), sizeof(AuxBuffer));
}
static void RxAudCallback(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;\
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (!xhdmi || !HdmiRxSsPtr) return;
hdmi_dbg("RxAudCallback()\n");
(void)HdmiRxSsPtr;
}
static void RxLnkStaCallback(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (!xhdmi || !HdmiRxSsPtr) return;
(void)HdmiRxSsPtr;
}
static void <API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (!xhdmi || !HdmiRxSsPtr) return;
(void)HdmiRxSsPtr;
hdmi_dbg("<API key>()\n");
xhdmi->hdmi_stream_is_up = 0;
xhdmi->hdcp_authenticated = 0;
}
static void <API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XVphy *VphyPtr = xhdmi->xvphy;
XVidC_VideoStream *<API key>;
u32 Status;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
BUG_ON(!VphyPtr);
if (!xhdmi || !HdmiRxSsPtr || !VphyPtr) return;
hdmi_dbg("<API key>\r\n");
// Calculate RX MMCM parameters
// In the application the YUV422 colordepth is 12 bits
// However the HDMI transports YUV422 in 8 bits.
// Therefore force the colordepth to 8 bits when the colorspace is YUV422
<API key> = <API key>(HdmiRxSsPtr);
xvphy_mutex_lock(xhdmi->phy[0]);
if (<API key>->ColorFormatId == XVIDC_CSF_YCRCB_422) {
Status = <API key>(VphyPtr, 0, <API key>,
XVPHY_DIR_RX,
<API key>->PixPerClk,
XVIDC_BPC_8);
// Other colorspaces
} else {
Status = <API key>(VphyPtr, 0, <API key>,
XVPHY_DIR_RX,
<API key>->PixPerClk,
<API key>->ColorDepth);
}
if (Status == XST_FAILURE) {
xvphy_mutex_unlock(xhdmi->phy[0]);
return;
}
// Enable and configure RX MMCM
XVphy_MmcmStart(VphyPtr, 0, XVPHY_DIR_RX);
xvphy_mutex_unlock(xhdmi->phy[0]);
}
static void RxStreamUpCallback(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XVidC_VideoStream *Stream;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
BUG_ON(!HdmiRxSsPtr->HdmiRxPtr);
if (!xhdmi || !HdmiRxSsPtr || !HdmiRxSsPtr->HdmiRxPtr) return;
hdmi_dbg("RxStreamUpCallback((; stream is up.\n");
Stream = &HdmiRxSsPtr->HdmiRxPtr->Stream.Video;
#ifdef DEBUG
<API key>(Stream);
XV_HdmiRx_DebugInfo(HdmiRxSsPtr->HdmiRxPtr);
#endif
xhdmi->detected_format.width = Stream->Timing.HActive;
xhdmi->detected_format.height = Stream->Timing.VActive;
xhdmi->detected_format.field = Stream->IsInterlaced? <API key>: V4L2_FIELD_NONE;
if (Stream->ColorFormatId == XVIDC_CSF_RGB) {
hdmi_dbg("xhdmi->detected_format.colorspace = <API key>\n");
xhdmi->detected_format.colorspace = <API key>;
} else {
hdmi_dbg("xhdmi->detected_format.colorspace = <API key>\n");
xhdmi->detected_format.colorspace = <API key>;
}
/* see UG934 page 8 */
/* the V4L2 media bus fmt codes match the AXI S format, and match those from TPG */
if (Stream->ColorFormatId == XVIDC_CSF_RGB) {
/* red blue green */
xhdmi->detected_format.code = <API key>;
hdmi_dbg("XVIDC_CSF_RGB -> <API key>\n");
} else if (Stream->ColorFormatId == XVIDC_CSF_YCRCB_444) {
xhdmi->detected_format.code = <API key>;
hdmi_dbg("XVIDC_CSF_YCRCB_444 -> <API key>\n");
} else if (Stream->ColorFormatId == XVIDC_CSF_YCRCB_422) {
xhdmi->detected_format.code = <API key>;
hdmi_dbg("XVIDC_CSF_YCRCB_422 -> <API key>\n");
} else if (Stream->ColorFormatId == XVIDC_CSF_YCRCB_420) {
/* similar mapping as 4:2:2 w/ omitted chroma every other line */
xhdmi->detected_format.code = <API key>;
hdmi_dbg("XVIDC_CSF_YCRCB_420 -> <API key>\n");
}
xhdmi->detected_format.xfer_func = <API key>;
xhdmi->detected_format.ycbcr_enc = <API key>;
xhdmi->detected_format.quantization = <API key>;
/* map to v4l2_dv_timings */
xhdmi->detected_timings.type = V4L2_DV_BT_656_1120;
/* Read Active Pixels */
xhdmi->detected_timings.bt.width = Stream->Timing.HActive;
/* Active lines field 1 */
xhdmi->detected_timings.bt.height = Stream->Timing.VActive;
/* Interlaced */
xhdmi->detected_timings.bt.interlaced = !!Stream->IsInterlaced;
xhdmi->detected_timings.bt.polarities =
/* Vsync polarity, Positive == 1 */
(Stream->Timing.VSyncPolarity? <API key>: 0) |
/* Hsync polarity, Positive == 1 */
(Stream->Timing.HSyncPolarity? <API key>: 0);
/* from xvid.c:<API key>() but without VmId */
if (Stream->IsInterlaced) {
xhdmi->detected_timings.bt.pixelclock =
(Stream->Timing.F0PVTotal + Stream->Timing.F1VTotal) *
Stream->FrameRate / 2;
} else {
xhdmi->detected_timings.bt.pixelclock =
Stream->Timing.F0PVTotal * Stream->FrameRate;
}
xhdmi->detected_timings.bt.pixelclock *= Stream->Timing.HTotal;
hdmi_dbg("HdmiRxSsPtr->HdmiRxPtr->Stream.PixelClk = %d\n", HdmiRxSsPtr->HdmiRxPtr->Stream.PixelClk);
/* Read HFront Porch */
xhdmi->detected_timings.bt.hfrontporch = Stream->Timing.HFrontPorch;
/* Read Hsync Width */
xhdmi->detected_timings.bt.hsync = Stream->Timing.HSyncWidth;
/* Read HBack Porch */
xhdmi->detected_timings.bt.hbackporch = Stream->Timing.HBackPorch;
/* Read VFront Porch field 1*/
xhdmi->detected_timings.bt.vfrontporch = Stream->Timing.F0PVFrontPorch;
/* Read VSync Width field 1*/
xhdmi->detected_timings.bt.vsync = Stream->Timing.F0PVSyncWidth;
/* Read VBack Porch field 1 */
xhdmi->detected_timings.bt.vbackporch = Stream->Timing.F0PVBackPorch;
/* Read VFront Porch field 2*/
xhdmi->detected_timings.bt.il_vfrontporch = Stream->Timing.F1VFrontPorch;
/* Read VSync Width field 2*/
xhdmi->detected_timings.bt.il_vsync = Stream->Timing.F1VSyncWidth;
/* Read VBack Porch field 2 */
xhdmi->detected_timings.bt.il_vbackporch = Stream->Timing.F1VBackPorch;
xhdmi->detected_timings.bt.standards = <API key>;
xhdmi->detected_timings.bt.flags = <API key>;
(void)Stream->VmId;
xhdmi->hdmi_stream_is_up = 1;
/* notify source format change event */
<API key>(&xhdmi->subdev, &xhdmi_ev_fmt);
#ifdef DEBUG
<API key>("xilinx-hdmi-rx", "", & xhdmi->detected_timings, 1);
#endif
}
/* Called from non-interrupt context with xvphy mutex locked
*/
static void <API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
XVphy *VphyPtr = xhdmi->xvphy;
BUG_ON(!xhdmi);
BUG_ON(!VphyPtr);
BUG_ON(!xhdmi->phy[0]);
if (!xhdmi || !VphyPtr) return;
hdmi_dbg("<API key>()\n");
/* a pair of mutexes must be locked in fixed order to prevent deadlock,
* and the order is RX SS then XVPHY, so first unlock XVPHY then lock both */
xvphy_mutex_unlock(xhdmi->phy[0]);
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
xvphy_mutex_lock(xhdmi->phy[0]);
<API key>(HdmiRxSsPtr);
/* @NOTE maybe implement <API key>(); */
VphyPtr-><API key> = HdmiRxSsPtr->TMDSClockRatio;
/* unlock RX SS but keep XVPHY locked */
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
}
/* Called from non-interrupt context with xvphy mutex locked
*/
static void <API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XVphy *VphyPtr = xhdmi->xvphy;
XVphy_PllType RxPllType;
BUG_ON(!xhdmi);
BUG_ON(!VphyPtr);
BUG_ON(!xhdmi->phy[0]);
if (!xhdmi || !VphyPtr) return;
hdmi_dbg("<API key>()\n");
/* a pair of mutexes must be locked in fixed order to prevent deadlock,
* and the order is RX SS then XVPHY, so first unlock XVPHY then lock both */
xvphy_mutex_unlock(xhdmi->phy[0]);
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
xvphy_mutex_lock(xhdmi->phy[0]);
RxPllType = XVphy_GetPllType(VphyPtr, 0, XVPHY_DIR_RX,
<API key>);
if (!(RxPllType == XVPHY_PLL_TYPE_CPLL)) {
<API key>(&xhdmi->xv_hdmirxss, VphyPtr->HdmiRxRefClkHz,
(XVphy_GetLineRateHz(VphyPtr, 0, <API key>)/1000000));
}
else {
<API key>(&xhdmi->xv_hdmirxss, VphyPtr->HdmiRxRefClkHz,
(XVphy_GetLineRateHz(VphyPtr, 0, <API key>)/1000000));
}
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
}
static void RxHdcp<API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
XV_HdmiRxSs *HdmiRxSsPtr;
int HdcpProtocol;
BUG_ON(!xhdmi);
HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
HdcpProtocol = <API key>(HdmiRxSsPtr);
xhdmi->hdcp_authenticated = 1;
switch (HdcpProtocol) {
case XV_HDMIRXSS_HDCP_22:
hdmi_dbg("HDCP 2.2 RX authenticated.\n");
break;
case XV_HDMIRXSS_HDCP_14:
hdmi_dbg("HDCP 1.4 RX authenticated.\n");
break;
}
}
static void RxHdcpUn<API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
BUG_ON(!xhdmi);
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
xhdmi->hdcp_authenticated = 0;
hdmi_dbg("HDCP RX unauthenticated.\n");
}
static void <API key>(void *CallbackRef)
{
struct xhdmi_device *xhdmi = (struct xhdmi_device *)CallbackRef;
BUG_ON(!xhdmi);
XV_HdmiRxSs *HdmiRxSsPtr = &xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
xhdmi->hdcp_encrypted = !!<API key>(HdmiRxSsPtr);
hdmi_dbg("HDCP RX encryption changed; now %s.\n", xhdmi->hdcp_encrypted? "enabled": "disabled");
}
/* this function is responsible for periodically calling <API key>() */
static void hdcp_poll_work(struct work_struct *work)
{
/* find our parent container structure */
struct xhdmi_device *xhdmi = container_of(work, struct xhdmi_device,
<API key>.work);
XV_HdmiRxSs *HdmiRxSsPtr;
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
<API key>(HdmiRxSsPtr);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
#ifdef DEBUG
xhdmi->hdcp_info_counter++;
if (xhdmi->hdcp_info_counter >= 10000) { //every 10sec
xhdmi->hdcp_info_counter = 0;
<API key>(&xhdmi-><API key>, 0);
}
#endif
/* reschedule this work again in 1 millisecond @TODO change */
<API key>(&xhdmi-><API key>, msecs_to_jiffies(1));
return;
}
#ifdef DEBUG
static void hdcp_info_work(struct work_struct *work)
{
/* find our parent container structure */
struct xhdmi_device *xhdmi = container_of(work, struct xhdmi_device,
<API key>.work);
XV_HdmiRxSs *HdmiRxSsPtr;
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
// <API key>(HdmiRxSsPtr);
// <API key>(HdmiRxSsPtr);
}
#endif
static int <API key>(uintptr_t BaseAddress, u8 *Hdcp14Key)
{
u32 RegValue;
u8 Row;
u8 i;
u8 *KeyPtr;
u8 Status;
/* Assign key pointer */
KeyPtr = Hdcp14Key;
/* Reset */
Xil_Out32((BaseAddress + 0x0c), (1<<31));
// There are 41 rows
for (Row=0; Row<41; Row++)
{
/* Set write enable */
Xil_Out32((BaseAddress + 0x20), 1);
/* High data */
RegValue = 0;
for (i=0; i<4; i++)
{
RegValue <<= 8;
RegValue |= *KeyPtr;
KeyPtr++;
}
/* Write high data */
Xil_Out32((BaseAddress + 0x2c), RegValue);
/* Low data */
RegValue = 0;
for (i=0; i<4; i++)
{
RegValue <<= 8;
RegValue |= *KeyPtr;
KeyPtr++;
}
/* Write low data */
Xil_Out32((BaseAddress + 0x30), RegValue);
/* Table / Row Address */
Xil_Out32((BaseAddress + 0x28), Row);
// Write in progress
do
{
RegValue = Xil_In32(BaseAddress + 0x24);
RegValue &= 1;
} while (RegValue != 0);
}
// Verify
/* Re-Assign key pointer */
KeyPtr = Hdcp14Key;
/* Default Status */
Status = XST_SUCCESS;
/* Start at row 0 */
Row = 0;
do
{
/* Set read enable */
Xil_Out32((BaseAddress + 0x20), (1<<1));
/* Table / Row Address */
Xil_Out32((BaseAddress + 0x28), Row);
// Read in progress
do
{
RegValue = Xil_In32(BaseAddress + 0x24);
RegValue &= 1;
} while (RegValue != 0);
/* High data */
RegValue = 0;
for (i=0; i<4; i++)
{
RegValue <<= 8;
RegValue |= *KeyPtr;
KeyPtr++;
}
if (RegValue != Xil_In32(BaseAddress + 0x2c))
Status = XST_FAILURE;
/* Low data */
RegValue = 0;
for (i=0; i<4; i++)
{
RegValue <<= 8;
RegValue |= *KeyPtr;
KeyPtr++;
}
if (RegValue != Xil_In32(BaseAddress + 0x30))
Status = XST_FAILURE;
/* Increment row */
Row++;
} while ((Row<41) && (Status == XST_SUCCESS));
if (Status == XST_SUCCESS)
{
/* Set read lockout */
Xil_Out32((BaseAddress + 0x20), (1<<31));
/* Start AXI-Stream */
Xil_Out32((BaseAddress + 0x0c), (1));
}
return Status;
}
static int instance = 0;
/* TX uses [1, 127] and RX uses [128, 254] */
/* The HDCP22 timer uses an additional offset of +64 */
#define RX_DEVICE_ID_BASE 128
/* Local Global table for sub-core instance(s) configuration settings */
XV_HdmiRx_Config <API key>[<API key>];
extern <API key> <API key>[];
extern XHdcp22_Rng_Config <API key>[];
extern <API key> <API key>[];
extern XHdcp1x_Config XHdcp1x_ConfigTable[];
extern XTmrCtr_Config XTmrCtr_ConfigTable[];
extern XHdcp22_Rx_Config <API key>[];
/* Compute the absolute address by adding subsystem base address
to sub-core offset */
static int <API key>(uintptr_t SubSys_BaseAddr,
uintptr_t SubSys_HighAddr,
uintptr_t SubCore_Offset,
uintptr_t *SubCore_AbsAddr)
{
int Status;
uintptr_t absAddr;
absAddr = SubSys_BaseAddr | SubCore_Offset;
if((absAddr>=SubSys_BaseAddr) && (absAddr<=SubSys_HighAddr)) {
*SubCore_AbsAddr = absAddr;
Status = XST_SUCCESS;
} else {
*SubCore_AbsAddr = 0;
Status = XST_FAILURE;
}
return(Status);
}
/* Each sub-core within the subsystem has defined offset read from
device-tree. */
static int <API key>(XV_HdmiRxSs_Config *config)
{
int ret;
/* Subcore: Rx */
ret = <API key>(config->BaseAddress,
config->HighAddress,
config->HdmiRx.AbsAddr,
&(config->HdmiRx.AbsAddr));
if (ret != XST_SUCCESS) {
hdmi_dbg("hdmirx sub-core address out-of range\n");
return -EFAULT;
}
<API key>[instance].BaseAddress = config->HdmiRx.AbsAddr;
/* Subcore: hdcp1x */
if (config->Hdcp14.IsPresent) {
ret = <API key>(config->BaseAddress,
config->HighAddress,
config->Hdcp14.AbsAddr,
&(config->Hdcp14.AbsAddr));
if (ret != XST_SUCCESS) {
hdmi_dbg("hdcp1x sub-core address out-of range\n");
return -EFAULT;
}
XHdcp1x_ConfigTable[<API key>/2 + instance].BaseAddress = config->Hdcp14.AbsAddr;
}
/* Subcore: hdcp1x timer */
if (config->HdcpTimer.IsPresent) {
ret = <API key>(config->BaseAddress,
config->HighAddress,
config->HdcpTimer.AbsAddr,
&(config->HdcpTimer.AbsAddr));
if (ret != XST_SUCCESS) {
hdmi_dbg("hdcp1x timer sub-core address out-of range\n");
return -EFAULT;
}
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 0].BaseAddress = config->HdcpTimer.AbsAddr;
}
/* Subcore: hdcp22 */
if (config->Hdcp22.IsPresent) {
ret = <API key>(config->BaseAddress,
config->HighAddress,
config->Hdcp22.AbsAddr,
&(config->Hdcp22.AbsAddr));
if (ret != XST_SUCCESS) {
hdmi_dbg("hdcp22 sub-core address out-of range\n");
return -EFAULT;
}
<API key>[instance].BaseAddress = config->Hdcp22.AbsAddr;
}
return (ret);
}
static ssize_t vphy_log_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
XVphy *VphyPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
VphyPtr = xhdmi->xvphy;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
BUG_ON(!VphyPtr);
count = XVphy_LogShow(VphyPtr, buf, PAGE_SIZE);
return count;
}
static ssize_t vphy_log_store(struct device *sysfs_dev, struct device_attribute *attr,
const char *buf, size_t count)
{ return count; }
static ssize_t hdmi_log_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
count = XV_HdmiRxSs_LogShow(HdmiRxSsPtr, buf, PAGE_SIZE);
return count;
}
static ssize_t hdcp_log_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
count = <API key>(HdmiRxSsPtr, buf, PAGE_SIZE);
return count;
}
static ssize_t hdcp_enable(struct device *sysfs_dev, struct device_attribute *attr,
const char *buf, size_t count)
{
long int i;
printk(KERN_INFO "hdcp_enable()\n");
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
if (kstrtol(buf, 10, &i)) {
printk(KERN_INFO "************ failed to convert buf to long\n");
return count;
}
i = !!i;
printk(KERN_INFO "hdcp_enable = %d\n", (int)i);
return count;
}
static ssize_t <API key>(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
count = scnprintf(buf, PAGE_SIZE, "%d", xhdmi->hdcp_authenticated);
return count;
}
static ssize_t hdcp_encrypted_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
count = scnprintf(buf, PAGE_SIZE, "%d", xhdmi->hdcp_encrypted);
return count;
}
/* This function decrypts the HDCP keys, uses aes256.c */
/* Note that the bare-metal implementation deciphers in-place in the cipherbuffer, then after that copies to the plaintext buffer,
* thus trashing the source.
*
* In this implementation, the cipher is first copied to the plain buffer, where it is then decrypted in-place. This leaves the
* source buffer intact.
*/
#if 0
Enter Password ->...........
Encrypt signature done
Write signature (16 bytes)
Verify signature ok (16 bytes)
Encrypt LC128 done
Write LC128 (16 bytes)
Verify lc128 ok (16 bytes)
Encrypt HDCP 2.2 Certificate done
Write HDCP 2.2 Certificate (912 bytes)
Verify HDCP 2.2 Certificate ok (902 bytes)
Encrypt HDCP 1.4 Key A done
Write HDCP 1.4 Key A (336 bytes)
Verify HDCP 1.4 Key A ok (328 bytes)
Encrypt HDCP 1.4 Key A done
Write HDCP 1.4 Key B (336 bytes)
Verify HDCP 1.4 Key B ok (328 bytes)
HDCP Key EEPROM completed.
This application is stopped.
#endif
static void Decrypt(const u8 *CipherBufferPtr/*src*/, u8 *PlainBufferPtr/*dst*/, u8 *Key, u16 Length)
{
u8 i;
u8 *AesBufferPtr;
u16 AesLength;
aes256_context ctx;
// Copy cipher into plain buffer // @NOTE: Added
memcpy(PlainBufferPtr, CipherBufferPtr, Length);
// Assign local Pointer // @NOTE: Changed
AesBufferPtr = PlainBufferPtr;
// Initialize AES256
aes256_init(&ctx, Key);
AesLength = Length/16;
if (Length % 16) {
AesLength++;
}
for (i=0; i<AesLength; i++)
{
// Decrypt
aes256_decrypt_ecb(&ctx, AesBufferPtr);
// Increment pointer
AesBufferPtr += 16; // The aes always encrypts 16 bytes
}
// Done
aes256_done(&ctx);
#if 0 // @NOTE: Removed
// Clear Buffer
memset(PlainBufferPtr, 0x00, Length);
// Copy buffers
memcpy(PlainBufferPtr, CipherBufferPtr, Length);
#endif
}
#define SIGNATURE_OFFSET 0
#define HDCP22_LC128_OFFSET 16
#define <API key> 32
#define HDCP14_KEY1_OFFSET 1024
#define HDCP14_KEY2_OFFSET 1536
/* buffer points to the encrypted data (from EEPROM), password points to a 32-character password */
static int XHdcp_LoadKeys(const u8 *Buffer, u8 *Password, u8 *Hdcp22Lc128, u32 Hdcp22Lc128Size, u8 *Hdcp22RxPrivateKey, u32 <API key>,
u8 *Hdcp14KeyA, u32 Hdcp14KeyASize, u8 *Hdcp14KeyB, u32 Hdcp14KeyBSize)
{
u8 i;
const u8 HdcpSignature[16] = { "xilinx_hdcp_keys" };
u8 Key[32];
u8 SignatureOk;
u8 HdcpSignatureBuffer[16];
// Generate password hash
<API key>(Password, 32, Key);
/* decrypt the signature */
Decrypt(&Buffer[SIGNATURE_OFFSET]/*source*/, HdcpSignatureBuffer/*destination*/, Key, sizeof(HdcpSignature));
SignatureOk = 1;
for (i = 0; i < sizeof(HdcpSignature); i++) {
if (HdcpSignature[i] != HdcpSignatureBuffer[i])
SignatureOk = 0;
}
/* password and buffer are correct, as the generated key could correctly decrypt the signature */
if (SignatureOk == 1) {
/* decrypt the keys */
Decrypt(&Buffer[HDCP22_LC128_OFFSET], Hdcp22Lc128, Key, Hdcp22Lc128Size);
Decrypt(&Buffer[<API key>], Hdcp22RxPrivateKey, Key, <API key>);
Decrypt(&Buffer[HDCP14_KEY1_OFFSET], Hdcp14KeyA, Key, Hdcp14KeyASize);
Decrypt(&Buffer[HDCP14_KEY2_OFFSET], Hdcp14KeyB, Key, Hdcp14KeyBSize);
return XST_SUCCESS;
} else {
printk(KERN_INFO "HDCP key store signature mismatch; HDCP key data and/or password are invalid.\n");
}
return XST_FAILURE;
}
/* assume the HDCP C structures containing the keys are valid, and sets them in the bare-metal driver / IP */
static int hdcp_keys_configure(struct xhdmi_device *xhdmi)
{
XV_HdmiRxSs *HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
if (xhdmi->config.Hdcp14.IsPresent && xhdmi->config.HdcpTimer.IsPresent && xhdmi-><API key>) {
u8 Status;
hdmi_dbg("HDCP1x components are all there.\n");
/* Set pointer to HDCP 1.4 key */
<API key>(HdmiRxSsPtr, <API key>, xhdmi->Hdcp14KeyB);
/* Key manager Init */
Status = <API key>((uintptr_t)xhdmi-><API key>, HdmiRxSsPtr->Hdcp14KeyPtr);
if (Status != XST_SUCCESS) {
dev_err(xhdmi->dev, "HDCP 1.4 RX Key Manager initialization error.\n");
return -EINVAL;
}
dev_info(xhdmi->dev, "HDCP 1.4 RX Key Manager initialized OK.\n");
}
if (xhdmi->config.Hdcp22.IsPresent) {
/* Set pointer to HDCP 2.2 LC128 */
<API key>(HdmiRxSsPtr, <API key>, xhdmi->Hdcp22Lc128);
/* Set pointer to HDCP 2.2 private key */
<API key>(HdmiRxSsPtr, <API key>, xhdmi->Hdcp22PrivateKey);
}
return 0;
}
/* the EEPROM contents (i.e. the encrypted HDCP keys) must be dumped as a binary blob;
* the user must first upload the password */
static ssize_t hdcp_key_store(struct device *sysfs_dev, struct device_attribute *attr,
const char *buf, size_t count)
{
long int i;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
XV_HdmiRxSs *HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
/* check for valid size of HDCP encrypted key binary blob, @TODO adapt */
if (count < 1872) {
printk(KERN_INFO "hdcp_key_store(count = %d, expected >=1872)\n", (int)count);
return -EINVAL;
}
xhdmi-><API key> = 0;
/* decrypt the keys from the binary blob (buffer) into the C structures for keys */
if (XHdcp_LoadKeys(buf, xhdmi->hdcp_password,
xhdmi->Hdcp22Lc128, sizeof(xhdmi->Hdcp22Lc128),
xhdmi->Hdcp22PrivateKey, sizeof(xhdmi->Hdcp22PrivateKey),
xhdmi->Hdcp14KeyA, sizeof(xhdmi->Hdcp14KeyA),
xhdmi->Hdcp14KeyB, sizeof(xhdmi->Hdcp14KeyB)) == XST_SUCCESS) {
xhdmi-><API key> = 1;
/* configure the keys in the IP */
hdcp_keys_configure(xhdmi);
/* configure HDCP in HDMI */
u8 Status = <API key>(HdmiRxSsPtr, &xhdmi->config, (uintptr_t)xhdmi->iomem);
if (Status != XST_SUCCESS)
{
dev_err(xhdmi->dev, "<API key>() failed with error %d\n", Status);
return -EINVAL;
}
<API key>(HdmiRxSsPtr, <API key>,
RxHdcp<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
RxHdcpUn<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
<API key>, (void *)xhdmi);
}
return count;
}
static ssize_t hdcp_password_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{
ssize_t count;
XV_HdmiRxSs *HdmiRxSsPtr;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
BUG_ON(!xhdmi);
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!HdmiRxSsPtr);
count = scnprintf(buf, PAGE_SIZE, "%s", xhdmi-><API key>? "accepted": "rejected");
return count;
}
/* store the HDCP key password, after this the HDCP key can be written to sysfs */
static ssize_t hdcp_password_store(struct device *sysfs_dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int i = 0;
struct xhdmi_device *xhdmi = (struct xhdmi_device *)dev_get_drvdata(sysfs_dev);
XV_HdmiRxSs *HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
BUG_ON(!xhdmi);
BUG_ON(!HdmiRxSsPtr);
if (count > sizeof(xhdmi->hdcp_password)) return -EINVAL;
/* copy password characters up to newline or carriage return */
while ((i < count) && (i < sizeof(xhdmi->hdcp_password))) {
/* do not include newline or carriage return in password */
if ((buf[i] == '\n') || (buf[i] == '\r') || (buf[i] == 0)) break;
xhdmi->hdcp_password[i] = buf[i];
i++;
}
/* zero remaining characters */
while (i < sizeof(xhdmi->hdcp_password)) {
xhdmi->hdcp_password[i] = 0;
i++;
}
return count;
}
static ssize_t null_show(struct device *sysfs_dev, struct device_attribute *attr,
char *buf)
{ return 0; }
static ssize_t null_store(struct device *sysfs_dev, struct device_attribute *attr,
const char *buf, size_t count)
{ return count; }
DEVICE_ATTR(vphy_log, 0444, vphy_log_show, vphy_log_store);
DEVICE_ATTR(hdmi_log, 0444, hdmi_log_show, NULL/*null_store*/);
DEVICE_ATTR(hdcp_log, 0444, hdcp_log_show, NULL/*null_store*/);
DEVICE_ATTR(hdcp_key, 0220, NULL/*null_show*/, hdcp_key_store);
DEVICE_ATTR(hdcp_password, 0660, hdcp_password_show, hdcp_password_store);
/* read-only status */
DEVICE_ATTR(hdcp_authenticated, 0444, <API key>, NULL/*store*/);
DEVICE_ATTR(hdcp_encrypted, 0444, hdcp_encrypted_show, NULL/*store*/);
static struct attribute *attrs[] = {
&dev_attr_vphy_log.attr,
&dev_attr_hdmi_log.attr,
&dev_attr_hdcp_log.attr,
&dev_attr_hdcp_key.attr,
&<API key>.attr,
&<API key>.attr,
&<API key>.attr,
NULL,
};
static struct attribute_group attr_group = {
.attrs = attrs,
};
#if 0
static const struct attribute_group *attr_groups[] = {
&attr_group,
NULL,
};
#endif
static int xhdmi_parse_of(struct xhdmi_device *xhdmi, XV_HdmiRxSs_Config *config)
{
struct device *dev = xhdmi->dev;
struct device_node *node = dev->of_node;
int rc;
bool isHdcp14_en, isHdcp22_en;
u32 val;
rc = <API key>(node, "xlnx,<API key>", &val);
if (rc < 0)
goto error_dt;
config->Ppc = val;
rc = <API key>(node, "xlnx,<API key>", &val);
if (rc < 0)
goto error_dt;
config->MaxBitsPerPixel = val;
rc = <API key>(node, "xlnx,edid-ram-size", &val);
if (rc == 0) {
if (val % 128)
goto error_dt;
xhdmi->edid_blocks_max = val / EDID_BLOCK_SIZE;
}
/* RX Core */
config->HdmiRx.DeviceId = RX_DEVICE_ID_BASE + instance;
config->HdmiRx.IsPresent = 1;
config->HdmiRx.AbsAddr = RXSS_RX_OFFSET;
<API key>[instance].DeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[instance].BaseAddress = RXSS_RX_OFFSET;
isHdcp14_en = <API key>(node, "xlnx,include-hdcp-1-4");
isHdcp22_en = <API key>(node, "xlnx,include-hdcp-2-2");
if (isHdcp14_en) {
/* HDCP14 Core */
/* make subcomponent of RXSS present */
config->Hdcp14.DeviceId = RX_DEVICE_ID_BASE + instance;
config->Hdcp14.IsPresent = 1;
config->Hdcp14.AbsAddr = RXSS_HDCP14_OFFSET;
/* and configure it */
XHdcp1x_ConfigTable[<API key>/2 + instance].DeviceId = config->Hdcp14.DeviceId;
XHdcp1x_ConfigTable[<API key>/2 + instance].BaseAddress = RXSS_HDCP14_OFFSET;
XHdcp1x_ConfigTable[<API key>/2 + instance].IsRx = 1;
XHdcp1x_ConfigTable[<API key>/2 + instance].IsHDMI = 1;
/* HDCP14 Timer Core */
/* make subcomponent of RXSS present */
config->HdcpTimer.DeviceId = RX_DEVICE_ID_BASE + instance;
config->HdcpTimer.IsPresent = 1;
config->HdcpTimer.AbsAddr = <API key>;
/* and configure it */
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 0].DeviceId = config->HdcpTimer.DeviceId;
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 0].BaseAddress = <API key>;
/* @TODO increment timer index */
}
if (isHdcp22_en) {
/* HDCP22 SS */
config->Hdcp22.DeviceId = RX_DEVICE_ID_BASE + instance;
config->Hdcp22.IsPresent = 1;
config->Hdcp22.AbsAddr = RXSS_HDCP22_OFFSET;
<API key>[instance].DeviceId = config->Hdcp22.DeviceId;
<API key>[instance].BaseAddress = RXSS_HDCP22_OFFSET;
<API key>[instance].Protocol = 0; /*HDCP22_RX_HDMI*/
<API key>[instance].Mode = 0; /*XHDCP22_RX_RECEIVER*/
<API key>[instance].TimerDeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[instance].CipherDeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[instance].MontMultDeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[instance].RngDeviceId = RX_DEVICE_ID_BASE + instance;
/* HDCP22 Cipher Core */
<API key>[<API key>/2 + instance].DeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[<API key>/2 + instance].BaseAddress = <API key>;
/* HDCP22 MMULT Core */
<API key>[<API key>/2 + instance].DeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[<API key>/2 + instance].BaseAddress = <API key>;
/* HDCP22-Timer Core */
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 1].DeviceId = RX_DEVICE_ID_BASE + 64 + instance;
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 1].BaseAddress = <API key>;
/* HDCP22 RNG Core */
<API key>[<API key>/2 + instance].DeviceId = RX_DEVICE_ID_BASE + instance;
<API key>[<API key>/2 + instance].BaseAddress = <API key>;
}
return 0;
error_dt:
dev_err(xhdmi->dev, "Error parsing device tree");
return rc;
}
static int xhdmi_probe(struct platform_device *pdev)
{
struct v4l2_subdev *subdev;
struct xhdmi_device *xhdmi;
int ret;
unsigned int index = 0;
struct resource *res;
const struct firmware *fw_edid;
const char *fw_edid_name = "xilinx/xilinx-hdmi-rx-edid.bin";
unsigned long flags;
unsigned long axi_clk_rate;
XV_HdmiRxSs *HdmiRxSsPtr;
u32 Status;
dev_info(&pdev->dev, "xlnx-hdmi-rx probed\n");
/* allocate zeroed HDMI RX device structure */
xhdmi = devm_kzalloc(&pdev->dev, sizeof(*xhdmi), GFP_KERNEL);
if (!xhdmi)
return -ENOMEM;
/* store pointer of the real device inside platform device */
xhdmi->dev = &pdev->dev;
xhdmi->edid_blocks_max = 2;
/* mutex that protects against concurrent access */
mutex_init(&xhdmi->xhdmi_mutex);
spin_lock_init(&xhdmi->irq_lock);
/* work queues */
xhdmi->work_queue = <API key>("xilinx-hdmi-rx");
if (!xhdmi->work_queue) {
dev_info(xhdmi->dev, "Could not create work queue\n");
return -ENOMEM;
}
INIT_DELAYED_WORK(&xhdmi-><API key>,
<API key>);
hdmi_dbg("xhdmi_probe DT parse start\n");
/* parse open firmware device tree data */
ret = xhdmi_parse_of(xhdmi, &xhdmi->config);
if (ret < 0)
return ret;
hdmi_dbg("xhdmi_probe DT parse done\n");
/* acquire vphy lanes */
for (index = 0; index < 3; index++)
{
char phy_name[16];
snprintf(phy_name, sizeof(phy_name), "hdmi-phy%d", index);
xhdmi->phy[index] = devm_phy_get(xhdmi->dev, phy_name);
if (IS_ERR(xhdmi->phy[index])) {
ret = PTR_ERR(xhdmi->phy[index]);
xhdmi->phy[index] = NULL;
if (ret == -EPROBE_DEFER) {
hdmi_dbg("xvphy not ready -EPROBE_DEFER\n");
return ret;
}
if (ret != -EPROBE_DEFER)
dev_err(xhdmi->dev, "failed to get phy lane %s index %d, error %d\n",
phy_name, index, ret);
goto error_phy;
}
ret = phy_init(xhdmi->phy[index]);
if (ret) {
dev_err(xhdmi->dev,
"failed to init phy lane %d\n", index);
goto error_phy;
}
}
/* get ownership of the HDMI RXSS MMIO register space resource */
res = <API key>(pdev, IORESOURCE_MEM, 0);
/* map the MMIO region */
xhdmi->iomem = <API key>(xhdmi->dev, res);
if (IS_ERR(xhdmi->iomem)) {
ret = PTR_ERR(xhdmi->iomem);
goto error_resource;
}
xhdmi->config.DeviceId = instance;
xhdmi->config.BaseAddress = (uintptr_t)xhdmi->iomem;
xhdmi->config.HighAddress = (uintptr_t)xhdmi->iomem + resource_size(res) - 1;
/* Compute AbsAddress for sub-cores */
ret = <API key>(&xhdmi->config);
if (ret == -EFAULT) {
dev_err(xhdmi->dev, "hdmi-rx sub-core address out-of range\n");
return ret;
}
/* video streaming bus clock */
xhdmi->clk = devm_clk_get(xhdmi->dev, "video");
if (IS_ERR(xhdmi->clk)) {
ret = PTR_ERR(xhdmi->clk);
if (ret == -EPROBE_DEFER)
dev_info(xhdmi->dev, "video-clk not ready -EPROBE_DEFER\n");
if (ret != -EPROBE_DEFER)
dev_err(xhdmi->dev, "failed to get video clk\n");
return ret;
}
clk_prepare_enable(xhdmi->clk);
/* AXI lite register bus clock */
xhdmi->axi_lite_clk = devm_clk_get(xhdmi->dev, "axi-lite");
if (IS_ERR(xhdmi->axi_lite_clk)) {
ret = PTR_ERR(xhdmi->clk);
if (ret == -EPROBE_DEFER)
dev_info(xhdmi->dev, "axi-lite clk not ready -EPROBE_DEFER\n");
if (ret != -EPROBE_DEFER)
dev_err(xhdmi->dev, "failed to get axi-lite clk\n");
return ret;
}
clk_prepare_enable(xhdmi->axi_lite_clk);
axi_clk_rate = clk_get_rate(xhdmi->axi_lite_clk);
hdmi_dbg("AXI Lite clock rate = %lu Hz\n", axi_clk_rate);
/* we now know the AXI clock rate */
XHdcp1x_ConfigTable[<API key>/2 + instance].SysFrequency = axi_clk_rate;
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 0].SysClockFreqHz = axi_clk_rate;
XTmrCtr_ConfigTable[<API key>/2 + instance * 2 + 1].SysClockFreqHz = axi_clk_rate;
/* get ownership of the HDCP1x key management MMIO register space resource */
res = <API key>(pdev, IORESOURCE_MEM, "hdcp1x-keymngmt");
if (res) {
hdmi_dbg("Mapping HDCP1x key management block.\n");
xhdmi-><API key> = <API key>(xhdmi->dev, res);
hdmi_dbg("HDCP1x key management block @%p.\n", xhdmi-><API key>);
if (IS_ERR(xhdmi-><API key>)) {
dev_err(xhdmi->dev, "Could not ioremap hdcp1x-keymngmt.\n");
return PTR_ERR(xhdmi-><API key>);
}
}
/* get HDMI RXSS irq */
xhdmi->irq = platform_get_irq(pdev, 0);
if (xhdmi->irq <= 0) {
dev_err(&pdev->dev, "platform_get_irq() failed\n");
return xhdmi->irq;
}
if (xhdmi->config.Hdcp14.IsPresent) {
xhdmi->hdcp1x_irq = <API key>(pdev, "hdcp1x");
hdmi_dbg("xhdmi->hdcp1x_irq = %d\n", xhdmi->hdcp1x_irq);
xhdmi->hdcp1x_timer_irq = <API key>(pdev, "hdcp1x-timer");
hdmi_dbg("xhdmi->hdcp1x_timer_irq = %d\n", xhdmi->hdcp1x_timer_irq);
}
if (xhdmi->config.Hdcp22.IsPresent) {
xhdmi->hdcp22_irq = <API key>(pdev, "hdcp22");
hdmi_dbg("xhdmi->hdcp22_irq = %d\n", xhdmi->hdcp22_irq);
xhdmi->hdcp22_timer_irq = <API key>(pdev, "hdcp22-timer");
hdmi_dbg("xhdmi->hdcp22_timer_irq = %d\n", xhdmi->hdcp22_timer_irq);
}
if (xhdmi->config.Hdcp14.IsPresent || xhdmi->config.Hdcp22.IsPresent) {
INIT_DELAYED_WORK(&xhdmi-><API key>, hdcp_poll_work/*function*/);
#ifdef DEBUG
INIT_DELAYED_WORK(&xhdmi-><API key>, hdcp_info_work/*function*/);
#endif
}
HdmiRxSsPtr = (XV_HdmiRxSs *)&xhdmi->xv_hdmirxss;
hdmi_mutex_lock(&xhdmi->xhdmi_mutex);
#if 0
ret = <API key>(&pdev->dev, xhdmi->irq, hdmirx_irq_handler, hdmirx_irq_thread,
IRQF_TRIGGER_HIGH, "xilinx-hdmi-rx", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
goto error_phy;
}
/* HDCP 1.4 Cipher interrupt */
if (xhdmi->hdcp1x_irq > 0) {
/* Request the HDCP14 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp1x_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp1x_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
/* HDCP 1.4 Timer interrupt */
if (xhdmi->hdcp1x_timer_irq > 0) {
/* Request the HDCP14 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp1x_timer_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp1x_timer_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
/* HDCP 2.2 interrupt, unused currently */
#if 0
if (xhdmi->hdcp22_irq > 0) {
/* Request the HDCP22 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp22_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp22_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
#endif
/* HDCP 2.2 Timer interrupt */
if (xhdmi->hdcp22_timer_irq > 0) {
/* Request the HDCP22 timer interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp22_timer_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp22_timer_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
#endif
#if 0
#if 0
/* could not set HDCP keys? */
if (hdcp_keys_configure(xhdmi) != 0) {
dev_err(xhdmi->dev, "HDCP 1.4 RX Key Manager initialization error, from hdcp_keys_configure()\n");
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return -EINVAL;
}
#error LEON
#else
if (xhdmi->config.Hdcp14.IsPresent && xhdmi->config.HdcpTimer.IsPresent && xhdmi-><API key>) {
u8 Status;
hdmi_dbg("HDCP1x components are all there.\n");
/* Set pointer to HDCP 1.4 key */
<API key>(HdmiRxSsPtr, <API key>, Hdcp14KeyB);
/* Key manager Init */
Status = <API key>((uintptr_t)xhdmi-><API key>, HdmiRxSsPtr->Hdcp14KeyPtr);
if (Status != XST_SUCCESS) {
dev_err(xhdmi->dev, "HDCP 1.4 RX Key Manager initialization error.\n");
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return -EINVAL;
}
dev_info(xhdmi->dev, "HDCP 1.4 RX Key Manager initialized OK.\n");
}
if (xhdmi->config.Hdcp22.IsPresent) {
/* Set pointer to HDCP 2.2 LC128 */
<API key>(HdmiRxSsPtr, <API key>, Hdcp22Lc128);
/* Set pointer to HDCP 2.2 private key */
<API key>(HdmiRxSsPtr, <API key>, Hdcp22PrivateKey);
}
#endif
#endif
/* sets pointer to the EDID used by <API key>() */
<API key>(HdmiRxSsPtr, (u8 *)&xilinx_edid[0], sizeof(xilinx_edid));
/* Initialize top level and all included sub-cores */
Status = <API key>(HdmiRxSsPtr, &xhdmi->config, (uintptr_t)xhdmi->iomem);
if (Status != XST_SUCCESS) {
dev_err(xhdmi->dev, "initialization failed with error %d\n", Status);
return -EINVAL;
}
/* disable interrupts */
spin_lock_irqsave(&xhdmi->irq_lock, flags);
<API key>(HdmiRxSsPtr);
<API key>(&xhdmi->irq_lock, flags);
/* retrieve EDID */
if (request_firmware(&fw_edid, fw_edid_name, xhdmi->dev) == 0) {
int blocks = fw_edid->size / 128;
if ((blocks == 0) || (blocks > xhdmi->edid_blocks_max) || (fw_edid->size % 128)) {
dev_err(xhdmi->dev, "%s must be n * 128 bytes, with 1 <= n <= %d, using Xilinx built-in EDID instead.\n",
fw_edid_name, xhdmi->edid_blocks_max);
} else {
memcpy(xhdmi->edid_user, fw_edid->data, 128 * blocks);
xhdmi->edid_user_blocks = blocks;
}
}
release_firmware(fw_edid);
if (xhdmi->edid_user_blocks) {
dev_info(xhdmi->dev, "Using %d EDID block%s (%d bytes) from '%s'.\n",
xhdmi->edid_user_blocks, xhdmi->edid_user_blocks > 1? "s":"", 128 * xhdmi->edid_user_blocks, fw_edid_name);
<API key>(HdmiRxSsPtr, (u8 *)&xhdmi->edid_user, 128 * xhdmi->edid_user_blocks);
} else {
dev_info(xhdmi->dev, "Using Xilinx built-in EDID.\n");
<API key>(HdmiRxSsPtr);
}
/* RX SS callback setup (from xapp1287/xhdmi_example.c:2146) */
<API key>(HdmiRxSsPtr, <API key>,
RxConnectCallback, (void *)xhdmi);
<API key>(HdmiRxSsPtr,<API key>,
RxAuxCallback,(void *)xhdmi);
<API key>(HdmiRxSsPtr,<API key>,
RxAudCallback, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
RxLnkStaCallback, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
RxStreamUpCallback, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
RxHdcp<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
RxHdcpUn<API key>, (void *)xhdmi);
<API key>(HdmiRxSsPtr, <API key>,
<API key>, (void *)xhdmi);
/* get a reference to the XVphy data structure */
xhdmi->xvphy = xvphy_get_xvphy(xhdmi->phy[0]);
BUG_ON(!xhdmi->xvphy);
xvphy_mutex_lock(xhdmi->phy[0]);
/* the callback is not specific to a single lane, but we need to
* provide one of the phy's as reference */
<API key>(xhdmi->xvphy, <API key>,
<API key>, (void *)xhdmi);
<API key>(xhdmi->xvphy, <API key>,
<API key>, (void *)xhdmi);
xvphy_mutex_unlock(xhdmi->phy[0]);
#ifdef DEBUG
//Enable detailed logging of HDCP cores
// <API key>(HdmiRxSsPtr, TRUE);
// <API key>(HdmiRxSsPtr);
#endif
<API key>(pdev, xhdmi);
/* Initialize V4L2 subdevice */
subdev = &xhdmi->subdev;
v4l2_subdev_init(subdev, &xhdmi_ops);
subdev->dev = &pdev->dev;
subdev->internal_ops = &xhdmi_internal_ops;
strlcpy(subdev->name, dev_name(&pdev->dev), sizeof(subdev->name));
v4l2_set_subdevdata(subdev, xhdmi);
subdev->flags |= <API key> | <API key>;
/* Initialize V4L2 media entity */
xhdmi->pad.flags = MEDIA_PAD_FL_SOURCE;
subdev->entity.ops = &xhdmi_media_ops;
ret = <API key>(&subdev->entity, 1/*npads*/, &xhdmi->pad);
if (ret < 0) {
dev_err(&pdev->dev, "failed to init media entity\n");
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
goto error_irq;
}
<API key>(&xhdmi->ctrl_handler, 0/*controls*/);
subdev->ctrl_handler = &xhdmi->ctrl_handler;
ret = <API key>(&xhdmi->ctrl_handler);
if (ret < 0) {
dev_err(&pdev->dev, "failed to set controls\n");
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
goto error_irq;
}
/* assume detected format */
xhdmi->detected_format.width = 1280;
xhdmi->detected_format.height = 720;
xhdmi->detected_format.field = V4L2_FIELD_NONE;
xhdmi->detected_format.colorspace = <API key>;
xhdmi->detected_format.code = <API key>;
xhdmi->detected_format.colorspace = <API key>;
xhdmi->detected_format.xfer_func = <API key>;
xhdmi->detected_format.ycbcr_enc = <API key>;
xhdmi->detected_format.quantization = <API key>;
ret = <API key>(subdev);
if (ret < 0) {
dev_err(&pdev->dev, "failed to register subdev\n");
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
goto error;
}
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
/* call into hdcp_poll_work, which will reschedule itself */
if (HdmiRxSsPtr->Config.Hdcp14.IsPresent || HdmiRxSsPtr->Config.Hdcp22.IsPresent) {
<API key>(&xhdmi-><API key>, msecs_to_jiffies(1));
}
#if 1 // typically sys/devices/platform/amba_pl\@0/<address>.v_hdmi_rx_ss/
ret = sysfs_create_group(&xhdmi->dev->kobj, &attr_group);
dev_info(xhdmi->dev, "sysfs_create_group() = %d\n", ret);
#endif
ret = <API key>(&pdev->dev, xhdmi->irq, hdmirx_irq_handler, hdmirx_irq_thread,
IRQF_TRIGGER_HIGH, "xilinx-hdmi-rx", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
goto error_phy;
}
/* HDCP 1.4 Cipher interrupt */
if (xhdmi->hdcp1x_irq > 0) {
/* Request the HDCP14 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp1x_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp1x_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
/* HDCP 1.4 Timer interrupt */
if (xhdmi->hdcp1x_timer_irq > 0) {
/* Request the HDCP14 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp1x_timer_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp1x_timer_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
/* HDCP 2.2 interrupt, unused currently */
#if 0
if (xhdmi->hdcp22_irq > 0) {
/* Request the HDCP22 interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp22_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp22_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
#endif
/* HDCP 2.2 Timer interrupt */
if (xhdmi->hdcp22_timer_irq > 0) {
/* Request the HDCP22 timer interrupt */
ret = <API key>(&pdev->dev, xhdmi->hdcp22_timer_irq, <API key>, <API key>,
IRQF_TRIGGER_HIGH /*| IRQF_SHARED*/, "<API key>", xhdmi/*dev_id*/);
if (ret) {
dev_err(&pdev->dev, "unable to request IRQ %d\n", xhdmi->hdcp22_timer_irq);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
hdmi_mutex_unlock(&xhdmi->xhdmi_mutex);
return ret;
}
}
/* enable interrupts */
spin_lock_irqsave(&xhdmi->irq_lock, flags);
<API key>(HdmiRxSsPtr);
<API key>(&xhdmi->irq_lock, flags);
/* probe has succeeded for this instance, increment instance index */
instance++;
dev_info(xhdmi->dev, "hdmi-rx probe successful\n");
/* return success */
return 0;
error:
<API key>(&xhdmi->ctrl_handler);
<API key>(&subdev->entity);
error_irq:
error_phy:
printk(KERN_INFO "xhdmirx_probe() error_phy:\n");
index = 0;
/* release the lanes that we did get, if we did not get all lanes */
if (xhdmi->phy[index]) {
printk(KERN_INFO "phy_exit() xhdmi->phy[%d] = %p\n", index, xhdmi->phy[index]);
phy_exit(xhdmi->phy[index]);
xhdmi->phy[index] = NULL;
}
error_resource:
printk(KERN_INFO "xhdmirx_probe() error_resource:\n");
return ret;
}
static int xhdmi_remove(struct platform_device *pdev)
{
struct xhdmi_device *xhdmi = <API key>(pdev);
struct v4l2_subdev *subdev = &xhdmi->subdev;
unsigned long flags;
spin_lock_irqsave(&xhdmi->irq_lock, flags);
<API key>(&xhdmi->xv_hdmirxss);
xhdmi->teardown = 1;
<API key>(&xhdmi->irq_lock, flags);
cancel_delayed_work(&xhdmi-><API key>);
destroy_workqueue(xhdmi->work_queue);
<API key>(subdev);
<API key>(&xhdmi->ctrl_handler);
<API key>(&subdev->entity);
<API key>(xhdmi->clk);
hdmi_dbg("removed.\n");
return 0;
}
static SIMPLE_DEV_PM_OPS(xhdmi_pm_ops, xhdmi_pm_suspend, xhdmi_pm_resume);
static const struct of_device_id xhdmi_of_id_table[] = {
{ .compatible = "xlnx,v-hdmi-rx-ss-2.0" },
{ }
};
MODULE_DEVICE_TABLE(of, xhdmi_of_id_table);
static struct platform_driver xhdmi_driver = {
.driver = {
.name = "xilinx-hdmi-rx",
.pm = &xhdmi_pm_ops,
.of_match_table = xhdmi_of_id_table,
},
.probe = xhdmi_probe,
.remove = xhdmi_remove,
};
<API key>(xhdmi_driver);
MODULE_DESCRIPTION("Xilinx HDMI RXSS V4L2 driver");
MODULE_AUTHOR("Leon Woestenberg <leon@sidebranch.com>");
MODULE_LICENSE("GPL v2"); |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="ru">
<head>
<title>HideObjRecord (POI API Documentation)</title>
<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="HideObjRecord (POI API Documentation)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/HideObjRecord.html">Use</a></li>
<li><a href="package-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><a href="../../../../../org/apache/poi/hssf/record/HeaderRecord.html" title="class in org.apache.poi.hssf.record"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/hssf/record/<API key>.html" title="class in org.apache.poi.hssf.record"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hssf/record/HideObjRecord.html" target="_top">Frames</a></li>
<li><a href="HideObjRecord.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.apache.poi.hssf.record</div>
<h2 title="Class HideObjRecord" class="title">Class HideObjRecord</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><a href="../../../../../org/apache/poi/hssf/record/RecordBase.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.RecordBase</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.Record</a></li>
<li>
<ul class="inheritance">
<li><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">org.apache.poi.hssf.record.StandardRecord</a></li>
<li>
<ul class="inheritance">
<li>org.apache.poi.hssf.record.HideObjRecord</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public final class <span class="strong">HideObjRecord</span>
extends <a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></pre>
<div class="block">Title: Hide Object Record<P>
Description: flag defines whether to hide placeholders and object<P>
REFERENCE: PG 321 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)<P></div>
<dl><dt><span class="strong">Version:</span></dt>
<dd>2.0-pre</dd>
<dt><span class="strong">Author:</span></dt>
<dd>Andrew C. Oliver (acoliver at apache dot org)</dd></dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_summary">
</a>
<h3>Field Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#HIDE_ALL">HIDE_ALL</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_ALL">SHOW_ALL</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_PLACEHOLDERS">SHOW_PLACEHOLDERS</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#sid">sid</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_summary">
</a>
<h3>Constructor Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#HideObjRecord()">HideObjRecord</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#HideObjRecord(org.apache.poi.hssf.record.RecordInputStream)">HideObjRecord</a></strong>(<a href="../../../../../org/apache/poi/hssf/record/RecordInputStream.html" title="class in org.apache.poi.hssf.record">RecordInputStream</a> in)</code> </td>
</tr>
</table>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected int</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#getDataSize()">getDataSize</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#getHideObj()">getHideObj</a></strong>()</code>
<div class="block">get hide object options</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>short</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#getSid()">getSid</a></strong>()</code>
<div class="block">return the non static version of the id for this record.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">serialize</a></strong>(<a href="../../../../../org/apache/poi/util/LittleEndianOutput.html" title="interface in org.apache.poi.util">LittleEndianOutput</a> out)</code>
<div class="block">Write the data content of this BIFF record.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#setHideObj(short)">setHideObj</a></strong>(short hide)</code>
<div class="block">set hide object options</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>java.lang.String</code></td>
<td class="colLast"><code><strong><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#toString()">toString</a></strong>()</code>
<div class="block">get a string representation of the record (for biffview/debugging)</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="<API key>.apache.poi.hssf.record.StandardRecord">
</a>
<h3>Methods inherited from class org.apache.poi.hssf.record.<a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></h3>
<code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html#getRecordSize()">getRecordSize</a>, <a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(int, byte[])">serialize</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="<API key>.apache.poi.hssf.record.Record">
</a>
<h3>Methods inherited from class org.apache.poi.hssf.record.<a href="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></h3>
<code><a href="../../../../../org/apache/poi/hssf/record/Record.html#clone()">clone</a>, <a href="../../../../../org/apache/poi/hssf/record/Record.html#cloneViaReserialise()">cloneViaReserialise</a>, <a href="../../../../../org/apache/poi/hssf/record/Record.html#serialize()">serialize</a></code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="<API key>.lang.Object">
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field_detail">
</a>
<h3>Field Detail</h3>
<a name="sid">
</a>
<ul class="blockList">
<li class="blockList">
<h4>sid</h4>
<pre>public static final short sid</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#org.apache.poi.hssf.record.HideObjRecord.sid">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="HIDE_ALL">
</a>
<ul class="blockList">
<li class="blockList">
<h4>HIDE_ALL</h4>
<pre>public static final short HIDE_ALL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#org.apache.poi.hssf.record.HideObjRecord.HIDE_ALL">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="SHOW_PLACEHOLDERS">
</a>
<ul class="blockList">
<li class="blockList">
<h4>SHOW_PLACEHOLDERS</h4>
<pre>public static final short SHOW_PLACEHOLDERS</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#org.apache.poi.hssf.record.HideObjRecord.SHOW_PLACEHOLDERS">Constant Field Values</a></dd></dl>
</li>
</ul>
<a name="SHOW_ALL">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>SHOW_ALL</h4>
<pre>public static final short SHOW_ALL</pre>
<dl><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../constant-values.html#org.apache.poi.hssf.record.HideObjRecord.SHOW_ALL">Constant Field Values</a></dd></dl>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="constructor_detail">
</a>
<h3>Constructor Detail</h3>
<a name="HideObjRecord()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>HideObjRecord</h4>
<pre>public HideObjRecord()</pre>
</li>
</ul>
<a name="HideObjRecord(org.apache.poi.hssf.record.RecordInputStream)">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>HideObjRecord</h4>
<pre>public HideObjRecord(<a href="../../../../../org/apache/poi/hssf/record/RecordInputStream.html" title="class in org.apache.poi.hssf.record">RecordInputStream</a> in)</pre>
</li>
</ul>
</li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="setHideObj(short)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>setHideObj</h4>
<pre>public void setHideObj(short hide)</pre>
<div class="block">set hide object options</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>hide</code> - options</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#HIDE_ALL"><code>HIDE_ALL</code></a>,
<a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_PLACEHOLDERS"><code>SHOW_PLACEHOLDERS</code></a>,
<a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_ALL"><code>SHOW_ALL</code></a></dd></dl>
</li>
</ul>
<a name="getHideObj()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getHideObj</h4>
<pre>public short getHideObj()</pre>
<div class="block">get hide object options</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>hide options</dd><dt><span class="strong">See Also:</span></dt><dd><a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#HIDE_ALL"><code>HIDE_ALL</code></a>,
<a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_PLACEHOLDERS"><code>SHOW_PLACEHOLDERS</code></a>,
<a href="../../../../../org/apache/poi/hssf/record/HideObjRecord.html#SHOW_ALL"><code>SHOW_ALL</code></a></dd></dl>
</li>
</ul>
<a name="toString()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>toString</h4>
<pre>public java.lang.String toString()</pre>
<div class="block"><strong>Description copied from class: <code><a href="../../../../../org/apache/poi/hssf/record/Record.html#toString()">Record</a></code></strong></div>
<div class="block">get a string representation of the record (for biffview/debugging)</div>
<dl>
<dt><strong>Overrides:</strong></dt>
<dd><code><a href="../../../../../org/apache/poi/hssf/record/Record.html#toString()">toString</a></code> in class <code><a href="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></code></dd>
</dl>
</li>
</ul>
<a name="serialize(org.apache.poi.util.LittleEndianOutput)">
</a>
<ul class="blockList">
<li class="blockList">
<h4>serialize</h4>
<pre>public void serialize(<a href="../../../../../org/apache/poi/util/LittleEndianOutput.html" title="interface in org.apache.poi.util">LittleEndianOutput</a> out)</pre>
<div class="block"><strong>Description copied from class: <code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">StandardRecord</a></code></strong></div>
<div class="block">Write the data content of this BIFF record. The 'ushort sid' and 'ushort size' header fields
have already been written by the superclass.<br/>
The number of bytes written must equal the record size reported by
<a href="../../../../../org/apache/poi/hssf/record/RecordBase.html#getRecordSize()"><code>RecordBase.getRecordSize()</code></a>} minus four
( record header consiting of a 'ushort sid' and 'ushort reclength' has already been written
by thye superclass).</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html#serialize(org.apache.poi.util.LittleEndianOutput)">serialize</a></code> in class <code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></code></dd>
</dl>
</li>
</ul>
<a name="getDataSize()">
</a>
<ul class="blockList">
<li class="blockList">
<h4>getDataSize</h4>
<pre>protected int getDataSize()</pre>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html#getDataSize()">getDataSize</a></code> in class <code><a href="../../../../../org/apache/poi/hssf/record/StandardRecord.html" title="class in org.apache.poi.hssf.record">StandardRecord</a></code></dd>
</dl>
</li>
</ul>
<a name="getSid()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getSid</h4>
<pre>public short getSid()</pre>
<div class="block"><strong>Description copied from class: <code><a href="../../../../../org/apache/poi/hssf/record/Record.html#getSid()">Record</a></code></strong></div>
<div class="block">return the non static version of the id for this record.</div>
<dl>
<dt><strong>Specified by:</strong></dt>
<dd><code><a href="../../../../../org/apache/poi/hssf/record/Record.html#getSid()">getSid</a></code> in class <code><a href="../../../../../org/apache/poi/hssf/record/Record.html" title="class in org.apache.poi.hssf.record">Record</a></code></dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</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 class="navBarCell1Rev">Class</li>
<li><a href="class-use/HideObjRecord.html">Use</a></li>
<li><a href="package-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><a href="../../../../../org/apache/poi/hssf/record/HeaderRecord.html" title="class in org.apache.poi.hssf.record"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../../org/apache/poi/hssf/record/<API key>.html" title="class in org.apache.poi.hssf.record"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/poi/hssf/record/HideObjRecord.html" target="_top">Frames</a></li>
<li><a href="HideObjRecord.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field_summary">Field</a> | </li>
<li><a href="#constructor_summary">Constr</a> | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field_detail">Field</a> | </li>
<li><a href="#constructor_detail">Constr</a> | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
<p class="legalCopy"><small>
<i>Copyright 2014 The Apache Software Foundation or
its licensors, as applicable.</i>
</small></p>
</body>
</html> |
<?php
/**
* The template for displaying the footer
*
* Contains footer content and the closing of the #main and #page div elements.
*
* @package WordPress
* @subpackage Twenty_Thirteen
* @since Twenty Thirteen 1.0
*/
?>
</div><!-- #main -->
<footer id="colophon" class="site-footer" role="contentinfo">
<div class="footer-inner">
<img src="http://wordpress.local:8080/wp-content/uploads/2015/03/footer.gif">
</div>
<div align="right">
<a href="
<a href="
</div>
<?//php get_sidebar( 'main' ); ?>
<div class="site-info">
<?php do_action( '<API key>' ); ?>
<a href="<?php echo esc_url( __( 'http:
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="<?php echo <API key>(); ?>/js/jquery.bxslider.js"></script>
<?php wp_footer(); ?>
</body>
</html> |
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include <string.h>
#include <assert.h>
#include <vlc_common.h>
#include <vlc_dialog.h>
#include <vlc_modules.h>
#include <vlc_aout.h>
#include <vlc_filter.h>
#include <vlc_vout.h> /* for vout_Request */
#include <vlc_input.h>
#include <libvlc.h>
#include "aout_internal.h"
static filter_t *CreateFilter (vlc_object_t *obj, const char *type,
const char *name, filter_owner_sys_t *owner,
const <API key> *infmt,
const <API key> *outfmt)
{
filter_t *filter = vlc_custom_create (obj, sizeof (*filter), type);
if (unlikely(filter == NULL))
return NULL;
filter->p_owner = owner;
filter->fmt_in.audio = *infmt;
filter->fmt_in.i_codec = infmt->i_format;
filter->fmt_out.audio = *outfmt;
filter->fmt_out.i_codec = outfmt->i_format;
filter->p_module = module_need (filter, type, name, false);
if (filter->p_module == NULL)
{
/* If probing failed, formats shall not have been modified. */
assert (AOUT_FMTS_IDENTICAL(&filter->fmt_in.audio, infmt));
assert (AOUT_FMTS_IDENTICAL(&filter->fmt_out.audio, outfmt));
vlc_object_release (filter);
filter = NULL;
}
else
assert (filter->pf_audio_filter != NULL);
return filter;
}
static filter_t *FindConverter (vlc_object_t *obj,
const <API key> *infmt,
const <API key> *outfmt)
{
return CreateFilter (obj, "audio converter", NULL, NULL, infmt, outfmt);
}
static filter_t *FindResampler (vlc_object_t *obj,
const <API key> *infmt,
const <API key> *outfmt)
{
return CreateFilter (obj, "audio resampler", "$audio-resampler", NULL,
infmt, outfmt);
}
/**
* Destroys a chain of audio filters.
*/
static void <API key>(filter_t *const *filters, unsigned n)
{
for( unsigned i = 0; i < n; i++ )
{
filter_t *p_filter = filters[i];
module_unneed( p_filter, p_filter->p_module );
vlc_object_release( p_filter );
}
}
static filter_t *TryFormat (vlc_object_t *obj, vlc_fourcc_t codec,
<API key> *restrict fmt)
{
<API key> output = *fmt;
assert (codec != fmt->i_format);
output.i_format = codec;
aout_FormatPrepare (&output);
filter_t *filter = FindConverter (obj, fmt, &output);
if (filter != NULL)
*fmt = output;
return filter;
}
/**
* Allocates audio format conversion filters
* @param obj parent VLC object for new filters
* @param filters table of filters [IN/OUT]
* @param count pointer to the number of filters in the table [IN/OUT]
* @param max size of filters table [IN]
* @param infmt input audio format
* @param outfmt output audio format
* @return 0 on success, -1 on failure
*/
static int <API key>(vlc_object_t *obj, filter_t **filters,
unsigned *count, unsigned max,
const <API key> *restrict infmt,
const <API key> *restrict outfmt)
{
aout_FormatsPrint (obj, "conversion:", infmt, outfmt);
max -= *count;
filters += *count;
/* There is a lot of second guessing on what the conversion plugins can
* and cannot do. This seems hardly avoidable, the conversion problem need
* to be reduced somehow. */
<API key> input = *infmt;
unsigned n = 0;
/* Encapsulate or decode non-linear formats */
if (!AOUT_FMT_LINEAR(infmt) && infmt->i_format != outfmt->i_format)
{
if (n == max)
goto overflow;
filter_t *f = TryFormat (obj, VLC_CODEC_S32N, &input);
if (f == NULL)
f = TryFormat (obj, VLC_CODEC_FL32, &input);
if (f == NULL)
{
msg_Err (obj, "cannot find %s for conversion pipeline",
"decoder");
goto error;
}
filters[n++] = f;
}
assert (AOUT_FMT_LINEAR(&input));
/* Remix channels */
if (infmt->i_physical_channels != outfmt->i_physical_channels
|| infmt->i_original_channels != outfmt->i_original_channels)
{ /* Remixing currently requires FL32... TODO: S16N */
if (input.i_format != VLC_CODEC_FL32)
{
if (n == max)
goto overflow;
filter_t *f = TryFormat (obj, VLC_CODEC_FL32, &input);
if (f == NULL)
{
msg_Err (obj, "cannot find %s for conversion pipeline",
"pre-mix converter");
goto error;
}
filters[n++] = f;
}
if (n == max)
goto overflow;
<API key> output;
output.i_format = input.i_format;
output.i_rate = input.i_rate;
output.i_physical_channels = outfmt->i_physical_channels;
output.i_original_channels = outfmt->i_original_channels;
aout_FormatPrepare (&output);
filter_t *f = FindConverter (obj, &input, &output);
if (f == NULL)
{
msg_Err (obj, "cannot find %s for conversion pipeline",
"remixer");
goto error;
}
input = output;
filters[n++] = f;
}
/* Resample */
if (input.i_rate != outfmt->i_rate)
{ /* Resampling works with any linear format, but may be ugly. */
if (n == max)
goto overflow;
<API key> output = input;
output.i_rate = outfmt->i_rate;
filter_t *f = FindConverter (obj, &input, &output);
if (f == NULL)
{
msg_Err (obj, "cannot find %s for conversion pipeline",
"resampler");
goto error;
}
input = output;
filters[n++] = f;
}
/* Format */
if (input.i_format != outfmt->i_format)
{
if (max == 0)
goto overflow;
filter_t *f = TryFormat (obj, outfmt->i_format, &input);
if (f == NULL)
{
msg_Err (obj, "cannot find %s for conversion pipeline",
"post-mix converter");
goto error;
}
filters[n++] = f;
}
msg_Dbg (obj, "conversion pipeline complete");
*count += n;
return 0;
overflow:
msg_Err (obj, "maximum of %u conversion filters reached", max);
dialog_Fatal (obj, _("Audio filtering failed"),
_("The maximum number of filters (%u) was reached."), max);
error:
<API key> (filters, n);
return -1;
}
/**
* Filters an audio buffer through a chain of filters.
*/
static block_t *<API key>(filter_t *const *filters,
unsigned count, block_t *block)
{
/* TODO: use filter chain */
for (unsigned i = 0; (i < count) && (block != NULL); i++)
{
filter_t *filter = filters[i];
/* Please note that p_block->i_nb_samples & i_buffer
* shall be set by the filter plug-in. */
block = filter->pf_audio_filter (filter, block);
}
return block;
}
#define AOUT_MAX_FILTERS 10
struct aout_filters
{
filter_t *rate_filter; /**< The filter adjusting samples count
(either the scaletempo filter or a resampler) */
filter_t *resampler; /**< The resampler */
int resampling; /**< Current resampling (Hz) */
unsigned count; /**< Number of filters */
filter_t *tab[AOUT_MAX_FILTERS]; /**< Configured user filters
(e.g. equalization) and their conversions */
};
/** Callback for visualization selection */
static int <API key> (vlc_object_t *obj, const char *var,
vlc_value_t oldval, vlc_value_t newval,
void *data)
{
const char *mode = newval.psz_string;
if (!*mode)
mode = "none";
/* FIXME: This ugly hack enforced by visual effect-list, as is the need for
* separate "visual" (external) and "audio-visual" (internal) variables...
* The visual plugin should have one submodule per effect instead. */
if (strcasecmp (mode, "none") && strcasecmp (mode, "goom")
&& strcasecmp (mode, "projectm") && strcasecmp (mode, "vsxu")
&& strcasecmp (mode, "glspectrum"))
{
var_Create (obj, "effect-list", VLC_VAR_STRING);
var_SetString (obj, "effect-list", mode);
mode = "visual";
}
var_SetString (obj, "audio-visual", mode);
<API key> ((audio_output_t *)obj);
(void) var; (void) oldval; (void) data;
return VLC_SUCCESS;
}
static int EqualizerCallback (vlc_object_t *obj, const char *var,
vlc_value_t oldval, vlc_value_t newval,
void *data)
{
const char *val = newval.psz_string;
if (!strcmp("equalizer", var) && *val)
{
var_Create (obj, "equalizer-preset", VLC_VAR_STRING);
var_SetString (obj, "equalizer-preset", val);
}
if (<API key> (obj, obj, "audio-filter", "equalizer", *val))
<API key> ((audio_output_t *)obj); /* <- That sucks! */
(void) var; (void) oldval; (void) data;
return VLC_SUCCESS;
}
vout_thread_t *<API key> (filter_t *filter, vout_thread_t *vout,
video_format_t *fmt)
{
/* NOTE: This only works from aout_filters_t.
* If you want to use visualization filters from another place, you will
* need to add a new <API key> callback or store a pointer
* to aout_request_vout_t inside filter_t (i.e. a level of indirection). */
const aout_request_vout_t *req = (void *)filter->p_owner;
char *visual = var_InheritString (filter->p_parent, "audio-visual");
/* NOTE: Disable recycling to always close the filter vout because OpenGL
* visualizations do not use this function to ask for a context. */
bool recycle = false;
free (visual);
return req->pf_request_vout (req->p_private, vout, fmt, recycle);
}
static int AppendFilter(vlc_object_t *obj, const char *type, const char *name,
aout_filters_t *restrict filters, const void *owner,
<API key> *restrict infmt,
const <API key> *restrict outfmt)
{
const unsigned max = sizeof (filters->tab) / sizeof (filters->tab[0]);
if (filters->count >= max)
{
msg_Err (obj, "maximum of %u filters reached", max);
return -1;
}
filter_t *filter = CreateFilter (obj, type, name,
(void *)owner, infmt, outfmt);
if (filter == NULL)
{
msg_Err (obj, "cannot add user %s \"%s\" (skipped)", type, name);
return -1;
}
/* convert to the filter input format if necessary */
if (<API key> (obj, filters->tab, &filters->count,
max - 1, infmt, &filter->fmt_in.audio))
{
msg_Err (filter, "cannot add user %s \"%s\" (skipped)", type, name);
module_unneed (filter, filter->p_module);
vlc_object_release (filter);
return -1;
}
assert (filters->count < max);
filters->tab[filters->count] = filter;
filters->count++;
*infmt = filter->fmt_out.audio;
return 0;
}
#undef aout_FiltersNew
/**
* Sets a chain of audio filters up.
* \param obj parent object for the filters
* \param infmt chain input format [IN]
* \param outfmt chain output format [IN]
* \param request_vout visualization video output request callback
* \return a filters chain or NULL on failure
*
* \note
* *request_vout (if not NULL) must remain valid until aout_FiltersDelete().
*
* \bug
* If request_vout is non NULL, obj is assumed to be an audio_output_t pointer.
*/
aout_filters_t *aout_FiltersNew (vlc_object_t *obj,
const <API key> *restrict infmt,
const <API key> *restrict outfmt,
const aout_request_vout_t *request_vout)
{
aout_filters_t *filters = malloc (sizeof (*filters));
if (unlikely(filters == NULL))
return NULL;
filters->rate_filter = NULL;
filters->resampler = NULL;
filters->resampling = 0;
filters->count = 0;
/* Prepare format structure */
aout_FormatPrint (obj, "input", infmt);
<API key> input_format = *infmt;
<API key> output_format = *outfmt;
/* Callbacks (before reading values and also before return statement) */
if (request_vout != NULL)
{
var_AddCallback (obj, "equalizer", EqualizerCallback, NULL);
var_AddCallback (obj, "equalizer-bands", EqualizerCallback, NULL);
var_AddCallback (obj, "visual", <API key>, NULL);
var_TriggerCallback( obj, "equalizer-bands" );
}
/* Now add user filters */
if (!AOUT_FMT_LINEAR(outfmt))
{ /* Non-linear output: just convert formats, no filters/visu */
if (!AOUT_FMTS_IDENTICAL(infmt, outfmt))
{
aout_FormatsPrint (obj, "pass-through:", infmt, outfmt);
filters->tab[0] = FindConverter(obj, infmt, outfmt);
if (filters->tab[0] == NULL)
{
msg_Err (obj, "cannot setup pass-through");
goto error;
}
filters->count++;
}
return filters;
}
/* parse user filter lists */
if (var_InheritBool (obj, "audio-time-stretch"))
{
if (AppendFilter(obj, "audio filter", "scaletempo",
filters, NULL, &input_format, &output_format) == 0)
filters->rate_filter = filters->tab[filters->count - 1];
}
char *str = var_InheritString (obj, "audio-filter");
if (str != NULL)
{
char *p = str, *name;
while ((name = strsep (&p, " :")) != NULL)
{
AppendFilter(obj, "audio filter", name, filters,
NULL, &input_format, &output_format);
}
free (str);
}
if (request_vout != NULL)
{
char *visual = var_InheritString (obj, "audio-visual");
if (visual != NULL && strcasecmp (visual, "none"))
AppendFilter(obj, "visualization", visual, filters,
request_vout, &input_format, &output_format);
free (visual);
}
/* convert to the output format (minus resampling) if necessary */
output_format.i_rate = input_format.i_rate;
if (<API key> (obj, filters->tab, &filters->count,
AOUT_MAX_FILTERS, &input_format, &output_format))
{
msg_Err (obj, "cannot setup filtering pipeline");
goto error;
}
input_format = output_format;
/* insert the resampler */
output_format.i_rate = outfmt->i_rate;
assert (AOUT_FMTS_IDENTICAL(&output_format, outfmt));
filters->resampler = FindResampler (obj, &input_format,
&output_format);
if (filters->resampler == NULL && input_format.i_rate != outfmt->i_rate)
{
msg_Err (obj, "cannot setup a resampler");
goto error;
}
if (filters->rate_filter == NULL)
filters->rate_filter = filters->resampler;
return filters;
error:
<API key> (filters->tab, filters->count);
var_DelCallback (obj, "equalizer", EqualizerCallback, NULL);
var_DelCallback (obj, "equalizer-bands", EqualizerCallback, NULL);
var_DelCallback (obj, "visual", <API key>, NULL);
free (filters);
return NULL;
}
#undef aout_FiltersDelete
/**
* Destroys a chain of audio filters.
* \param obj object used with aout_FiltersNew()
* \param filters chain to be destroyed
* \bug
* obj must be NULL iff request_vout was NULL in aout_FiltersNew()
* (this implies obj is an audio_output_t pointer if non NULL).
*/
void aout_FiltersDelete (vlc_object_t *obj, aout_filters_t *filters)
{
if (filters->resampler != NULL)
<API key> (&filters->resampler, 1);
<API key> (filters->tab, filters->count);
if (obj != NULL)
{
var_DelCallback (obj, "equalizer", EqualizerCallback, NULL);
var_DelCallback (obj, "equalizer-bands", EqualizerCallback, NULL);
var_DelCallback (obj, "visual", <API key>, NULL);
}
free (filters);
}
bool <API key> (aout_filters_t *filters, int adjust)
{
if (filters->resampler == NULL)
return false;
if (adjust)
filters->resampling += adjust;
else
filters->resampling = 0;
return filters->resampling != 0;
}
block_t *aout_FiltersPlay (aout_filters_t *filters, block_t *block, int rate)
{
int nominal_rate = 0;
if (rate != INPUT_RATE_DEFAULT)
{
filter_t *rate_filter = filters->rate_filter;
if (rate_filter == NULL)
goto drop; /* Without linear, non-nominal rate is impossible. */
/* Override input rate */
nominal_rate = rate_filter->fmt_in.audio.i_rate;
rate_filter->fmt_in.audio.i_rate =
(nominal_rate * INPUT_RATE_DEFAULT) / rate;
}
block = <API key> (filters->tab, filters->count, block);
if (filters->resampler != NULL)
{ /* NOTE: the resampler needs to run even if resampling is 0.
* The decoder and output rates can still be different. */
filters->resampler->fmt_in.audio.i_rate += filters->resampling;
block = <API key> (&filters->resampler, 1, block);
filters->resampler->fmt_in.audio.i_rate -= filters->resampling;
}
if (nominal_rate != 0)
{ /* Restore input rate */
assert (filters->rate_filter != NULL);
filters->rate_filter->fmt_in.audio.i_rate = nominal_rate;
}
return block;
drop:
block_Release (block);
return NULL;
} |
<?php
/**
* Re-create the thumbnails of all images
*/
elgg_require_js('tidypics/resize_thumbnails');
/* @var $count Integer */
$count = elgg_extract('count', $vars);
echo elgg_format_element('span', ['class' => 'hidden', 'id' => '<API key>'], $count);
echo elgg_format_element('span', ['class' => 'hidden', 'id' => '<API key>'], '0');
echo elgg_format_element('div', ['class' => 'elgg-progressbar mvl'],
elgg_format_element('span', ['class' => '<API key>', 'id' => '<API key>'], '0%')
);
echo elgg_format_element('ul', ['class' => 'mvl'],
elgg_format_element('li', [], elgg_echo('tidypics:resize_thumbnails:success_processed')
. elgg_format_element('span', ['id' => '<API key>'], '0'))
. elgg_format_element('li', [], elgg_echo('tidypics:resize_thumbnails:<API key>')
. elgg_format_element('span', ['id' => '<API key>'], '0'))
. elgg_format_element('li', [], elgg_echo('tidypics:resize_thumbnails:<API key>')
. elgg_format_element('span', ['id' => '<API key>'], '0'))
);
echo elgg_format_element('div', ['class' => 'elgg-ajax-loader hidden', 'id' => '<API key>'], '');
echo elgg_format_element('ul', ['class' => 'mvl', 'id' => '<API key>'], '');
$footer = elgg_view_field([
'#type' => 'submit',
'value' => elgg_echo('tidypics:settings:<API key>'),
'id' => '<API key>',
]);
<API key>($footer); |
/* $Id: <API key>.h 56295 2015-06-09 14:29:55Z vboxsync $ */
/** @file
* TestExecServ - Basic Remote Execution Service, Internal Header.
*/
#ifndef <API key>
#define <API key>
#include <iprt/getopt.h>
#include <iprt/stream.h>
RT_C_DECLS_BEGIN
/**
* Packet header.
*/
typedef struct TXSPKTHDR
{
/** The unpadded packet length. This include this header. */
uint32_t cb;
/** The CRC-32 for the packet starting from the opcode field. 0 if the packet
* hasn't been CRCed. */
uint32_t uCrc32;
/** Packet opcode, an unterminated ASCII string. */
uint8_t achOpcode[8];
} TXSPKTHDR;
AssertCompileSize(TXSPKTHDR, 16);
/** Pointer to a packet header. */
typedef TXSPKTHDR *PTXSPKTHDR;
/** Pointer to a packet header. */
typedef TXSPKTHDR const *PCTXSPKTHDR;
/** Pointer to a packet header pointer. */
typedef PTXSPKTHDR *PPTXSPKTHDR;
/** Packet alignment. */
#define TXSPKT_ALIGNMENT 16
/** Max packet size. */
#define TXSPKT_MAX_SIZE _256K
/**
* Transport layer descriptor.
*/
typedef struct TXSTRANSPORT
{
/** The name. */
char szName[16];
/** The description. */
const char *pszDesc;
/** Pointer to an array of options. */
PCRTGETOPTDEF paOpts;
/** The number of options in the array. */
size_t cOpts;
/**
* Print the usage information for this transport layer.
*
* @param pThis Pointer to the transport layer descriptor.
* @param pStream The stream to print the usage info to.
*
* @remarks This is only required if TXSTRANSPORT::cOpts is greater than 0.
*/
<API key>(void, pfnUsage,(PRTSTREAM pStream));
/**
* Handle an option.
*
* When encountering an options that is not part of the base options, we'll call
* this method for each transport layer until one handles it.
*
* @retval VINF_SUCCESS if handled.
* @retval VERR_TRY_AGAIN if not handled.
* @retval <API key> if we should exit with a non-zero status.
*
* @param pThis Pointer to the transport layer descriptor.
* @param ch The short option value.
* @param pVal Pointer to the value union.
*
* @remarks This is only required if TXSTRANSPORT::cOpts is greater than 0.
*/
<API key>(int, pfnOption,(int ch, PCRTGETOPTUNION pVal));
/**
* Initializes the transport layer.
*
* @returns IPRT status code. On errors, the transport layer shall call
* RTMsgError to display the error details to the user.
*/
<API key>(int, pfnInit,(void));
/**
* Terminate the transport layer, closing and freeing resources.
*
* On errors, the transport layer shall call RTMsgError to display the error
* details to the user.
*/
<API key>(void, pfnTerm,(void));
/**
* Polls for incoming packets.
*
* @returns true if there are pending packets, false if there isn't.
*/
<API key>(bool, pfnPollIn,(void));
/**
* Adds any pollable handles to the poll set.
*
* This is optional and layers that doesn't have anything that can be polled
* shall set this method pointer to NULL to indicate that pfnPollIn must be used
* instead.
*
* @returns IPRT status code.
* @param hPollSet The poll set to add them to.
* @param idStart The handle ID to start at.
*/
<API key>(int, pfnPollSetAdd,(RTPOLLSET hPollSet, uint32_t idStart));
/**
* Receives an incoming packet.
*
* This will block until the data becomes available or we're interrupted by a
* signal or something.
*
* @returns IPRT status code. On error conditions other than VERR_INTERRUPTED,
* the current operation will be aborted when applicable. When
* interrupted, the transport layer will store the data until the next
* receive call.
*
* @param ppPktHdr Where to return the pointer to the packet we've
* read. This is allocated from the heap using
* RTMemAlloc (w/ TXSPKT_ALIGNMENT) and must be
* free by calling RTMemFree.
*/
<API key>(int, pfnRecvPkt,(PPTXSPKTHDR ppPktHdr));
/**
* Sends an outgoing packet.
*
* This will block until the data has been written.
*
* @returns IPRT status code.
* @retval VERR_INTERRUPTED if interrupted before anything was sent.
*
* @param pPktHdr The packet to send. The size is given by
* aligning the size in the header by
* TXSPKT_ALIGNMENT.
*/
<API key>(int, pfnSendPkt,(PCTXSPKTHDR pPktHdr));
/**
* Sends a babble packet and disconnects the client (if applicable).
*
* @param pPktHdr The packet to send. The size is given by
* aligning the size in the header by
* TXSPKT_ALIGNMENT.
* @param cMsSendTimeout The send timeout measured in milliseconds.
*/
<API key>(void, pfnBabble,(PCTXSPKTHDR pPktHdr, RTMSINTERVAL cMsSendTimeout));
/**
* Notification about a client HOWDY.
*/
<API key>(void, pfnNotifyHowdy,(void));
/**
* Notification about a client BYE.
*
* For connection oriented transport layers, it would be good to disconnect the
* client at this point.
*/
<API key>(void, pfnNotifyBye,(void));
/**
* Notification about a REBOOT or SHUTDOWN.
*
* For connection oriented transport layers, stop listening for and
* accepting at this point.
*/
<API key>(void, pfnNotifyReboot,(void));
/** Non-zero end marker. */
uint32_t u32EndMarker;
} TXSTRANSPORT;
/** Pointer to a const transport layer descriptor. */
typedef const struct TXSTRANSPORT *PCTXSTRANSPORT;
extern TXSTRANSPORT const g_TcpTransport;
extern TXSTRANSPORT const g_SerialTransport;
extern TXSTRANSPORT const g_FileSysTransport;
extern TXSTRANSPORT const <API key>;
extern TXSTRANSPORT const g_TestDevTransport;
RT_C_DECLS_END
#endif |
using System;
using System.Collections;
using Server.Items;
using Server.Multis;
using Server.Mobiles;
using Server.Network;
namespace Server.Custom
{
public class CustomBag : Bag
{
public void EnhanceWeapon( Item item, string name )
{
if ( item is BaseWeapon )
{
BaseWeapon weap = item as BaseWeapon;
int num = Utility.Random( 3, 5 );
for (int count = 0; count<num; count++)
{
int attribute = Utility.RandomMinMax( 1, 25 );
switch( attribute )
{
case (int)<API key>.LowerStatReq:
{
weap.WeaponAttributes.LowerStatReq = Utility.RandomMinMax( 4, 10 );
goto case 99;
}
case (int)<API key>.SelfRepair:
{
weap.WeaponAttributes.SelfRepair = Utility.RandomMinMax( 3, 12 );
goto case 99;
}
case (int)<API key>.HitLeechHits:
{
weap.WeaponAttributes.HitLeechHits = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitLeechStam:
{
weap.WeaponAttributes.HitLeechStam = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitLeechMana:
{
weap.WeaponAttributes.HitLeechMana = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitLowerAttack:
{
weap.WeaponAttributes.HitLowerAttack = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitLowerDefend:
{
weap.WeaponAttributes.HitLowerDefend = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitMagicArrow:
{
weap.WeaponAttributes.HitMagicArrow = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitHarm:
{
weap.WeaponAttributes.HitHarm = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitFireball:
{
weap.WeaponAttributes.HitFireball = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitLightning:
{
weap.WeaponAttributes.HitLightning = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitDispel:
{
weap.WeaponAttributes.HitDispel = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.HitColdArea:
{
weap.WeaponAttributes.HitColdArea = Utility.RandomMinMax( 2, 16 );
goto case 99;
}
case (int)<API key>.HitFireArea:
{
weap.WeaponAttributes.HitFireArea = Utility.RandomMinMax( 2, 16 );
goto case 99;
}
case (int)<API key>.HitPoisonArea:
{
weap.WeaponAttributes.HitPoisonArea = Utility.RandomMinMax( 2, 16 );
goto case 99;
}
case (int)<API key>.HitEnergyArea:
{
weap.WeaponAttributes.HitEnergyArea = Utility.RandomMinMax( 2, 16 );
goto case 99;
}
case (int)<API key>.HitPhysicalArea:
{
weap.WeaponAttributes.HitPhysicalArea = Utility.RandomMinMax( 2, 16 );
goto case 99;
}
case (int)<API key>.ResistPhysicalBonus:
{
weap.WeaponAttributes.ResistPhysicalBonus = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.ResistFireBonus:
{
weap.WeaponAttributes.ResistFireBonus = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.ResistColdBonus:
{
weap.WeaponAttributes.ResistColdBonus = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.ResistPoisonBonus:
{
weap.WeaponAttributes.ResistPoisonBonus = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.ResistEnergyBonus:
{
weap.WeaponAttributes.ResistEnergyBonus = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.UseBestSkill:
{
weap.WeaponAttributes.UseBestSkill = 1;
goto case 99;
}
case (int)<API key>.MageWeapon:
{
weap.WeaponAttributes.MageWeapon = 1;
goto case 99;
}
case (int)<API key>.DurabilityBonus:
{
weap.WeaponAttributes.DurabilityBonus = Utility.RandomMinMax( 20, 50 );
goto case 99;
}
case 99:
{
weap.PropertyList.Add( name );
break;
}
default: break;
}
}
}
}
public void EnhanceArmor( Item item, string name )
{
if ( item is BaseArmor )
{
BaseArmor armor = item as BaseArmor;
int num = Utility.RandomMinMax( 3, 5 );
for (int count = 0; count<num; count++)
{
int attribute = Utility.RandomMinMax( 1, 25 );
switch( attribute )
{
case (int)<API key>.RegenHits:
{
armor.Attributes.RegenHits = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.RegenStam:
{
armor.Attributes.RegenStam = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.RegenMana:
{
armor.Attributes.RegenMana = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.DefendChance:
{
armor.Attributes.DefendChance = Utility.RandomMinMax( 5, 40 );
goto case 99;
}
case (int)<API key>.AttackChance:
{
armor.Attributes.AttackChance = Utility.RandomMinMax( 5, 40 );
goto case 99;
}
case (int)<API key>.BonusStr:
{
armor.Attributes.BonusStr = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusDex:
{
armor.Attributes.BonusDex = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusInt:
{
armor.Attributes.BonusInt = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusHits:
{
armor.Attributes.BonusHits = Utility.RandomMinMax( 5, 50 );
goto case 99;
}
case (int)<API key>.BonusStam:
{
armor.Attributes.BonusStam = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.BonusMana:
{
armor.Attributes.BonusMana = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.WeaponDamage:
{
armor.Attributes.WeaponDamage = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.WeaponSpeed:
{
armor.Attributes.WeaponSpeed = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.SpellDamage:
{
armor.Attributes.SpellDamage = Utility.RandomMinMax( 10, 40 );
goto case 99;
}
case (int)<API key>.CastRecovery:
{
armor.Attributes.CastRecovery = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.CastSpeed:
{
armor.Attributes.CastSpeed = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.LowerManaCost:
{
armor.Attributes.LowerManaCost = Utility.RandomMinMax( 4, 30 );
goto case 99;
}
case (int)<API key>.LowerRegCost:
{
armor.Attributes.LowerRegCost = Utility.RandomMinMax( 10, 25 );
goto case 99;
}
case (int)<API key>.ReflectPhysical:
{
armor.Attributes.ReflectPhysical = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.EnhancePotions:
{
armor.Attributes.EnhancePotions = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.Luck:
{
armor.Attributes.Luck = Utility.RandomMinMax( 10, 200 );
goto case 99;
}
case (int)<API key>.SpellChanneling:
{
armor.Attributes.SpellChanneling = 1;
goto case 99;
}
case (int)<API key>.NightSight:
{
armor.Attributes.NightSight = 1;
goto case 99;
}
case 99:
{
armor.PropertyList.Add( name );
break;
}
default: break;
}
}
}
}
public void EnhanceJewel( Item item, string name )
{
if ( item is BaseJewel )
{
BaseJewel jewel = item as BaseJewel;
int num = Utility.RandomMinMax( 3, 5 );
for (int count = 0; count<num; count++)
{
int attribute = Utility.RandomMinMax( 1, 24 );
switch( attribute )
{
case (int)<API key>.RegenHits:
{
jewel.Attributes.RegenHits = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.RegenStam:
{
jewel.Attributes.RegenStam = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.RegenMana:
{
jewel.Attributes.RegenMana = Utility.RandomMinMax( 5, 25 );
goto case 99;
}
case (int)<API key>.DefendChance:
{
jewel.Attributes.DefendChance = Utility.RandomMinMax( 5, 40 );
goto case 99;
}
case (int)<API key>.AttackChance:
{
jewel.Attributes.AttackChance = Utility.RandomMinMax( 5, 40 );
goto case 99;
}
case (int)<API key>.BonusStr:
{
jewel.Attributes.BonusStr = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusDex:
{
jewel.Attributes.BonusDex = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusInt:
{
jewel.Attributes.BonusInt = Utility.RandomMinMax( 2, 20 );
goto case 99;
}
case (int)<API key>.BonusHits:
{
jewel.Attributes.BonusHits = Utility.RandomMinMax( 5, 50 );
goto case 99;
}
case (int)<API key>.BonusStam:
{
jewel.Attributes.BonusStam = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.BonusMana:
{
jewel.Attributes.BonusMana = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.WeaponDamage:
{
jewel.Attributes.WeaponDamage = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.WeaponSpeed:
{
jewel.Attributes.WeaponSpeed = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.SpellDamage:
{
jewel.Attributes.SpellDamage = Utility.RandomMinMax( 10, 40 );
goto case 99;
}
case (int)<API key>.CastRecovery:
{
jewel.Attributes.CastRecovery = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.CastSpeed:
{
jewel.Attributes.CastSpeed = Utility.RandomMinMax( 5, 30 );
goto case 99;
}
case (int)<API key>.LowerManaCost:
{
jewel.Attributes.LowerManaCost = Utility.RandomMinMax( 4, 30 );
goto case 99;
}
case (int)<API key>.LowerRegCost:
{
jewel.Attributes.LowerRegCost = Utility.RandomMinMax( 10, 25 );
goto case 99;
}
case (int)<API key>.ReflectPhysical:
{
jewel.Attributes.ReflectPhysical = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.EnhancePotions:
{
jewel.Attributes.EnhancePotions = Utility.RandomMinMax( 10, 50 );
goto case 99;
}
case (int)<API key>.Luck:
{
jewel.Attributes.Luck = Utility.RandomMinMax( 10, 200 );
goto case 99;
}
case (int)<API key>.NightSight:
{
jewel.Attributes.NightSight = 1;
goto case 99;
}
case 99:
{
jewel.PropertyList.Add( name );
break;
}
default: break;
}
}
}
}
[Constructable]
public CustomBag() : base()
{
Name = "Custom Bag";
Weight = 2.0;
}
public CustomBag( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
}
} |
#!/bin/bash
# This program is free software; you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#text colors
export BLUE='\033[1;94m'
export GREEN='\033[1;92m'
export RED='\e[0;31m'
export NORMAL='\033[1;00m'
err_echo () #echo on stderr
{
>&2 echo -e "$*"
}
err ()
{
err_echo $RED"[!] "$*$NORMAL
}
inf ()
{
err_echo $BLUE"[*] "$*$NORMAL
}
ok ()
{
err_echo $BLUE"[+] "$*$NORMAL
}
control () #check argv
{
for arg
do
if [ "$arg" = "-h" -o "$arg" = "--help" ]; then export h="TRUE";
elif [ "$arg" = "-u" -o "$arg" = "--upgrade" ]; then export u="TRUE";
elif [ "$arg" = "-d" -o "$arg" = "--dist-upgrade" ]; then export d="TRUE";
else help
fi
done
}
help()
{
err_echo "Use: "$0" [options]\n"
err_echo "Options:"
err_echo "-h, --help Show this screen and exit"
err_echo "-u, --upgrade Upgrades packages"
err_echo "-d, --dist-upgrade Upgrade your operating system\n"
exit 1
}
ARGC="$
if [ $ARGC -eq 0 ]
then
help
else
control $*
if [ -n "$h" ] || [ -z "$u" ] && [ -z "$d" ]; then help; fi
if [ `id -u` -eq 0 ] #if it is run as root
then
inf "Ongoing updates..."
apt-get update
if [ $u ]; then apt-get -y upgrade; fi
if [ $d ]; then apt-get -y dist-upgrade; fi
if [ $? -eq 0 ]; then ok "Successful updates!"; fi
else
err "This script must be run as root!"
exit 1
fi
fi
exit 0 |
#ifndef __BATTLEGROUNDWS_H
#define __BATTLEGROUNDWS_H
#include "BattleGround.h"
#define <API key> 3
#define <API key> (23*IN_MILLISECONDS)
#define <API key> (10*IN_MILLISECONDS)
#define BG_WS_TIME_LIMIT (25*MINUTE*IN_MILLISECONDS)
#define <API key> 8563
enum BG_WS_Sound
{
<API key> = 8173,
<API key> = 8213,
<API key> = 8232,
<API key> = 8192,
<API key> = 8212,
<API key> = 8174,
<API key> = 8232
};
enum BG_WS_SpellId
{
<API key> = 23333,
<API key> = 23334,
<API key> = 23335,
<API key> = 23336
};
enum BG_WS_WorldStates
{
<API key> = 1545,
<API key> = 1546,
// FLAG_UNK = 1547,
<API key> = 1581,
<API key> = 1582,
<API key> = 1601,
<API key> = 2338,
<API key> = 2339,
BG_WS_TIME_ENABLED = 4247,
<API key> = 4248
};
enum BG_WS_FlagState
{
<API key> = 0,
<API key> = 1,
<API key> = 2,
<API key> = 3
};
enum BG_WS_Graveyards
{
<API key> = 769,
<API key> = 770,
<API key> = 771,
<API key> = 772
};
class BattleGroundWGScore : public BattleGroundScore
{
public:
BattleGroundWGScore() : FlagCaptures(0), FlagReturns(0) {};
virtual ~BattleGroundWGScore() {};
uint32 FlagCaptures;
uint32 FlagReturns;
};
enum BG_WS_Events
{
WS_EVENT_FLAG_A = 0,
WS_EVENT_FLAG_H = 1,
// spiritguides will spawn (same moment, like WS_EVENT_DOOR_OPEN)
<API key> = 2
};
class BattleGroundWS : public BattleGround
{
friend class BattleGroundMgr;
public:
/* Construction */
BattleGroundWS();
~BattleGroundWS();
void Update(uint32 diff) override;
/* inherited from BattlegroundClass */
virtual void AddPlayer(Player* plr) override;
virtual void <API key>() override;
virtual void <API key>() override;
/* BG Flags */
ObjectGuid <API key>() const { return <API key>; }
ObjectGuid <API key>() const { return m_flagCarrierHorde; }
void <API key>(ObjectGuid guid) { <API key> = guid; }
void SetHordeFlagCarrier(ObjectGuid guid) { m_flagCarrierHorde = guid; }
void <API key>() { <API key>.Clear(); }
void <API key>() { m_flagCarrierHorde.Clear(); }
bool <API key>() const { return !<API key>.IsEmpty(); }
bool IsHordeFlagPickedUp() const { return !m_flagCarrierHorde.IsEmpty(); }
void RespawnFlag(Team team, bool captured);
void RespawnDroppedFlag(Team team);
uint8 GetFlagState(Team team) { return m_FlagState[<API key>(team)]; }
/* Battleground Events */
virtual void <API key>(Player* source) override;
virtual void <API key>(Player* source, GameObject* target_obj) override;
virtual void <API key>(Player* source) override;
void RemovePlayer(Player* plr, ObjectGuid guid) override;
void HandleAreaTrigger(Player* source, uint32 trigger) override;
void HandleKillPlayer(Player* player, Player* killer) override;
bool SetupBattleGround() override;
virtual void Reset() override;
void EndBattleGround(Team winner) override;
virtual WorldSafeLocsEntry const* GetClosestGraveYard(Player* player) override;
uint32 <API key>() { return m_EndTimer ? (m_EndTimer - 1) / (MINUTE * IN_MILLISECONDS) + 1 : 0; }
void UpdateFlagState(Team team, uint32 value);
void UpdateTeamScore(Team team);
void UpdatePlayerScore(Player* source, uint32 type, uint32 value) override;
void SetDroppedFlagGuid(ObjectGuid guid, Team team) { m_DroppedFlagGuid[<API key>(team)] = guid;}
void <API key>(Team team) { m_DroppedFlagGuid[<API key>(team)].Clear();}
ObjectGuid const& GetDroppedFlagGuid(Team team) const { return m_DroppedFlagGuid[<API key>(team)];}
virtual void <API key>(WorldPacket& data, uint32& count) override;
private:
ObjectGuid <API key>;
ObjectGuid m_flagCarrierHorde;
ObjectGuid m_DroppedFlagGuid[BG_TEAMS_COUNT];
uint8 m_FlagState[BG_TEAMS_COUNT];
int32 m_FlagsTimer[BG_TEAMS_COUNT];
int32 m_FlagsDropTimer[BG_TEAMS_COUNT];
uint32 m_ReputationCapture;
uint32 m_HonorWinKills;
uint32 m_HonorEndKills;
uint32 m_EndTimer;
Team <API key>;
};
#endif |
# Sloan Digital Sky Survey III (SDSS-III)
# Code for product: idlutils
# IDL utilities for image analysis
# M.R. Blanton
# This Makefile & all Makefiles in this product are GNU make compliant.
# Please help keep them that way. See
# $Id: Makefile 130264 2012-02-10 19:06:45Z weaver $
# Pass these flags to the C compiler
# SDSS_CFLAGS X_CFLAGS X_LD_FLAGS SO_EXT are defined by evilmake
# CCCHK is NOT defined by evilmake but is defined by sdssmake
# CCCHK = -Wall is the standard for Linux
INC = $(IDLUTILS_DIR)/include
LIB = $(IDLUTILS_DIR)/lib
CFLAGS = $(SDSS_CFLAGS) -DCHECK_LEAKS -I$(INC)
CCCHK = -Wall
# How to make objects from c files
%.o : %.c
$(CC) -c $(CCCHK) $(CFLAGS) $(X_CFLAGS) $<
# Objects to compile
OBJECTS = \
idl_dmedsmooth.o \
dmedsmooth.o \
dselip.o \
dfind.o \
idl_dsmooth.o \
dsmooth.o \
dsigma.o \
idl_dobjects_multi.o \
dobjects_multi.o
# SDSS-III Makefiles should always define this target.
all : $(LIB)/libdimage.$(SO_EXT)
$(LIB)/libdimage.$(SO_EXT): $(OBJECTS)
$(LD) $(X_LD_FLAGS) -o $(LIB)/libdimage.$(SO_EXT) $(OBJECTS)
# nm -s .$(LIB)/libdimage.$(SO_EXT)
# GNU make pre-defines $(RM). The - in front of $(RM) causes make to
# ignore any errors produced by $(RM).
clean :
- $(RM) *~ core *.o $(LIB)/libdimage.$(SO_EXT) |
<?php get_header(); ?>
<?php get_template_part('sub-header'); ?>
<?php
$term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );
query_posts( array( 'post_type'=>'putovanja', 'kategorija' => $term->name, 'terms' => 'izdvojeno-iz-ponude', 'posts_per_page'=>-1, 'paged'=>$paged ) );
?>
<!-- START #main -->
<section id="main" class="clearfix">
<!-- START #content -->
<section id="content">
<header>
<h1>Izdvojeno iz ponude</h1>
</header>
<article id="post-content" class="clearfix">
<ul>
<?php if (have_posts()): while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink() ?>" title="Više o <?php the_title_attribute(); ?>">
<figure>
<?php
if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
the_post_thumbnail(array(255,157));
}
else echo '<img src="' . <API key>() . '/img/default-thumb.png" alt="thumb" />';
?>
<figcaption>
<hgroup>
<h1><?php the_title(); ?></h1>
<h2><?php $meta_values = get_post_meta($post->ID, 'meta_dana', true); echo $meta_values; ?> dana, putovanje <?php $meta_values = get_post_meta($post->ID, 'meta_putovanje', true); echo $meta_values; ?><br>
termini: <span><?php $meta_values = get_post_meta($post->ID, 'meta_termini', true); echo $meta_values; ?></span></h2>
</hgroup>
<div class="price">
<span>Cijena:</span> <strong><?php $meta_values = get_post_meta($post->ID, 'meta_cijena', true); echo $meta_values; ?> kn</strong>
</div>
<div class="more">više</div>
</figcaption>
</figure>
</a>
</li>
<?php endwhile; ?>
</ul>
<?php //get_template_part('pagination'); ?>
</article>
<?php else: ?>
<p class="not-found">Dogodila se greška.</p>
<?php endif; ?>
</section>
<?php get_sidebar(); ?>
<?php get_footer(); ?> |
.page-products .<API key> .view-content .views-row {
float: left;
width: 145px;
border: 1px solid #A0A0A0;
margin-right: 5px;
margin-bottom: 10px;
padding: 0 8px;
}
.page-products .<API key> .view-content .views-row.views-row-colnum-0 {
clear: both;
}
.page-products .<API key> .view-content .views-row.views-row-colnum-3 {
margin-right: 0;
}
.page-products .<API key> .view-content .views-row .node {
border-bottom: none;
margin-bottom: 0;
padding-bottom: 0;
}
.page-products .<API key> .view-content .views-row .node .<API key> {
text-align: center;
}
.page-products #content .section {
padding: 0 23px 1px 21px;
}
#<API key> ul {
margin: 0;
padding: 0;
}
#<API key> ul li {
float: left;
display: inline;
list-style: none;
padding: 0;
margin: 0 8px 10px 0;
width: 218px;
height: 226px;
overflow: hidden;
text-align: center;
}
#<API key> ul li.views-row-colnum-4 {
margin-right: 0;
}
#<API key> .box {
height: 224px;
}
#<API key> .box .inner{
padding: 5px;
}
#<API key> .title,
#<API key> .photo,
#<API key> .des,
#<API key> .attr {
overflow: hidden;
}
#<API key> .title {
height: 18px;
margin-bottom: 8px;
margin-top: 5px;
line-height: 16px;
}
#<API key> .photo {
height: 146px;
}
#<API key> .attr {
height: 24px;
padding-top: 15px;
}
#<API key> .des {
font-size: 10px;
line-height: 12px;
}
#<API key> .title a {
font-size: 14px;
font-weight: bold;
color: #855932;
}
#<API key> .attr {
position: relative;
}
#<API key> .attr .add-cart {
position: absolute;
right: 5px;
bottom: 2px;
}
#<API key> .attr span, #<API key> .attr .add-cart div {
display: inline;
float: left;
}
#<API key> .attr label {
display: none;
}
#<API key> .attr input.form-submit {
background: none;
border: none;
}
#<API key> .attr input.form-text {
width: 20px;
height: 20px;
border: 1px solid #990033;
padding: 0;
margin: 0 8px 0 0;
text-align: center;
}
#<API key> .attr input.form-submit {
border-radius: 0;
padding: 0;
margin: 0;
text-indent: -99999999px;
line-height: 1;
overflow: hidden;
width: 21px;
height: 20px;
background: url('../../images/shopping-cart.png') no-repeat 0 -20px;
}
#<API key> .attr input.form-submit:hover {
background-position: 0 0;
}
/*
#<API key> .attr input.form-submit[disabled='disabled']{
background: url('../../images/<API key>.png') no-repeat 0 0;
cursor: inherit;
}
*/
#<API key> .attr input#out-of-stock {
background: none;
cursor: inherit;
overflow: inherit;
text-indent: 0;
width: auto;
height: auto;
border: 1px solid #fff;
border-radius: 15px;
}
#<API key> .attr input#out-of-stock:hover {
color: #fff;
border-color: #B18500;
background-color: #ad1e38;
}
#<API key> .attr .form-item {
margin: 0;
}
#<API key> .attr .price {
color: #a23741;
font-size: 15px;
padding-left: 15px;
}
#<API key> .attr .orgin-price {
color: #696969;
font-size: 10px;
text-decoration: line-through;
}
#<API key> .s-2 .photo {
float: left;
display: inline;
height: auto;
padding-left: 7px;
}
#<API key> .s-2 .title, #<API key> .s-2 .des, #<API key> .s-2 .attr {
margin-left: 69px;
text-align: left;
}
#<API key> .s-2 .title {
height: 60px;
margin-bottom: 5px;
}
#<API key> .s-2 .des {
height: 80px;
}
#<API key> .s-2 .attr {
height: auto;
text-align: right;
padding-top: 7px;
}
#<API key> .s-2 .attr .add-cart {
position:inherit;
}
#<API key> .s-2 .attr .add-cart .form-item-quantity {
padding-left: 83px;
}
#<API key> .s-2 .attr .price {
padding-right: 7px;
padding-bottom: 7px;
}
#<API key> .s-3 .photo {
height: 110px;
}
#<API key> .s-3 .title {
margin-top: 5px;
margin-bottom: 5px;
}
#<API key> .s-3 .des {
height: 28px;
text-align: left;
}
#<API key> .s-3 .attr{
margin-top: 5px;
}
.<API key> .chzn-single {
background-color: #af1a3a;
/*background-image: linear-gradient(#FFFFFF 20%, #fff 50%, #fff 52%, #fff 100%);*/
background-image: none;
border: 2px solid #a33842 !important;
border-radius: 5px;
height: 36px;
line-height: 36px;
padding: 0 8px 0 14px;
font-size: 13px;
color: #fff;
font-weight: bold;
text-transform: uppercase;
}
.chzn-container .chzn-results li {
padding: 5px 8px;
color: #B28500;
}
.chzn-container .chzn-drop {
border-color: -moz-use-text-color #B28500 #B28500;
}
.chzn-container {
width: 100px !important;
}
.<API key> .chzn-single span {
width: 80px;
}
.<API key> input {
border: 1px solid #af1a3a;
border-radius: 5px;
padding: 10px;
margin: 0;
}
#main-wrapper .<API key> input.form-submit {
margin-right: 0;
}
.views-exposed-form #edit-title {
width: 140px;
}
.views-exposed-form .<API key>.views-submit-button {
clear: both;
} |
<?php
$HEADING['MODIFY_PAGE'] = 'Modifica Pàgina';
$HEADING['<API key>'] = 'Modifica els Paràmetres de la Pàgina';
$TEXT['ADMINISTRATORS'] = 'Administradors';
$TEXT['ALLOWED_VIEWERS'] = 'Allowed Viewers';
$TEXT['CURRENT_PAGE'] = 'Pàgina Actual';
$TEXT['DESCRIPTION'] = 'Descripció';
$TEXT['DISABLED'] = 'Inhabilitat';
$TEXT['ENABLED'] = 'Habilitat';
$TEXT['GROUP'] = 'Grup';
$TEXT['HIDDEN'] = 'Amagat';
$TEXT['KEYWORDS'] = 'Paraules Clau';
$TEXT['LANGUAGE'] = 'Idioma';
$TEXT['LAST_MODIFIED'] = 'Last modified by';
$TEXT['MANAGE_SECTIONS'] = 'Manage Sections';
$TEXT['MENU'] = 'Menú';
$TEXT['MENU_TITLE'] = 'Títol del Menú';
$TEXT['MODIFY'] = 'Modifica';
$TEXT['MODIFY_PAGE'] = 'Modify page';
$TEXT['NEW_WINDOW'] = 'Nova Finestra';
$TEXT['NO_SELECTION'] = 'no selection';
$TEXT['NONE'] = 'Cap';
$TEXT['PAGE_CODE'] = 'PageLanguageCode';
$TEXT['PAGE_LANG_LOADED'] = 'Pagelanguage loaded';
$TEXT['PAGE_TITLE'] = 'Títol de la Pàgina';
$TEXT['PARENT'] = 'Mare';
$TEXT['PLEASE_SELECT'] = 'Per favor trieu';
$TEXT['PRIVATE'] = 'Privat';
$TEXT['PUBLIC'] = 'Públic';
$TEXT['REGISTERED'] = 'Registrat';
$TEXT['RESET'] = 'Reinicia';
$TEXT['SAME_WINDOW'] = 'La Mateixa Finestra';
$TEXT['SAVE'] = 'Desa';
$TEXT['SEARCHING'] = 'Recerca';
$TEXT['SYSTEM_DEFAULT'] = 'Per Defecte del Sistema';
$TEXT['TARGET'] = 'Destí';
$TEXT['TEMPLATE'] = 'Plantilla';
$TEXT['TOP_FRAME'] = 'Top Frame';
$TEXT['TYPE'] = 'Tipus';
$TEXT['USER'] = 'Usuari';
$TEXT['VISIBILITY'] = 'Visibilitat';
$TEXT['SECTION_GENERAL'] = 'General';
$TEXT['<API key>'] = 'Organisation';
$TEXT['SECTION_CONTENT'] = 'Content';
$TEXT['SECTION_SECURITY'] = 'Security';
$TEXT['SEO_TITLE'] = 'Filename';
$TEXT['PAGE_ICON'] = 'Page image';
$TEXT['PAGE_ICON_DIR'] = 'Folder Page image';
$TEXT['MENU_ICON_0'] = 'Menu image normal';
$TEXT['MENU_ICON_0_DIR'] = 'Folder Menu image normal';
$TEXT['MENU_ICON_1'] = 'Menu image hover';
$TEXT['MENU_ICON_1_DIR'] = 'Folder Menu image hover';
$MESSAGE['PAGES_LAST_MODIFIED'] = 'Last modification by';
$MESSAGE['<API key>'] = 'Please enter a Filename';
$MESSAGE['PAGES_ADDED'] = 'Page added successfully';
$MESSAGE['PAGES_SAVED'] = 'Page saved successfully';
$MESSAGE['<API key>'] = 'Page settings saved successfully';
$MESSAGE['<API key>'] = 'Protected File, Page cannot be add!';
$MESSAGE['<API key>'] = 'Protected File, Page cannot be modified!';
$HELP['PAGE_IMAGE_DIR'] = '<p>The topical side picture path is<br /> <b>{{icon_dir}}</b>.</p><p>As a system administrator you can change the folder for side pictures and menu pictures under options extendet options in server setting.</p><p>Example::<br /><b>/media/banner</b></p><p> </p>';
$HELP['PAGE_CODE'] = '<p>If you see this field, you have registered the module for the multilingual facility.<br/>The first step is to be provided a side tree like in the WB-help described<br/>The side linguistic tree is provided from the provided sides of the standard language (<i>Options</i>).<br/>They can update any time the side linguistic tree by click on the title! The assigned sides remain unchanged.<br/>If you have put a side into another language, confirm from this list the matching entry of the standard language<br/>Example:<br />Created page in sub DE: <b>Impressum</b> choose Default Language EN: <b>Imprint</b></p>';
$HELP['SEO_TITLE'] = '<p>Path and file name of the access file of this page. <br /> <b>{{filename}}</b></p><p>In this field you can define a well readable, expressive name for the access file, regardless of menu title or page title. This is also usable well to create SEO friendly links..</p><p><b>For Example:</b><br /><br />Input Menu Title: <b>Pressemitteilung</b><br />Input Filename: <b>Pressemitteilung and Downloads</b><br />Create Accessfile: <b><API key>.php</b></p>'; |
#include "Graph.h"
#include "UVerticesArestas.h"
#include <queue>
#include <limits>
using namespace std;
VerticesDjikstra::VerticesDjikstra(shared_ptr<TVerticeGeral> vertex, double Distancia)
{
_vertex = vertex;
distancia = Distancia;
}
bool VerticesDjikstra::operator<(const VerticesDjikstra& right) const
{
return distancia > right.distancia;
}
bool VerticesDjikstra::operator>(const VerticesDjikstra& right) const
{
return distancia < right.distancia;
}
Graph::Graph() :
_verticesGerais( make_shared<TVerticesGerais>() )
{
}
void Graph::merge( shared_ptr<Graph> other )
{
_arestas.insert( _arestas.end(), other->_arestas.begin(), other->_arestas.end() );
_verticesGerais->vertices.insert( _verticesGerais->vertices.end(), other->_verticesGerais->vertices.begin(), other->_verticesGerais->vertices.end() );
}
bool Graph::<API key>( shared_ptr<TVerticeGeral> vertice[2], vector< shared_ptr<TVerticeGeral> > &anterior, vector< shared_ptr<TAresta> > &vArestas, string layer )
{
vector<double> DistanciaDjikstra( _verticesGerais->vertices.size() );
priority_queue<VerticesDjikstra> heap;
heap.push(VerticesDjikstra(vertice[0], 0));
bool achou_final = false;
/* initialize single source */
for ( int n = 0; n < _verticesGerais->vertices.size(); n++ )
{
DistanciaDjikstra[n] = std::numeric_limits<double>::max();
anterior[n] = shared_ptr<TVerticeGeral>();
_verticesGerais->vertices[n]->IndiceOriginal = n;
}
DistanciaDjikstra[ vertice[0]->IndiceOriginal ] = 0;
while(heap.size())
{
shared_ptr<TVerticeGeral> vfila = heap.top()._vertex;
//printf( "VFila: %f %f %d %s\n", vfila->pos.x, vfila->pos.y, vfila->IndiceOriginal, vfila->texto.c_str() );
double dist = heap.top().distancia;
heap.pop();
if(vfila == vertice[1])
achou_final = true;
if(dist > DistanciaDjikstra[vfila->IndiceOriginal])
continue;
for( auto VerticeEArestaTemp : vfila-><API key>->list )
{
shared_ptr<TAresta> edge = VerticeEArestaTemp.Aresta;
if ( edge->_layer != "" && edge->_layer != layer )
continue;
shared_ptr<TVerticeGeral> vatual = VerticeEArestaTemp.Vertice;
//printf( "vatual: %f %f %d %s\n", vatual->pos.x, vatual->pos.y, vatual->IndiceOriginal, vatual->texto.c_str() );
int alt = DistanciaDjikstra[vfila->IndiceOriginal] + edge->Tam;
if ( alt < DistanciaDjikstra[vatual->IndiceOriginal] )
{
DistanciaDjikstra[vatual->IndiceOriginal] = alt;
anterior[vatual->IndiceOriginal] = vfila;
vArestas[vatual->IndiceOriginal] = edge;
heap.push(VerticesDjikstra(vatual, alt));
}
}
}
return achou_final;
}
void Graph::getEdgesFromPath( vector< shared_ptr<TVerticeGeral> > &anterior, vector< shared_ptr<TAresta> > &vArestas,
vector< shared_ptr<TAresta> > &ListaArestas, std::vector< std::string > &vertexLabels, shared_ptr<TVerticeGeral> vertex ) const
{
string lastText;
shared_ptr<TAresta> ArestaTemp;
shared_ptr<TVerticeGeral> vatual = vertex;
while (anterior[vatual->IndiceOriginal].get() != 0)
{
if( !vatual->texto.empty() && vatual->texto != lastText )
{
vertexLabels.push_back( vatual->texto );
lastText = vatual->texto;
}
ArestaTemp = vArestas[vatual->IndiceOriginal];
ListaArestas.push_back( ArestaTemp );
vatual = anterior[vatual->IndiceOriginal];
}
}
void Graph::<API key>()
{
for ( auto edge : _arestas )
TAresta::createAdjancency( edge );
}
Graph* Graph::getCopy() const
{
Graph *copy = new Graph();
map<TVerticeGeral*, shared_ptr<TVerticeGeral>> verticesMap;
for( int i(0); i < _verticesGerais->vertices.size(); ++i )
{
shared_ptr<TVerticeGeral> verticeTemp = make_shared<TVerticeGeral>( *(_verticesGerais->vertices[i].get()) );
verticesMap[_verticesGerais->vertices[i].get()] = verticeTemp;
copy->_verticesGerais->vertices.push_back( verticeTemp );
}
for( int i(0); i < _arestas.size(); ++i)
{
shared_ptr<TAresta> newEdge = make_shared<TAresta>( _arestas[i].get() );
for( int j(0); j < 2; ++j )
newEdge->_vertices[j] = verticesMap[ _arestas[i]->_vertices[j].get() ];
copy->_arestas.push_back( newEdge );
}
copy-><API key>();
return copy;
}
void Graph::reduce()
{
vector<shared_ptr<TVerticeGeral> > vertices[2];
for( int i(0); i < _verticesGerais->vertices.size(); ++i)
{
if( !_verticesGerais->vertices[i]->texto.empty() )
continue;
shared_ptr<<API key>> <API key> = _verticesGerais->vertices[i]-><API key>;
if( <API key>->list.size() == 1 )
vertices[0].push_back( _verticesGerais->vertices[i] );
}
// eliminate vertices with no text and only one edge
for( int i(0); i < vertices[0].size(); ++i )
{
shared_ptr<TVerticeGeral> vertex = vertices[0][i];
// mark the edge to be removed
vertex-><API key>->list[0].Aresta->_autogenId = -1;
vertex->removeEdges();
// mark the vertex to be removed
vertex->_autogenId = -1;
}
for( int i(0); i < _verticesGerais->vertices.size(); ++i)
{
shared_ptr<TVerticeGeral> vertex = _verticesGerais->vertices[i];
if( !vertex->texto.empty() )
continue;
shared_ptr<<API key>> <API key> = vertex-><API key>;
if ( <API key>->list.size() == 2 )
vertices[1].push_back( vertex );
}
// eliminate vertices with no text and two edges
for( int i(0); i < vertices[1].size(); ++i )
{
shared_ptr<TVerticeGeral> vertex = vertices[1][i];
shared_ptr<TAresta> newEdge = make_shared<TAresta>( vertex-><API key>->list[0].Aresta->_layer );
// remove old edges
for( int j(0); j < 2; ++j )
{
TVerticeEAresta &verticeEAresta = vertex-><API key>->list[j];
newEdge->Tam += verticeEAresta.Aresta->Tam;
newEdge->_vertices[j] = verticeEAresta.Vertice;
// mark the edge to be removed
verticeEAresta.Aresta->_autogenId = -1;
vertex->removeEdges();
vertex->_autogenId = -1;
}
_arestas.push_back( newEdge );
TAresta::createAdjancency( newEdge );
}
// remove marked vertices
for( int i( _verticesGerais->vertices.size() - 1); i >= 0; --i )
{
if( _verticesGerais->vertices[i]->_autogenId < 0 )
_verticesGerais->vertices.erase( _verticesGerais->vertices.begin() + i );
}
// remove marked edges
for( int i( _arestas.size() - 1); i >= 0; --i )
{
if( _arestas[i]->_autogenId < 0 )
_arestas.erase( _arestas.begin() + i );
}
} |
//>>built
define("dojox/drawing/library/greek",{alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,
Psi:936,Omega:937});
//@ sourceMappingURL=greek.js.map |
/* CSS Document */
.buttonok {width:52px; font-family:Verdana; font-size:11px; line-height:25px; text-align:center;}
.buttonok a {height:28px; text-decoration: none;}
.buttonok a:link, .buttonok a:visited {
color: #002157; display: block;
background: url(images/button-ok.gif);}
.buttonok a:hover,.buttonok a:active { color:#ffffff; background:url(images/button-ok.gif) 0 -28px;}
.buttonquit {width:100px; font-family:Verdana; font-size:11px; line-height:20px; text-align:center; }
.buttonquit a { height:31px; text-decoration:none; }
.buttonquit a:link, .buttonquit a:visited {
color:#002157; display:block; background:url(images/button-quit.gif) no-repeat; text-decoration:none;}
.buttonquit a:hover,.buttonquit a:active { color: #ffffff; background: url(images/button-quit.gif) no-repeat 0 -31px; text-decoration:none;}
.top-message {
font-family:Arial, Verdana;
font-size:11px;
color:#000000;
border-left:2px dotted #97A9B2;
padding-left:10px;
padding-right:0px;
background: #c5d2d6;
}
.top-message a:link, .top-message a:visited{
text-decoration:underline;
}
.top-messagebold {
font-family:Verdana;
font-size:11px;
color:#FFF;
line-height:180%;
font-weight:bold;
}
.top-input {
font-family:Verdana;
font-size:11px;
color:#FFFFFF;
line-height:200%;
border: 1px solid #1F2D35;
background-color:#1F2D35;
width:150px;
height:30px;
margin-top:0px;
}
#top-logo {
font-size:17px;
font-family:Arial, Helvetica, sans-serif;
font-weight:bolder;
font-stretch:wider;
color:#FFFFFF;
letter-spacing:1px;
background:url(images/top-02.gif) #c5d2d6 no-repeat;
padding:20px 0 0 50px; /* Control the position of product name */
}
.FormTitle{
line-height:160%;
font-size:12px;
font-family:Arial, Verdana, Arial, Helvetica, sans-serif;
border:1px solid #4D595D;
color:white;
position:relative;
*margin-top:-1px;
-<API key>: 3px;
-<API key>: 3px;
-<API key>: 3px;
-<API key>: 3px;
<API key>: 3px;
<API key>: 3px;
behavior: url(/PIE.htc);
border-radius: 0 0 3px 3px;
}
.FormTitle thead{
color:#FFF;
font-size:13px;
text-align:center;
font-weight:bold;
background-color:#4D595D;
}
.FormTitle tbody{
line-height:180%;
}
.FormTitle_firefox{
margin-top:-100px;
line-height:160%;
font-size:12px;
font-family:Arial, Verdana, Arial, Helvetica, sans-serif;
border:1px solid #4D595D;
color:white;
}
.FormTitle_firefox thead{
color:#FFF;
font-size:13px;
text-align:center;
font-weight:bold;
background-color:#4D595D;
}
.FormTitle_firefox tbody{
line-height:180%;
}
.FormTable{
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
border: 1px solid #000000;
border-collapse: collapse;
}
.FormTable th{
font-family:Arial, Helvetica, sans-serif;
background-color:#1F2D35;
color:#FFFFFF ; /*Viz add*/
font-weight:normal;
line-height:15px;
height: 30px;
text-align:left;
font-size:12px;
width:35%; /*Viz add*/
padding-left: 10px;
border: 1px solid #222;
border-collapse: collapse;
background:#2F3A3E;
}
.FormTable thead td{
color: #FFF;
font-size:12px;
background-color:#4D595D;
text-align:left;
font-weight:bolder;
border: 1px solid #222;
padding: 3px;
padding-left: 10px;
border-collapse: collapse;
background: #92A0A5; /* Old browsers */
background: -moz-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#92A0A5 ), color-stop(100%,#66757C)); /* Chrome,Safari4+ */
background: -<API key>(top, #92A0A5 0%, #66757C 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* IE10+ */
background: linear-gradient(to bottom, #92A0A5 0%, #66757C 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92A0A5', endColorstr='#66757C',GradientType=0 ); /* IE6-9 */
}
.FormTable thead th{
color: #000000;
font-size:12px;
text-align: center;
font-weight:normal;
border: 1px solid #222;
border-collapse: collapse;
}
.FormTable td{
padding-left: 10px;
background-color:#475A5F;
border: 1px solid #222;
border-collapse: collapse;
}
.FormTable td span{
background-color:#475a5f;
color:#FFCC00;
}
.FormTable td span#wl_nmode_x_hint{
margin-top:3px;
}
/* for Table (for Add List) */
.FormTable_table{
margin-top:10px;
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
border: 1px solid #222;
border-collapse: collapse;
}
.FormTable_table th{
font-family:Arial, Helvetica, sans-serif;
background-color:#1f2d35;
font-weight:normal;
text-align:center;
font-size:12px;
height:25px;
border: 1px solid #222;
border-collapse: collapse;
background:#2F3A3E;
}
.FormTable_table th.select_table{
width:100px;
text-align:center;
}
.FormTable_table td.select_table{
width:150px;
text-align:left;
}
.FormTable_table th.edit_table{
width:110px;
text-align:center;
}
.FormTable_table td{
background-color:#475a5f;
text-align:center;
border: 1px solid #222;
border-collapse: collapse;
}
.FormTable_table td span{
color:#FFCC00;
}
.FormTable_table thead td{
color: #FFF;
font-size:12px;
background-color:#4D595D;
text-align:left;
font-weight:bolder;
border: 1px solid #222;
padding: 3px;
border-collapse: collapse;
padding-left: 10px;
background: #92A0A5; /* Old browsers */
background: -moz-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#92A0A5 ), color-stop(100%,#66757C)); /* Chrome,Safari4+ */
background: -<API key>(top, #92A0A5 0%, #66757C 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* IE10+ */
background: linear-gradient(to bottom, #92A0A5 0%, #66757C 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92A0A5', endColorstr='#66757C',GradientType=0 ); /* IE6-9 */
}
.FormTable_table thead th{
width: 98px;
color: #000000;
font-size:12px;
background-color:#1F2D35;
text-align: center;
font-weight:normal;
border: 1px solid #222;
border-collapse: collapse;
}
/* for NWM */
.FormTable_NWM{
/*margin-top:10px;*/
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
border: 1px solid #222;
border-collapse: collapse;
}
.FormTable_NWM th{
font-family:Arial, Helvetica, sans-serif;
background-color:#1f2d35;
font-weight:normal;
text-align:center;
font-size:12px;
height:25px;
border: 1px solid #222;
border-collapse: collapse;
background: #92A0A5; /* Old browsers */
background: -moz-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#92A0A5 ), color-stop(100%,#66757C)); /* Chrome,Safari4+ */
background: -<API key>(top, #92A0A5 0%, #66757C 100%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* Opera 11.10+ */
background: -ms-linear-gradient(top, #92A0A5 0%, #66757C 100%); /* IE10+ */
background: linear-gradient(to bottom, #92A0A5 0%, #66757C 100%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#92A0A5', endColorstr='#66757C',GradientType=0 ); /* IE6-9 */
}
.FormTable_NWM th.select_table{
width:100px;
text-align:center;
}
.FormTable_NWM td.select_table{
width:150px;
text-align:left;
}
.FormTable_NWM th.edit_table{
width:110px;
text-align:center;
}
.FormTable_NWM td{
background-color:#475a5f;
text-align:center;
border: 1px solid #222;
border-collapse: collapse;
height:35px;
}
.FormTable_NWM td span{
/*background-color:#475a5f;*/
/*color:#FF3300; */
color:#569AC7;
}
.FormTable_NWM thead td{
color: #FFF;
font-size:12px;
background-color:#4D595D;
text-align:left;
font-weight:bolder;
border: 1px solid #222;
padding: 2px;
border-collapse: collapse;
background:#2F3A3E;
}
.FormTable_NWM thead th{
width: 98px;
color: #000000;
font-size:12px;
background-color:#1F2D35;
text-align: center;
font-weight:normal;
border: 1px solid #222;
border-collapse: collapse;
}
.table_text{
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-decoration:none;
}
/* for Table */
.input{
color:#FFFFFF;
font-family: Arial, Helvetica, sans-serif;
font-size:12px;
padding-left:2px;
}
.input_option{
height:25px;
background-color:#576D73;
border-top-width:1px;
border-bottom-width:1px;
border-color:#888;
color:#FFFFFF;
font-family: Lucida Console;
font-size:13px;
}
.input_option_lang{
margin-top:15px;
margin-left:280px;
height:25px;
background-color:#222;
*background-color:#FFF;
border-top-width:1px;
border-bottom-width:1px;
border-color:#888;
color:#FFFFFF;
*color:#000;
font-size:13px;
font-family: Lucida Console;
}
.input_option_left{
float: right;
height:25px;
/*background-image:url(/images/New_ui/inputbg.png); Ban by Viz, cuz my Chrome show out white color*/
background-color:#576D73;
border-top-width:1px;
border-bottom-width:1px;
border-color:#888;
color:#FFFFFF;
margin:8px 10px 0 0;
font-family: Lucida Console;
font-size:13px;
}
.input_32_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:345px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_30_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:315px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_25_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:235px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_22_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:202px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_20_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:180px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_18_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:160px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_15_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:120px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_12_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:90px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_6_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:50px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_3_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:28px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
.input_macaddr_table{
margin-left:2px;
padding-left:0.4em;
height:23px;
width:125px;
line-height:23px \9;
font-size:12px;
font-family: Lucida Console;
background-image:url(/images/New_ui/inputbg.png);
border-width:0;
color:#FFFFFF;
}
/* Viz add start */
.titledownbutton{
text-shadow: 1px 1px 0px black;
font-weight: bolder;
background: transparent url(/images/New_ui/contentbt_normal.png) no-repeat scroll center top;
border:0;
color: #FFFFFF;
height:34px;
font-family:Verdana;
font-size:12px;
/*margin-right:5px;
margin-left:5px;*/
padding:0 .70em 0 .70em;
width:122px;
overflow:visible;
}
.titledownbutton:hover /*, .button:active*/{
background:url(/images/New_ui/contentbt_over.png) no-repeat;
height:34px;
width:122px;
/*margin-right:5px;
margin-left:5px;*/
padding:0 .70em 0 .70em;
background-position: 7px;
cursor:pointer;
}
.button_gen{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
background: transparent url(/images/New_ui/contentbt_normal.png) no-repeat scroll center top;
_background: transparent url(/images/New_ui/<API key>.png) no-repeat scroll center top;
border:0;
color: #FFFFFF;
height:33px;
font-family:Verdana;
font-size:12px;
padding:0 .70em 0 .70em;
width:122px;
overflow:visible;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
white-space:normal;
}
.button_gen:hover{
font-weight: bolder;
background:url(/images/New_ui/contentbt_over.png) no-repeat;
height:33px;
width:122px;
padding:0 .70em 0 .70em;
background-position:0px;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_dis{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
background: transparent url(/images/New_ui/contentbt_normal.png) no-repeat scroll center top;
_background: transparent url(/images/New_ui/<API key>.png) no-repeat scroll center top;
border:0;
color: #333333;
height:33px;
font-family:Verdana,Bold;
font-size:12px;
padding:0 .70em 0 .70em;
width:122px;
overflow:visible;
/*cursor:pointer;*/
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_dis:hover{
background:url(/images/New_ui/contentbt_over.png) no-repeat;
height:33px;
width:122px;
padding:0 .70em 0 .70em;
background-position:0px;
/*cursor:pointer;*/
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_touch{
color: #FFFFFF;
background:url(/images/New_ui/contentbt_over.png) no-repeat;
height:33px;
width:122px;
padding:0 .70em 0 .70em;
background-position:0px;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_long{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
background: transparent url(/images/New_ui/logout_bt.png) no-repeat scroll center top;
border:0;
color: #FFFFFF;
height:34px;
font-family:Verdana;
font-size:12px;
width:155px;
overflow:visible;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_long:hover /*, .button:active*/{
background: transparent url(/images/New_ui/logout_btover.png) no-repeat scroll center top;
border:0;
color: #FFFFFF;
height:34px;
font-family:Verdana;
font-size:12px;
width:155px;
overflow:visible;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_long_dis{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
background: transparent url(/images/New_ui/logout_bt.png) no-repeat scroll center top;
border:0;
color: #333333;
height:34px;
font-family:Verdana;
font-size:12px;
width:155px;
overflow:visible;
/*cursor:pointer;*/
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_long_dis:hover /*, .button:active*/{
background: transparent url(/images/New_ui/logout_btover.png) no-repeat scroll center top;
border:0;
color: #333333;
height:34px;
font-family:Verdana;
font-size:12px;
width:155px;
overflow:visible;
/*cursor:pointer;*/
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.<API key>{
color: #FFFFFF;
background:url(/images/New_ui/contentbt_over.png) no-repeat;
height:33px;
width:155px;
padding:0 .70em 0 .70em;
background-position:0px;
cursor:pointer;
}
.button_gen_short{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
background: transparent url(/images/New_ui/flowbt_normal.png) no-repeat scroll center top;
border:0;
color: #FFFFFF;
height:33px;
font-family:Verdana;
font-size:12px;
padding:0 .70em 0 .70em;
width:91px;
overflow:visible;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.button_gen_short:hover{
font-weight: bolder;
background:url(/images/New_ui/flowbt_over.png) no-repeat;
height:33px;
width:91px;
padding:0 .70em 0 .70em;
background-position:0px;
cursor:pointer;
outline: none; /* for Firefox */
hlbr:expression(this.onFocus=this.blur()); /* for IE */
}
.sbtn{ /*Lock 1206 modified*/
border: 1px outset #333;
background:url(images/sbtn0.gif) #FFCC66;
height:20px;
font-family:Verdana;
font-size:12px;
margin-right:5px;
margin-left:5px;
padding:0 .70em 0 .70em;
width:auto;
overflow:visible;
cursor:pointer;
}
.sbtn:hover{
background:url(images/sbtn.gif) #FFCC66;
color:#FFFFFF;
}
form{
margin:0px;
}
textarea{
width:99%;
}
.hint_word{
color: #FF0000;
font:Verdana, Arial, Helvetica, sans-serif;
font-size:9pt;
padding:5px 5px 5px 0px;
}
.short_btn {
width: 105px;
font-family:Verdana ;
font-size : 13px;
text-align:center;
line-height:25px;
}
.short_btn a { height: 31px; text-decoration: none; }
.short_btn a:link, .short_btn a:visited {
color: #002157; display: block; background: url(../images/button-next.gif);
}
.short_btn a:hover,.short_btn a:active { color: #ffffff; background: url(../images/button-next.gif) 0 -31px;}
.upnp_btn {
width: 150px;
font-family:Verdana ;
font-size : 13px;
text-align:center;
line-height:25px;
}
.upnp_btn a { height: 31px; text-decoration: none; }
.upnp_btn a:link, .short_btn a:visited {
color: #002157; display: block; background: url(../images/button-upnp.gif);
}
.upnp_btn a:hover,.short_btn a:active { color: #ffffff; background: url(../images/button-upnp.gif) 0 -31px;}
/*0103 lock*/
.popTable {
border:1px solid #666;
}
.popTable thead td{
background-image:url(images/title-bg-2.gif);
border-bottom:1px solid #666;
}
.popTable thead span{
font-family:Verdana;
font-size:12px;
font-weight:bold;
color:#000000;
float:left;
margin:6px 5px 0px 5px;
}
.popTable thead img{
float:right;
margin:0px 4px 0px 4px;
cursor:pointer;
}
.popTable tbody{
background-color:#FFF;
text-align:left;
}
.popTable tbody th{
font-family:Verdana;
font-size:12px;
text-align:right;
padding-right:5px;
height:30px;
color: #000;
}
.popTable tbody td{
color: #666666;
font-family: Verdana, Arial, Helvetica, sans-serif;
font-size:10pt;
padding:4px;
}
.inputpin{
color:#333333;
border:1px inset #000;
background: url(images/bg_ipt_field.gif) repeat-x #FFF;
font-family:Verdana;
font-size:11px;
padding-left:2px;
font-weight:bold;
}
.devicepin{
border:0px;
color:#FFFFFF;
background-color:#475A5F;
font-family:Verdana;
font-size:11px;
padding-left:2px;
font-weight:bold;
cursor:text;
}
#ClientList_Block{
border:2px outset #999;
background-color:#576D73;
position:absolute;
margin-top:24px;
margin-left:2px;
*margin-left:-145px;
text-align:left;
width:200px;
height:auto;
overflow-y:auto;
z-index:200;
padding: 1px;
display:none;
}
#ClientList_Block div{
background-color:#576D73;
height:20px;
line-height:20px;
text-decoration:none;
padding-left:2px;
}
#ClientList_Block a{
background-color:#EFEFEF;
color:#FFF;
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
text-decoration:none;
}
#ClientList_Block div:hover, #ClientList_Block a:hover{
background-color:#3366FF;
color:#FFFFFF;
cursor:default;
}
#QoSList_Block{
border:1px outset #999;
background-color:#576D73;
position:absolute;
margin-top:25px;
margin-left:1px;
*margin-left:-132px;
text-align:left;
width:250px;
height:400px;
overflow-y:auto;
z-index:200;
padding: 1px;
display:none;
}
#QoSList_Block div{
background-color:#576D73;
height:20px;
line-height:20px;
text-decoration:none;
padding-left:2px;
}
#QoSList_Block a{
background-color:#EFEFEF;
color:#FFF;
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
}
#QoSList_Block div:hover, #ClientList_Block a:hover{
background-color:#3366FF;
color:#FFFFFF;
cursor:default;
}
.hackiframe2 /* iframe for Hack IE 6.0 to avoid select menu over DIV layer. */
{
display:none;/*sorry for IE5*/
display:block;
position:absolute;/*must have*/
top:0px;
left:0px;
margin-top:0px;
margin-left:0px;
z-index: -1;
filter:mask();
width:205px;/*must have for any big value*/
height:125px;/*must have for any big value*/
}
.pull_arrow{
float:left;
cursor:pointer;
border:2px outset #EFEFEF;
background-color:#CCC;
padding:3px 2px 4px 0px;
}
#pull_arrow{
float:left;
cursor:pointer;
border:2px outset #EFEFEF;
background-color:#CCC;
padding:3px 2px 4px 0px;
}
.list_table{
border: 1px solid #000000;
border-collapse: collapse;
background-color:#475a5f;
text-align:center;
font-size:12px;
}
.list_table td{
border: 1px solid #000000;
border-collapse: collapse;
font-family: Lucida Console;
height:25px;
}
.list_table td.list_32_table{
height:25px;
width:350px;
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
font-size:12px;
}
.list_table td.list_15_table{
height:25px;
width:110px;
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
font-size:12px;
}
.list_table td.list_12_table{
height:25px;
width:90px;
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
font-size:12px;
}
.list_table td.list_6_table{
height:25px;
width:50px;
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
font-size:12px;
}
.list_table td.list_3_table{
height:25px;
width:28px;
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
text-align:center;
font-size:12px;
}
.list_table td.select_table{
width:150px;
}
.list_table td.edit_table{
width:110px;
text-align:center;
}
.list_table .whenClick{
background-color: #FFFF99;
}
.IPaddr{
font-size:12px;
font-weight:normal;
font-family:Arial, Helvetica, sans-serif;
border: 2px inset #F4F4F4;
background-color:#4D595D;
/*background-image:url(/images/New_ui/inputbg.png);*/
width:130px;
display: inline-block;
}
.IPaddr input{
border:0px solid #CCC;
color:white;
font-size:12px;
font-family:Arial, Helvetica, sans-serif;
width:27px;
text-align:center;
margin:0px auto;
ime-mode:disabled;
background-color:#4D595D;
}
.inputinfo{
border:0px;
background-color: #A7D2E2;
font-family:Verdana;
font-size:11px;
padding-left:2px;
font-weight:bold;
cursor:text;
color:#000;
}
/* btns in table */
.add_btn{
background: transparent url(/images/New_ui/accountadd.png) no-repeat scroll center top;
border:0;
height:34px;
width:35px;
cursor:pointer;
}
.add_btn:hover, .add_btn:active{
/*background: transparent url(/images/New_ui/UserAdd_0.png) no-repeat scroll center top;*/
border:0;
height:34px;
width:35px;
cursor:pointer;
}
.remove_btn{
background: transparent url(/images/New_ui/accountdelete.png) no-repeat scroll center top;
border:0;
height:30px;
width:35px;
cursor:pointer;
}
.remove_btn:hover, .remove_btn:active{
/*background: transparent url(/images/New_ui/UserDel_0.png) no-repeat scroll center top;*/
border:0;
height:30px;
width:35px;
cursor:pointer;
}
.remove_btn_NM{
background: transparent url(/images/zoomout.png) no-repeat scroll center top;
border:0;
height:27px;
width:23px;
cursor:pointer;
margin-top:5px;
}
.edit_btn{
background: transparent url(/images/New_ui/accountedit.png) no-repeat scroll center top;
border:0;
height:34px;
width:35px;
cursor:pointer;
}
.edit_btn:hover, .edit_btn:active{
/*background: transparent url(/images/New_ui/UserMod_0.png) no-repeat scroll center top;*/
border:0;
height:34px;
width:35px;
cursor:pointer;
}
/* btns in table */
/*Viz add apply_gen */
.apply_gen{
text-align:center;
background-color:#4D595D;
width:100%;
margin-top:10px;
}
/*Viz add apply_gen */
.zoomin_btn{
background: transparent url(/images/zoomin.png) no-repeat scroll center top;
border:0;
height:28px;
width:35px;
cursor:pointer;
}
.zoomout_btn{
background: transparent url(/images/zoomout.png) no-repeat scroll center top;
border:0;
height:28px;
width:35px;
cursor:pointer;
}
.help_icon{
padding-right: 20px;
background: url(/images/New_ui/helpicon.png) no-repeat;
}
/* CSS Document */
body{
color:#FFFFFF;
font-family:Arial, Helvetica, sans-serif;
font-size:13px;
color:#FFFFFF;
}
a:link {
text-decoration: none;
color: #FFFFFF;
}
a:visited {
text-decoration: none;
color: #FFFFFF;
}
a:hover {
text-decoration: none;
color: #FFFFFF;
}
a:active {
text-decoration: none;
color: #FFFFFF;
}
p{margin-top: 0;margin-bottom: 0}
/* Move to index_style.css By Viz , aidisk still use this*/
.titlebtn {
background: transparent url(images/New_ui/btn.png) no-repeat scroll right top;
color: White;
display: block;
float: left;
height: 34px;
padding-right: 10px;
margin-right: 10px;
text-decoration: none;
text-align:center;
width: auto;
/**width: expression(document.body.clientWidth < 136? "136px" : "auto");*/
min-width:136px;
white-space:nowrap;
}
.titlebtn span {
background: transparent url(images/New_ui/btnspan.png) no-repeat;
display: block;
padding: 5px 1px 5px 11px;
height: 24px;
line-height: 22px;
font-weight: bold;
}
.titlebtn:hover {
background-position: right -34px;
}
.titlebtn:hover span {
background-position: left -34px;
}
.titlebtn:active {
background-position: right -68px;
outline: none;
}
.titlebtn:active span {
background-position: left -68px;
}
.titledropdownbtn {
background-image:url(images/New_ui/dropdown_bt.png);
font-size:12px;
color:#FFFFFF;
text-decoration:none;
width:147px;
height:33px;
line-height:33px;
}
.titledropdownbtn:hover{
background-image:url(images/New_ui/dropdown_btover.png);
}
.titledown{
font:Arial, Helvetica, sans-serif;
color:#FFFFFF;
font-size:12px;
}
.titledown a:link{
color:#FFFFFF;
}
.titledown:hover{
color:#FFFFFF;
}
.titledownbt{
font:Arial, Helvetica, sans-serif;
padding-left:2px;
margin-left:2px;
color:#FFFFFF;
font-size:12px;
/*text-decoration:underline;*/
}
.tab:hover{
background-position:right -73px;
cursor: pointer;
}
.tab:hover span{
background-position:left -73px;
cursor: pointer;
}
.tab {
background: transparent url(/images/New_ui/hightaba.png) no-repeat scroll right top;
color: White;
float: left;
height: 40px;
padding-right: 8px;
margin-right: 2px;
text-align:center;
text-decoration: none;
font-family: Verdana;
z-index: -1;
}
.tab span {
background: transparent url(/images/New_ui/hightabspan.png) no-repeat;
height: 40px;
padding-left: 6px;
padding-top: 10px \9;
line-height: 15px;
font-family: Verdana;
font-size: 12px;
vertical-align: middle;
display: table-cell;
display: inline-block \9;
width: auto;
z-index: -1;
}
.tabclick {
background: transparent url(/images/New_ui/hightabclicka.png) no-repeat scroll right top;
color: White;
float: left;
height: 40px;
padding-right: 8px;
margin-right: 2px;
text-align: center;
text-decoration: none;
font-family: Verdana;
}
.tabclick span {
background: transparent url(/images/New_ui/hightabclickspan.png) repeat;
height: 40px;
padding-left: 6px;
padding-top: 10px \9;
line-height: 15px;
font-family: Verdana;
font-size: 12px;
vertical-align: middle;
display: table-cell;
display: inline-block \9;
width: auto;
}
div.tabclick {
height: 40px !important;
}
.tab_NW {
font-weight: bolder;
background: transparent url(images/New_ui/taba.png) no-repeat scroll right top;
color: White;
display: block;
float: left;
height: 28px;
padding-right: 8px;
margin-right:2px;
text-decoration: none;
text-align:center;
max-width:240px;
}
.tab_NW span {
cursor:pointer;
font-weight: bolder;
white-space:nowrap;
font-weight: bolder;
background: transparent url(images/New_ui/tabspan.png) no-repeat;
display: block;
padding: 5px 4px 5px 12px;
line-height: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
}
.tab_NW:hover{
background-position:right -28px;
}
.tab_NW:hover span{
background-position:left -28px;
}
.tabclick_NW {
font-weight: bolder;
background: transparent url(images/New_ui/tabclicka.png) no-repeat scroll right top;
font-family: Verdana;
color: White;
display: block;
float: left;
height: 28px;
padding-right: 8px;
margin-right:2px;
text-align:center;
text-decoration: none;
max-width:240px;
}
.tabclick_NW span {
cursor:pointer;
font-weight: bolder;
white-space:nowrap;
font-weight: bolder;
background: transparent url(images/New_ui/tabclickspan.png) no-repeat;
font-family: Arial, Helvetica, sans-serif;
display: block;
padding: 5px 4px 5px 12px;
line-height: 20px;
font-size: 13px;
}
.flowfont{
font:Arial, Helvetica, sans-serif;
color:#FFFFFF;
font-size:12px;
}
.flowfontbt{
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/flowbt_normal.png);
color:#FFFFFF;
font-size:12px;
}
.flowfontbt:link{
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/flowbt_normal.png);
color:#FFFFFF;
font-size:12px;
}
.flowfontbt:hover{
background-image:url(images/New_ui/flowbt_over.png);
}
.fromdropdownbt{
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/networkmap/formdropdown.png);
color:#FFFFFF;
font-size:12px;
}
.fromdropdownbt:link{
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/networkmap/formdropdown.png);
color:#FFFFFF;
font-size:12px;
}
.fromdropdownbt:hover{
background-image:url(images/New_ui/networkmap/formdropdown_over.png);
}
.formfont{
font:Arial, Helvetica, sans-serif;
font-size:16px;
color:#FFFFFF;
padding-left:10px;
padding-top:1px;
margin-top:5px;
}
.formfonttitle{
text-shadow: 1px 1px 0px black;
font-family:Arial, Helvetica, sans-serif;
font-size:16px;
color:#FFFFFF;
margin-left:5px;
margin-bottom:10px;
font-weight: bolder;
}
.formfonttitle_nwm{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#FFFFFF;
margin-left:5px;
margin-bottom:10px;
font-weight: bolder;
}
.formfontcontent{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#FFFFFF;
padding-top:1px;
}
.formfontdesc{
font-family: Arial, Helvetica, sans-serif;
font-size:13px;
color:#FFFFFF;
margin-left:5px;
margin-bottom:10px;
}
.formlinkfont{
font-family: Arial, Helvetica, sans-serif;
font-size:13px;
color:#FFFFFF;
text-decoration:underline;
}
.input_2{
height:23px;
width:104px;
background-image:url(images/New_ui/inputbg_2.png);
border:0px;
}
.contentbt{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/contentbt_normal.png);
color:#FFFFFF;
font-size:12px;
}
.contentbt:link{
font-weight: bolder;
text-shadow: 1px 1px 0px black;
font:Arial, Helvetica, sans-serif;
background-image:url(images/New_ui/contentbt_normal.png);
color:#FFFFFF;
font-size:12px;
}
.contentbt:hover{
background-image:url(images/New_ui/contentbt_over.png);
cursor: pointer;
}
.coolerstatuson{
background-image:url(/images/New_ui/coolerstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.coolerstatusoff{
background-image:url(/images/New_ui/coolerstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:29px;
width:30px;
cursor: pointer;
}
.wifihwswstatuson{
background-image:url(/images/wifi_hw_sw.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.<API key>{
background-image:url(/images/wifi_hw_sw.png);
background-repeat:no-repeat;
background-position:2px -73px;
height:29px;
width:30px;
cursor: pointer;
}
.wifihwswstatusoff{
background-image:url(/images/wifi_hw_sw.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:29px;
width:30px;
cursor: pointer;
}
.<API key>{
background-image:url(/images/New_ui/multiplessidstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.<API key>{
background-image:url(/images/New_ui/multiplessidstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:29px;
width:30px;
cursor: pointer;
}
.connectstatuson{
background-image:url(images/New_ui/connectstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.connectstatusoff{
background-image:url(images/New_ui/connectstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:30px;
width:30px;
cursor: pointer;
}
/*Viz add 2013.03 for adsl sync status start*/
.linestatusup{
background-image:url(/images/New_ui/DSLstatus.png);
background-repeat:no-repeat;
background-position:2px 0px;
height:29px;
width:29px;
cursor: pointer;
}
.linestatuselse{
background-image:url(/images/New_ui/DSL_Act.gif);
background-repeat:no-repeat;
background-position:3px 2px;
height:29px;
width:29px;
cursor: pointer;
}
.linestatusdown{
background-image:url(/images/New_ui/DSLstatus.png);
background-repeat:no-repeat;
background-position:2px -50px;
height:29px;
width:29px;
cursor: pointer;
}
/*Viz add 2013.03 for adsl sync status end*/
/*Viz add 2014.10 for adsl diag status start*/
.linestatusdiag{
background-image:url(/images/New_ui/DSL_diag.gif);
background-repeat:no-repeat;
background-position:3px 2px;
height:29px;
width:29px;
cursor: pointer;
}
/*Viz add 2014.10 for adsl diag status end*/
.printstatuson{
background-image:url(images/New_ui/printstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:30px;
width:30px;
cursor: pointer;
}
.printstatusoff{
background-image:url(images/New_ui/printstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:30px;
width:30px;
cursor: pointer;
}
.usbstatuson{
background-image:url(images/New_ui/usbstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:30px;
width:30px;
cursor: pointer;
}
.usbstatusoff{
background-image:url(images/New_ui/usbstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:30px;
width:30px;
cursor: pointer;
}
.notificationon{
position: absolute;
display:inline;
background-image:url(images/New_ui/notification.png);
background-repeat:no-repeat;
background-position:2px 2px;
margin-top:-5px;
margin-top:3px \9;
height:30px;
width:30px;
cursor: pointer;
}
.notificationoff{
position: absolute;
display:none;
background-image:url(images/New_ui/notification.png);
background-repeat:no-repeat;
background-position:2px -48px;
margin-top:-5px;
margin-top:3px \9;
height:30px;
width:30px;
cursor: pointer;
}
/* Cherry Cho added for mobile broadband in 2014/8/22.*/
.simexist{
background-image:url(images/mobile/sim_state.png);
background-repeat:no-repeat;
background-position:4px -23px;
height:29px;
width:30px;
cursor: pointer;
}
.simnone{
background-image:url(images/mobile/sim_state.png);
background-repeat:no-repeat;
background-position:4px 2px;
height:30px;
width:30px;
cursor: pointer;
}
.simfail{
background-image:url(images/mobile/sim_state.png);
background-repeat:no-repeat;
background-position:4px -73px;
height:30px;
width:30px;
cursor: pointer;
}
.simlock{
background-image:url(images/mobile/sim_state.png);
background-repeat:no-repeat;
background-position:4px -46px;
height:30px;
width:30px;
cursor: pointer;
}
.simroamingon{
background-image:url(images/mobile/roaming.png);
background-repeat:no-repeat;
background-position:4px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.simroamingoff{
background-image:url(images/mobile/roaming.png);
background-repeat:no-repeat;
background-position:4px -50px;
height:30px;
width:30px;
cursor: pointer;
}
.simsignalfull{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:3px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.simsignalexcellent{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:2px -22px;
height:30px;
width:30px;
cursor: pointer;
}
.simsignalgood{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:2px -47px;
height:30px;
width:30px;
cursor: pointer;
}
.simsignalok{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:2px -72px;
height:30px;
width:30px;
cursor: pointer;
}
.simsignalmarginal{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:2px -97px;
height:30px;
width:30px;
cursor: pointer;
}
.simsignalno{
background-image:url(images/mobile/signal_strength.png);
background-repeat:no-repeat;
background-position:2px -122px;
height:30px;
width:30px;
cursor: pointer;
}
.img_wrap{
width:20px;
height:15px;
overflow:hidden;
position:relative;left:0px;top:0px;
}
.signalsysimg img{
position: relative;
top: 0px;
left: 4px;
max-width:15px;
cursor: pointer;
}
.img_wrap2{
width:30px;
height:30px;
overflow:hidden;
position:relative;left:2px;top:2px;
}
.<API key>{
cursor: pointer;
font-weight: bold;
background-color: #3366FF;
color: #FFFFFF;
margin-bottom: 10px;
}
.StatusClickHint{
text-decoration: underline;
cursor:pointer;
font-weight:bold;
margin-bottom: 10px;
}
.StatusHint{
font-weight:bold;
}
#overDiv{
filter:alpha(opacity=95);
opacity:.95;
z-index: 500;
}
#overDiv_table1{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 3px 3px 4px #333;
-webkit-box-shadow: 3px 3px 4px #333;
box-shadow: 3px 3px 4px #333;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#333333')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#333333');
text-shadow: 1px 1px 0px #FFF;
}
#overDiv_table2{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#overDiv_table3{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 3px 3px 4px #333;
-webkit-box-shadow: 3px 3px 4px #333;
box-shadow: 3px 3px 4px #000;
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#333333')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#333333');
}
#overDiv_table4{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
}
#overDiv_table5{
-<API key>: 5px;
-<API key>: 5px;
-<API key>: 5px;
-<API key>: 5px;
<API key>: 5px;
<API key>: 5px;
}
#notiDiv{
position: absolute;
filter:alpha(opacity=95);
opacity:.95;
z-index: 98;
width:250px;
margin-top:15px;
margin-left:-70px;
}
#notiDiv_table3{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: 3px 3px 4px #333;
-webkit-box-shadow: 3px 3px 4px #333;
box-shadow: 3px 3px 4px #000;
behavior: url(/PIE.htc);
*behavior: !important;
}
#notiDiv_table4{
-<API key>: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
behavior: url(/PIE.htc);
}
#notiDiv_table5{
behavior: url(/PIE.htc);
-<API key>: 5px;
-<API key>: 5px;
-<API key>: 5px;
-<API key>: 5px;
border-radius: 5px 5px 5px 5px ;
margin:3px 0px 0px 3px ;
behavior: url(/PIE.htc);
}
.aidisk1_table{
width:740px;
height:760px;
position:relative;
background-color:#4d595d;
}
.navigation {
margin-left:790px;
*margin-left:45px;
margin-top:13px;
width:100px;
list-style-type:none;
font:12px Arial, Helvetica, sans-serif;
position:absolute;
z-index:80;
}
.navigation li {
/*float:left; */
width:145px;
*width:145px;
}
.navigation li dl {
margin:0;
padding:0;
/* border:solid 2px #666; */
/* background-color:#fff;*/
}
.navigation li dt a , .navigation li dd a{
display:block;
}
.navigation li dt {
background-image:url('/images/New_ui/dropdown_bt.png');
padding-top:8px;
padding-right:8px;
text-align:center;
/*background-color:transparent;*/
font-size: 13px;
font-weight: bold;
height:24px;
overflow:hidden;
width:144px;
}
.navigation li dt:hover{
background-image:url('/images/New_ui/dropdown_btover.png');
background-color:transparent;
}
.navigation li dt a ,.navigation li dt a:visited {
display:block;
color:#fff;
}
.navigation li dd {
/*margin:0;*/
margin-left:3px;
/*padding:0;*/
color: #fff;
background-color:#333;
border-bottom:solid 1px #666;
width:145px;
}
.navigation li dd.last {
border-bottom:0;
}
.navigation li dd a, .navigation li dd a:visited {
display:block;
color:#fff;
padding:4px 5px 4px 5px;
}
.navigation li dd {
display:none;
}
.navigation li:hover dd, .navigation li a:hover dd {
cursor:pointer;
display:block;
}
.navigation li dd:hover{
text-decoration:underline;
background-color:#065280;
}
.textarea_ssh_table{
margin-left:2px;
padding-left:0.4em;
width: 500px;
height:184px;
line-height:23px;
font-size:12px;
font-family: Lucida Console;
background: #576D73;
border: 2px ridge #777;
border-style:bevel;
color:#FFFFFF;
}
.notification_on{
background-image:url(/images/New_ui/notification.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
}
.notification_off{
display: none;
}
.notification_on1{
cursor: pointer;
}
.vpnstatuson{
background-image:url(/images/New_ui/vpnstatus.png);
background-repeat:no-repeat;
background-position:2px 2px;
height:29px;
width:30px;
cursor: pointer;
display: none;
}
.vpnstatusoff{
background-image:url(/images/New_ui/vpnstatus.png);
background-repeat:no-repeat;
background-position:2px -48px;
height:29px;
width:30px;
cursor: pointer;
display: none;
}
.<API key>{
background-color: #000;
height: 30px;
cursor: pointer;
border: 1px solid #222;
}
.<API key>{
background-color: #4D595D;
height: 30px;
cursor: pointer;
border: 1px solid #222;
}
.traffictable th{
height:30px;
background-image: url(images/general_th.gif);
}
.traffictable th:hover{
cursor:pointer;
text-decoration: underline;
}
.traffictable_footer td{
color: cyan;
background-color:#4d595d;
}
.traffictable_link:hover {
cursor:pointer;
text-decoration: underline;
}
.panel_folder{
font-family:Courier ;
width:500px;
position:absolute;
z-index:2000;
display:none;
background-image:url(images/Tree/bg_01.png);
background-repeat:no-repeat;
}
/*Folder Tree*/
.folder_tree{
font-size:10pt;
margin:7px 0px 1px 30px;
height:332px;
overflow:auto;
overflow-x: hidden;
width:450px;
padding-right: 5px;
}
/* user account and folder "add", "delete", "modify"*/
.createAccountBtn{
background-image:url(images/New_ui/advancesetting/UserAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.deleteAccountBtn{
background-image:url(images/New_ui/advancesetting/UserDel_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserDel_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserDel_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.modifyAccountBtn{
background-image:url(images/New_ui/advancesetting/UserMod_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserMod_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/UserMod_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.createFolderBtn{
background-image:url(images/New_ui/advancesetting/FolderAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/FolderAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.createFolderBtn_add{
background-image:url(images/New_ui/advancesetting/FolderAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.createFolderBtn_add:hover{
background-image:url(images/New_ui/advancesetting/FolderAdd_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.deleteFolderBtn{
background-image:url(images/New_ui/advancesetting/FolderDel_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/FolderDel_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.deleteFolderBtn_add{
background-image:url(images/New_ui/advancesetting/FolderDel_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.deleteFolderBtn_add:hover{
background-image:url(images/New_ui/advancesetting/FolderDel_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.modifyFolderBtn{
background-image:url(images/New_ui/advancesetting/FolderMod_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
height:30px;
width:31px;
}
.<API key>{
background-image:url(images/New_ui/advancesetting/FolderMod_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.modifyFolderBtn_add{
background-image:url(images/New_ui/advancesetting/FolderMod_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
height:30px;
width:31px;
cursor: pointer;
}
.modifyFolderBtn_add:hover{
background-image:url(images/New_ui/advancesetting/FolderMod_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
height:30px;
width:31px;
cursor: pointer;
}
.userIcon{
background-image:url(images/New_ui/advancesetting/user_icon_ALL.png);
background-repeat:no-repeat;
background-position:0px -62px;
padding-left:30px;
height:30px;
width:31px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
line-height:25px;
}
.userIcon:hover{
background-image:url(images/New_ui/advancesetting/user_icon_ALL.png);
background-repeat:no-repeat;
background-position:0px -31px;
padding-left:30px;
height:30px;
width:31px;
cursor: pointer;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
line-height:25px;
}
.userIcon_click{
background-image:url(images/New_ui/advancesetting/user_icon_ALL.png);
background-repeat:no-repeat;
background-position:0px 0px;
padding-left:30px;
height:30px;
width:31px;
font-family:Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
line-height:25px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/line_dualwan.png);
background-repeat:no-repeat;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/<API key>.png);
background-repeat:no-repeat;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/line_dualwan.png);
background-repeat:no-repeat;
margin-left:68px;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/<API key>.png);
background-repeat:no-repeat;
margin-left:68px;
height:40px;
width:20px;
}
.primary_wan_standby{
background-image:url(/images/New_ui/networkmap/line_dualwan_dot.png);
background-repeat:no-repeat;
margin-left:68px;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/line_dualwan.png);
background-repeat:no-repeat;
margin-left:105px;
*margin-left:103px;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/<API key>.png);
background-repeat:no-repeat;
margin-left:105px;
*margin-left:103px;
height:40px;
width:20px;
}
.<API key>{
background-image:url(/images/New_ui/networkmap/line_dualwan_dot.png);
background-repeat:no-repeat;
margin-left:105px;
*margin-left:103px;
height:40px;
width:20px;
}
.link{
cursor:pointer !important;
text-decoration:underline !important;
} |
#include "<API key>.h"
namespace zigbee {
void
<API key>::add(<API key>::DeviceInfoObserver * observer, NwkAddr address) {
if (observer != nullptr) {
observers[address].insert(observer);
}
}
void
<API key>::remove( <API key>::DeviceInfoObserver * observer, NwkAddr address) {
if (observer != nullptr) {
observers[address].erase(observer);
}
}
void <API key>::dispatch(DeviceInfoMessage *deviceInfo) {
NwkAddr nwkAddr(deviceInfo->nwkAddr);
for (<API key>::DeviceInfoObserver* observer: observers[nwkAddr]){
observer->newDeviceInfo(deviceInfo);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace SshDotNet
{
public abstract class MacAlgorithm : IDisposable, ICloneable
{
protected KeyedHashAlgorithm _algorithm; // Algorithm to use.
private bool _isDisposed = false; // True if object has been disposed.
public MacAlgorithm()
{
}
~MacAlgorithm()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
{
// Dispose managed resources.
if (_algorithm != null) _algorithm.Clear();
}
// Dispose unmanaged resources.
}
_isDisposed = true;
}
public abstract string Name
{
get;
}
public abstract int DigestLength
{
get;
}
public KeyedHashAlgorithm Algorithm
{
get { return _algorithm; }
}
public virtual byte[] ComputeHash(byte[] input)
{
return _algorithm.ComputeHash(input);
}
public abstract object Clone();
}
} |
package org.eclipse.nebula.paperclips.core.grid;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.eclipse.nebula.paperclips.core.PaperClips;
import org.eclipse.nebula.paperclips.core.internal.util.PaperClipsUtil;
import org.eclipse.nebula.paperclips.core.internal.util.Util;
import org.eclipse.swt.SWT;
/**
* Describes the properties of a column in a GridPrint.
*
* @author Matthew Hall
*/
public class GridColumn {
/**
* The default alignment used when alignment is not specified. Value is
* SWT.LEFT.
*/
public static final int DEFAULT_ALIGN = SWT.LEFT;
/**
* The default size used when size is not specified. Value is SWT.DEFAULT.
*/
public static final int DEFAULT_SIZE = SWT.DEFAULT;
/**
* The default weight used when weight is not specified. Value is 0.
*/
public static final int DEFAULT_WEIGHT = 0;
/**
* The size property for this GridColumn. Possible values:
* <ul>
* <li>GridPrint.PREFERRED - indicates that the column should be as wide as
* the preferred width of its widest element.
* <li>SWT.DEFAULT - Similar to GridPrint.PREFERRED, except that the column
* may shrink down to its minimum width if space is scarce.
* <li>A value > 0 indicates that the column should be <code>size</code>
* points wide (72pts = 1").
* </ul>
*/
public final int size;
/**
* The default alignment for Prints in this column. Possible values are
* SWT.LEFT, SWT.CENTER, SWT.RIGHT, or SWT.DEFAULT. Note that alignment
* affects the placement of PrintPieces within the grid's cell--the
* alignment elements of the PrintPiece themselves are not affected. Thus,
* in order to achieve the desired effect, a Print having an alignment
* property should be set to the same alignment as the grid cell it is added
* to. For example, a TextPrint in a right-aligned grid cell should be set
* to right alignment as well.
* <p>
* Cells that span multiple columns use the alignment of the left-most cell
* in the cell span.
*/
public final int align;
/**
* The weight of this column. If the available print space is wider than the
* grid's preferred width, this field determines how much of that extra
* space should be given to this column. A larger weight causes the column
* to receive more of the extra width. A value of 0 indicates that the
* column should not be given any excess width.
*/
public final int weight;
/**
* Constructs a GridColumn.
*
* @param align
* The default alignment for Prints in this column.
* @param size
* The size this column should be given.
* @param weight
* The weight this column should be given.
*/
public GridColumn(int align, int size, int weight) {
this.align = checkAlign(align);
this.size = checkSize(size);
this.weight = checkWeight(weight);
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + align;
result = prime * result + size;
result = prime * result + weight;
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
GridColumn other = (GridColumn) obj;
if (align != other.align)
return false;
if (size != other.size)
return false;
if (weight != other.weight)
return false;
return true;
}
private static int checkAlign(int align) {
align = PaperClipsUtil.firstMatch(align, new int[] { SWT.LEFT,
SWT.CENTER, SWT.RIGHT, SWT.DEFAULT }, 0);
if (align == 0)
PaperClips
.error(
SWT.<API key>,
"Alignment argument must be one of SWT.LEFT, SWT.CENTER, SWT.RIGHT, or SWT.DEFAULT"); //$NON-NLS-1$
if (align == SWT.DEFAULT)
return DEFAULT_ALIGN;
return align;
}
private static int checkSize(int size) {
if (size != SWT.DEFAULT && size != GridPrint.PREFERRED && size <= 0)
PaperClips
.error(SWT.<API key>,
"Size argument must be SWT.DEFAULT, GridPrint.PREFERRED, or > 0"); //$NON-NLS-1$
return size;
}
private static int checkWeight(int grow) {
if (grow < 0)
PaperClips.error(SWT.<API key>,
"Weight argument must be >= 0"); //$NON-NLS-1$
return grow;
}
/**
* Parses the given column spec and returns a GridColumn matching that spec.
* <p>
* Format:
*
* <pre>
* [align:]size[:grow]
*
* align = L | LEFT |
* C | CENTER |
* R | RIGHT
* size = P | PREF | PREFERRED |
* D | DEF | DEFAULT |
* (Positive number)[PT|IN|INCH|CM|MM]
* weight = N | NONE |
* G | GROW | G(#) | GROW(#)
* </pre>
*
* The default alignment is LEFT. The
*
* <code>weight</code> argument expresses the weight property: NONE
* indicates a weight of 0; GROW indicates a weight of 1; and GROW(3)
* indicates a weight of 3. The default weight (if <code>weight</code> is
* omitted) is 0.
* <p>
* Examples:
*
* <pre>
* LEFT:DEFAULT:GROW // left-aligned, default size, weight=1
* R:72PT:N // light-aligned, 72 points (1") wide, weight=0
* right:72 // identical to previous line
* c:pref:none // center-aligned, preferred size, weight=0
* p // left-aligned (default), preferred size, weight=0
* r:2inch // right-aligned, 2 inches (50.8mm)
* r:50.8mm // right-aligned, 50.8 mm (2")
* </pre>
*
* @param spec
* the column spec that will be parsed.
* @return a GridColumn matching the column spec.
* @see #align
* @see #size
* @see #weight
*/
public static GridColumn parse(String spec) {
Util.notNull(spec);
String[] matches = spec.split("\\s*:\\s*"); //$NON-NLS-1$
if (matches.length == 0)
PaperClips.error(SWT.<API key>, "Missing column spec"); //$NON-NLS-1$
int align = DEFAULT_ALIGN;
int size = DEFAULT_SIZE;
int grow = DEFAULT_WEIGHT;
if (matches.length == 1) {
// One option: must be size
size = parseSize(matches[0]);
} else if (matches.length == 2) {
// Two possible scenarios:
// 1. align:size
// 2. size:weight
if (isAlign(matches[0])) {
align = parseAlign(matches[0]);
size = parseSize(matches[1]);
} else {
size = parseSize(matches[0]);
grow = parseWeight(matches[1]);
}
} else if (matches.length == 3) {
align = parseAlign(matches[0]);
size = parseSize(matches[1]);
grow = parseWeight(matches[2]);
}
return new GridColumn(align, size, grow);
}
// Alignment patterns
private static final Pattern LEFT_ALIGN_PATTERN = Pattern.compile(
"^l(eft)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern <API key> = Pattern.compile(
"^c(enter)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern RIGHT_ALIGN_PATTERN = Pattern.compile(
"^r(ight)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern ANY_ALIGN_PATTERN = Pattern.compile(
"^l(eft)?|c(enter)?|r(ight)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static boolean isAlign(String alignmentString) {
return ANY_ALIGN_PATTERN.matcher(alignmentString).matches();
}
private static int parseAlign(String alignmentString) {
if (LEFT_ALIGN_PATTERN.matcher(alignmentString).matches())
return SWT.LEFT;
else if (<API key>.matcher(alignmentString).matches())
return SWT.CENTER;
else if (RIGHT_ALIGN_PATTERN.matcher(alignmentString).matches())
return SWT.RIGHT;
PaperClips.error(SWT.<API key>,
"Unknown alignment \"" + alignmentString + "\""); //$NON-NLS-1$//$NON-NLS-2$
return 0; // unreachable
}
// Size patterns.
private static final Pattern <API key> = Pattern.compile(
"^d(ef(ault)?)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern <API key> = Pattern.compile(
"^p(ref(erred)?)?", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern <API key> = Pattern.compile(
"^(\\d+(\\.\\d+)?)\\s*(pt|in(ch)?|mm|cm)?$", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static int parseSize(String sizeString) {
Matcher matcher;
if (<API key>.matcher(sizeString).matches())
return SWT.DEFAULT;
else if (<API key>.matcher(sizeString).matches())
return GridPrint.PREFERRED;
else if ((matcher = <API key>.matcher(sizeString))
.matches()) {
return (int) Math.ceil(convertToPoints(Double.parseDouble(matcher
.group(1)), matcher.group(3)));
} else {
PaperClips.error(SWT.<API key>,
"Unknown size pattern: \"" + sizeString + "\""); //$NON-NLS-1$ //$NON-NLS-2$
return 0; // unreachable
}
}
private static double convertToPoints(double value, String unit) {
if (unit == null || unit.length() == 0 || unit.equalsIgnoreCase("pt")) //$NON-NLS-1$
return value;
else if (unit.equalsIgnoreCase("in") || unit.equalsIgnoreCase("inch")) //$NON-NLS-1$ //$NON-NLS-2$
return 72 * value;
else if (unit.equalsIgnoreCase("cm")) //$NON-NLS-1$
return 72 * value / 2.54;
else if (unit.equalsIgnoreCase("mm")) //$NON-NLS-1$
return 72 * value / 25.4;
PaperClips.error(SWT.<API key>,
"Unknown unit \"" + unit + "\"."); //$NON-NLS-1$ //$NON-NLS-2$
return 0;
}
private static final Pattern WEIGHTLESS_PATTERN = Pattern.compile(
"n(one)?", //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static final Pattern WEIGHTED_PATTERN = Pattern.compile(
"(g(row)?)(\\((\\d+)\\))?", // yikes //$NON-NLS-1$
Pattern.CASE_INSENSITIVE);
private static int parseWeight(String weightString) {
Matcher matcher;
if (WEIGHTLESS_PATTERN.matcher(weightString).matches())
return 0;
else if ((matcher = WEIGHTED_PATTERN.matcher(weightString)).matches()) {
String weight = matcher.group(4);
return (weight == null) ? 1 : Integer.parseInt(weight);
} else {
PaperClips.error(SWT.<API key>,
"Illegal grow pattern: \"" + weightString //$NON-NLS-1$
+ "\""); //$NON-NLS-1$
return 0; // unreachable
}
}
GridColumn copy() {
return new GridColumn(align, size, weight);
}
} |
#ifndef _tags_h
#define _tags_h
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define SYSCALL_TAG 0x11 /* Tag for server system calls */
#define SEMGET_TAG 0x10 /* Server subcommand i860_semget() */
#define SEMCTL_TAG 0x11 /* Server subcommand i860_semctl() */
#define SEMOP_TAG 0x12 /* Server subcommand i860_semop() */
#define SYNCALL_TAG 0x13 /* Server subcommand i860_syncall() */
#endif /* _tags_h */ |
#include <asm/uaccess.h>
#include <linux/bitops.h>
#include <linux/capability.h>
#include <linux/cpu.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/hash.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/mutex.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/sockios.h>
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#include <linux/notifier.h>
#include <linux/skbuff.h>
#include <net/net_namespace.h>
#include <net/sock.h>
#include <linux/rtnetlink.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/stat.h>
#include <net/dst.h>
#include <net/pkt_sched.h>
#include <net/checksum.h>
#include <net/xfrm.h>
#include <linux/highmem.h>
#include <linux/init.h>
#include <linux/kmod.h>
#include <linux/module.h>
#include <linux/netpoll.h>
#include <linux/rcupdate.h>
#include <linux/delay.h>
#include <net/wext.h>
#include <net/iw_handler.h>
#include <asm/current.h>
#include <linux/audit.h>
#include <linux/dmaengine.h>
#include <linux/err.h>
#include <linux/ctype.h>
#include <linux/if_arp.h>
#include <linux/if_vlan.h>
#include <linux/ip.h>
#include <net/ip.h>
#include <linux/ipv6.h>
#include <linux/in.h>
#include <linux/jhash.h>
#include <linux/random.h>
#include <trace/events/napi.h>
#include <trace/events/net.h>
#include <trace/events/skb.h>
#include <linux/pci.h>
#include <linux/inetdevice.h>
#include <linux/cpu_rmap.h>
#include <linux/net_tstamp.h>
#include <linux/static_key.h>
#include <net/flow_keys.h>
#include "net-sysfs.h"
/* Instead of increasing this, you should create a hash table. */
#define MAX_GRO_SKBS 8
/* This should be increased if a protocol with a bigger head is added. */
#define GRO_MAX_HEAD (MAX_HEADER + 128)
/*
* The list of packet types we will receive (as opposed to discard)
* and the routines to invoke.
*
* Why 16. Because with 16 the only overlap we get on a hash of the
* low nibble of the protocol value is RARP/SNAP/X.25.
*
* NOTE: That is no longer true with the addition of VLAN tags. Not
* sure which should go first, but I bet it won't make much
* difference if we are running VLANs. The good news is that
* this protocol won't be in the list unless compiled in, so
* the average user (w/out VLANs) will not be adversely affected.
* --BLG
*
* 0800 IP
* 8100 802.1Q VLAN
* 0001 802.3
* 0002 AX.25
* 0004 802.2
* 8035 RARP
* 0005 SNAP
* 0805 X.25
* 0806 ARP
* 8137 IPX
* 0009 Localtalk
* 86DD IPv6
*/
#define PTYPE_HASH_SIZE (16)
#define PTYPE_HASH_MASK (PTYPE_HASH_SIZE - 1)
static DEFINE_SPINLOCK(ptype_lock);
static struct list_head ptype_base[PTYPE_HASH_SIZE] __read_mostly;
static struct list_head ptype_all __read_mostly; /* Taps */
/*
* The @dev_base_head list is protected by @dev_base_lock and the rtnl
* semaphore.
*
* Pure readers hold dev_base_lock for reading, or rcu_read_lock()
*
* Writers must hold the rtnl semaphore while they loop through the
* dev_base_head list, and hold dev_base_lock for writing when they do the
* actual updates. This allows pure readers to access the list even
* while a writer is preparing to update it.
*
* To put it another way, dev_base_lock is held for writing only to
* protect against pure readers; the rtnl semaphore provides the
* protection against other writers.
*
* See, for example usages, register_netdevice() and
* <API key>(), which must be called with the rtnl
* semaphore held.
*/
DEFINE_RWLOCK(dev_base_lock);
EXPORT_SYMBOL(dev_base_lock);
static inline void dev_base_seq_inc(struct net *net)
{
while (++net->dev_base_seq == 0);
}
static inline struct hlist_head *dev_name_hash(struct net *net, const char *name)
{
unsigned int hash = full_name_hash(name, strnlen(name, IFNAMSIZ));
return &net->dev_name_head[hash_32(hash, NETDEV_HASHBITS)];
}
static inline struct hlist_head *dev_index_hash(struct net *net, int ifindex)
{
return &net->dev_index_head[ifindex & (NETDEV_HASHENTRIES - 1)];
}
static inline void rps_lock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_lock(&sd->input_pkt_queue.lock);
#endif
}
static inline void rps_unlock(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
spin_unlock(&sd->input_pkt_queue.lock);
#endif
}
/* Device list insertion */
static int list_netdevice(struct net_device *dev)
{
struct net *net = dev_net(dev);
ASSERT_RTNL();
write_lock_bh(&dev_base_lock);
list_add_tail_rcu(&dev->dev_list, &net->dev_base_head);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
hlist_add_head_rcu(&dev->index_hlist,
dev_index_hash(net, dev->ifindex));
write_unlock_bh(&dev_base_lock);
dev_base_seq_inc(net);
return 0;
}
/* Device list removal
* caller must respect a RCU grace period before freeing/reusing dev
*/
static void unlist_netdevice(struct net_device *dev)
{
ASSERT_RTNL();
/* Unlink dev from the device chain */
write_lock_bh(&dev_base_lock);
list_del_rcu(&dev->dev_list);
hlist_del_rcu(&dev->name_hlist);
hlist_del_rcu(&dev->index_hlist);
write_unlock_bh(&dev_base_lock);
dev_base_seq_inc(dev_net(dev));
}
/*
* Our notifier list
*/
static RAW_NOTIFIER_HEAD(netdev_chain);
/*
* Device drivers call our routines to queue packets here. We empty the
* queue in the local softnet handler.
*/
<API key>(struct softnet_data, softnet_data);
<API key>(softnet_data);
#ifdef CONFIG_LOCKDEP
/*
* register_netdevice() inits txq->_xmit_lock and sets lockdep class
* according to dev->type
*/
static const unsigned short netdev_lock_type[] =
{ARPHRD_NETROM, ARPHRD_ETHER, ARPHRD_EETHER, ARPHRD_AX25,
ARPHRD_PRONET, ARPHRD_CHAOS, ARPHRD_IEEE802, ARPHRD_ARCNET,
ARPHRD_APPLETLK, ARPHRD_DLCI, ARPHRD_ATM, ARPHRD_METRICOM,
ARPHRD_IEEE1394, ARPHRD_EUI64, ARPHRD_INFINIBAND, ARPHRD_SLIP,
ARPHRD_CSLIP, ARPHRD_SLIP6, ARPHRD_CSLIP6, ARPHRD_RSRVD,
ARPHRD_ADAPT, ARPHRD_ROSE, ARPHRD_X25, ARPHRD_HWX25,
ARPHRD_PPP, ARPHRD_CISCO, ARPHRD_LAPB, ARPHRD_DDCMP,
ARPHRD_RAWHDLC, ARPHRD_TUNNEL, ARPHRD_TUNNEL6, ARPHRD_FRAD,
ARPHRD_SKIP, ARPHRD_LOOPBACK, ARPHRD_LOCALTLK, ARPHRD_FDDI,
ARPHRD_BIF, ARPHRD_SIT, ARPHRD_IPDDP, ARPHRD_IPGRE,
ARPHRD_PIMREG, ARPHRD_HIPPI, ARPHRD_ASH, ARPHRD_ECONET,
ARPHRD_IRDA, ARPHRD_FCPP, ARPHRD_FCAL, ARPHRD_FCPL,
ARPHRD_FCFABRIC, ARPHRD_IEEE80211, <API key>,
<API key>, ARPHRD_PHONET, ARPHRD_PHONET_PIPE,
ARPHRD_IEEE802154, ARPHRD_VOID, ARPHRD_NONE};
static const char *const netdev_lock_name[] =
{"_xmit_NETROM", "_xmit_ETHER", "_xmit_EETHER", "_xmit_AX25",
"_xmit_PRONET", "_xmit_CHAOS", "_xmit_IEEE802", "_xmit_ARCNET",
"_xmit_APPLETLK", "_xmit_DLCI", "_xmit_ATM", "_xmit_METRICOM",
"_xmit_IEEE1394", "_xmit_EUI64", "_xmit_INFINIBAND", "_xmit_SLIP",
"_xmit_CSLIP", "_xmit_SLIP6", "_xmit_CSLIP6", "_xmit_RSRVD",
"_xmit_ADAPT", "_xmit_ROSE", "_xmit_X25", "_xmit_HWX25",
"_xmit_PPP", "_xmit_CISCO", "_xmit_LAPB", "_xmit_DDCMP",
"_xmit_RAWHDLC", "_xmit_TUNNEL", "_xmit_TUNNEL6", "_xmit_FRAD",
"_xmit_SKIP", "_xmit_LOOPBACK", "_xmit_LOCALTLK", "_xmit_FDDI",
"_xmit_BIF", "_xmit_SIT", "_xmit_IPDDP", "_xmit_IPGRE",
"_xmit_PIMREG", "_xmit_HIPPI", "_xmit_ASH", "_xmit_ECONET",
"_xmit_IRDA", "_xmit_FCPP", "_xmit_FCAL", "_xmit_FCPL",
"_xmit_FCFABRIC", "_xmit_IEEE80211", "<API key>",
"<API key>", "_xmit_PHONET", "_xmit_PHONET_PIPE",
"_xmit_IEEE802154", "_xmit_VOID", "_xmit_NONE"};
static struct lock_class_key <API key>[ARRAY_SIZE(netdev_lock_type)];
static struct lock_class_key <API key>[ARRAY_SIZE(netdev_lock_type)];
static inline unsigned short netdev_lock_pos(unsigned short dev_type)
{
int i;
for (i = 0; i < ARRAY_SIZE(netdev_lock_type); i++)
if (netdev_lock_type[i] == dev_type)
return i;
/* the last key is used by default */
return ARRAY_SIZE(netdev_lock_type) - 1;
}
static inline void <API key>(spinlock_t *lock,
unsigned short dev_type)
{
int i;
i = netdev_lock_pos(dev_type);
<API key>(lock, &<API key>[i],
netdev_lock_name[i]);
}
static inline void <API key>(struct net_device *dev)
{
int i;
i = netdev_lock_pos(dev->type);
<API key>(&dev->addr_list_lock,
&<API key>[i],
netdev_lock_name[i]);
}
#else
static inline void <API key>(spinlock_t *lock,
unsigned short dev_type)
{
}
static inline void <API key>(struct net_device *dev)
{
}
#endif
/*
* Add a protocol ID to the list. Now that the input handler is
* smarter we can dispense with all the messy stuff that used to be
* here.
*
* BEWARE!!! Protocol handlers, mangling input packets,
* MUST BE last in hash buckets and checking protocol handlers
* MUST start from promiscuous ptype_all chain in net_bh.
* It is true now, do not change it.
* Explanation follows: if protocol handler, mangling packet, will
* be the first on list, it is not able to sense, that packet
* is cloned and should be copied-on-write, so that it will
* change it and subsequent readers will get broken packet.
* --ANK (980803)
*/
static inline struct list_head *ptype_head(const struct packet_type *pt)
{
if (pt->type == htons(ETH_P_ALL))
return &ptype_all;
else
return &ptype_base[ntohs(pt->type) & PTYPE_HASH_MASK];
}
/**
* dev_add_pack - add packet handler
* @pt: packet type declaration
*
* Add a protocol handler to the networking stack. The passed &packet_type
* is linked into kernel lists and may not be freed until it has been
* removed from the kernel lists.
*
* This call does not sleep therefore it can not
* guarantee all CPU's that are in middle of receiving packets
* will see the new packet type (until the next received packet).
*/
void dev_add_pack(struct packet_type *pt)
{
struct list_head *head = ptype_head(pt);
spin_lock(&ptype_lock);
list_add_rcu(&pt->list, head);
spin_unlock(&ptype_lock);
}
EXPORT_SYMBOL(dev_add_pack);
/**
* __dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* The packet type might still be in use by receivers
* and must not be freed until after all the CPU's have gone
* through a quiescent state.
*/
void __dev_remove_pack(struct packet_type *pt)
{
struct list_head *head = ptype_head(pt);
struct packet_type *pt1;
spin_lock(&ptype_lock);
list_for_each_entry(pt1, head, list) {
if (pt == pt1) {
list_del_rcu(&pt->list);
goto out;
}
}
pr_warn("dev_remove_pack: %p not found\n", pt);
out:
spin_unlock(&ptype_lock);
}
EXPORT_SYMBOL(__dev_remove_pack);
/**
* dev_remove_pack - remove packet handler
* @pt: packet type declaration
*
* Remove a protocol handler that was previously added to the kernel
* protocol handlers by dev_add_pack(). The passed &packet_type is removed
* from the kernel lists and can be freed or reused once this function
* returns.
*
* This call sleeps to guarantee that no CPU is looking at the packet
* type after return.
*/
void dev_remove_pack(struct packet_type *pt)
{
__dev_remove_pack(pt);
synchronize_net();
}
EXPORT_SYMBOL(dev_remove_pack);
/* Boot time configuration table */
static struct netdev_boot_setup dev_boot_setup[<API key>];
/**
* <API key> - add new setup entry
* @name: name of the device
* @map: configured settings for the device
*
* Adds new setup entry to the dev_boot_setup list. The function
* returns 0 on error and 1 on success. This is a generic routine to
* all netdevices.
*/
static int <API key>(char *name, struct ifmap *map)
{
struct netdev_boot_setup *s;
int i;
s = dev_boot_setup;
for (i = 0; i < <API key>; i++) {
if (s[i].name[0] == '\0' || s[i].name[0] == ' ') {
memset(s[i].name, 0, sizeof(s[i].name));
strlcpy(s[i].name, name, IFNAMSIZ);
memcpy(&s[i].map, map, sizeof(s[i].map));
break;
}
}
return i >= <API key> ? 0 : 1;
}
/**
* <API key> - check boot time settings
* @dev: the netdevice
*
* Check boot time settings for the device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found, 1 if they are.
*/
int <API key>(struct net_device *dev)
{
struct netdev_boot_setup *s = dev_boot_setup;
int i;
for (i = 0; i < <API key>; i++) {
if (s[i].name[0] != '\0' && s[i].name[0] != ' ' &&
!strcmp(dev->name, s[i].name)) {
dev->irq = s[i].map.irq;
dev->base_addr = s[i].map.base_addr;
dev->mem_start = s[i].map.mem_start;
dev->mem_end = s[i].map.mem_end;
return 1;
}
}
return 0;
}
EXPORT_SYMBOL(<API key>);
/**
* netdev_boot_base - get address from boot time settings
* @prefix: prefix for network device
* @unit: id for network device
*
* Check boot time settings for the base address of device.
* The found settings are set for the device to be used
* later in the device probing.
* Returns 0 if no settings found.
*/
unsigned long netdev_boot_base(const char *prefix, int unit)
{
const struct netdev_boot_setup *s = dev_boot_setup;
char name[IFNAMSIZ];
int i;
sprintf(name, "%s%d", prefix, unit);
/*
* If device already registered then return base of 1
* to indicate not to probe for this interface
*/
if (__dev_get_by_name(&init_net, name))
return 1;
for (i = 0; i < <API key>; i++)
if (!strcmp(name, s[i].name))
return s[i].map.base_addr;
return 0;
}
/*
* Saves at boot time configured settings for any netdevice.
*/
int __init netdev_boot_setup(char *str)
{
int ints[5];
struct ifmap map;
str = get_options(str, ARRAY_SIZE(ints), ints);
if (!str || !*str)
return 0;
/* Save settings */
memset(&map, 0, sizeof(map));
if (ints[0] > 0)
map.irq = ints[1];
if (ints[0] > 1)
map.base_addr = ints[2];
if (ints[0] > 2)
map.mem_start = ints[3];
if (ints[0] > 3)
map.mem_end = ints[4];
/* Add new entry to the list */
return <API key>(str, &map);
}
__setup("netdev=", netdev_boot_setup);
/**
* __dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. Must be called under RTNL semaphore
* or @dev_base_lock. If the name is found a pointer to the device
* is returned. If the name is not found then %NULL is returned. The
* reference counters are not incremented so the caller must be
* careful with locks.
*/
struct net_device *__dev_get_by_name(struct net *net, const char *name)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
<API key>(dev, p, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_name);
/**
* dev_get_by_name_rcu - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name.
* If the name is found a pointer to the device is returned.
* If the name is not found then %NULL is returned.
* The reference counters are not incremented so the caller must be
* careful with locks. The caller must hold RCU lock.
*/
struct net_device *dev_get_by_name_rcu(struct net *net, const char *name)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_name_hash(net, name);
<API key>(dev, p, head, name_hlist)
if (!strncmp(dev->name, name, IFNAMSIZ))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_get_by_name_rcu);
/**
* dev_get_by_name - find a device by its name
* @net: the applicable net namespace
* @name: name to find
*
* Find an interface by name. This can be called from any
* context and does its own locking. The returned handle has
* the usage count incremented and the caller must use dev_put() to
* release it when it is no longer needed. %NULL is returned if no
* matching device is found.
*/
struct net_device *dev_get_by_name(struct net *net, const char *name)
{
struct net_device *dev;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, name);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_name);
/**
* __dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold either the RTNL semaphore
* or @dev_base_lock.
*/
struct net_device *__dev_get_by_index(struct net *net, int ifindex)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
<API key>(dev, p, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(__dev_get_by_index);
/**
* <API key> - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns %NULL if the device
* is not found or a pointer to the device. The device has not
* had its reference counter increased so the caller must be careful
* about locking. The caller must hold RCU lock.
*/
struct net_device *<API key>(struct net *net, int ifindex)
{
struct hlist_node *p;
struct net_device *dev;
struct hlist_head *head = dev_index_hash(net, ifindex);
<API key>(dev, p, head, index_hlist)
if (dev->ifindex == ifindex)
return dev;
return NULL;
}
EXPORT_SYMBOL(<API key>);
/**
* dev_get_by_index - find a device by its ifindex
* @net: the applicable net namespace
* @ifindex: index of device
*
* Search for an interface by index. Returns NULL if the device
* is not found or a pointer to the device. The device returned has
* had a reference added and the pointer is safe until the user calls
* dev_put to indicate they have finished with it.
*/
struct net_device *dev_get_by_index(struct net *net, int ifindex)
{
struct net_device *dev;
rcu_read_lock();
dev = <API key>(net, ifindex);
if (dev)
dev_hold(dev);
rcu_read_unlock();
return dev;
}
EXPORT_SYMBOL(dev_get_by_index);
/**
* dev_getbyhwaddr_rcu - find a device by its hardware address
* @net: the applicable net namespace
* @type: media type of device
* @ha: hardware address
*
* Search for an interface by MAC address. Returns NULL if the device
* is not found or a pointer to the device.
* The caller must hold RCU or RTNL.
* The returned device has not had its ref count increased
* and the caller must therefore be careful about locking
*
*/
struct net_device *dev_getbyhwaddr_rcu(struct net *net, unsigned short type,
const char *ha)
{
struct net_device *dev;
for_each_netdev_rcu(net, dev)
if (dev->type == type &&
!memcmp(dev->dev_addr, ha, dev->addr_len))
return dev;
return NULL;
}
EXPORT_SYMBOL(dev_getbyhwaddr_rcu);
struct net_device *<API key>(struct net *net, unsigned short type)
{
struct net_device *dev;
ASSERT_RTNL();
for_each_netdev(net, dev)
if (dev->type == type)
return dev;
return NULL;
}
EXPORT_SYMBOL(<API key>);
struct net_device *<API key>(struct net *net, unsigned short type)
{
struct net_device *dev, *ret = NULL;
rcu_read_lock();
for_each_netdev_rcu(net, dev)
if (dev->type == type) {
dev_hold(dev);
ret = dev;
break;
}
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - find any device with given flags
* @net: the applicable net namespace
* @if_flags: IFF_* values
* @mask: bitmask of bits in if_flags to check
*
* Search for any interface with the given flags. Returns NULL if a device
* is not found or a pointer to the device. Must be called inside
* rcu_read_lock(), and result refcount is unchanged.
*/
struct net_device *<API key>(struct net *net, unsigned short if_flags,
unsigned short mask)
{
struct net_device *dev, *ret;
ret = NULL;
for_each_netdev_rcu(net, dev) {
if (((dev->flags ^ if_flags) & mask) == 0) {
ret = dev;
break;
}
}
return ret;
}
EXPORT_SYMBOL(<API key>);
/**
* dev_valid_name - check if name is okay for network device
* @name: name string
*
* Network device names need to be valid file names to
* to allow sysfs to work. We also disallow any kind of
* whitespace.
*/
bool dev_valid_name(const char *name)
{
if (*name == '\0')
return false;
if (strlen(name) >= IFNAMSIZ)
return false;
if (!strcmp(name, ".") || !strcmp(name, ".."))
return false;
while (*name) {
if (*name == '/' || isspace(*name))
return false;
name++;
}
return true;
}
EXPORT_SYMBOL(dev_valid_name);
/**
* __dev_alloc_name - allocate a name for a device
* @net: network namespace to allocate the device name in
* @name: name format string
* @buf: scratch buffer and result name string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
static int __dev_alloc_name(struct net *net, const char *name, char *buf)
{
int i = 0;
const char *p;
const int max_netdevices = 8*PAGE_SIZE;
unsigned long *inuse;
struct net_device *d;
p = strnchr(name, IFNAMSIZ-1, '%');
if (p) {
/*
* Verify the string as this thing may have come from
* the user. There must be either one "%d" and no other "%"
* characters.
*/
if (p[1] != 'd' || strchr(p + 2, '%'))
return -EINVAL;
/* Use one page as a bit array of possible slots */
inuse = (unsigned long *) get_zeroed_page(GFP_ATOMIC);
if (!inuse)
return -ENOMEM;
for_each_netdev(net, d) {
if (!sscanf(d->name, name, &i))
continue;
if (i < 0 || i >= max_netdevices)
continue;
/* avoid cases where sscanf is not exact inverse of printf */
snprintf(buf, IFNAMSIZ, name, i);
if (!strncmp(buf, d->name, IFNAMSIZ))
set_bit(i, inuse);
}
i = find_first_zero_bit(inuse, max_netdevices);
free_page((unsigned long) inuse);
}
if (buf != name)
snprintf(buf, IFNAMSIZ, name, i);
if (!__dev_get_by_name(net, buf))
return i;
/* It is possible to run out of possible slots
* when the name is long and there isn't enough space left
* for the digits, or if all bits are used.
*/
return -ENFILE;
}
/**
* dev_alloc_name - allocate a name for a device
* @dev: device
* @name: name format string
*
* Passed a format string - eg "lt%d" it will try and find a suitable
* id. It scans list of devices to build up a free map, then chooses
* the first empty slot. The caller must hold the dev_base or rtnl lock
* while allocating the name and adding the device in order to avoid
* duplicates.
* Limited to bits_per_byte * page size devices (ie 32K on most platforms).
* Returns the number of the unit assigned or a negative errno code.
*/
int dev_alloc_name(struct net_device *dev, const char *name)
{
char buf[IFNAMSIZ];
struct net *net;
int ret;
BUG_ON(!dev_net(dev));
net = dev_net(dev);
ret = __dev_alloc_name(net, name, buf);
if (ret >= 0)
strlcpy(dev->name, buf, IFNAMSIZ);
return ret;
}
EXPORT_SYMBOL(dev_alloc_name);
static int dev_get_valid_name(struct net_device *dev, const char *name)
{
struct net *net;
BUG_ON(!dev_net(dev));
net = dev_net(dev);
if (!dev_valid_name(name))
return -EINVAL;
if (strchr(name, '%'))
return dev_alloc_name(dev, name);
else if (__dev_get_by_name(net, name))
return -EEXIST;
else if (dev->name != name)
strlcpy(dev->name, name, IFNAMSIZ);
return 0;
}
/**
* dev_change_name - change name of a device
* @dev: device
* @newname: name (or format string) must be at least IFNAMSIZ
*
* Change name of a device, can pass format strings "eth%d".
* for wildcarding.
*/
int dev_change_name(struct net_device *dev, const char *newname)
{
char oldname[IFNAMSIZ];
int err = 0;
int ret;
struct net *net;
ASSERT_RTNL();
BUG_ON(!dev_net(dev));
net = dev_net(dev);
if (dev->flags & IFF_UP)
return -EBUSY;
if (strncmp(newname, dev->name, IFNAMSIZ) == 0)
return 0;
memcpy(oldname, dev->name, IFNAMSIZ);
err = dev_get_valid_name(dev, newname);
if (err < 0)
return err;
rollback:
ret = device_rename(&dev->dev, dev->name);
if (ret) {
memcpy(dev->name, oldname, IFNAMSIZ);
return ret;
}
write_lock_bh(&dev_base_lock);
hlist_del_rcu(&dev->name_hlist);
write_unlock_bh(&dev_base_lock);
synchronize_rcu();
write_lock_bh(&dev_base_lock);
hlist_add_head_rcu(&dev->name_hlist, dev_name_hash(net, dev->name));
write_unlock_bh(&dev_base_lock);
ret = <API key>(NETDEV_CHANGENAME, dev);
ret = notifier_to_errno(ret);
if (ret) {
/* err >= 0 after dev_alloc_name() or stores the first errno */
if (err >= 0) {
err = ret;
memcpy(dev->name, oldname, IFNAMSIZ);
goto rollback;
} else {
pr_err("%s: name change rollback failed: %d\n",
dev->name, ret);
}
}
return err;
}
/**
* dev_set_alias - change ifalias of a device
* @dev: device
* @alias: name up to IFALIASZ
* @len: limit of bytes to copy from info
*
* Set ifalias for a device,
*/
int dev_set_alias(struct net_device *dev, const char *alias, size_t len)
{
ASSERT_RTNL();
if (len >= IFALIASZ)
return -EINVAL;
if (!len) {
if (dev->ifalias) {
kfree(dev->ifalias);
dev->ifalias = NULL;
}
return 0;
}
dev->ifalias = krealloc(dev->ifalias, len + 1, GFP_KERNEL);
if (!dev->ifalias)
return -ENOMEM;
strlcpy(dev->ifalias, alias, len+1);
return len;
}
/**
* <API key> - device changes features
* @dev: device to cause notification
*
* Called to indicate a device has changed features.
*/
void <API key>(struct net_device *dev)
{
<API key>(NETDEV_FEAT_CHANGE, dev);
}
EXPORT_SYMBOL(<API key>);
/**
* netdev_state_change - device changes state
* @dev: device to cause notification
*
* Called to indicate a device has changed state. This function calls
* the notifier chains for netdev_chain and sends a NEWLINK message
* to the routing socket.
*/
void netdev_state_change(struct net_device *dev)
{
if (dev->flags & IFF_UP) {
<API key>(NETDEV_CHANGE, dev);
rtmsg_ifinfo(RTM_NEWLINK, dev, 0);
}
}
EXPORT_SYMBOL(netdev_state_change);
int <API key>(struct net_device *dev, unsigned long event)
{
return <API key>(event, dev);
}
EXPORT_SYMBOL(<API key>);
/**
* dev_load - load a network module
* @net: the applicable net namespace
* @name: name of interface
*
* If a network interface is not present and the process has suitable
* privileges this function loads the module. If module loading is not
* available in this kernel then it becomes a nop.
*/
void dev_load(struct net *net, const char *name)
{
struct net_device *dev;
int no_module;
rcu_read_lock();
dev = dev_get_by_name_rcu(net, name);
rcu_read_unlock();
no_module = !dev;
if (no_module && capable(CAP_NET_ADMIN))
no_module = request_module("netdev-%s", name);
if (no_module && capable(CAP_SYS_MODULE)) {
if (!request_module("%s", name))
pr_warn("Loading kernel module for a network device with CAP_SYS_MODULE (deprecated). Use CAP_NET_ADMIN and alias netdev-%s instead.\n",
name);
}
}
EXPORT_SYMBOL(dev_load);
static int __dev_open(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
int ret;
ASSERT_RTNL();
if (!<API key>(dev))
return -ENODEV;
ret = <API key>(NETDEV_PRE_UP, dev);
ret = notifier_to_errno(ret);
if (ret)
return ret;
set_bit(__LINK_STATE_START, &dev->state);
if (ops->ndo_validate_addr)
ret = ops->ndo_validate_addr(dev);
if (!ret && ops->ndo_open)
ret = ops->ndo_open(dev);
if (ret)
clear_bit(__LINK_STATE_START, &dev->state);
else {
dev->flags |= IFF_UP;
net_dmaengine_get();
dev_set_rx_mode(dev);
dev_activate(dev);
}
return ret;
}
/**
* dev_open - prepare an interface for use.
* @dev: device to open
*
* Takes a device from down to up state. The device's private open
* function is invoked and then the multicast lists are loaded. Finally
* the device is moved into the up state and a %NETDEV_UP message is
* sent to the netdev notifier chain.
*
* Calling this function on an active interface is a nop. On a failure
* a negative errno code is returned.
*/
int dev_open(struct net_device *dev)
{
int ret;
if (dev->flags & IFF_UP)
return 0;
ret = __dev_open(dev);
if (ret < 0)
return ret;
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
<API key>(NETDEV_UP, dev);
return ret;
}
EXPORT_SYMBOL(dev_open);
static int __dev_close_many(struct list_head *head)
{
struct net_device *dev;
ASSERT_RTNL();
might_sleep();
list_for_each_entry(dev, head, unreg_list) {
<API key>(NETDEV_GOING_DOWN, dev);
clear_bit(__LINK_STATE_START, &dev->state);
/* Synchronize to scheduled poll. We cannot touch poll list, it
* can be even on different cpu. So just clear netif_running().
*
* dev->stop() will invoke napi_disable() on all of it's
* napi_struct instances on this device.
*/
<API key>(); /* Commit netif_running(). */
}
dev_deactivate_many(head);
list_for_each_entry(dev, head, unreg_list) {
const struct net_device_ops *ops = dev->netdev_ops;
/*
* Call the device specific close. This cannot fail.
* Only if device is UP
*
* We allow it to be called even after a DETACH hot-plug
* event.
*/
if (ops->ndo_stop)
ops->ndo_stop(dev);
dev->flags &= ~IFF_UP;
net_dmaengine_put();
}
return 0;
}
static int __dev_close(struct net_device *dev)
{
int retval;
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
retval = __dev_close_many(&single);
list_del(&single);
return retval;
}
static int dev_close_many(struct list_head *head)
{
struct net_device *dev, *tmp;
LIST_HEAD(tmp_list);
<API key>(dev, tmp, head, unreg_list)
if (!(dev->flags & IFF_UP))
list_move(&dev->unreg_list, &tmp_list);
__dev_close_many(head);
list_for_each_entry(dev, head, unreg_list) {
rtmsg_ifinfo(RTM_NEWLINK, dev, IFF_UP|IFF_RUNNING);
<API key>(NETDEV_DOWN, dev);
}
/* <API key> needs the complete original list */
list_splice(&tmp_list, head);
return 0;
}
/**
* dev_close - shutdown an interface.
* @dev: device to shutdown
*
* This function moves an active device into down state. A
* %NETDEV_GOING_DOWN is sent to the netdev notifier chain. The device
* is then deactivated and finally a %NETDEV_DOWN is sent to the notifier
* chain.
*/
int dev_close(struct net_device *dev)
{
if (dev->flags & IFF_UP) {
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
dev_close_many(&single);
list_del(&single);
}
return 0;
}
EXPORT_SYMBOL(dev_close);
/**
* dev_disable_lro - disable Large Receive Offload on a device
* @dev: device
*
* Disable Large Receive Offload (LRO) on a net device. Must be
* called under RTNL. This is needed if received packets may be
* forwarded to another interface.
*/
void dev_disable_lro(struct net_device *dev)
{
/*
* If we're trying to disable lro on a vlan device
* use the underlying physical device instead
*/
if (is_vlan_dev(dev))
dev = vlan_dev_real_dev(dev);
dev->wanted_features &= ~NETIF_F_LRO;
<API key>(dev);
if (unlikely(dev->features & NETIF_F_LRO))
netdev_WARN(dev, "failed to disable LRO!\n");
}
EXPORT_SYMBOL(dev_disable_lro);
static int dev_boot_phase = 1;
/**
* <API key> - register a network notifier block
* @nb: notifier
*
* Register a notifier to be called when network device events occur.
* The notifier passed is linked into the kernel structures and must
* not be reused until it has been unregistered. A negative errno code
* is returned on a failure.
*
* When registered all registration and up events are replayed
* to the new notifier to allow device to have a race free
* view of the network device list.
*/
int <API key>(struct notifier_block *nb)
{
struct net_device *dev;
struct net_device *last;
struct net *net;
int err;
rtnl_lock();
err = <API key>(&netdev_chain, nb);
if (err)
goto unlock;
if (dev_boot_phase)
goto unlock;
for_each_net(net) {
for_each_netdev(net, dev) {
err = nb->notifier_call(nb, NETDEV_REGISTER, dev);
err = notifier_to_errno(err);
if (err)
goto rollback;
if (!(dev->flags & IFF_UP))
continue;
nb->notifier_call(nb, NETDEV_UP, dev);
}
}
unlock:
rtnl_unlock();
return err;
rollback:
last = dev;
for_each_net(net) {
for_each_netdev(net, dev) {
if (dev == last)
goto outroll;
if (dev->flags & IFF_UP) {
nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);
nb->notifier_call(nb, NETDEV_DOWN, dev);
}
nb->notifier_call(nb, NETDEV_UNREGISTER, dev);
nb->notifier_call(nb, <API key>, dev);
}
}
outroll:
<API key>(&netdev_chain, nb);
goto unlock;
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - unregister a network notifier block
* @nb: notifier
*
* Unregister a notifier previously registered by
* <API key>(). The notifier is unlinked into the
* kernel structures and may then be reused. A negative errno code
* is returned on a failure.
*
* After unregistering unregister and down device events are synthesized
* for all devices on the device list to the removed notifier to remove
* the need for special case cleanup code.
*/
int <API key>(struct notifier_block *nb)
{
struct net_device *dev;
struct net *net;
int err;
rtnl_lock();
err = <API key>(&netdev_chain, nb);
if (err)
goto unlock;
for_each_net(net) {
for_each_netdev(net, dev) {
if (dev->flags & IFF_UP) {
nb->notifier_call(nb, NETDEV_GOING_DOWN, dev);
nb->notifier_call(nb, NETDEV_DOWN, dev);
}
nb->notifier_call(nb, NETDEV_UNREGISTER, dev);
nb->notifier_call(nb, <API key>, dev);
}
}
unlock:
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - call all network notifier blocks
* @val: value passed unmodified to notifier function
* @dev: net_device pointer passed unmodified to notifier function
*
* Call all network notifier blocks. Parameters and return value
* are as for <API key>().
*/
int <API key>(unsigned long val, struct net_device *dev)
{
ASSERT_RTNL();
return <API key>(&netdev_chain, val, dev);
}
EXPORT_SYMBOL(<API key>);
static struct static_key netstamp_needed __read_mostly;
#ifdef HAVE_JUMP_LABEL
/* We are not allowed to call static_key_slow_dec() from irq context
* If <API key>() is called from irq context, defer the
* static_key_slow_dec() calls.
*/
static atomic_t <API key>;
#endif
void <API key>(void)
{
#ifdef HAVE_JUMP_LABEL
int deferred = atomic_xchg(&<API key>, 0);
if (deferred) {
while (--deferred)
static_key_slow_dec(&netstamp_needed);
return;
}
#endif
WARN_ON(in_interrupt());
static_key_slow_inc(&netstamp_needed);
}
EXPORT_SYMBOL(<API key>);
void <API key>(void)
{
#ifdef HAVE_JUMP_LABEL
if (in_interrupt()) {
atomic_inc(&<API key>);
return;
}
#endif
static_key_slow_dec(&netstamp_needed);
}
EXPORT_SYMBOL(<API key>);
static inline void net_timestamp_set(struct sk_buff *skb)
{
skb->tstamp.tv64 = 0;
if (static_key_false(&netstamp_needed))
__net_timestamp(skb);
}
#define net_timestamp_check(COND, SKB) \
if (static_key_false(&netstamp_needed)) { \
if ((COND) && !(SKB)->tstamp.tv64) \
__net_timestamp(SKB); \
} \
static int <API key>(struct ifreq *ifr)
{
struct hwtstamp_config cfg;
enum hwtstamp_tx_types tx_type;
enum hwtstamp_rx_filters rx_filter;
int tx_type_valid = 0;
int rx_filter_valid = 0;
if (copy_from_user(&cfg, ifr->ifr_data, sizeof(cfg)))
return -EFAULT;
if (cfg.flags) /* reserved for future extensions */
return -EINVAL;
tx_type = cfg.tx_type;
rx_filter = cfg.rx_filter;
switch (tx_type) {
case HWTSTAMP_TX_OFF:
case HWTSTAMP_TX_ON:
case <API key>:
tx_type_valid = 1;
break;
}
switch (rx_filter) {
case <API key>:
case HWTSTAMP_FILTER_ALL:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
case <API key>:
rx_filter_valid = 1;
break;
}
if (!tx_type_valid || !rx_filter_valid)
return -ERANGE;
return 0;
}
static inline bool is_skb_forwardable(struct net_device *dev,
struct sk_buff *skb)
{
unsigned int len;
if (!(dev->flags & IFF_UP))
return false;
len = dev->mtu + dev->hard_header_len + VLAN_HLEN;
if (skb->len <= len)
return true;
/* if TSO is enabled, we don't care about the length as the packet
* could be forwarded without being segmented before
*/
if (skb_is_gso(skb))
return true;
return false;
}
/**
* dev_forward_skb - loopback an skb to another netif
*
* @dev: destination network device
* @skb: buffer to forward
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped, but freed)
*
* dev_forward_skb can be used for injecting an skb from the
* start_xmit function of one device into the receive queue
* of another device.
*
* The receiving device may be in another namespace, so
* we have to clear all information in the skb that could
* impact namespace isolation.
*/
int dev_forward_skb(struct net_device *dev, struct sk_buff *skb)
{
if (skb_shinfo(skb)->tx_flags & SKBTX_DEV_ZEROCOPY) {
if (skb_copy_ubufs(skb, GFP_ATOMIC)) {
atomic_long_inc(&dev->rx_dropped);
kfree_skb(skb);
return NET_RX_DROP;
}
}
skb_orphan(skb);
nf_reset(skb);
if (unlikely(!is_skb_forwardable(dev, skb))) {
atomic_long_inc(&dev->rx_dropped);
kfree_skb(skb);
return NET_RX_DROP;
}
skb->skb_iif = 0;
skb->dev = dev;
skb_dst_drop(skb);
skb->tstamp.tv64 = 0;
skb->pkt_type = PACKET_HOST;
skb->protocol = eth_type_trans(skb, dev);
skb->mark = 0;
secpath_reset(skb);
nf_reset(skb);
return netif_rx(skb);
}
EXPORT_SYMBOL_GPL(dev_forward_skb);
static inline int deliver_skb(struct sk_buff *skb,
struct packet_type *pt_prev,
struct net_device *orig_dev)
{
atomic_inc(&skb->users);
return pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
}
/*
* Support routine. Sends outgoing frames to any network
* taps currently in use.
*/
static void dev_queue_xmit_nit(struct sk_buff *skb, struct net_device *dev)
{
struct packet_type *ptype;
struct sk_buff *skb2 = NULL;
struct packet_type *pt_prev = NULL;
rcu_read_lock();
<API key>(ptype, &ptype_all, list) {
/* Never send packets back to the socket
* they originated from - MvS (miquels@drinkel.ow.org)
*/
if ((ptype->dev == dev || !ptype->dev) &&
(ptype->af_packet_priv == NULL ||
(struct sock *)ptype->af_packet_priv != skb->sk)) {
if (pt_prev) {
deliver_skb(skb2, pt_prev, skb->dev);
pt_prev = ptype;
continue;
}
skb2 = skb_clone(skb, GFP_ATOMIC);
if (!skb2)
break;
net_timestamp_set(skb2);
/* skb->nh should be correctly
set by sender, so that the second statement is
just protection against buggy protocols.
*/
<API key>(skb2);
if (skb_network_header(skb2) < skb2->data ||
skb2->network_header > skb2->tail) {
<API key>("protocol %04x is buggy, dev %s\n",
ntohs(skb2->protocol),
dev->name);
<API key>(skb2);
}
skb2->transport_header = skb2->network_header;
skb2->pkt_type = PACKET_OUTGOING;
pt_prev = ptype;
}
}
if (pt_prev)
pt_prev->func(skb2, skb->dev, pt_prev, skb->dev);
rcu_read_unlock();
}
/* netif_setup_tc - Handle tc mappings on real_num_tx_queues change
* @dev: Network device
* @txq: number of queues available
*
* If real_num_tx_queues is changed the tc mappings may no longer be
* valid. To resolve this verify the tc mapping remains valid and if
* not NULL the mapping. With no priorities mapping to this
* offset/count pair it will no longer be used. In the worst case TC0
* is invalid nothing can be done so disable priority mappings. If is
* expected that drivers will fix this mapping if they can before
* calling <API key>.
*/
static void netif_setup_tc(struct net_device *dev, unsigned int txq)
{
int i;
struct netdev_tc_txq *tc = &dev->tc_to_txq[0];
/* If TC0 is invalidated disable TC mapping */
if (tc->offset + tc->count > txq) {
pr_warn("Number of in use tx queues changed invalidating tc mappings. Priority traffic classification disabled!\n");
dev->num_tc = 0;
return;
}
/* Invalidated prio to tc mappings set to TC0 */
for (i = 1; i < TC_BITMASK + 1; i++) {
int q = <API key>(dev, i);
tc = &dev->tc_to_txq[q];
if (tc->offset + tc->count > txq) {
pr_warn("Number of in use tx queues changed. Priority %i to tc mapping %i is no longer valid. Setting map to 0\n",
i, q);
<API key>(dev, i, 0);
}
}
}
/*
* Routine to help set real_num_tx_queues. To avoid skbs mapped to queues
* greater then real_num_tx_queues stale skbs on the qdisc must be flushed.
*/
int <API key>(struct net_device *dev, unsigned int txq)
{
int rc;
if (txq < 1 || txq > dev->num_tx_queues)
return -EINVAL;
if (dev->reg_state == NETREG_REGISTERED ||
dev->reg_state == <API key>) {
ASSERT_RTNL();
rc = <API key>(dev, dev->real_num_tx_queues,
txq);
if (rc)
return rc;
if (dev->num_tc)
netif_setup_tc(dev, txq);
if (txq < dev->real_num_tx_queues)
<API key>(dev, txq);
}
dev->real_num_tx_queues = txq;
return 0;
}
EXPORT_SYMBOL(<API key>);
#ifdef CONFIG_RPS
/**
* <API key> - set actual number of RX queues used
* @dev: Network device
* @rxq: Actual number of RX queues
*
* This must be called either with the rtnl_lock held or before
* registration of the net device. Returns 0 on success, or a
* negative error code. If called before registration, it always
* succeeds.
*/
int <API key>(struct net_device *dev, unsigned int rxq)
{
int rc;
if (rxq < 1 || rxq > dev->num_rx_queues)
return -EINVAL;
if (dev->reg_state == NETREG_REGISTERED) {
ASSERT_RTNL();
rc = <API key>(dev, dev->real_num_rx_queues,
rxq);
if (rc)
return rc;
}
dev->real_num_rx_queues = rxq;
return 0;
}
EXPORT_SYMBOL(<API key>);
#endif
static inline void __netif_reschedule(struct Qdisc *q)
{
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = &__get_cpu_var(softnet_data);
q->next_sched = NULL;
*sd->output_queue_tailp = q;
sd->output_queue_tailp = &q->next_sched;
<API key>(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
void __netif_schedule(struct Qdisc *q)
{
if (!test_and_set_bit(__QDISC_STATE_SCHED, &q->state))
__netif_reschedule(q);
}
EXPORT_SYMBOL(__netif_schedule);
void dev_kfree_skb_irq(struct sk_buff *skb)
{
if (atomic_dec_and_test(&skb->users)) {
struct softnet_data *sd;
unsigned long flags;
local_irq_save(flags);
sd = &__get_cpu_var(softnet_data);
skb->next = sd->completion_queue;
sd->completion_queue = skb;
<API key>(NET_TX_SOFTIRQ);
local_irq_restore(flags);
}
}
EXPORT_SYMBOL(dev_kfree_skb_irq);
void dev_kfree_skb_any(struct sk_buff *skb)
{
if (in_irq() || irqs_disabled())
dev_kfree_skb_irq(skb);
else
dev_kfree_skb(skb);
}
EXPORT_SYMBOL(dev_kfree_skb_any);
/**
* netif_device_detach - mark device as removed
* @dev: network device
*
* Mark device as removed from system and therefore no longer available.
*/
void netif_device_detach(struct net_device *dev)
{
if (test_and_clear_bit(<API key>, &dev->state) &&
netif_running(dev)) {
<API key>(dev);
}
}
EXPORT_SYMBOL(netif_device_detach);
/**
* netif_device_attach - mark device as attached
* @dev: network device
*
* Mark device as attached from system and restart if needed.
*/
void netif_device_attach(struct net_device *dev)
{
if (!test_and_set_bit(<API key>, &dev->state) &&
netif_running(dev)) {
<API key>(dev);
<API key>(dev);
}
}
EXPORT_SYMBOL(netif_device_attach);
static void <API key>(const struct sk_buff *skb)
{
static const netdev_features_t null_features = 0;
struct net_device *dev = skb->dev;
const char *driver = "";
if (dev && dev->dev.parent)
driver = dev_driver_string(dev->dev.parent);
WARN(1, "%s: caps=(%pNF, %pNF) len=%d data_len=%d gso_size=%d "
"gso_type=%d ip_summed=%d\n",
driver, dev ? &dev->features : &null_features,
skb->sk ? &skb->sk->sk_route_caps : &null_features,
skb->len, skb->data_len, skb_shinfo(skb)->gso_size,
skb_shinfo(skb)->gso_type, skb->ip_summed);
}
/*
* Invalidate hardware checksum when packet is to be mangled, and
* complete checksum manually on outgoing path.
*/
int skb_checksum_help(struct sk_buff *skb)
{
__wsum csum;
int ret = 0, offset;
if (skb->ip_summed == CHECKSUM_COMPLETE)
goto out_set_summed;
if (unlikely(skb_shinfo(skb)->gso_size)) {
<API key>(skb);
return -EINVAL;
}
offset = <API key>(skb);
BUG_ON(offset >= skb_headlen(skb));
csum = skb_checksum(skb, offset, skb->len - offset, 0);
offset += skb->csum_offset;
BUG_ON(offset + sizeof(__sum16) > skb_headlen(skb));
if (skb_cloned(skb) &&
!skb_clone_writable(skb, offset + sizeof(__sum16))) {
ret = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (ret)
goto out;
}
*(__sum16 *)(skb->data + offset) = csum_fold(csum);
out_set_summed:
skb->ip_summed = CHECKSUM_NONE;
out:
return ret;
}
EXPORT_SYMBOL(skb_checksum_help);
/**
* skb_gso_segment - Perform segmentation on skb.
* @skb: buffer to segment
* @features: features for the output path (see dev->features)
*
* This function segments the given skb and returns a list of segments.
*
* It may return NULL if the skb requires no segmentation. This is
* only possible when GSO is used for verifying header integrity.
*/
struct sk_buff *skb_gso_segment(struct sk_buff *skb,
netdev_features_t features)
{
struct sk_buff *segs = ERR_PTR(-EPROTONOSUPPORT);
struct packet_type *ptype;
__be16 type = skb->protocol;
int vlan_depth = ETH_HLEN;
int err;
while (type == htons(ETH_P_8021Q)) {
struct vlan_hdr *vh;
if (unlikely(!pskb_may_pull(skb, vlan_depth + VLAN_HLEN)))
return ERR_PTR(-EINVAL);
vh = (struct vlan_hdr *)(skb->data + vlan_depth);
type = vh-><API key>;
vlan_depth += VLAN_HLEN;
}
<API key>(skb);
skb->mac_len = skb->network_header - skb->mac_header;
__skb_pull(skb, skb->mac_len);
if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
<API key>(skb);
if (skb_header_cloned(skb) &&
(err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC)))
return ERR_PTR(err);
}
rcu_read_lock();
<API key>(ptype,
&ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
if (ptype->type == type && !ptype->dev && ptype->gso_segment) {
if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL)) {
err = ptype->gso_send_check(skb);
segs = ERR_PTR(err);
if (err || skb_gso_ok(skb, features))
break;
__skb_push(skb, (skb->data -
skb_network_header(skb)));
}
segs = ptype->gso_segment(skb, features);
break;
}
}
rcu_read_unlock();
__skb_push(skb, skb->data - skb_mac_header(skb));
return segs;
}
EXPORT_SYMBOL(skb_gso_segment);
/* Take action when hardware reception checksum errors are detected. */
#ifdef CONFIG_BUG
void <API key>(struct net_device *dev)
{
if (net_ratelimit()) {
pr_err("%s: hw csum failure\n", dev ? dev->name : "<unknown>");
dump_stack();
}
}
EXPORT_SYMBOL(<API key>);
#endif
/* Actually, we should eliminate this check as soon as we know, that:
* 1. IOMMU is present and allows to map all the memory.
* 2. No high memory really exists on this machine.
*/
static int illegal_highdma(struct net_device *dev, struct sk_buff *skb)
{
#ifdef CONFIG_HIGHMEM
int i;
if (!(dev->features & NETIF_F_HIGHDMA)) {
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
if (PageHighMem(skb_frag_page(frag)))
return 1;
}
}
if (PCI_DMA_BUS_IS_PHYS) {
struct device *pdev = dev->dev.parent;
if (!pdev)
return 0;
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
dma_addr_t addr = page_to_phys(skb_frag_page(frag));
if (!pdev->dma_mask || addr + PAGE_SIZE - 1 > *pdev->dma_mask)
return 1;
}
}
#endif
return 0;
}
struct dev_gso_cb {
void (*destructor)(struct sk_buff *skb);
};
#define DEV_GSO_CB(skb) ((struct dev_gso_cb *)(skb)->cb)
static void <API key>(struct sk_buff *skb)
{
struct dev_gso_cb *cb;
do {
struct sk_buff *nskb = skb->next;
skb->next = nskb->next;
nskb->next = NULL;
kfree_skb(nskb);
} while (skb->next);
cb = DEV_GSO_CB(skb);
if (cb->destructor)
cb->destructor(skb);
}
/**
* dev_gso_segment - Perform emulated hardware segmentation on skb.
* @skb: buffer to segment
* @features: device features as applicable to this skb
*
* This function segments the given skb and stores the list of segments
* in skb->next.
*/
static int dev_gso_segment(struct sk_buff *skb, netdev_features_t features)
{
struct sk_buff *segs;
segs = skb_gso_segment(skb, features);
/* Verifying header integrity only. */
if (!segs)
return 0;
if (IS_ERR(segs))
return PTR_ERR(segs);
skb->next = segs;
DEV_GSO_CB(skb)->destructor = skb->destructor;
skb->destructor = <API key>;
return 0;
}
static bool <API key>(netdev_features_t features, __be16 protocol)
{
return ((features & NETIF_F_GEN_CSUM) ||
((features & NETIF_F_V4_CSUM) &&
protocol == htons(ETH_P_IP)) ||
((features & NETIF_F_V6_CSUM) &&
protocol == htons(ETH_P_IPV6)) ||
((features & NETIF_F_FCOE_CRC) &&
protocol == htons(ETH_P_FCOE)));
}
static netdev_features_t harmonize_features(struct sk_buff *skb,
__be16 protocol, netdev_features_t features)
{
if (!<API key>(features, protocol)) {
features &= ~NETIF_F_ALL_CSUM;
features &= ~NETIF_F_SG;
} else if (illegal_highdma(skb->dev, skb)) {
features &= ~NETIF_F_SG;
}
return features;
}
netdev_features_t netif_skb_features(struct sk_buff *skb)
{
__be16 protocol = skb->protocol;
netdev_features_t features = skb->dev->features;
if (skb_shinfo(skb)->gso_segs > skb->dev->gso_max_segs)
features &= ~NETIF_F_GSO_MASK;
if (protocol == htons(ETH_P_8021Q)) {
struct vlan_ethhdr *veh = (struct vlan_ethhdr *)skb->data;
protocol = veh-><API key>;
} else if (!vlan_tx_tag_present(skb)) {
return harmonize_features(skb, protocol, features);
}
features &= (skb->dev->vlan_features | NETIF_F_HW_VLAN_TX);
if (protocol != htons(ETH_P_8021Q)) {
return harmonize_features(skb, protocol, features);
} else {
features &= NETIF_F_SG | NETIF_F_HIGHDMA | NETIF_F_FRAGLIST |
NETIF_F_GEN_CSUM | NETIF_F_HW_VLAN_TX;
return harmonize_features(skb, protocol, features);
}
}
EXPORT_SYMBOL(netif_skb_features);
/*
* Returns true if either:
* 1. skb has frag_list and the device doesn't support FRAGLIST, or
* 2. skb is fragmented and the device does not support SG, or if
* at least one of fragments is in highmem and device does not
* support DMA from it.
*/
static inline int skb_needs_linearize(struct sk_buff *skb,
int features)
{
return skb_is_nonlinear(skb) &&
((skb_has_frag_list(skb) &&
!(features & NETIF_F_FRAGLIST)) ||
(skb_shinfo(skb)->nr_frags &&
!(features & NETIF_F_SG)));
}
int dev_hard_start_xmit(struct sk_buff *skb, struct net_device *dev,
struct netdev_queue *txq)
{
const struct net_device_ops *ops = dev->netdev_ops;
int rc = NETDEV_TX_OK;
unsigned int skb_len;
if (likely(!skb->next)) {
netdev_features_t features;
/*
* If device doesn't need skb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & <API key>)
skb_dst_drop(skb);
if (!list_empty(&ptype_all))
dev_queue_xmit_nit(skb, dev);
features = netif_skb_features(skb);
if (vlan_tx_tag_present(skb) &&
!(features & NETIF_F_HW_VLAN_TX)) {
skb = __vlan_put_tag(skb, vlan_tx_tag_get(skb));
if (unlikely(!skb))
goto out;
skb->vlan_tci = 0;
}
if (netif_needs_gso(skb, features)) {
if (unlikely(dev_gso_segment(skb, features)))
goto out_kfree_skb;
if (skb->next)
goto gso;
} else {
if (skb_needs_linearize(skb, features) &&
__skb_linearize(skb))
goto out_kfree_skb;
/* If packet is not checksummed and device does not
* support checksumming for this protocol, complete
* checksumming here.
*/
if (skb->ip_summed == CHECKSUM_PARTIAL) {
<API key>(skb,
<API key>(skb));
if (!(features & NETIF_F_ALL_CSUM) &&
skb_checksum_help(skb))
goto out_kfree_skb;
}
}
skb_len = skb->len;
rc = ops->ndo_start_xmit(skb, dev);
trace_net_dev_xmit(skb, rc, dev, skb_len);
if (rc == NETDEV_TX_OK)
txq_trans_update(txq);
return rc;
}
gso:
do {
struct sk_buff *nskb = skb->next;
skb->next = nskb->next;
nskb->next = NULL;
/*
* If device doesn't need nskb->dst, release it right now while
* its hot in this cpu cache
*/
if (dev->priv_flags & <API key>)
skb_dst_drop(nskb);
skb_len = nskb->len;
rc = ops->ndo_start_xmit(nskb, dev);
trace_net_dev_xmit(nskb, rc, dev, skb_len);
if (unlikely(rc != NETDEV_TX_OK)) {
if (rc & ~NETDEV_TX_MASK)
goto out_kfree_gso_skb;
nskb->next = skb->next;
skb->next = nskb;
return rc;
}
txq_trans_update(txq);
if (unlikely(netif_xmit_stopped(txq) && skb->next))
return NETDEV_TX_BUSY;
} while (skb->next);
out_kfree_gso_skb:
if (likely(skb->next == NULL))
skb->destructor = DEV_GSO_CB(skb)->destructor;
out_kfree_skb:
kfree_skb(skb);
out:
return rc;
}
static u32 hashrnd __read_mostly;
/*
* Returns a Tx hash based on the given packet descriptor a Tx queues' number
* to be used as a distribution range.
*/
u16 __skb_tx_hash(const struct net_device *dev, const struct sk_buff *skb,
unsigned int num_tx_queues)
{
u32 hash;
u16 qoffset = 0;
u16 qcount = num_tx_queues;
if (<API key>(skb)) {
hash = skb_get_rx_queue(skb);
while (unlikely(hash >= num_tx_queues))
hash -= num_tx_queues;
return hash;
}
if (dev->num_tc) {
u8 tc = <API key>(dev, skb->priority);
qoffset = dev->tc_to_txq[tc].offset;
qcount = dev->tc_to_txq[tc].count;
}
if (skb->sk && skb->sk->sk_hash)
hash = skb->sk->sk_hash;
else
hash = (__force u16) skb->protocol;
hash = jhash_1word(hash, hashrnd);
return (u16) (((u64) hash * qcount) >> 32) + qoffset;
}
EXPORT_SYMBOL(__skb_tx_hash);
static inline u16 dev_cap_txqueue(struct net_device *dev, u16 queue_index)
{
if (unlikely(queue_index >= dev->real_num_tx_queues)) {
<API key>("%s selects TX queue %d, but real number of TX queues is %d\n",
dev->name, queue_index,
dev->real_num_tx_queues);
return 0;
}
return queue_index;
}
static inline int get_xps_queue(struct net_device *dev, struct sk_buff *skb)
{
#ifdef CONFIG_XPS
struct xps_dev_maps *dev_maps;
struct xps_map *map;
int queue_index = -1;
rcu_read_lock();
dev_maps = rcu_dereference(dev->xps_maps);
if (dev_maps) {
map = rcu_dereference(
dev_maps->cpu_map[<API key>()]);
if (map) {
if (map->len == 1)
queue_index = map->queues[0];
else {
u32 hash;
if (skb->sk && skb->sk->sk_hash)
hash = skb->sk->sk_hash;
else
hash = (__force u16) skb->protocol ^
skb->rxhash;
hash = jhash_1word(hash, hashrnd);
queue_index = map->queues[
((u64)hash * map->len) >> 32];
}
if (unlikely(queue_index >= dev->real_num_tx_queues))
queue_index = -1;
}
}
rcu_read_unlock();
return queue_index;
#else
return -1;
#endif
}
static struct netdev_queue *dev_pick_tx(struct net_device *dev,
struct sk_buff *skb)
{
int queue_index;
const struct net_device_ops *ops = dev->netdev_ops;
if (dev->real_num_tx_queues == 1)
queue_index = 0;
else if (ops->ndo_select_queue) {
queue_index = ops->ndo_select_queue(dev, skb);
queue_index = dev_cap_txqueue(dev, queue_index);
} else {
struct sock *sk = skb->sk;
queue_index = sk_tx_queue_get(sk);
if (queue_index < 0 || skb->ooo_okay ||
queue_index >= dev->real_num_tx_queues) {
int old_index = queue_index;
queue_index = get_xps_queue(dev, skb);
if (queue_index < 0)
queue_index = skb_tx_hash(dev, skb);
if (queue_index != old_index && sk) {
struct dst_entry *dst =
<API key>(sk->sk_dst_cache, 1);
if (dst && skb_dst(skb) == dst)
sk_tx_queue_set(sk, queue_index);
}
}
}
<API key>(skb, queue_index);
return netdev_get_tx_queue(dev, queue_index);
}
static inline int __dev_xmit_skb(struct sk_buff *skb, struct Qdisc *q,
struct net_device *dev,
struct netdev_queue *txq)
{
spinlock_t *root_lock = qdisc_lock(q);
bool contended;
int rc;
qdisc_skb_cb(skb)->pkt_len = skb->len;
<API key>(skb, q);
/*
* Heuristic to force contended enqueues to serialize on a
* separate lock before trying to get qdisc main lock.
* This permits <API key> owner to get the lock more often
* and dequeue packets faster.
*/
contended = qdisc_is_running(q);
if (unlikely(contended))
spin_lock(&q->busylock);
spin_lock(root_lock);
if (unlikely(test_bit(<API key>, &q->state))) {
kfree_skb(skb);
rc = NET_XMIT_DROP;
} else if ((q->flags & TCQ_F_CAN_BYPASS) && !qdisc_qlen(q) &&
qdisc_run_begin(q)) {
/*
* This is a work-conserving queue; there are no old skbs
* waiting to be sent out; and the qdisc is not running -
* xmit the skb directly.
*/
if (!(dev->priv_flags & <API key>))
skb_dst_force(skb);
qdisc_bstats_update(q, skb);
if (sch_direct_xmit(skb, q, dev, txq, root_lock)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
} else
qdisc_run_end(q);
rc = NET_XMIT_SUCCESS;
} else {
skb_dst_force(skb);
rc = q->enqueue(skb, q) & NET_XMIT_MASK;
if (qdisc_run_begin(q)) {
if (unlikely(contended)) {
spin_unlock(&q->busylock);
contended = false;
}
__qdisc_run(q);
}
}
spin_unlock(root_lock);
if (unlikely(contended))
spin_unlock(&q->busylock);
return rc;
}
#if IS_ENABLED(<API key>)
static void skb_update_prio(struct sk_buff *skb)
{
struct netprio_map *map = rcu_dereference_bh(skb->dev->priomap);
if (!skb->priority && skb->sk && map) {
unsigned int prioidx = skb->sk->sk_cgrp_prioidx;
if (prioidx < map->priomap_len)
skb->priority = map->priomap[prioidx];
}
}
#else
#define skb_update_prio(skb)
#endif
static DEFINE_PER_CPU(int, xmit_recursion);
#define RECURSION_LIMIT 10
int dev_queue_xmit(struct sk_buff *skb)
{
struct net_device *dev = skb->dev;
struct netdev_queue *txq;
struct Qdisc *q;
int rc = -ENOMEM;
/* Disable soft irqs for various locks below. Also
* stops preemption for RCU.
*/
rcu_read_lock_bh();
skb_update_prio(skb);
txq = dev_pick_tx(dev, skb);
q = rcu_dereference_bh(txq->qdisc);
#ifdef CONFIG_NET_CLS_ACT
skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_EGRESS);
#endif
trace_net_dev_queue(skb);
if (q->enqueue) {
rc = __dev_xmit_skb(skb, q, dev, txq);
goto out;
}
/* The device has no queue. Common case for software devices:
loopback, all the sorts of tunnels...
Really, it is unlikely that netif_tx_lock protection is necessary
here. (f.e. loopback and IP tunnels are clean ignoring statistics
counters.)
However, it is possible, that they rely on protection
made by us here.
Check this and shot the lock. It is not prone from deadlocks.
Either shot noqueue qdisc, it is even simpler 8)
*/
if (dev->flags & IFF_UP) {
int cpu = smp_processor_id(); /* ok because BHs are off */
if (txq->xmit_lock_owner != cpu) {
if (__this_cpu_read(xmit_recursion) > RECURSION_LIMIT)
goto recursion_alert;
HARD_TX_LOCK(dev, txq, cpu);
if (!netif_xmit_stopped(txq)) {
__this_cpu_inc(xmit_recursion);
rc = dev_hard_start_xmit(skb, dev, txq);
__this_cpu_dec(xmit_recursion);
if (dev_xmit_complete(rc)) {
HARD_TX_UNLOCK(dev, txq);
goto out;
}
}
HARD_TX_UNLOCK(dev, txq);
<API key>("Virtual device %s asks to queue packet!\n",
dev->name);
} else {
/* Recursion is detected! It is possible,
* unfortunately
*/
recursion_alert:
<API key>("Dead loop on virtual device %s, fix it urgently!\n",
dev->name);
}
}
rc = -ENETDOWN;
rcu_read_unlock_bh();
kfree_skb(skb);
return rc;
out:
rcu_read_unlock_bh();
return rc;
}
EXPORT_SYMBOL(dev_queue_xmit);
int netdev_max_backlog __read_mostly = 1000;
int <API key> __read_mostly = 1;
int netdev_budget __read_mostly = 300;
int weight_p __read_mostly = 64; /* old backlog weight */
/* Called with irq disabled */
static inline void ____napi_schedule(struct softnet_data *sd,
struct napi_struct *napi)
{
list_add_tail(&napi->poll_list, &sd->poll_list);
<API key>(NET_RX_SOFTIRQ);
}
/*
* __skb_get_rxhash: calculate a flow hash based on src/dst addresses
* and src/dst port numbers. Sets rxhash in skb to non-zero hash value
* on success, zero indicates no valid hash. Also, sets l4_rxhash in skb
* if hash is a canonical 4-tuple hash over transport ports.
*/
void __skb_get_rxhash(struct sk_buff *skb)
{
struct flow_keys keys;
u32 hash;
if (!skb_flow_dissect(skb, &keys))
return;
if (keys.ports) {
if ((__force u16)keys.port16[1] < (__force u16)keys.port16[0])
swap(keys.port16[0], keys.port16[1]);
skb->l4_rxhash = 1;
}
/* get a consistent hash (same value on both flow directions) */
if ((__force u32)keys.dst < (__force u32)keys.src)
swap(keys.dst, keys.src);
hash = jhash_3words((__force u32)keys.dst,
(__force u32)keys.src,
(__force u32)keys.ports, hashrnd);
if (!hash)
hash = 1;
skb->rxhash = hash;
}
EXPORT_SYMBOL(__skb_get_rxhash);
#ifdef CONFIG_RPS
/* One global table that all flow-based protocols share. */
struct rps_sock_flow_table __rcu *rps_sock_flow_table __read_mostly;
EXPORT_SYMBOL(rps_sock_flow_table);
struct static_key rps_needed __read_mostly;
static struct rps_dev_flow *
set_rps_cpu(struct net_device *dev, struct sk_buff *skb,
struct rps_dev_flow *rflow, u16 next_cpu)
{
if (next_cpu != RPS_NO_CPU) {
#ifdef CONFIG_RFS_ACCEL
struct netdev_rx_queue *rxqueue;
struct rps_dev_flow_table *flow_table;
struct rps_dev_flow *old_rflow;
u32 flow_id;
u16 rxq_index;
int rc;
/* Should we steer this flow to a different hardware queue? */
if (!<API key>(skb) || !dev->rx_cpu_rmap ||
!(dev->features & NETIF_F_NTUPLE))
goto out;
rxq_index = <API key>(dev->rx_cpu_rmap, next_cpu);
if (rxq_index == skb_get_rx_queue(skb))
goto out;
rxqueue = dev->_rx + rxq_index;
flow_table = rcu_dereference(rxqueue->rps_flow_table);
if (!flow_table)
goto out;
flow_id = skb->rxhash & flow_table->mask;
rc = dev->netdev_ops->ndo_rx_flow_steer(dev, skb,
rxq_index, flow_id);
if (rc < 0)
goto out;
old_rflow = rflow;
rflow = &flow_table->flows[flow_id];
rflow->filter = rc;
if (old_rflow->filter == rflow->filter)
old_rflow->filter = RPS_NO_FILTER;
out:
#endif
rflow->last_qtail =
per_cpu(softnet_data, next_cpu).input_queue_head;
}
rflow->cpu = next_cpu;
return rflow;
}
/*
* get_rps_cpu is called from netif_receive_skb and returns the target
* CPU from the RPS map of the receiving queue for a given skb.
* rcu_read_lock must be held on entry.
*/
static int get_rps_cpu(struct net_device *dev, struct sk_buff *skb,
struct rps_dev_flow **rflowp)
{
struct netdev_rx_queue *rxqueue;
struct rps_map *map;
struct rps_dev_flow_table *flow_table;
struct rps_sock_flow_table *sock_flow_table;
int cpu = -1;
u16 tcpu;
if (<API key>(skb)) {
u16 index = skb_get_rx_queue(skb);
if (unlikely(index >= dev->real_num_rx_queues)) {
WARN_ONCE(dev->real_num_rx_queues > 1,
"%s received packet on queue %u, but number "
"of RX queues is %u\n",
dev->name, index, dev->real_num_rx_queues);
goto done;
}
rxqueue = dev->_rx + index;
} else
rxqueue = dev->_rx;
map = rcu_dereference(rxqueue->rps_map);
if (map) {
if (map->len == 1 &&
!rcu_access_pointer(rxqueue->rps_flow_table)) {
tcpu = map->cpus[0];
if (cpu_online(tcpu))
cpu = tcpu;
goto done;
}
} else if (!rcu_access_pointer(rxqueue->rps_flow_table)) {
goto done;
}
<API key>(skb);
if (!skb_get_rxhash(skb))
goto done;
flow_table = rcu_dereference(rxqueue->rps_flow_table);
sock_flow_table = rcu_dereference(rps_sock_flow_table);
if (flow_table && sock_flow_table) {
u16 next_cpu;
struct rps_dev_flow *rflow;
rflow = &flow_table->flows[skb->rxhash & flow_table->mask];
tcpu = rflow->cpu;
next_cpu = sock_flow_table->ents[skb->rxhash &
sock_flow_table->mask];
/*
* If the desired CPU (where last recvmsg was done) is
* different from current CPU (one in the rx-queue flow
* table entry), switch if one of the following holds:
* - Current CPU is unset (equal to RPS_NO_CPU).
* - Current CPU is offline.
* - The current CPU's queue tail has advanced beyond the
* last packet that was enqueued using this table entry.
* This guarantees that all previous packets for the flow
* have been dequeued, thus preserving in order delivery.
*/
if (unlikely(tcpu != next_cpu) &&
(tcpu == RPS_NO_CPU || !cpu_online(tcpu) ||
((int)(per_cpu(softnet_data, tcpu).input_queue_head -
rflow->last_qtail)) >= 0))
rflow = set_rps_cpu(dev, skb, rflow, next_cpu);
if (tcpu != RPS_NO_CPU && cpu_online(tcpu)) {
*rflowp = rflow;
cpu = tcpu;
goto done;
}
}
if (map) {
tcpu = map->cpus[((u64) skb->rxhash * map->len) >> 32];
if (cpu_online(tcpu)) {
cpu = tcpu;
goto done;
}
}
done:
return cpu;
}
#ifdef CONFIG_RFS_ACCEL
/**
* rps_may_expire_flow - check whether an RFS hardware filter may be removed
* @dev: Device on which the filter was set
* @rxq_index: RX queue index
* @flow_id: Flow ID passed to ndo_rx_flow_steer()
* @filter_id: Filter ID returned by ndo_rx_flow_steer()
*
* Drivers that implement ndo_rx_flow_steer() should periodically call
* this function for each installed filter and remove the filters for
* which it returns %true.
*/
bool rps_may_expire_flow(struct net_device *dev, u16 rxq_index,
u32 flow_id, u16 filter_id)
{
struct netdev_rx_queue *rxqueue = dev->_rx + rxq_index;
struct rps_dev_flow_table *flow_table;
struct rps_dev_flow *rflow;
bool expire = true;
int cpu;
rcu_read_lock();
flow_table = rcu_dereference(rxqueue->rps_flow_table);
if (flow_table && flow_id <= flow_table->mask) {
rflow = &flow_table->flows[flow_id];
cpu = ACCESS_ONCE(rflow->cpu);
if (rflow->filter == filter_id && cpu != RPS_NO_CPU &&
((int)(per_cpu(softnet_data, cpu).input_queue_head -
rflow->last_qtail) <
(int)(10 * flow_table->mask)))
expire = false;
}
rcu_read_unlock();
return expire;
}
EXPORT_SYMBOL(rps_may_expire_flow);
#endif /* CONFIG_RFS_ACCEL */
/* Called from hardirq (IPI) context */
static void rps_trigger_softirq(void *data)
{
struct softnet_data *sd = data;
____napi_schedule(sd, &sd->backlog);
sd->received_rps++;
}
#endif /* CONFIG_RPS */
/*
* Check if this softnet_data structure is another cpu one
* If yes, queue it to our IPI list and return 1
* If no, return 0
*/
static int rps_ipi_queued(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *mysd = &__get_cpu_var(softnet_data);
if (sd != mysd) {
sd->rps_ipi_next = mysd->rps_ipi_list;
mysd->rps_ipi_list = sd;
<API key>(NET_RX_SOFTIRQ);
return 1;
}
#endif /* CONFIG_RPS */
return 0;
}
/*
* enqueue_to_backlog is called to queue an skb to a per CPU backlog
* queue (may be a remote CPU queue).
*/
static int enqueue_to_backlog(struct sk_buff *skb, int cpu,
unsigned int *qtail)
{
struct softnet_data *sd;
unsigned long flags;
sd = &per_cpu(softnet_data, cpu);
local_irq_save(flags);
rps_lock(sd);
if (skb_queue_len(&sd->input_pkt_queue) <= netdev_max_backlog) {
if (skb_queue_len(&sd->input_pkt_queue)) {
enqueue:
__skb_queue_tail(&sd->input_pkt_queue, skb);
<API key>(sd, qtail);
rps_unlock(sd);
local_irq_restore(flags);
return NET_RX_SUCCESS;
}
/* Schedule NAPI for backlog device
* We can use non atomic operation since we own the queue lock
*/
if (!__test_and_set_bit(NAPI_STATE_SCHED, &sd->backlog.state)) {
if (!rps_ipi_queued(sd))
____napi_schedule(sd, &sd->backlog);
}
goto enqueue;
}
sd->dropped++;
rps_unlock(sd);
local_irq_restore(flags);
atomic_long_inc(&skb->dev->rx_dropped);
kfree_skb(skb);
return NET_RX_DROP;
}
/**
* netif_rx - post buffer to the network code
* @skb: buffer to post
*
* This function receives a packet from a device driver and queues it for
* the upper (protocol) levels to process. It always succeeds. The buffer
* may be dropped during processing for congestion control or by the
* protocol layers.
*
* return values:
* NET_RX_SUCCESS (no congestion)
* NET_RX_DROP (packet was dropped)
*
*/
int netif_rx(struct sk_buff *skb)
{
int ret;
/* if netpoll wants it, pretend we never saw it */
if (netpoll_rx(skb))
return NET_RX_DROP;
net_timestamp_check(<API key>, skb);
trace_netif_rx(skb);
#ifdef CONFIG_RPS
if (static_key_false(&rps_needed)) {
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu;
preempt_disable();
rcu_read_lock();
cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu < 0)
cpu = smp_processor_id();
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
preempt_enable();
} else
#endif
{
unsigned int qtail;
ret = enqueue_to_backlog(skb, get_cpu(), &qtail);
put_cpu();
}
return ret;
}
EXPORT_SYMBOL(netif_rx);
int netif_rx_ni(struct sk_buff *skb)
{
int err;
preempt_disable();
err = netif_rx(skb);
if (<API key>())
do_softirq();
preempt_enable();
return err;
}
EXPORT_SYMBOL(netif_rx_ni);
static void net_tx_action(struct softirq_action *h)
{
struct softnet_data *sd = &__get_cpu_var(softnet_data);
if (sd->completion_queue) {
struct sk_buff *clist;
local_irq_disable();
clist = sd->completion_queue;
sd->completion_queue = NULL;
local_irq_enable();
while (clist) {
struct sk_buff *skb = clist;
clist = clist->next;
WARN_ON(atomic_read(&skb->users));
trace_kfree_skb(skb, net_tx_action);
__kfree_skb(skb);
}
}
if (sd->output_queue) {
struct Qdisc *head;
local_irq_disable();
head = sd->output_queue;
sd->output_queue = NULL;
sd->output_queue_tailp = &sd->output_queue;
local_irq_enable();
while (head) {
struct Qdisc *q = head;
spinlock_t *root_lock;
head = head->next_sched;
root_lock = qdisc_lock(q);
if (spin_trylock(root_lock)) {
<API key>();
clear_bit(__QDISC_STATE_SCHED,
&q->state);
qdisc_run(q);
spin_unlock(root_lock);
} else {
if (!test_bit(<API key>,
&q->state)) {
__netif_reschedule(q);
} else {
<API key>();
clear_bit(__QDISC_STATE_SCHED,
&q->state);
}
}
}
}
}
#if (defined(CONFIG_BRIDGE) || defined(<API key>)) && \
(defined(CONFIG_ATM_LANE) || defined(<API key>))
/* This hook is defined here for ATM LANE */
int (*<API key>)(struct net_device *dev,
unsigned char *addr) __read_mostly;
EXPORT_SYMBOL_GPL(<API key>);
#endif
#ifdef CONFIG_NET_CLS_ACT
/* TODO: Maybe we should just force sch_ingress to be compiled in
* when CONFIG_NET_CLS_ACT is? otherwise some useless instructions
* a compare and 2 stores extra right now if we dont have it on
* but have CONFIG_NET_CLS_ACT
* NOTE: This doesn't stop any functionality; if you dont have
* the ingress scheduler, you just can't add policies on ingress.
*
*/
static int ing_filter(struct sk_buff *skb, struct netdev_queue *rxq)
{
struct net_device *dev = skb->dev;
u32 ttl = G_TC_RTTL(skb->tc_verd);
int result = TC_ACT_OK;
struct Qdisc *q;
if (unlikely(MAX_RED_LOOP < ttl++)) {
<API key>("Redir loop detected Dropping packet (%d->%d)\n",
skb->skb_iif, dev->ifindex);
return TC_ACT_SHOT;
}
skb->tc_verd = SET_TC_RTTL(skb->tc_verd, ttl);
skb->tc_verd = SET_TC_AT(skb->tc_verd, AT_INGRESS);
q = rxq->qdisc;
if (q != &noop_qdisc) {
spin_lock(qdisc_lock(q));
if (likely(!test_bit(<API key>, &q->state)))
result = qdisc_enqueue_root(skb, q);
spin_unlock(qdisc_lock(q));
}
return result;
}
static inline struct sk_buff *handle_ing(struct sk_buff *skb,
struct packet_type **pt_prev,
int *ret, struct net_device *orig_dev)
{
struct netdev_queue *rxq = rcu_dereference(skb->dev->ingress_queue);
if (!rxq || rxq->qdisc == &noop_qdisc)
goto out;
if (*pt_prev) {
*ret = deliver_skb(skb, *pt_prev, orig_dev);
*pt_prev = NULL;
}
switch (ing_filter(skb, rxq)) {
case TC_ACT_SHOT:
case TC_ACT_STOLEN:
kfree_skb(skb);
return NULL;
}
out:
skb->tc_verd = 0;
return skb;
}
#endif
/**
* <API key> - register receive handler
* @dev: device to register a handler for
* @rx_handler: receive handler to register
* @rx_handler_data: data pointer that is used by rx handler
*
* Register a receive hander for a device. This handler will then be
* called from __netif_receive_skb. A negative errno code is returned
* on a failure.
*
* The caller must hold the rtnl_mutex.
*
* For a general description of rx_handler, see enum rx_handler_result.
*/
int <API key>(struct net_device *dev,
rx_handler_func_t *rx_handler,
void *rx_handler_data)
{
ASSERT_RTNL();
if (dev->rx_handler)
return -EBUSY;
rcu_assign_pointer(dev->rx_handler_data, rx_handler_data);
rcu_assign_pointer(dev->rx_handler, rx_handler);
return 0;
}
EXPORT_SYMBOL_GPL(<API key>);
/**
* <API key> - unregister receive handler
* @dev: device to unregister a handler from
*
* Unregister a receive hander from a device.
*
* The caller must hold the rtnl_mutex.
*/
void <API key>(struct net_device *dev)
{
ASSERT_RTNL();
RCU_INIT_POINTER(dev->rx_handler, NULL);
RCU_INIT_POINTER(dev->rx_handler_data, NULL);
}
EXPORT_SYMBOL_GPL(<API key>);
static int __netif_receive_skb(struct sk_buff *skb)
{
struct packet_type *ptype, *pt_prev;
rx_handler_func_t *rx_handler;
struct net_device *orig_dev;
struct net_device *null_or_dev;
bool deliver_exact = false;
int ret = NET_RX_DROP;
__be16 type;
net_timestamp_check(!<API key>, skb);
<API key>(skb);
/* if we've gotten here through NAPI, check netpoll */
if (netpoll_receive_skb(skb))
return NET_RX_DROP;
if (!skb->skb_iif)
skb->skb_iif = skb->dev->ifindex;
orig_dev = skb->dev;
<API key>(skb);
<API key>(skb);
skb_reset_mac_len(skb);
pt_prev = NULL;
rcu_read_lock();
another_round:
__this_cpu_inc(softnet_data.processed);
if (skb->protocol == cpu_to_be16(ETH_P_8021Q)) {
skb = vlan_untag(skb);
if (unlikely(!skb))
goto out;
}
#ifdef CONFIG_NET_CLS_ACT
if (skb->tc_verd & TC_NCLS) {
skb->tc_verd = CLR_TC_NCLS(skb->tc_verd);
goto ncls;
}
#endif
<API key>(ptype, &ptype_all, list) {
if (!ptype->dev || ptype->dev == skb->dev) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
}
#ifdef CONFIG_NET_CLS_ACT
skb = handle_ing(skb, &pt_prev, &ret, orig_dev);
if (!skb)
goto out;
ncls:
#endif
rx_handler = rcu_dereference(skb->dev->rx_handler);
if (vlan_tx_tag_present(skb)) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
if (vlan_do_receive(&skb, !rx_handler))
goto another_round;
else if (unlikely(!skb))
goto out;
}
if (rx_handler) {
if (pt_prev) {
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = NULL;
}
switch (rx_handler(&skb)) {
case RX_HANDLER_CONSUMED:
goto out;
case RX_HANDLER_ANOTHER:
goto another_round;
case RX_HANDLER_EXACT:
deliver_exact = true;
case RX_HANDLER_PASS:
break;
default:
BUG();
}
}
/* deliver only exact match when indicated */
null_or_dev = deliver_exact ? skb->dev : NULL;
type = skb->protocol;
<API key>(ptype,
&ptype_base[ntohs(type) & PTYPE_HASH_MASK], list) {
if (ptype->type == type &&
(ptype->dev == null_or_dev || ptype->dev == skb->dev ||
ptype->dev == orig_dev)) {
if (pt_prev)
ret = deliver_skb(skb, pt_prev, orig_dev);
pt_prev = ptype;
}
}
if (pt_prev) {
ret = pt_prev->func(skb, skb->dev, pt_prev, orig_dev);
} else {
atomic_long_inc(&skb->dev->rx_dropped);
kfree_skb(skb);
/* Jamal, now you will not able to escape explaining
* me how you were going to use this. :-)
*/
ret = NET_RX_DROP;
}
out:
rcu_read_unlock();
return ret;
}
/**
* netif_receive_skb - process receive buffer from network
* @skb: buffer to process
*
* netif_receive_skb() is the main receive data processing function.
* It always succeeds. The buffer may be dropped during processing
* for congestion control or by the protocol layers.
*
* This function may only be called from softirq context and interrupts
* should be enabled.
*
* Return values (usually ignored):
* NET_RX_SUCCESS: no congestion
* NET_RX_DROP: packet was dropped
*/
int netif_receive_skb(struct sk_buff *skb)
{
net_timestamp_check(<API key>, skb);
if (<API key>(skb))
return NET_RX_SUCCESS;
#ifdef CONFIG_RPS
if (static_key_false(&rps_needed)) {
struct rps_dev_flow voidflow, *rflow = &voidflow;
int cpu, ret;
rcu_read_lock();
cpu = get_rps_cpu(skb->dev, skb, &rflow);
if (cpu >= 0) {
ret = enqueue_to_backlog(skb, cpu, &rflow->last_qtail);
rcu_read_unlock();
return ret;
}
rcu_read_unlock();
}
#endif
return __netif_receive_skb(skb);
}
EXPORT_SYMBOL(netif_receive_skb);
/* Network device is going away, flush any packets still pending
* Called with irqs disabled.
*/
static void flush_backlog(void *arg)
{
struct net_device *dev = arg;
struct softnet_data *sd = &__get_cpu_var(softnet_data);
struct sk_buff *skb, *tmp;
rps_lock(sd);
skb_queue_walk_safe(&sd->input_pkt_queue, skb, tmp) {
if (skb->dev == dev) {
__skb_unlink(skb, &sd->input_pkt_queue);
kfree_skb(skb);
<API key>(sd);
}
}
rps_unlock(sd);
skb_queue_walk_safe(&sd->process_queue, skb, tmp) {
if (skb->dev == dev) {
__skb_unlink(skb, &sd->process_queue);
kfree_skb(skb);
<API key>(sd);
}
}
}
static int napi_gro_complete(struct sk_buff *skb)
{
struct packet_type *ptype;
__be16 type = skb->protocol;
struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
int err = -ENOENT;
if (NAPI_GRO_CB(skb)->count == 1) {
skb_shinfo(skb)->gso_size = 0;
goto out;
}
rcu_read_lock();
<API key>(ptype, head, list) {
if (ptype->type != type || ptype->dev || !ptype->gro_complete)
continue;
err = ptype->gro_complete(skb);
break;
}
rcu_read_unlock();
if (err) {
WARN_ON(&ptype->list == head);
kfree_skb(skb);
return NET_RX_SUCCESS;
}
out:
return netif_receive_skb(skb);
}
inline void napi_gro_flush(struct napi_struct *napi)
{
struct sk_buff *skb, *next;
for (skb = napi->gro_list; skb; skb = next) {
next = skb->next;
skb->next = NULL;
napi_gro_complete(skb);
}
napi->gro_count = 0;
napi->gro_list = NULL;
}
EXPORT_SYMBOL(napi_gro_flush);
enum gro_result dev_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff **pp = NULL;
struct packet_type *ptype;
__be16 type = skb->protocol;
struct list_head *head = &ptype_base[ntohs(type) & PTYPE_HASH_MASK];
int same_flow;
int mac_len;
enum gro_result ret;
if (!(skb->dev->features & NETIF_F_GRO) || netpoll_rx_on(skb))
goto normal;
if (skb_is_gso(skb) || skb_has_frag_list(skb))
goto normal;
rcu_read_lock();
<API key>(ptype, head, list) {
if (ptype->type != type || ptype->dev || !ptype->gro_receive)
continue;
<API key>(skb, skb_gro_offset(skb));
mac_len = skb->network_header - skb->mac_header;
skb->mac_len = mac_len;
NAPI_GRO_CB(skb)->same_flow = 0;
NAPI_GRO_CB(skb)->flush = 0;
NAPI_GRO_CB(skb)->free = 0;
pp = ptype->gro_receive(&napi->gro_list, skb);
break;
}
rcu_read_unlock();
if (&ptype->list == head)
goto normal;
same_flow = NAPI_GRO_CB(skb)->same_flow;
ret = NAPI_GRO_CB(skb)->free ? GRO_MERGED_FREE : GRO_MERGED;
if (pp) {
struct sk_buff *nskb = *pp;
*pp = nskb->next;
nskb->next = NULL;
napi_gro_complete(nskb);
napi->gro_count
}
if (same_flow)
goto ok;
if (NAPI_GRO_CB(skb)->flush || napi->gro_count >= MAX_GRO_SKBS)
goto normal;
napi->gro_count++;
NAPI_GRO_CB(skb)->count = 1;
skb_shinfo(skb)->gso_size = skb_gro_len(skb);
skb->next = napi->gro_list;
napi->gro_list = skb;
ret = GRO_HELD;
pull:
if (skb_headlen(skb) < skb_gro_offset(skb)) {
int grow = skb_gro_offset(skb) - skb_headlen(skb);
BUG_ON(skb->end - skb->tail < grow);
memcpy(skb_tail_pointer(skb), NAPI_GRO_CB(skb)->frag0, grow);
skb->tail += grow;
skb->data_len -= grow;
skb_shinfo(skb)->frags[0].page_offset += grow;
skb_frag_size_sub(&skb_shinfo(skb)->frags[0], grow);
if (unlikely(!skb_frag_size(&skb_shinfo(skb)->frags[0]))) {
skb_frag_unref(skb, 0);
memmove(skb_shinfo(skb)->frags,
skb_shinfo(skb)->frags + 1,
--skb_shinfo(skb)->nr_frags * sizeof(skb_frag_t));
}
}
ok:
return ret;
normal:
ret = GRO_NORMAL;
goto pull;
}
EXPORT_SYMBOL(dev_gro_receive);
static inline gro_result_t
__napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
struct sk_buff *p;
unsigned int maclen = skb->dev->hard_header_len;
for (p = napi->gro_list; p; p = p->next) {
unsigned long diffs;
diffs = (unsigned long)p->dev ^ (unsigned long)skb->dev;
diffs |= p->vlan_tci ^ skb->vlan_tci;
if (maclen == ETH_HLEN)
diffs |= <API key>(skb_mac_header(p),
skb_gro_mac_header(skb));
else if (!diffs)
diffs = memcmp(skb_mac_header(p),
skb_gro_mac_header(skb),
maclen);
NAPI_GRO_CB(p)->same_flow = !diffs;
NAPI_GRO_CB(p)->flush = 0;
}
return dev_gro_receive(napi, skb);
}
gro_result_t napi_skb_finish(gro_result_t ret, struct sk_buff *skb)
{
switch (ret) {
case GRO_NORMAL:
if (netif_receive_skb(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
kfree_skb(skb);
break;
case GRO_MERGED_FREE:
if (NAPI_GRO_CB(skb)->free == <API key>)
kmem_cache_free(skbuff_head_cache, skb);
else
__kfree_skb(skb);
break;
case GRO_HELD:
case GRO_MERGED:
break;
}
return ret;
}
EXPORT_SYMBOL(napi_skb_finish);
void <API key>(struct sk_buff *skb)
{
NAPI_GRO_CB(skb)->data_offset = 0;
NAPI_GRO_CB(skb)->frag0 = NULL;
NAPI_GRO_CB(skb)->frag0_len = 0;
if (skb->mac_header == skb->tail &&
!PageHighMem(skb_frag_page(&skb_shinfo(skb)->frags[0]))) {
NAPI_GRO_CB(skb)->frag0 =
skb_frag_address(&skb_shinfo(skb)->frags[0]);
NAPI_GRO_CB(skb)->frag0_len = skb_frag_size(&skb_shinfo(skb)->frags[0]);
}
}
EXPORT_SYMBOL(<API key>);
gro_result_t napi_gro_receive(struct napi_struct *napi, struct sk_buff *skb)
{
<API key>(skb);
return napi_skb_finish(__napi_gro_receive(napi, skb), skb);
}
EXPORT_SYMBOL(napi_gro_receive);
static void napi_reuse_skb(struct napi_struct *napi, struct sk_buff *skb)
{
__skb_pull(skb, skb_headlen(skb));
/* restore the reserve we had after <API key>() */
skb_reserve(skb, NET_SKB_PAD + NET_IP_ALIGN - skb_headroom(skb));
skb->vlan_tci = 0;
skb->dev = napi->dev;
skb->skb_iif = 0;
napi->skb = skb;
}
struct sk_buff *napi_get_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
if (!skb) {
skb = <API key>(napi->dev, GRO_MAX_HEAD);
if (skb)
napi->skb = skb;
}
return skb;
}
EXPORT_SYMBOL(napi_get_frags);
gro_result_t napi_frags_finish(struct napi_struct *napi, struct sk_buff *skb,
gro_result_t ret)
{
switch (ret) {
case GRO_NORMAL:
case GRO_HELD:
skb->protocol = eth_type_trans(skb, skb->dev);
if (ret == GRO_HELD)
skb_gro_pull(skb, -ETH_HLEN);
else if (netif_receive_skb(skb))
ret = GRO_DROP;
break;
case GRO_DROP:
case GRO_MERGED_FREE:
napi_reuse_skb(napi, skb);
break;
case GRO_MERGED:
break;
}
return ret;
}
EXPORT_SYMBOL(napi_frags_finish);
static struct sk_buff *napi_frags_skb(struct napi_struct *napi)
{
struct sk_buff *skb = napi->skb;
struct ethhdr *eth;
unsigned int hlen;
unsigned int off;
napi->skb = NULL;
<API key>(skb);
<API key>(skb);
off = skb_gro_offset(skb);
hlen = off + sizeof(*eth);
eth = skb_gro_header_fast(skb, off);
if (skb_gro_header_hard(skb, hlen)) {
eth = skb_gro_header_slow(skb, hlen, off);
if (unlikely(!eth)) {
napi_reuse_skb(napi, skb);
skb = NULL;
goto out;
}
}
skb_gro_pull(skb, sizeof(*eth));
/*
* This works because the only protocols we care about don't require
* special handling. We'll fix it up properly at the end.
*/
skb->protocol = eth->h_proto;
out:
return skb;
}
gro_result_t napi_gro_frags(struct napi_struct *napi)
{
struct sk_buff *skb = napi_frags_skb(napi);
if (!skb)
return GRO_DROP;
return napi_frags_finish(napi, skb, __napi_gro_receive(napi, skb));
}
EXPORT_SYMBOL(napi_gro_frags);
/*
* net_rps_action sends any pending IPI's for rps.
* Note: called with local irq disabled, but exits with local irq enabled.
*/
static void <API key>(struct softnet_data *sd)
{
#ifdef CONFIG_RPS
struct softnet_data *remsd = sd->rps_ipi_list;
if (remsd) {
sd->rps_ipi_list = NULL;
local_irq_enable();
/* Send pending IPI's to kick RPS processing on remote cpus. */
while (remsd) {
struct softnet_data *next = remsd->rps_ipi_next;
if (cpu_online(remsd->cpu))
<API key>(remsd->cpu,
&remsd->csd, 0);
remsd = next;
}
} else
#endif
local_irq_enable();
}
static int process_backlog(struct napi_struct *napi, int quota)
{
int work = 0;
struct softnet_data *sd = container_of(napi, struct softnet_data, backlog);
#ifdef CONFIG_RPS
/* Check if we have pending ipi, its better to send them now,
* not waiting net_rx_action() end.
*/
if (sd->rps_ipi_list) {
local_irq_disable();
<API key>(sd);
}
#endif
napi->weight = weight_p;
local_irq_disable();
while (work < quota) {
struct sk_buff *skb;
unsigned int qlen;
while ((skb = __skb_dequeue(&sd->process_queue))) {
local_irq_enable();
__netif_receive_skb(skb);
local_irq_disable();
<API key>(sd);
if (++work >= quota) {
local_irq_enable();
return work;
}
}
rps_lock(sd);
qlen = skb_queue_len(&sd->input_pkt_queue);
if (qlen)
<API key>(&sd->input_pkt_queue,
&sd->process_queue);
if (qlen < quota - work) {
/*
* Inline a custom version of __napi_complete().
* only current cpu owns and manipulates this napi,
* and NAPI_STATE_SCHED is the only possible flag set on backlog.
* we can use a plain write instead of clear_bit(),
* and we dont need an smp_mb() memory barrier.
*/
list_del(&napi->poll_list);
napi->state = 0;
quota = work + qlen;
}
rps_unlock(sd);
}
local_irq_enable();
return work;
}
/**
* __napi_schedule - schedule for receive
* @n: entry to schedule
*
* The entry's receive function will be scheduled to run
*/
void __napi_schedule(struct napi_struct *n)
{
unsigned long flags;
local_irq_save(flags);
____napi_schedule(&__get_cpu_var(softnet_data), n);
local_irq_restore(flags);
}
EXPORT_SYMBOL(__napi_schedule);
void __napi_complete(struct napi_struct *n)
{
BUG_ON(!test_bit(NAPI_STATE_SCHED, &n->state));
BUG_ON(n->gro_list);
list_del(&n->poll_list);
<API key>();
clear_bit(NAPI_STATE_SCHED, &n->state);
}
EXPORT_SYMBOL(__napi_complete);
void napi_complete(struct napi_struct *n)
{
unsigned long flags;
/*
* don't let napi dequeue from the cpu poll list
* just in case its running on a different cpu
*/
if (unlikely(test_bit(NAPI_STATE_NPSVC, &n->state)))
return;
napi_gro_flush(n);
local_irq_save(flags);
__napi_complete(n);
local_irq_restore(flags);
}
EXPORT_SYMBOL(napi_complete);
void netif_napi_add(struct net_device *dev, struct napi_struct *napi,
int (*poll)(struct napi_struct *, int), int weight)
{
INIT_LIST_HEAD(&napi->poll_list);
napi->gro_count = 0;
napi->gro_list = NULL;
napi->skb = NULL;
napi->poll = poll;
napi->weight = weight;
list_add(&napi->dev_list, &dev->napi_list);
napi->dev = dev;
#ifdef CONFIG_NETPOLL
spin_lock_init(&napi->poll_lock);
napi->poll_owner = -1;
#endif
set_bit(NAPI_STATE_SCHED, &napi->state);
}
EXPORT_SYMBOL(netif_napi_add);
void netif_napi_del(struct napi_struct *napi)
{
struct sk_buff *skb, *next;
list_del_init(&napi->dev_list);
napi_free_frags(napi);
for (skb = napi->gro_list; skb; skb = next) {
next = skb->next;
skb->next = NULL;
kfree_skb(skb);
}
napi->gro_list = NULL;
napi->gro_count = 0;
}
EXPORT_SYMBOL(netif_napi_del);
static void net_rx_action(struct softirq_action *h)
{
struct softnet_data *sd = &__get_cpu_var(softnet_data);
unsigned long time_limit = jiffies + 2;
int budget = netdev_budget;
void *have;
local_irq_disable();
while (!list_empty(&sd->poll_list)) {
struct napi_struct *n;
int work, weight;
/* If softirq window is exhuasted then punt.
* Allow this to run for 2 jiffies since which will allow
* an average latency of 1.5/HZ.
*/
if (unlikely(budget <= 0 || time_after(jiffies, time_limit)))
goto softnet_break;
local_irq_enable();
/* Even though interrupts have been re-enabled, this
* access is safe because interrupts can only add new
* entries to the tail of this list, and only ->poll()
* calls can remove this head entry from the list.
*/
n = list_first_entry(&sd->poll_list, struct napi_struct, poll_list);
have = netpoll_poll_lock(n);
weight = n->weight;
/* This NAPI_STATE_SCHED test is for avoiding a race
* with netpoll's poll_napi(). Only the entity which
* obtains the lock and sees NAPI_STATE_SCHED set will
* actually make the ->poll() call. Therefore we avoid
* accidentally calling ->poll() when NAPI is not scheduled.
*/
work = 0;
if (test_bit(NAPI_STATE_SCHED, &n->state)) {
work = n->poll(n, weight);
trace_napi_poll(n);
}
WARN_ON_ONCE(work > weight);
budget -= work;
local_irq_disable();
/* Drivers must not modify the NAPI state if they
* consume the entire weight. In such cases this code
* still "owns" the NAPI instance and therefore can
* move the instance around on the list at-will.
*/
if (unlikely(work == weight)) {
if (unlikely(<API key>(n))) {
local_irq_enable();
napi_complete(n);
local_irq_disable();
} else
list_move_tail(&n->poll_list, &sd->poll_list);
}
netpoll_poll_unlock(have);
}
out:
<API key>(sd);
#ifdef CONFIG_NET_DMA
/*
* There may not be any more sk_buffs coming right now, so push
* any pending DMA copies to hardware
*/
<API key>();
#endif
return;
softnet_break:
sd->time_squeeze++;
<API key>(NET_RX_SOFTIRQ);
goto out;
}
static gifconf_func_t *gifconf_list[NPROTO];
/**
* register_gifconf - register a SIOCGIF handler
* @family: Address family
* @gifconf: Function handler
*
* Register protocol dependent address dumping routines. The handler
* that is passed must not be freed or reused until it has been replaced
* by another handler.
*/
int register_gifconf(unsigned int family, gifconf_func_t *gifconf)
{
if (family >= NPROTO)
return -EINVAL;
gifconf_list[family] = gifconf;
return 0;
}
EXPORT_SYMBOL(register_gifconf);
/*
* Map an interface index to its name (SIOCGIFNAME)
*/
/*
* We need this ioctl for efficient implementation of the
* if_indextoname() function required by the IPv6 API. Without
* it, we would have to search all the interfaces to find a
* match. --pb
*/
static int dev_ifname(struct net *net, struct ifreq __user *arg)
{
struct net_device *dev;
struct ifreq ifr;
/*
* Fetch the caller's info block.
*/
if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
return -EFAULT;
rcu_read_lock();
dev = <API key>(net, ifr.ifr_ifindex);
if (!dev) {
rcu_read_unlock();
return -ENODEV;
}
strcpy(ifr.ifr_name, dev->name);
rcu_read_unlock();
if (copy_to_user(arg, &ifr, sizeof(struct ifreq)))
return -EFAULT;
return 0;
}
/*
* Perform a SIOCGIFCONF call. This structure will change
* size eventually, and there is nothing I can do about it.
* Thus we will need a 'compatibility mode'.
*/
static int dev_ifconf(struct net *net, char __user *arg)
{
struct ifconf ifc;
struct net_device *dev;
char __user *pos;
int len;
int total;
int i;
/*
* Fetch the caller's info block.
*/
if (copy_from_user(&ifc, arg, sizeof(struct ifconf)))
return -EFAULT;
pos = ifc.ifc_buf;
len = ifc.ifc_len;
/*
* Loop over the interfaces, and write an info block for each.
*/
total = 0;
for_each_netdev(net, dev) {
for (i = 0; i < NPROTO; i++) {
if (gifconf_list[i]) {
int done;
if (!pos)
done = gifconf_list[i](dev, NULL, 0);
else
done = gifconf_list[i](dev, pos + total,
len - total);
if (done < 0)
return -EFAULT;
total += done;
}
}
}
/*
* All done. Write the updated control block back to the caller.
*/
ifc.ifc_len = total;
/*
* Both BSD and Solaris return 0 here, so we do too.
*/
return copy_to_user(arg, &ifc, sizeof(struct ifconf)) ? -EFAULT : 0;
}
#ifdef CONFIG_PROC_FS
#define BUCKET_SPACE (32 - NETDEV_HASHBITS - 1)
#define get_bucket(x) ((x) >> BUCKET_SPACE)
#define get_offset(x) ((x) & ((1 << BUCKET_SPACE) - 1))
#define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
static inline struct net_device *<API key>(struct seq_file *seq, loff_t *pos)
{
struct net *net = seq_file_net(seq);
struct net_device *dev;
struct hlist_node *p;
struct hlist_head *h;
unsigned int count = 0, offset = get_offset(*pos);
h = &net->dev_name_head[get_bucket(*pos)];
<API key>(dev, p, h, name_hlist) {
if (++count == offset)
return dev;
}
return NULL;
}
static inline struct net_device *dev_from_bucket(struct seq_file *seq, loff_t *pos)
{
struct net_device *dev;
unsigned int bucket;
do {
dev = <API key>(seq, pos);
if (dev)
return dev;
bucket = get_bucket(*pos) + 1;
*pos = set_bucket_offset(bucket, 1);
} while (bucket < NETDEV_HASHENTRIES);
return NULL;
}
/*
* This is invoked by the /proc filesystem handler to display a device
* in detail.
*/
void *dev_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
if (!*pos)
return SEQ_START_TOKEN;
if (get_bucket(*pos) >= NETDEV_HASHENTRIES)
return NULL;
return dev_from_bucket(seq, pos);
}
void *dev_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return dev_from_bucket(seq, pos);
}
void dev_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static void <API key>(struct seq_file *seq, struct net_device *dev)
{
struct rtnl_link_stats64 temp;
const struct rtnl_link_stats64 *stats = dev_get_stats(dev, &temp);
seq_printf(seq, "%6s: %7llu %7llu %4llu %4llu %4llu %5llu %10llu %9llu "
"%8llu %7llu %4llu %4llu %4llu %5llu %7llu %10llu\n",
dev->name, stats->rx_bytes, stats->rx_packets,
stats->rx_errors,
stats->rx_dropped + stats->rx_missed_errors,
stats->rx_fifo_errors,
stats->rx_length_errors + stats->rx_over_errors +
stats->rx_crc_errors + stats->rx_frame_errors,
stats->rx_compressed, stats->multicast,
stats->tx_bytes, stats->tx_packets,
stats->tx_errors, stats->tx_dropped,
stats->tx_fifo_errors, stats->collisions,
stats->tx_carrier_errors +
stats->tx_aborted_errors +
stats->tx_window_errors +
stats->tx_heartbeat_errors,
stats->tx_compressed);
}
/*
* Called from the PROCfs module. This now uses the new arbitrary sized
* /proc/net interface to create /proc/net/dev
*/
static int dev_seq_show(struct seq_file *seq, void *v)
{
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Inter-| Receive "
" | Transmit\n"
" face |bytes packets errs drop fifo frame "
"compressed multicast|bytes packets errs "
"drop fifo colls carrier compressed\n");
else
<API key>(seq, v);
return 0;
}
static struct softnet_data *softnet_get_online(loff_t *pos)
{
struct softnet_data *sd = NULL;
while (*pos < nr_cpu_ids)
if (cpu_online(*pos)) {
sd = &per_cpu(softnet_data, *pos);
break;
} else
++*pos;
return sd;
}
static void *softnet_seq_start(struct seq_file *seq, loff_t *pos)
{
return softnet_get_online(pos);
}
static void *softnet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
++*pos;
return softnet_get_online(pos);
}
static void softnet_seq_stop(struct seq_file *seq, void *v)
{
}
static int softnet_seq_show(struct seq_file *seq, void *v)
{
struct softnet_data *sd = v;
seq_printf(seq, "%08x %08x %08x %08x %08x %08x %08x %08x %08x %08x\n",
sd->processed, sd->dropped, sd->time_squeeze, 0,
0, 0, 0, 0, /* was fastroute */
sd->cpu_collision, sd->received_rps);
return 0;
}
static const struct seq_operations dev_seq_ops = {
.start = dev_seq_start,
.next = dev_seq_next,
.stop = dev_seq_stop,
.show = dev_seq_show,
};
static int dev_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &dev_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations dev_seq_fops = {
.owner = THIS_MODULE,
.open = dev_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static const struct seq_operations softnet_seq_ops = {
.start = softnet_seq_start,
.next = softnet_seq_next,
.stop = softnet_seq_stop,
.show = softnet_seq_show,
};
static int softnet_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &softnet_seq_ops);
}
static const struct file_operations softnet_seq_fops = {
.owner = THIS_MODULE,
.open = softnet_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
static void *ptype_get_idx(loff_t pos)
{
struct packet_type *pt = NULL;
loff_t i = 0;
int t;
<API key>(pt, &ptype_all, list) {
if (i == pos)
return pt;
++i;
}
for (t = 0; t < PTYPE_HASH_SIZE; t++) {
<API key>(pt, &ptype_base[t], list) {
if (i == pos)
return pt;
++i;
}
}
return NULL;
}
static void *ptype_seq_start(struct seq_file *seq, loff_t *pos)
__acquires(RCU)
{
rcu_read_lock();
return *pos ? ptype_get_idx(*pos - 1) : SEQ_START_TOKEN;
}
static void *ptype_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
struct packet_type *pt;
struct list_head *nxt;
int hash;
++*pos;
if (v == SEQ_START_TOKEN)
return ptype_get_idx(0);
pt = v;
nxt = pt->list.next;
if (pt->type == htons(ETH_P_ALL)) {
if (nxt != &ptype_all)
goto found;
hash = 0;
nxt = ptype_base[0].next;
} else
hash = ntohs(pt->type) & PTYPE_HASH_MASK;
while (nxt == &ptype_base[hash]) {
if (++hash >= PTYPE_HASH_SIZE)
return NULL;
nxt = ptype_base[hash].next;
}
found:
return list_entry(nxt, struct packet_type, list);
}
static void ptype_seq_stop(struct seq_file *seq, void *v)
__releases(RCU)
{
rcu_read_unlock();
}
static int ptype_seq_show(struct seq_file *seq, void *v)
{
struct packet_type *pt = v;
if (v == SEQ_START_TOKEN)
seq_puts(seq, "Type Device Function\n");
else if (pt->dev == NULL || dev_net(pt->dev) == seq_file_net(seq)) {
if (pt->type == htons(ETH_P_ALL))
seq_puts(seq, "ALL ");
else
seq_printf(seq, "%04x", ntohs(pt->type));
seq_printf(seq, " %-8s %pF\n",
pt->dev ? pt->dev->name : "", pt->func);
}
return 0;
}
static const struct seq_operations ptype_seq_ops = {
.start = ptype_seq_start,
.next = ptype_seq_next,
.stop = ptype_seq_stop,
.show = ptype_seq_show,
};
static int ptype_seq_open(struct inode *inode, struct file *file)
{
return seq_open_net(inode, file, &ptype_seq_ops,
sizeof(struct seq_net_private));
}
static const struct file_operations ptype_seq_fops = {
.owner = THIS_MODULE,
.open = ptype_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_net,
};
static int __net_init dev_proc_net_init(struct net *net)
{
int rc = -ENOMEM;
if (!<API key>(net, "dev", S_IRUGO, &dev_seq_fops))
goto out;
if (!<API key>(net, "softnet_stat", S_IRUGO, &softnet_seq_fops))
goto out_dev;
if (!<API key>(net, "ptype", S_IRUGO, &ptype_seq_fops))
goto out_softnet;
if (wext_proc_init(net))
goto out_ptype;
rc = 0;
out:
return rc;
out_ptype:
proc_net_remove(net, "ptype");
out_softnet:
proc_net_remove(net, "softnet_stat");
out_dev:
proc_net_remove(net, "dev");
goto out;
}
static void __net_exit dev_proc_net_exit(struct net *net)
{
wext_proc_exit(net);
proc_net_remove(net, "ptype");
proc_net_remove(net, "softnet_stat");
proc_net_remove(net, "dev");
}
static struct pernet_operations __net_initdata dev_proc_ops = {
.init = dev_proc_net_init,
.exit = dev_proc_net_exit,
};
static int __init dev_proc_init(void)
{
return <API key>(&dev_proc_ops);
}
#else
#define dev_proc_init() 0
#endif /* CONFIG_PROC_FS */
/**
* netdev_set_master - set up master pointer
* @slave: slave device
* @master: new master device
*
* Changes the master device of the slave. Pass %NULL to break the
* bonding. The caller must hold the RTNL semaphore. On a failure
* a negative errno code is returned. On success the reference counts
* are adjusted and the function returns zero.
*/
int netdev_set_master(struct net_device *slave, struct net_device *master)
{
struct net_device *old = slave->master;
ASSERT_RTNL();
if (master) {
if (old)
return -EBUSY;
dev_hold(master);
}
slave->master = master;
if (old)
dev_put(old);
return 0;
}
EXPORT_SYMBOL(netdev_set_master);
/**
* <API key> - set up bonding master/slave pair
* @slave: slave device
* @master: new master device
*
* Changes the master device of the slave. Pass %NULL to break the
* bonding. The caller must hold the RTNL semaphore. On a failure
* a negative errno code is returned. On success %RTM_NEWLINK is sent
* to the routing socket and the function returns zero.
*/
int <API key>(struct net_device *slave, struct net_device *master)
{
int err;
ASSERT_RTNL();
err = netdev_set_master(slave, master);
if (err)
return err;
if (master)
slave->flags |= IFF_SLAVE;
else
slave->flags &= ~IFF_SLAVE;
rtmsg_ifinfo(RTM_NEWLINK, slave, IFF_SLAVE);
return 0;
}
EXPORT_SYMBOL(<API key>);
static void dev_change_rx_flags(struct net_device *dev, int flags)
{
const struct net_device_ops *ops = dev->netdev_ops;
if ((dev->flags & IFF_UP) && ops->ndo_change_rx_flags)
ops->ndo_change_rx_flags(dev, flags);
}
static int <API key>(struct net_device *dev, int inc)
{
unsigned int old_flags = dev->flags;
uid_t uid;
gid_t gid;
ASSERT_RTNL();
dev->flags |= IFF_PROMISC;
dev->promiscuity += inc;
if (dev->promiscuity == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch promisc and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_PROMISC;
else {
dev->promiscuity -= inc;
pr_warn("%s: promiscuity touches roof, set promiscuity failed. promiscuity feature of device might be broken.\n",
dev->name);
return -EOVERFLOW;
}
}
if (dev->flags != old_flags) {
pr_info("device %s %s promiscuous mode\n",
dev->name,
dev->flags & IFF_PROMISC ? "entered" : "left");
if (audit_enabled) {
current_uid_gid(&uid, &gid);
audit_log(current->audit_context, GFP_ATOMIC,
<API key>,
"dev=%s prom=%d old_prom=%d auid=%u uid=%u gid=%u ses=%u",
dev->name, (dev->flags & IFF_PROMISC),
(old_flags & IFF_PROMISC),
audit_get_loginuid(current),
uid, gid,
audit_get_sessionid(current));
}
dev_change_rx_flags(dev, IFF_PROMISC);
}
return 0;
}
/**
* dev_set_promiscuity - update promiscuity count on a device
* @dev: device
* @inc: modifier
*
* Add or remove promiscuity from a device. While the count in the device
* remains above zero the interface remains promiscuous. Once it hits zero
* the device reverts back to normal filtering operation. A negative inc
* value is used to drop promiscuity on the device.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_promiscuity(struct net_device *dev, int inc)
{
unsigned int old_flags = dev->flags;
int err;
err = <API key>(dev, inc);
if (err < 0)
return err;
if (dev->flags != old_flags)
dev_set_rx_mode(dev);
return err;
}
EXPORT_SYMBOL(dev_set_promiscuity);
/**
* dev_set_allmulti - update allmulti count on a device
* @dev: device
* @inc: modifier
*
* Add or remove reception of all multicast frames to a device. While the
* count in the device remains above zero the interface remains listening
* to all interfaces. Once it hits zero the device reverts back to normal
* filtering operation. A negative @inc value is used to drop the counter
* when releasing a resource needing all multicasts.
* Return 0 if successful or a negative errno code on error.
*/
int dev_set_allmulti(struct net_device *dev, int inc)
{
unsigned int old_flags = dev->flags;
ASSERT_RTNL();
dev->flags |= IFF_ALLMULTI;
dev->allmulti += inc;
if (dev->allmulti == 0) {
/*
* Avoid overflow.
* If inc causes overflow, untouch allmulti and return error.
*/
if (inc < 0)
dev->flags &= ~IFF_ALLMULTI;
else {
dev->allmulti -= inc;
pr_warn("%s: allmulti touches roof, set allmulti failed. allmulti feature of device might be broken.\n",
dev->name);
return -EOVERFLOW;
}
}
if (dev->flags ^ old_flags) {
dev_change_rx_flags(dev, IFF_ALLMULTI);
dev_set_rx_mode(dev);
}
return 0;
}
EXPORT_SYMBOL(dev_set_allmulti);
/*
* Upload unicast and multicast address lists to device and
* configure RX filtering. When the device doesn't support unicast
* filtering it is put in promiscuous mode while unicast addresses
* are present.
*/
void __dev_set_rx_mode(struct net_device *dev)
{
const struct net_device_ops *ops = dev->netdev_ops;
/* dev_open will call this function so the list will stay sane. */
if (!(dev->flags&IFF_UP))
return;
if (!<API key>(dev))
return;
if (!(dev->priv_flags & IFF_UNICAST_FLT)) {
/* Unicast addresses changes may only happen under the rtnl,
* therefore calling <API key> here is safe.
*/
if (!netdev_uc_empty(dev) && !dev->uc_promisc) {
<API key>(dev, 1);
dev->uc_promisc = true;
} else if (netdev_uc_empty(dev) && dev->uc_promisc) {
<API key>(dev, -1);
dev->uc_promisc = false;
}
}
if (ops->ndo_set_rx_mode)
ops->ndo_set_rx_mode(dev);
}
void dev_set_rx_mode(struct net_device *dev)
{
netif_addr_lock_bh(dev);
__dev_set_rx_mode(dev);
<API key>(dev);
}
/**
* dev_get_flags - get flags reported to userspace
* @dev: device
*
* Get the combination of flag bits exported through APIs to userspace.
*/
unsigned int dev_get_flags(const struct net_device *dev)
{
unsigned int flags;
flags = (dev->flags & ~(IFF_PROMISC |
IFF_ALLMULTI |
IFF_RUNNING |
IFF_LOWER_UP |
IFF_DORMANT)) |
(dev->gflags & (IFF_PROMISC |
IFF_ALLMULTI));
if (netif_running(dev)) {
if (netif_oper_up(dev))
flags |= IFF_RUNNING;
if (netif_carrier_ok(dev))
flags |= IFF_LOWER_UP;
if (netif_dormant(dev))
flags |= IFF_DORMANT;
}
return flags;
}
EXPORT_SYMBOL(dev_get_flags);
int __dev_change_flags(struct net_device *dev, unsigned int flags)
{
unsigned int old_flags = dev->flags;
int ret;
ASSERT_RTNL();
/*
* Set the flags on our device.
*/
dev->flags = (flags & (IFF_DEBUG | IFF_NOTRAILERS | IFF_NOARP |
IFF_DYNAMIC | IFF_MULTICAST | IFF_PORTSEL |
IFF_AUTOMEDIA | IFF_NOMULTIPATH | IFF_MPBACKUP |
IFF_MPHANDOVER)) |
(dev->flags & (IFF_UP | IFF_VOLATILE | IFF_PROMISC |
IFF_ALLMULTI));
/*
* Load in the correct multicast list now the flags have changed.
*/
if ((old_flags ^ flags) & IFF_MULTICAST)
dev_change_rx_flags(dev, IFF_MULTICAST);
dev_set_rx_mode(dev);
/*
* Have we downed the interface. We handle IFF_UP ourselves
* according to user attempts to set it, rather than blindly
* setting it.
*/
ret = 0;
if ((old_flags ^ flags) & IFF_UP) { /* Bit is different ? */
ret = ((old_flags & IFF_UP) ? __dev_close : __dev_open)(dev);
if (!ret)
dev_set_rx_mode(dev);
}
if ((flags ^ dev->gflags) & IFF_PROMISC) {
int inc = (flags & IFF_PROMISC) ? 1 : -1;
dev->gflags ^= IFF_PROMISC;
dev_set_promiscuity(dev, inc);
}
/* NOTE: order of synchronization of IFF_PROMISC and IFF_ALLMULTI
is important. Some (broken) drivers set IFF_PROMISC, when
IFF_ALLMULTI is requested not asking us and not reporting.
*/
if ((flags ^ dev->gflags) & IFF_ALLMULTI) {
int inc = (flags & IFF_ALLMULTI) ? 1 : -1;
dev->gflags ^= IFF_ALLMULTI;
dev_set_allmulti(dev, inc);
}
return ret;
}
void __dev_notify_flags(struct net_device *dev, unsigned int old_flags)
{
unsigned int changes = dev->flags ^ old_flags;
if (changes & IFF_UP) {
if (dev->flags & IFF_UP)
<API key>(NETDEV_UP, dev);
else
<API key>(NETDEV_DOWN, dev);
}
if (dev->flags & IFF_UP &&
(changes & ~(IFF_UP | IFF_PROMISC | IFF_ALLMULTI | IFF_VOLATILE)))
<API key>(NETDEV_CHANGE, dev);
}
/**
* dev_change_flags - change device settings
* @dev: device
* @flags: device state flags
*
* Change settings on device based state flags. The flags are
* in the userspace exported format.
*/
int dev_change_flags(struct net_device *dev, unsigned int flags)
{
int ret;
unsigned int changes, old_flags = dev->flags;
ret = __dev_change_flags(dev, flags);
if (ret < 0)
return ret;
changes = old_flags ^ dev->flags;
if (changes)
rtmsg_ifinfo(RTM_NEWLINK, dev, changes);
__dev_notify_flags(dev, old_flags);
return ret;
}
EXPORT_SYMBOL(dev_change_flags);
/**
* dev_set_mtu - Change maximum transfer unit
* @dev: device
* @new_mtu: new transfer unit
*
* Change the maximum transfer size of the network device.
*/
int dev_set_mtu(struct net_device *dev, int new_mtu)
{
const struct net_device_ops *ops = dev->netdev_ops;
int err;
if (new_mtu == dev->mtu)
return 0;
/* MTU must be positive. */
if (new_mtu < 0)
return -EINVAL;
if (!<API key>(dev))
return -ENODEV;
err = 0;
if (ops->ndo_change_mtu)
err = ops->ndo_change_mtu(dev, new_mtu);
else
dev->mtu = new_mtu;
if (!err && dev->flags & IFF_UP)
<API key>(NETDEV_CHANGEMTU, dev);
return err;
}
EXPORT_SYMBOL(dev_set_mtu);
/**
* dev_set_group - Change group this device belongs to
* @dev: device
* @new_group: group this device should belong to
*/
void dev_set_group(struct net_device *dev, int new_group)
{
dev->group = new_group;
}
EXPORT_SYMBOL(dev_set_group);
/**
* dev_set_mac_address - Change Media Access Control Address
* @dev: device
* @sa: new address
*
* Change the hardware (MAC) address of the device
*/
int dev_set_mac_address(struct net_device *dev, struct sockaddr *sa)
{
const struct net_device_ops *ops = dev->netdev_ops;
int err;
if (!ops->ndo_set_mac_address)
return -EOPNOTSUPP;
if (sa->sa_family != dev->type)
return -EINVAL;
if (!<API key>(dev))
return -ENODEV;
err = ops->ndo_set_mac_address(dev, sa);
if (!err)
<API key>(NETDEV_CHANGEADDR, dev);
return err;
}
EXPORT_SYMBOL(dev_set_mac_address);
/*
* Perform the SIOCxIFxxx calls, inside rcu_read_lock()
*/
static int dev_ifsioc_locked(struct net *net, struct ifreq *ifr, unsigned int cmd)
{
int err;
struct net_device *dev = dev_get_by_name_rcu(net, ifr->ifr_name);
if (!dev)
return -ENODEV;
switch (cmd) {
case SIOCGIFFLAGS: /* Get interface flags */
ifr->ifr_flags = (short) dev_get_flags(dev);
return 0;
case SIOCGIFMETRIC: /* Get the metric on the interface
(currently unused) */
ifr->ifr_metric = 0;
return 0;
case SIOCGIFMTU: /* Get the MTU of a device */
ifr->ifr_mtu = dev->mtu;
return 0;
case SIOCGIFHWADDR:
if (!dev->addr_len)
memset(ifr->ifr_hwaddr.sa_data, 0, sizeof ifr->ifr_hwaddr.sa_data);
else
memcpy(ifr->ifr_hwaddr.sa_data, dev->dev_addr,
min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
ifr->ifr_hwaddr.sa_family = dev->type;
return 0;
case SIOCGIFSLAVE:
err = -EINVAL;
break;
case SIOCGIFMAP:
ifr->ifr_map.mem_start = dev->mem_start;
ifr->ifr_map.mem_end = dev->mem_end;
ifr->ifr_map.base_addr = dev->base_addr;
ifr->ifr_map.irq = dev->irq;
ifr->ifr_map.dma = dev->dma;
ifr->ifr_map.port = dev->if_port;
return 0;
case SIOCGIFINDEX:
ifr->ifr_ifindex = dev->ifindex;
return 0;
case SIOCGIFTXQLEN:
ifr->ifr_qlen = dev->tx_queue_len;
return 0;
default:
/* dev_ioctl() should ensure this case
* is never reached
*/
WARN_ON(1);
err = -ENOTTY;
break;
}
return err;
}
/*
* Perform the SIOCxIFxxx calls, inside rtnl_lock()
*/
static int dev_ifsioc(struct net *net, struct ifreq *ifr, unsigned int cmd)
{
int err;
struct net_device *dev = __dev_get_by_name(net, ifr->ifr_name);
const struct net_device_ops *ops;
if (!dev)
return -ENODEV;
ops = dev->netdev_ops;
switch (cmd) {
case SIOCSIFFLAGS: /* Set interface flags */
return dev_change_flags(dev, ifr->ifr_flags);
case SIOCSIFMETRIC: /* Set the metric on the interface
(currently unused) */
return -EOPNOTSUPP;
case SIOCSIFMTU: /* Set the MTU of a device */
return dev_set_mtu(dev, ifr->ifr_mtu);
case SIOCSIFHWADDR:
return dev_set_mac_address(dev, &ifr->ifr_hwaddr);
case SIOCSIFHWBROADCAST:
if (ifr->ifr_hwaddr.sa_family != dev->type)
return -EINVAL;
memcpy(dev->broadcast, ifr->ifr_hwaddr.sa_data,
min(sizeof ifr->ifr_hwaddr.sa_data, (size_t) dev->addr_len));
<API key>(NETDEV_CHANGEADDR, dev);
return 0;
case SIOCSIFMAP:
if (ops->ndo_set_config) {
if (!<API key>(dev))
return -ENODEV;
return ops->ndo_set_config(dev, &ifr->ifr_map);
}
return -EOPNOTSUPP;
case SIOCADDMULTI:
if (!ops->ndo_set_rx_mode ||
ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
return -EINVAL;
if (!<API key>(dev))
return -ENODEV;
return dev_mc_add_global(dev, ifr->ifr_hwaddr.sa_data);
case SIOCDELMULTI:
if (!ops->ndo_set_rx_mode ||
ifr->ifr_hwaddr.sa_family != AF_UNSPEC)
return -EINVAL;
if (!<API key>(dev))
return -ENODEV;
return dev_mc_del_global(dev, ifr->ifr_hwaddr.sa_data);
case SIOCSIFTXQLEN:
if (ifr->ifr_qlen < 0)
return -EINVAL;
dev->tx_queue_len = ifr->ifr_qlen;
return 0;
case SIOCSIFNAME:
ifr->ifr_newname[IFNAMSIZ-1] = '\0';
return dev_change_name(dev, ifr->ifr_newname);
case SIOCSHWTSTAMP:
err = <API key>(ifr);
if (err)
return err;
/* fall through */
/*
* Unknown or private ioctl
*/
default:
if ((cmd >= SIOCDEVPRIVATE &&
cmd <= SIOCDEVPRIVATE + 15) ||
cmd == SIOCBONDENSLAVE ||
cmd == SIOCBONDRELEASE ||
cmd == SIOCBONDSETHWADDR ||
cmd == <API key> ||
cmd == SIOCBONDINFOQUERY ||
cmd == <API key> ||
cmd == SIOCGMIIPHY ||
cmd == SIOCGMIIREG ||
cmd == SIOCSMIIREG ||
cmd == SIOCBRADDIF ||
cmd == SIOCBRDELIF ||
cmd == SIOCSHWTSTAMP ||
cmd == SIOCWANDEV) {
err = -EOPNOTSUPP;
if (ops->ndo_do_ioctl) {
if (<API key>(dev))
err = ops->ndo_do_ioctl(dev, ifr, cmd);
else
err = -ENODEV;
}
} else
err = -EINVAL;
}
return err;
}
/*
* This function handles all "interface"-type I/O control requests. The actual
* 'doing' part of this is dev_ifsioc above.
*/
/**
* dev_ioctl - network device ioctl
* @net: the applicable net namespace
* @cmd: command to issue
* @arg: pointer to a struct ifreq in user space
*
* Issue ioctl functions to devices. This is normally called by the
* user space syscall interfaces but can sometimes be useful for
* other purposes. The return value is the return from the syscall if
* positive or a negative errno code on error.
*/
int dev_ioctl(struct net *net, unsigned int cmd, void __user *arg)
{
struct ifreq ifr;
int ret;
char *colon;
/* One special case: SIOCGIFCONF takes ifconf argument
and requires shared lock, because it sleeps writing
to user space.
*/
if (cmd == SIOCGIFCONF) {
rtnl_lock();
ret = dev_ifconf(net, (char __user *) arg);
rtnl_unlock();
return ret;
}
if (cmd == SIOCGIFNAME)
return dev_ifname(net, (struct ifreq __user *)arg);
if (copy_from_user(&ifr, arg, sizeof(struct ifreq)))
return -EFAULT;
ifr.ifr_name[IFNAMSIZ-1] = 0;
colon = strchr(ifr.ifr_name, ':');
if (colon)
*colon = 0;
/*
* See which interface the caller is talking about.
*/
switch (cmd) {
/*
* These ioctl calls:
* - can be done by all.
* - atomic and do not require locking.
* - return a value
*/
case SIOCGIFFLAGS:
case SIOCGIFMETRIC:
case SIOCGIFMTU:
case SIOCGIFHWADDR:
case SIOCGIFSLAVE:
case SIOCGIFMAP:
case SIOCGIFINDEX:
case SIOCGIFTXQLEN:
dev_load(net, ifr.ifr_name);
rcu_read_lock();
ret = dev_ifsioc_locked(net, &ifr, cmd);
rcu_read_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
case SIOCETHTOOL:
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ethtool(net, &ifr);
rtnl_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
/*
* These ioctl calls:
* - require superuser power.
* - require strict serialization.
* - return a value
*/
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSIFNAME:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
if (!ret) {
if (colon)
*colon = ':';
if (copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
}
return ret;
/*
* These ioctl calls:
* - require superuser power.
* - require strict serialization.
* - do not return a value
*/
case SIOCSIFFLAGS:
case SIOCSIFMETRIC:
case SIOCSIFMTU:
case SIOCSIFMAP:
case SIOCSIFHWADDR:
case SIOCSIFSLAVE:
case SIOCADDMULTI:
case SIOCDELMULTI:
case SIOCSIFHWBROADCAST:
case SIOCSIFTXQLEN:
case SIOCSMIIREG:
case SIOCBONDENSLAVE:
case SIOCBONDRELEASE:
case SIOCBONDSETHWADDR:
case <API key>:
case SIOCBRADDIF:
case SIOCBRDELIF:
case SIOCSHWTSTAMP:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
/* fall through */
case <API key>:
case SIOCBONDINFOQUERY:
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
return ret;
case SIOCGIFMEM:
/* Get the per device memory space. We can add this but
* currently do not support it */
case SIOCSIFMEM:
/* Set the per device memory buffer space.
* Not applicable in our case */
case SIOCSIFLINK:
return -ENOTTY;
/*
* Unknown or private ioctl.
*/
default:
if (cmd == SIOCWANDEV ||
(cmd >= SIOCDEVPRIVATE &&
cmd <= SIOCDEVPRIVATE + 15)) {
dev_load(net, ifr.ifr_name);
rtnl_lock();
ret = dev_ifsioc(net, &ifr, cmd);
rtnl_unlock();
if (!ret && copy_to_user(arg, &ifr,
sizeof(struct ifreq)))
ret = -EFAULT;
return ret;
}
/* Take care of Wireless Extensions */
if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)
return wext_handle_ioctl(net, &ifr, cmd, arg);
return -ENOTTY;
}
}
/**
* dev_new_index - allocate an ifindex
* @net: the applicable net namespace
*
* Returns a suitable unique value for a new device interface
* number. The caller must hold the rtnl semaphore or the
* dev_base_lock to be sure it remains unique.
*/
static int dev_new_index(struct net *net)
{
static int ifindex;
for (;;) {
if (++ifindex <= 0)
ifindex = 1;
if (!__dev_get_by_index(net, ifindex))
return ifindex;
}
}
/* Delayed registration/unregisteration */
static LIST_HEAD(net_todo_list);
static void net_set_todo(struct net_device *dev)
{
list_add_tail(&dev->todo_list, &net_todo_list);
}
static void <API key>(struct list_head *head)
{
struct net_device *dev, *tmp;
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
<API key>(dev, tmp, head, unreg_list) {
/* Some devices call without registering
* for initialization unwind. Remove those
* devices and proceed with the remaining.
*/
if (dev->reg_state == <API key>) {
pr_debug("<API key>: device %s/%p never was registered\n",
dev->name, dev);
WARN_ON(1);
list_del(&dev->unreg_list);
continue;
}
dev->dismantle = true;
BUG_ON(dev->reg_state != NETREG_REGISTERED);
}
/* If device is running, close it first. */
dev_close_many(head);
list_for_each_entry(dev, head, unreg_list) {
/* And unlink it from device chain. */
unlist_netdevice(dev);
dev->reg_state = <API key>;
}
synchronize_net();
list_for_each_entry(dev, head, unreg_list) {
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
this device. They should clean all the things.
*/
<API key>(NETDEV_UNREGISTER, dev);
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == <API key>)
rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
/* Notifier chain MUST detach us from master device. */
WARN_ON(dev->master);
/* Remove entries from kobject tree */
<API key>(dev);
}
/* Process any work delayed until the end of the batch */
dev = list_first_entry(head, struct net_device, unreg_list);
<API key>(<API key>, dev);
synchronize_net();
list_for_each_entry(dev, head, unreg_list)
dev_put(dev);
}
static void rollback_registered(struct net_device *dev)
{
LIST_HEAD(single);
list_add(&dev->unreg_list, &single);
<API key>(&single);
list_del(&single);
}
static netdev_features_t netdev_fix_features(struct net_device *dev,
netdev_features_t features)
{
if ((features & NETIF_F_HW_CSUM) &&
(features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
netdev_warn(dev, "mixed HW and IP checksum settings.\n");
features &= ~(NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM);
}
if ((features & NETIF_F_SG) &&
!(features & NETIF_F_ALL_CSUM)) {
netdev_dbg(dev,
"Dropping NETIF_F_SG since no checksum feature.\n");
features &= ~NETIF_F_SG;
}
/* TSO requires that SG is present as well. */
if ((features & NETIF_F_ALL_TSO) && !(features & NETIF_F_SG)) {
netdev_dbg(dev, "Dropping TSO features since no SG feature.\n");
features &= ~NETIF_F_ALL_TSO;
}
/* TSO ECN requires that TSO is present as well. */
if ((features & NETIF_F_ALL_TSO) == NETIF_F_TSO_ECN)
features &= ~NETIF_F_TSO_ECN;
/* Software GSO depends on SG. */
if ((features & NETIF_F_GSO) && !(features & NETIF_F_SG)) {
netdev_dbg(dev, "Dropping NETIF_F_GSO since no SG feature.\n");
features &= ~NETIF_F_GSO;
}
/* UFO needs SG and checksumming */
if (features & NETIF_F_UFO) {
/* maybe split UFO into V4 and V6? */
if (!((features & NETIF_F_GEN_CSUM) ||
(features & (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))
== (NETIF_F_IP_CSUM|NETIF_F_IPV6_CSUM))) {
netdev_dbg(dev,
"Dropping NETIF_F_UFO since no checksum offload features.\n");
features &= ~NETIF_F_UFO;
}
if (!(features & NETIF_F_SG)) {
netdev_dbg(dev,
"Dropping NETIF_F_UFO since no NETIF_F_SG feature.\n");
features &= ~NETIF_F_UFO;
}
}
return features;
}
int <API key>(struct net_device *dev)
{
netdev_features_t features;
int err = 0;
ASSERT_RTNL();
features = <API key>(dev);
if (dev->netdev_ops->ndo_fix_features)
features = dev->netdev_ops->ndo_fix_features(dev, features);
/* driver might be less strict about feature dependencies */
features = netdev_fix_features(dev, features);
if (dev->features == features)
return 0;
netdev_dbg(dev, "Features changed: %pNF -> %pNF\n",
&dev->features, &features);
if (dev->netdev_ops->ndo_set_features)
err = dev->netdev_ops->ndo_set_features(dev, features);
if (unlikely(err < 0)) {
netdev_err(dev,
"set_features() failed (%d); wanted %pNF, left %pNF\n",
err, &features, &dev->features);
return -1;
}
if (!err)
dev->features = features;
return 1;
}
/**
* <API key> - recalculate device features
* @dev: the device to check
*
* Recalculate dev->features set and send notifications if it
* has changed. Should be called after driver or hardware dependent
* conditions might have changed that influence the features.
*/
void <API key>(struct net_device *dev)
{
if (<API key>(dev))
<API key>(dev);
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - recalculate device features
* @dev: the device to check
*
* Recalculate dev->features set and send notifications even
* if they have not changed. Should be called instead of
* <API key>() if also dev->vlan_features might
* have changed to allow the changes to be propagated to stacked
* VLAN devices.
*/
void <API key>(struct net_device *dev)
{
<API key>(dev);
<API key>(dev);
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - transfer operstate
* @rootdev: the root or lower level device to transfer state from
* @dev: the device to transfer operstate to
*
* Transfer operational state from root to device. This is normally
* called when a stacking relationship exists between the root
* device and the device(a leaf device).
*/
void <API key>(const struct net_device *rootdev,
struct net_device *dev)
{
if (rootdev->operstate == IF_OPER_DORMANT)
netif_dormant_on(dev);
else
netif_dormant_off(dev);
if (netif_carrier_ok(rootdev)) {
if (!netif_carrier_ok(dev))
netif_carrier_on(dev);
} else {
if (netif_carrier_ok(dev))
netif_carrier_off(dev);
}
}
EXPORT_SYMBOL(<API key>);
#ifdef CONFIG_RPS
static int <API key>(struct net_device *dev)
{
unsigned int i, count = dev->num_rx_queues;
struct netdev_rx_queue *rx;
BUG_ON(count < 1);
rx = kcalloc(count, sizeof(struct netdev_rx_queue), GFP_KERNEL);
if (!rx) {
pr_err("netdev: Unable to allocate %u rx queues\n", count);
return -ENOMEM;
}
dev->_rx = rx;
for (i = 0; i < count; i++)
rx[i].dev = dev;
return 0;
}
#endif
static void <API key>(struct net_device *dev,
struct netdev_queue *queue, void *_unused)
{
/* Initialize queue lock */
spin_lock_init(&queue->_xmit_lock);
<API key>(&queue->_xmit_lock, dev->type);
queue->xmit_lock_owner = -1;
<API key>(queue, NUMA_NO_NODE);
queue->dev = dev;
#ifdef CONFIG_BQL
dql_init(&queue->dql, HZ);
#endif
}
static int <API key>(struct net_device *dev)
{
unsigned int count = dev->num_tx_queues;
struct netdev_queue *tx;
BUG_ON(count < 1);
tx = kcalloc(count, sizeof(struct netdev_queue), GFP_KERNEL);
if (!tx) {
pr_err("netdev: Unable to allocate %u tx queues\n", count);
return -ENOMEM;
}
dev->_tx = tx;
<API key>(dev, <API key>, NULL);
spin_lock_init(&dev->tx_global_lock);
return 0;
}
/**
* register_netdevice - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* Callers must hold the rtnl semaphore. You may want
* register_netdev() instead of this.
*
* BUGS:
* The locking appears insufficient to guarantee two parallel registers
* will not get the same name.
*/
int register_netdevice(struct net_device *dev)
{
int ret;
struct net *net = dev_net(dev);
BUG_ON(dev_boot_phase);
ASSERT_RTNL();
might_sleep();
/* When net_device's are persistent, this will be fatal. */
BUG_ON(dev->reg_state != <API key>);
BUG_ON(!net);
spin_lock_init(&dev->addr_list_lock);
<API key>(dev);
dev->iflink = -1;
ret = dev_get_valid_name(dev, dev->name);
if (ret < 0)
goto out;
/* Init, if this function is available */
if (dev->netdev_ops->ndo_init) {
ret = dev->netdev_ops->ndo_init(dev);
if (ret) {
if (ret > 0)
ret = -EIO;
goto out;
}
}
dev->ifindex = dev_new_index(net);
if (dev->iflink == -1)
dev->iflink = dev->ifindex;
/* Transfer changeable features to wanted_features and enable
* software offloads (GSO and GRO).
*/
dev->hw_features |= <API key>;
dev->features |= <API key>;
dev->wanted_features = dev->features & dev->hw_features;
/* Turn on no cache copy if HW is doing checksum */
if (!(dev->flags & IFF_LOOPBACK)) {
dev->hw_features |= <API key>;
if (dev->features & NETIF_F_ALL_CSUM) {
dev->wanted_features |= <API key>;
dev->features |= <API key>;
}
}
/* Make NETIF_F_HIGHDMA inheritable to VLAN devices.
*/
dev->vlan_features |= NETIF_F_HIGHDMA;
ret = <API key>(NETDEV_POST_INIT, dev);
ret = notifier_to_errno(ret);
if (ret)
goto err_uninit;
ret = <API key>(dev);
if (ret)
goto err_uninit;
dev->reg_state = NETREG_REGISTERED;
<API key>(dev);
/*
* Default initial state at registry is that the
* device is present.
*/
set_bit(<API key>, &dev->state);
dev_init_scheduler(dev);
dev_hold(dev);
list_netdevice(dev);
/* Notify protocols, that a new device appeared. */
ret = <API key>(NETDEV_REGISTER, dev);
ret = notifier_to_errno(ret);
if (ret) {
rollback_registered(dev);
dev->reg_state = NETREG_UNREGISTERED;
}
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
if (!dev->rtnl_link_ops ||
dev->rtnl_link_state == <API key>)
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
out:
return ret;
err_uninit:
if (dev->netdev_ops->ndo_uninit)
dev->netdev_ops->ndo_uninit(dev);
goto out;
}
EXPORT_SYMBOL(register_netdevice);
/**
* init_dummy_netdev - init a dummy network device for NAPI
* @dev: device to init
*
* This takes a network device structure and initialize the minimum
* amount of fields so it can be used to schedule NAPI polls without
* registering a full blown interface. This is to be used by drivers
* that need to tie several hardware interfaces to a single NAPI
* poll scheduler due to HW limitations.
*/
int init_dummy_netdev(struct net_device *dev)
{
/* Clear everything. Note we don't initialize spinlocks
* are they aren't supposed to be taken by any of the
* NAPI code and this dummy netdev is supposed to be
* only ever used for NAPI polls
*/
memset(dev, 0, sizeof(struct net_device));
/* make sure we BUG if trying to hit standard
* register/unregister code path
*/
dev->reg_state = NETREG_DUMMY;
/* NAPI wants this */
INIT_LIST_HEAD(&dev->napi_list);
/* a dummy interface is started by default */
set_bit(<API key>, &dev->state);
set_bit(__LINK_STATE_START, &dev->state);
/* Note : We dont allocate pcpu_refcnt for dummy devices,
* because users of this 'device' dont need to change
* its refcount.
*/
return 0;
}
EXPORT_SYMBOL_GPL(init_dummy_netdev);
/**
* register_netdev - register a network device
* @dev: device to register
*
* Take a completed network device structure and add it to the kernel
* interfaces. A %NETDEV_REGISTER message is sent to the netdev notifier
* chain. 0 is returned on success. A negative errno code is returned
* on a failure to set up the device, or if the name is a duplicate.
*
* This is a wrapper around register_netdevice that takes the rtnl semaphore
* and expands the device name if you passed a format string to
* alloc_netdev.
*/
int register_netdev(struct net_device *dev)
{
int err;
rtnl_lock();
err = register_netdevice(dev);
rtnl_unlock();
return err;
}
EXPORT_SYMBOL(register_netdev);
int netdev_refcnt_read(const struct net_device *dev)
{
int i, refcnt = 0;
<API key>(i)
refcnt += *per_cpu_ptr(dev->pcpu_refcnt, i);
return refcnt;
}
EXPORT_SYMBOL(netdev_refcnt_read);
/*
* netdev_wait_allrefs - wait until all references are gone.
*
* This is called when unregistering network devices.
*
* Any protocol or device that holds a reference should register
* for netdevice notification, and cleanup and put back the
* reference if they receive an UNREGISTER event.
* We can get stuck here if buggy protocols don't correctly
* call dev_put.
*/
static void netdev_wait_allrefs(struct net_device *dev)
{
unsigned long rebroadcast_time, warning_time;
int refcnt;
<API key>(dev);
rebroadcast_time = warning_time = jiffies;
refcnt = netdev_refcnt_read(dev);
while (refcnt != 0) {
if (time_after(jiffies, rebroadcast_time + 1 * HZ)) {
rtnl_lock();
/* Rebroadcast unregister notification */
<API key>(NETDEV_UNREGISTER, dev);
/* don't resend <API key>, _BATCH users
* should have already handle it the first time */
if (test_bit(<API key>,
&dev->state)) {
/* We must not have linkwatch events
* pending on unregister. If this
* happens, we simply run the queue
* unscheduled, resulting in a noop
* for this device.
*/
linkwatch_run_queue();
}
__rtnl_unlock();
rebroadcast_time = jiffies;
}
msleep(250);
refcnt = netdev_refcnt_read(dev);
if (time_after(jiffies, warning_time + 10 * HZ)) {
pr_emerg("<API key>: waiting for %s to become free. Usage count = %d\n",
dev->name, refcnt);
warning_time = jiffies;
}
}
}
/* The sequence is:
*
* rtnl_lock();
* ...
* register_netdevice(x1);
* register_netdevice(x2);
* ...
* <API key>(y1);
* <API key>(y2);
* ...
* rtnl_unlock();
* free_netdev(y1);
* free_netdev(y2);
*
* We are invoked by rtnl_unlock().
* This allows us to deal with problems:
* 1) We can delete sysfs objects which invoke hotplug
* without deadlocking with linkwatch via keventd.
* 2) Since we run with the RTNL semaphore not held, we can sleep
* safely in order to wait for the netdev refcnt to drop to zero.
*
* We must not return until all unregister events added during
* the interval the lock was held have been completed.
*/
void netdev_run_todo(void)
{
struct list_head list;
/* Snapshot list, allow later requests */
list_replace_init(&net_todo_list, &list);
__rtnl_unlock();
/* Wait for rcu callbacks to finish before attempting to drain
* the device list. This usually avoids a 250ms wait.
*/
if (!list_empty(&list))
rcu_barrier();
while (!list_empty(&list)) {
struct net_device *dev
= list_first_entry(&list, struct net_device, todo_list);
list_del(&dev->todo_list);
if (unlikely(dev->reg_state != <API key>)) {
pr_err("network todo '%s' but state %d\n",
dev->name, dev->reg_state);
dump_stack();
continue;
}
dev->reg_state = NETREG_UNREGISTERED;
on_each_cpu(flush_backlog, dev, 1);
netdev_wait_allrefs(dev);
/* paranoia */
BUG_ON(netdev_refcnt_read(dev));
WARN_ON(rcu_access_pointer(dev->ip_ptr));
WARN_ON(rcu_access_pointer(dev->ip6_ptr));
WARN_ON(dev->dn_ptr);
if (dev->destructor)
dev->destructor(dev);
/* Free network device */
kobject_put(&dev->dev.kobj);
}
}
/* Convert net_device_stats to rtnl_link_stats64. They have the same
* fields in the same order, with only the type differing.
*/
void <API key>(struct rtnl_link_stats64 *stats64,
const struct net_device_stats *netdev_stats)
{
#if BITS_PER_LONG == 64
BUILD_BUG_ON(sizeof(*stats64) != sizeof(*netdev_stats));
memcpy(stats64, netdev_stats, sizeof(*stats64));
#else
size_t i, n = sizeof(*stats64) / sizeof(u64);
const unsigned long *src = (const unsigned long *)netdev_stats;
u64 *dst = (u64 *)stats64;
BUILD_BUG_ON(sizeof(*netdev_stats) / sizeof(unsigned long) !=
sizeof(*stats64) / sizeof(u64));
for (i = 0; i < n; i++)
dst[i] = src[i];
#endif
}
EXPORT_SYMBOL(<API key>);
/**
* dev_get_stats - get network device statistics
* @dev: device to get statistics from
* @storage: place to store stats
*
* Get network statistics from device. Return @storage.
* The device driver may provide its own method by setting
* dev->netdev_ops->get_stats64 or dev->netdev_ops->get_stats;
* otherwise the internal statistics structure is used.
*/
struct rtnl_link_stats64 *dev_get_stats(struct net_device *dev,
struct rtnl_link_stats64 *storage)
{
const struct net_device_ops *ops = dev->netdev_ops;
if (ops->ndo_get_stats64) {
memset(storage, 0, sizeof(*storage));
ops->ndo_get_stats64(dev, storage);
} else if (ops->ndo_get_stats) {
<API key>(storage, ops->ndo_get_stats(dev));
} else {
<API key>(storage, &dev->stats);
}
storage->rx_dropped += atomic_long_read(&dev->rx_dropped);
return storage;
}
EXPORT_SYMBOL(dev_get_stats);
struct netdev_queue *<API key>(struct net_device *dev)
{
struct netdev_queue *queue = dev_ingress_queue(dev);
#ifdef CONFIG_NET_CLS_ACT
if (queue)
return queue;
queue = kzalloc(sizeof(*queue), GFP_KERNEL);
if (!queue)
return NULL;
<API key>(dev, queue, NULL);
queue->qdisc = &noop_qdisc;
queue->qdisc_sleeping = &noop_qdisc;
rcu_assign_pointer(dev->ingress_queue, queue);
#endif
return queue;
}
/**
* alloc_netdev_mqs - allocate network device
* @sizeof_priv: size of private data to allocate space for
* @name: device name format string
* @setup: callback to initialize device
* @txqs: the number of TX subqueues to allocate
* @rxqs: the number of RX subqueues to allocate
*
* Allocates a struct net_device with private data area for driver use
* and performs basic initialization. Also allocates subquue structs
* for each queue on the device.
*/
struct net_device *alloc_netdev_mqs(int sizeof_priv, const char *name,
void (*setup)(struct net_device *),
unsigned int txqs, unsigned int rxqs)
{
struct net_device *dev;
size_t alloc_size;
struct net_device *p;
BUG_ON(strlen(name) >= sizeof(dev->name));
if (txqs < 1) {
pr_err("alloc_netdev: Unable to allocate device with zero queues\n");
return NULL;
}
#ifdef CONFIG_RPS
if (rxqs < 1) {
pr_err("alloc_netdev: Unable to allocate device with zero RX queues\n");
return NULL;
}
#endif
alloc_size = sizeof(struct net_device);
if (sizeof_priv) {
/* ensure 32-byte alignment of private area */
alloc_size = ALIGN(alloc_size, NETDEV_ALIGN);
alloc_size += sizeof_priv;
}
/* ensure 32-byte alignment of whole construct */
alloc_size += NETDEV_ALIGN - 1;
p = kzalloc(alloc_size, GFP_KERNEL);
if (!p) {
pr_err("alloc_netdev: Unable to allocate device\n");
return NULL;
}
dev = PTR_ALIGN(p, NETDEV_ALIGN);
dev->padded = (char *)dev - (char *)p;
dev->pcpu_refcnt = alloc_percpu(int);
if (!dev->pcpu_refcnt)
goto free_p;
if (dev_addr_init(dev))
goto free_pcpu;
dev_mc_init(dev);
dev_uc_init(dev);
dev_net_set(dev, &init_net);
dev->gso_max_size = GSO_MAX_SIZE;
dev->gso_max_segs = GSO_MAX_SEGS;
INIT_LIST_HEAD(&dev->napi_list);
INIT_LIST_HEAD(&dev->unreg_list);
INIT_LIST_HEAD(&dev->link_watch_list);
dev->priv_flags = <API key>;
setup(dev);
dev->num_tx_queues = txqs;
dev->real_num_tx_queues = txqs;
if (<API key>(dev))
goto free_all;
#ifdef CONFIG_RPS
dev->num_rx_queues = rxqs;
dev->real_num_rx_queues = rxqs;
if (<API key>(dev))
goto free_all;
#endif
strcpy(dev->name, name);
dev->group = INIT_NETDEV_GROUP;
return dev;
free_all:
free_netdev(dev);
return NULL;
free_pcpu:
free_percpu(dev->pcpu_refcnt);
kfree(dev->_tx);
#ifdef CONFIG_RPS
kfree(dev->_rx);
#endif
free_p:
kfree(p);
return NULL;
}
EXPORT_SYMBOL(alloc_netdev_mqs);
/**
* free_netdev - free network device
* @dev: device
*
* This function does the last stage of destroying an allocated device
* interface. The reference to the device object is released.
* If this is the last reference then it will be freed.
*/
void free_netdev(struct net_device *dev)
{
struct napi_struct *p, *n;
release_net(dev_net(dev));
kfree(dev->_tx);
#ifdef CONFIG_RPS
kfree(dev->_rx);
#endif
kfree(<API key>(dev->ingress_queue, 1));
/* Flush device addresses */
dev_addr_flush(dev);
<API key>(p, n, &dev->napi_list, dev_list)
netif_napi_del(p);
free_percpu(dev->pcpu_refcnt);
dev->pcpu_refcnt = NULL;
/* Compatibility with error handling in drivers */
if (dev->reg_state == <API key>) {
kfree((char *)dev - dev->padded);
return;
}
BUG_ON(dev->reg_state != NETREG_UNREGISTERED);
dev->reg_state = NETREG_RELEASED;
/* will free via device release */
put_device(&dev->dev);
}
EXPORT_SYMBOL(free_netdev);
/**
* synchronize_net - Synchronize with packet receive processing
*
* Wait for packets currently being received to be done.
* Does not block later packets from starting.
*/
void synchronize_net(void)
{
might_sleep();
if (rtnl_is_locked())
<API key>();
else
synchronize_rcu();
}
EXPORT_SYMBOL(synchronize_net);
/**
* <API key> - remove device from the kernel
* @dev: device
* @head: list
*
* This function shuts down a device interface and removes it
* from the kernel tables.
* If head not NULL, device is queued to be unregistered later.
*
* Callers must hold the rtnl semaphore. You may want
* unregister_netdev() instead of this.
*/
void <API key>(struct net_device *dev, struct list_head *head)
{
ASSERT_RTNL();
if (head) {
list_move_tail(&dev->unreg_list, head);
} else {
rollback_registered(dev);
/* Finish processing unregister after unlock */
net_set_todo(dev);
}
}
EXPORT_SYMBOL(<API key>);
/**
* <API key> - unregister many devices
* @head: list of devices
*/
void <API key>(struct list_head *head)
{
struct net_device *dev;
if (!list_empty(head)) {
<API key>(head);
list_for_each_entry(dev, head, unreg_list)
net_set_todo(dev);
}
}
EXPORT_SYMBOL(<API key>);
/**
* unregister_netdev - remove device from the kernel
* @dev: device
*
* This function shuts down a device interface and removes it
* from the kernel tables.
*
* This is just a wrapper for <API key> that takes
* the rtnl semaphore. In general you want to use this and not
* <API key>.
*/
void unregister_netdev(struct net_device *dev)
{
rtnl_lock();
<API key>(dev);
rtnl_unlock();
}
EXPORT_SYMBOL(unregister_netdev);
/**
* <API key> - move device to different nethost namespace
* @dev: device
* @net: network namespace
* @pat: If not NULL name pattern to try if the current device name
* is already taken in the destination network namespace.
*
* This function shuts down a device interface and moves it
* to a new network namespace. On success 0 is returned, on
* a failure a netagive errno code is returned.
*
* Callers must hold the rtnl semaphore.
*/
int <API key>(struct net_device *dev, struct net *net, const char *pat)
{
int err;
ASSERT_RTNL();
/* Don't allow namespace local devices to be moved. */
err = -EINVAL;
if (dev->features & NETIF_F_NETNS_LOCAL)
goto out;
/* Ensure the device has been registrered */
err = -EINVAL;
if (dev->reg_state != NETREG_REGISTERED)
goto out;
/* Get out if there is nothing todo */
err = 0;
if (net_eq(dev_net(dev), net))
goto out;
/* Pick the destination device name, and ensure
* we can use it in the destination network namespace.
*/
err = -EEXIST;
if (__dev_get_by_name(net, dev->name)) {
/* We get here if we can't use the current device name */
if (!pat)
goto out;
if (dev_get_valid_name(dev, pat) < 0)
goto out;
}
/*
* And now a mini version of register_netdevice <API key>.
*/
/* If device is running close it first. */
dev_close(dev);
/* And unlink it from device chain */
err = -ENODEV;
unlist_netdevice(dev);
synchronize_net();
/* Shutdown queueing discipline. */
dev_shutdown(dev);
/* Notify protocols, that we are about to destroy
this device. They should clean all the things.
Note that dev->reg_state stays at NETREG_REGISTERED.
This is wanted because this way 8021q and macvlan know
the device is just moving and can keep their slaves up.
*/
<API key>(NETDEV_UNREGISTER, dev);
<API key>(<API key>, dev);
rtmsg_ifinfo(RTM_DELLINK, dev, ~0U);
/*
* Flush the unicast and multicast chains
*/
dev_uc_flush(dev);
dev_mc_flush(dev);
/* Actually switch the network namespace */
dev_net_set(dev, net);
/* If there is an ifindex conflict assign a new one */
if (__dev_get_by_index(net, dev->ifindex)) {
int iflink = (dev->iflink == dev->ifindex);
dev->ifindex = dev_new_index(net);
if (iflink)
dev->iflink = dev->ifindex;
}
/* Fixup kobjects */
err = device_rename(&dev->dev, dev->name);
WARN_ON(err);
/* Add the device back in the hashes */
list_netdevice(dev);
/* Notify protocols, that a new device appeared. */
<API key>(NETDEV_REGISTER, dev);
/*
* Prevent userspace races by waiting until the network
* device is fully setup before sending notifications.
*/
rtmsg_ifinfo(RTM_NEWLINK, dev, ~0U);
synchronize_net();
err = 0;
out:
return err;
}
EXPORT_SYMBOL_GPL(<API key>);
static int dev_cpu_callback(struct notifier_block *nfb,
unsigned long action,
void *ocpu)
{
struct sk_buff **list_skb;
struct sk_buff *skb;
unsigned int cpu, oldcpu = (unsigned long)ocpu;
struct softnet_data *sd, *oldsd;
if (action != CPU_DEAD && action != CPU_DEAD_FROZEN)
return NOTIFY_OK;
local_irq_disable();
cpu = smp_processor_id();
sd = &per_cpu(softnet_data, cpu);
oldsd = &per_cpu(softnet_data, oldcpu);
/* Find end of our completion_queue. */
list_skb = &sd->completion_queue;
while (*list_skb)
list_skb = &(*list_skb)->next;
/* Append completion queue from offline CPU. */
*list_skb = oldsd->completion_queue;
oldsd->completion_queue = NULL;
/* Append output queue from offline CPU. */
if (oldsd->output_queue) {
*sd->output_queue_tailp = oldsd->output_queue;
sd->output_queue_tailp = oldsd->output_queue_tailp;
oldsd->output_queue = NULL;
oldsd->output_queue_tailp = &oldsd->output_queue;
}
/* Append NAPI poll list from offline CPU. */
if (!list_empty(&oldsd->poll_list)) {
list_splice_init(&oldsd->poll_list, &sd->poll_list);
<API key>(NET_RX_SOFTIRQ);
}
<API key>(NET_TX_SOFTIRQ);
local_irq_enable();
/* Process offline CPU's input_pkt_queue */
while ((skb = __skb_dequeue(&oldsd->process_queue))) {
netif_rx(skb);
<API key>(oldsd);
}
while ((skb = __skb_dequeue(&oldsd->input_pkt_queue))) {
netif_rx(skb);
<API key>(oldsd);
}
return NOTIFY_OK;
}
/**
* <API key> - increment feature set by one
* @all: current feature set
* @one: new feature set
* @mask: mask feature set
*
* Computes a new feature set after adding a device with feature set
* @one to the master device with current feature set @all. Will not
* enable anything that is off in @mask. Returns the new feature set.
*/
netdev_features_t <API key>(netdev_features_t all,
netdev_features_t one, netdev_features_t mask)
{
if (mask & NETIF_F_GEN_CSUM)
mask |= NETIF_F_ALL_CSUM;
mask |= <API key>;
all |= one & (NETIF_F_ONE_FOR_ALL|NETIF_F_ALL_CSUM) & mask;
all &= one | ~NETIF_F_ALL_FOR_ALL;
/* If one device supports hw checksumming, set for all. */
if (all & NETIF_F_GEN_CSUM)
all &= ~(NETIF_F_ALL_CSUM & ~NETIF_F_GEN_CSUM);
return all;
}
EXPORT_SYMBOL(<API key>);
static struct hlist_head *netdev_create_hash(void)
{
int i;
struct hlist_head *hash;
hash = kmalloc(sizeof(*hash) * NETDEV_HASHENTRIES, GFP_KERNEL);
if (hash != NULL)
for (i = 0; i < NETDEV_HASHENTRIES; i++)
INIT_HLIST_HEAD(&hash[i]);
return hash;
}
/* Initialize per network namespace state */
static int __net_init netdev_init(struct net *net)
{
if (net != &init_net)
INIT_LIST_HEAD(&net->dev_base_head);
net->dev_name_head = netdev_create_hash();
if (net->dev_name_head == NULL)
goto err_name;
net->dev_index_head = netdev_create_hash();
if (net->dev_index_head == NULL)
goto err_idx;
return 0;
err_idx:
kfree(net->dev_name_head);
err_name:
return -ENOMEM;
}
/**
* netdev_drivername - network driver for the device
* @dev: network device
*
* Determine network driver for device.
*/
const char *netdev_drivername(const struct net_device *dev)
{
const struct device_driver *driver;
const struct device *parent;
const char *empty = "";
parent = dev->dev.parent;
if (!parent)
return empty;
driver = parent->driver;
if (driver && driver->name)
return driver->name;
return empty;
}
int __netdev_printk(const char *level, const struct net_device *dev,
struct va_format *vaf)
{
int r;
if (dev && dev->dev.parent)
r = dev_printk(level, dev->dev.parent, "%s: %pV",
netdev_name(dev), vaf);
else if (dev)
r = printk("%s%s: %pV", level, netdev_name(dev), vaf);
else
r = printk("%s(NULL net_device): %pV", level, vaf);
return r;
}
EXPORT_SYMBOL(__netdev_printk);
int netdev_printk(const char *level, const struct net_device *dev,
const char *format, ...)
{
struct va_format vaf;
va_list args;
int r;
va_start(args, format);
vaf.fmt = format;
vaf.va = &args;
r = __netdev_printk(level, dev, &vaf);
va_end(args);
return r;
}
EXPORT_SYMBOL(netdev_printk);
#define <API key>(func, level) \
int func(const struct net_device *dev, const char *fmt, ...) \
{ \
int r; \
struct va_format vaf; \
va_list args; \
\
va_start(args, fmt); \
\
vaf.fmt = fmt; \
vaf.va = &args; \
\
r = __netdev_printk(level, dev, &vaf); \
va_end(args); \
\
return r; \
} \
EXPORT_SYMBOL(func);
<API key>(netdev_emerg, KERN_EMERG);
<API key>(netdev_alert, KERN_ALERT);
<API key>(netdev_crit, KERN_CRIT);
<API key>(netdev_err, KERN_ERR);
<API key>(netdev_warn, KERN_WARNING);
<API key>(netdev_notice, KERN_NOTICE);
<API key>(netdev_info, KERN_INFO);
static void __net_exit netdev_exit(struct net *net)
{
kfree(net->dev_name_head);
kfree(net->dev_index_head);
}
static struct pernet_operations __net_initdata netdev_net_ops = {
.init = netdev_init,
.exit = netdev_exit,
};
static void __net_exit default_device_exit(struct net *net)
{
struct net_device *dev, *aux;
/*
* Push all migratable network devices back to the
* initial network namespace
*/
rtnl_lock();
<API key>(net, dev, aux) {
int err;
char fb_name[IFNAMSIZ];
/* Ignore unmoveable devices (i.e. loopback) */
if (dev->features & NETIF_F_NETNS_LOCAL)
continue;
/* Leave virtual devices for the generic cleanup */
if (dev->rtnl_link_ops)
continue;
/* Push remaining network devices to init_net */
snprintf(fb_name, IFNAMSIZ, "dev%d", dev->ifindex);
err = <API key>(dev, &init_net, fb_name);
if (err) {
pr_emerg("%s: failed to move %s to init_net: %d\n",
__func__, dev->name, err);
BUG();
}
}
rtnl_unlock();
}
static void __net_exit <API key>(struct list_head *net_list)
{
/* At exit all network devices most be removed from a network
* namespace. Do this in the reverse order of registration.
* Do this across as many network namespaces as possible to
* improve batching efficiency.
*/
struct net_device *dev;
struct net *net;
LIST_HEAD(dev_kill_list);
rtnl_lock();
list_for_each_entry(net, net_list, exit_list) {
<API key>(net, dev) {
if (dev->rtnl_link_ops)
dev->rtnl_link_ops->dellink(dev, &dev_kill_list);
else
<API key>(dev, &dev_kill_list);
}
}
<API key>(&dev_kill_list);
list_del(&dev_kill_list);
rtnl_unlock();
}
static struct pernet_operations __net_initdata default_device_ops = {
.exit = default_device_exit,
.exit_batch = <API key>,
};
/*
* Initialize the DEV module. At boot time this walks the device list and
* unhooks any devices that fail to initialise (normally hardware not
* present) and leaves us with a valid list of present and active devices.
*
*/
/*
* This is called single threaded during boot, so no need
* to take the rtnl semaphore.
*/
static int __init net_dev_init(void)
{
int i, rc = -ENOMEM;
BUG_ON(!dev_boot_phase);
if (dev_proc_init())
goto out;
if (netdev_kobject_init())
goto out;
INIT_LIST_HEAD(&ptype_all);
for (i = 0; i < PTYPE_HASH_SIZE; i++)
INIT_LIST_HEAD(&ptype_base[i]);
if (<API key>(&netdev_net_ops))
goto out;
/*
* Initialise the packet receive queues.
*/
<API key>(i) {
struct softnet_data *sd = &per_cpu(softnet_data, i);
memset(sd, 0, sizeof(*sd));
skb_queue_head_init(&sd->input_pkt_queue);
skb_queue_head_init(&sd->process_queue);
sd->completion_queue = NULL;
INIT_LIST_HEAD(&sd->poll_list);
sd->output_queue = NULL;
sd->output_queue_tailp = &sd->output_queue;
#ifdef CONFIG_RPS
sd->csd.func = rps_trigger_softirq;
sd->csd.info = sd;
sd->csd.flags = 0;
sd->cpu = i;
#endif
sd->backlog.poll = process_backlog;
sd->backlog.weight = weight_p;
sd->backlog.gro_list = NULL;
sd->backlog.gro_count = 0;
}
dev_boot_phase = 0;
/* The loopback device is special if any other network devices
* is present in a network namespace the loopback device must
* be present. Since we now dynamically allocate and free the
* loopback device ensure this invariant is maintained by
* keeping the loopback device as the first device on the
* list of network devices. Ensuring the loopback devices
* is the first device that appears and the last network device
* that disappears.
*/
if (<API key>(&loopback_net_ops))
goto out;
if (<API key>(&default_device_ops))
goto out;
open_softirq(NET_TX_SOFTIRQ, net_tx_action);
open_softirq(NET_RX_SOFTIRQ, net_rx_action);
hotcpu_notifier(dev_cpu_callback, 0);
dst_init();
dev_mcast_init();
rc = 0;
out:
return rc;
}
subsys_initcall(net_dev_init);
static int __init initialize_hashrnd(void)
{
get_random_bytes(&hashrnd, sizeof(hashrnd));
return 0;
}
late_initcall_sync(initialize_hashrnd); |
// Open Computer and Software Inventory Next Generation
// This code is open source and may be copied and modified as long as the source
// code is always made freely available.
// OcsUtils.cpp: implementation of the OcsUtils.
#include "stdafx.h"
#include "OcsUtils.h"
#include <shlwapi.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CStringA <API key> GetAnsiFromUnicode(LPCTSTR a_wstrString)
{
static CStringA csAnsi;
CT2W pszA( a_wstrString);
// Avoid producing "(null)" string we converting
if ((a_wstrString != NULL) && (_tcslen( a_wstrString) > 0))
csAnsi = pszA;
else
csAnsi.Empty();
return csAnsi;
}
CStringW <API key> GetUnicodeFromAnsi(LPCSTR a_strString)
{
static CStringW csWide;
CA2W pszW( a_strString);
// Avoid producing "(null)" string we converting
if ((a_strString != NULL) && (strlen( a_strString) > 0))
csWide = pszW;
else
csWide.Empty();
return csWide;
}
CStringA <API key> GetUTF8FromUnicode( LPCTSTR a_wstrString)
{
static CStringA utf8;
CT2W pszA( a_wstrString, CP_UTF8);
// Avoid producing "(null)" string we converting
if ((a_wstrString != NULL) && (_tcslen( a_wstrString) > 0))
utf8 = pszA;
else
utf8.Empty();
return utf8;
}
CStringW <API key> GetUnicodeFromUTF8( LPCSTR a_strString)
{
static CStringW unicode;
CA2W pszW( a_strString, CP_UTF8);
// Avoid producing "(null)" string we converting
if ((a_strString != NULL) && (strlen( a_strString) > 0))
unicode = pszW;
else
unicode.Empty();
return unicode;
}
BOOL <API key> isValidUTF8( LPCSTR a_strString)
{
if (a_strString == NULL)
return TRUE;
if (MultiByteToWideChar( CP_UTF8, <API key>, a_strString, strlen( a_strString), NULL, 0) > 0)
// Return the required size for output buffer, so success, all character are UTF8 encoded
return TRUE;
if (GetLastError() == <API key>)
// Text include non UTF8 encoded characters
return FALSE;
// Function fails
return FALSE;
}
BOOL <API key> directoryCreate( LPCTSTR lpstrDir)
{
// Create it if not exists
if (fileExists( lpstrDir))
return TRUE;
switch (SHCreateDirectoryEx( NULL, lpstrDir, NULL))
{
case ERROR_SUCCESS: // Directory create successful
case ERROR_FILE_EXISTS: // Directory already exists
case <API key>:
return TRUE;
default:
return FALSE;
}
}
BOOL <API key> directoryDelete( LPCTSTR lpstrDir)
{
CFileFind cFinder;
CString csPath;
BOOL bWorking;
try
{
csPath.Format( _T( "%s\\*.*"), lpstrDir);
bWorking = cFinder.FindFile( csPath);
while (bWorking)
{
bWorking = cFinder.FindNextFile();
if (cFinder.IsDots())
continue;
if (cFinder.IsDirectory())
directoryDelete( cFinder.GetFilePath());
else
DeleteFile( cFinder.GetFilePath());
}
cFinder.Close();
return RemoveDirectory( lpstrDir);
}
catch (CException *pEx)
{
cFinder.Close();
pEx->Delete();
return FALSE;
}
}
BOOL <API key> fileExists( LPCTSTR lpstrFile)
{
return PathFileExists( lpstrFile);
}
__int64 <API key> GetDiskFree( LPCTSTR lpstrDrive)
{
DWORD dwSectPerClust,
dwBytesPerSect,
dwFreeClusters,
dwTotalClusters;
unsigned __int64 <API key>,
i64TotalBytes,
i64FreeBytes;
BOOL fResult;
typedef BOOL (WINAPI *P_GDFSE)(LPCTSTR, PULARGE_INTEGER,
PULARGE_INTEGER, PULARGE_INTEGER);
P_GDFSE pGetDiskFreeSpaceEx = NULL;
// Use GetDiskFreeSpaceEx if available; otherwise, use
// GetDiskFreeSpace.
// Note: Since GetDiskFreeSpaceEx is not in Windows 95 Retail, we
// dynamically link to it and only call it if it is present. We
// don't need to call LoadLibrary on KERNEL32.DLL because it is
// already loaded into every Win32 process's address space.
#ifndef _UNICODE
pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress(
GetModuleHandle( _T( "KERNEL32.DLL")),
"GetDiskFreeSpaceExA");
#else
pGetDiskFreeSpaceEx = (P_GDFSE)GetProcAddress(
GetModuleHandle( _T( "KERNEL32.DLL")),
"GetDiskFreeSpaceExW");
#endif
if (pGetDiskFreeSpaceEx)
{
fResult = pGetDiskFreeSpaceEx (lpstrDrive,
(PULARGE_INTEGER)&<API key>,
(PULARGE_INTEGER)&i64TotalBytes,
(PULARGE_INTEGER)&i64FreeBytes);
}
else
{
// Cannot load GetDiskFreeSpaceEx => use GetDiskFreeSpace
fResult = GetDiskFreeSpace (lpstrDrive,
&dwSectPerClust,
&dwBytesPerSect,
&dwFreeClusters,
&dwTotalClusters);
if (fResult)
{
// force 64-bit math
i64TotalBytes = (__int64)dwTotalClusters * dwSectPerClust *
dwBytesPerSect;
i64FreeBytes = (__int64)dwFreeClusters * dwSectPerClust *
dwBytesPerSect;
}
}
if (!fResult)
// Error
return -1;
return (__int64) (i64FreeBytes);
}
CByteArray <API key> * LoadFileToByteArray( LPCTSTR lpstrFilename)
{
CByteArray* res = NULL;
try
{
BYTE lu;
CFile myFile;
res = new CByteArray();
if( myFile.Open( lpstrFilename,CFile::modeRead|CFile::shareDenyNone))
{
while (myFile.Read(&lu,1))
res->Add( lu );
myFile.Close();
}
else
{
delete res;
res = NULL;
}
}
catch (CException* pEx)
{
pEx->Delete();
if (res != NULL)
delete res;
res = NULL;
}
return res;
}
BOOL <API key> <API key>( CByteArray* pByte, LPCTSTR lpstrFilename)
{
if (pByte==NULL)
return FALSE;
try
{
CFile myFile;
if (!myFile.Open( lpstrFilename, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite))
{
return FALSE;
}
myFile.Write( pByte->GetData(), pByte->GetSize());
myFile.Close();
}
catch (CException* pEx)
{
pEx->Delete();
return FALSE;
}
return TRUE;
}
BOOL <API key> LoadFileToText( CString &csBuffer, LPCTSTR lpstrFilename)
{
CStdioFile cFile;
CString csLine;
try
{
// Open the file for reading, using file specified encoding
if (!cFile.Open( lpstrFilename, CFile::modeRead|CFile::typeText|CFile::shareDenyNone))
return FALSE;
while (cFile.ReadString( csLine))
csBuffer += csLine;
cFile.Close();
}
catch( CException *pEx)
{
// Exception=> free exception, but continue
pEx->Delete();
cFile.Abort();
return FALSE;
}
return TRUE;
}
BOOL <API key> WriteTextToFile( LPCTSTR lpstrText, LPCTSTR lpstrFilename)
{
CStdioFile cFile;
try
{
// Open the file for writing using OS default encoding
if (!cFile.Open( lpstrFilename, CFile::modeCreate|CFile::modeWrite|CFile::typeText|CFile::shareDenyWrite))
return FALSE;
cFile.WriteString( lpstrText);
cFile.Close();
}
catch( CException *pEx)
{
// Exception=> free exception, but continue
pEx->Delete();
cFile.Abort();
return FALSE;
}
return TRUE;
}
BOOL <API key> WriteTextToUTF8File( LPCTSTR lpstrText, LPCTSTR lpstrFilename)
{
FILE *pFile = NULL;
try
{
if ((lpstrText == NULL) || (lpstrFilename == NULL))
return FALSE;
// Open the file for writing with UTF-8 encoding
if (_tfopen_s( &pFile, lpstrFilename, _T( "w,ccs=UTF-8")) != 0)
return FALSE;
size_t len = _tcslen( lpstrText) * sizeof( TCHAR);
if (fwrite( lpstrText, 1, len, pFile) != len)
{
fclose( pFile);
return FALSE;
}
fclose( pFile);
}
catch( CException *pEx)
{
// Exception=> free exception, but continue
pEx->Delete();
if (pFile)
fclose( pFile);
return FALSE;
}
return TRUE;
}
BOOL <API key> WriteVoidToFile( LPCVOID lpVoid, UINT uLength, LPCTSTR lpstrFilename)
{
CFile cFile;
try
{
if (!cFile.Open( lpstrFilename, CFile::modeCreate|CFile::modeWrite|CFile::shareDenyWrite))
return FALSE;
cFile.Write( lpVoid, uLength);
cFile.Close();
}
catch( CException *pEx)
{
// Exception=> free exception, but continue
pEx->Delete();
cFile.Abort();
return FALSE;
}
return TRUE;
}
BOOL <API key> fileDigest( LPCTSTR lpstrFile, CString &csDigest, LPCTSTR lpstrAlgo, BOOL bBase64)
{
CFile fRead;
BYTE pBuffer[1024],
pDigest[EVP_MAX_MD_SIZE];
ASSERT( lpstrFile);
ASSERT( lpstrAlgo);
// Compute digest on file
if( ! fRead.Open( lpstrFile, CFile::modeRead|CFile::shareDenyNone))
return FALSE;
// Initialize checksum computing
const EVP_MD *evpMD;
EVP_MD_CTX ctx;
UINT uLength;
<API key>();
// Set the algorithm
if (!(evpMD = <API key>( GetAnsiFromUnicode( lpstrAlgo))))
// Unsupported digest
return FALSE;
// Computing the checksum
EVP_DigestInit (&ctx, evpMD);
int nByteRead;
do
{
nByteRead = fRead.Read( pBuffer, 1024);
EVP_DigestUpdate (&ctx, pBuffer, nByteRead);
}
while(nByteRead>0);
EVP_DigestFinal( &ctx, pDigest, &uLength);
// Close file
fRead.Close();
// Now, encode result
if (bBase64)
// Digest is base64 encoded
return base64_encode( pDigest, uLength, csDigest);
// Digest is hexadecimal encoded
return hex_encode( pDigest, uLength, csDigest);
}
BOOL <API key> is_hex( LPCTSTR lpstrString)
{
DWORD_PTR dw;
TCHAR ch;
return (1 == _stscanf( lpstrString, TEXT("%x%c"), &dw, &ch));
}
BOOL <API key> hex_encode( LPBYTE pBuffer, UINT uLength, CString &csHex)
{
ASSERT( pBuffer);
csHex.Empty();
for (UINT uIndex = 0; uIndex<uLength; uIndex++)
{
csHex.AppendFormat( _T( "%02x"), pBuffer[uIndex]);
}
return TRUE;
}
LPBYTE <API key> hex_decode( CString csHex, UINT *uLength)
{
CString csBuffer;
INT_PTR i = 0;
BYTE x;
LPBYTE pBuffer;
*uLength = 0;
if ((pBuffer = (LPBYTE) malloc( sizeof(BYTE))) == NULL)
return NULL;
while(!csHex.IsEmpty() && (i<(csHex.GetLength()-2)))
{
csBuffer.Format( _T( "%c%c"), csHex.GetAt( i), csHex.GetAt( i+1));
_stscanf( csBuffer, _T( "%2X"), &x);
pBuffer[*uLength] = x;
*uLength++;
if ((pBuffer = (LPBYTE) realloc(pBuffer, (*uLength+1)*sizeof(BYTE))) == NULL)
{
*uLength = 0;
free( pBuffer);
return NULL;
}
i += 2;
}
pBuffer[*uLength] = 0;
return pBuffer;
}
BOOL <API key> is_base64( CString myString)
{
TCHAR ch;
BOOL bIsB64CharOnly = TRUE;
for (int i=0; i<myString.GetLength(); i++)
{
ch = myString.GetAt(i);
if (((ch<'A') || (ch>'Z')) && ((ch<'a') || (ch>'z')) && ((ch='=') && (i>=myString.GetLength()-2)))
bIsB64CharOnly = FALSE;
}
return ((myString.GetLength() % 4) == 0) && bIsB64CharOnly;
}
/* A helper function for base64 encoding */
BOOL <API key> base64_encode( LPBYTE pBuffer, UINT uLength, CString &csBase64)
{
LPBYTE pRet = NULL;
int nLengthB64;
ASSERT( pBuffer);
try
{
csBase64.Empty();
/* Base64 encoded data is 4/3 bigger than orignal data,
so allocated more than 4/3 of length.
However, we allocated the 2*size of input data for base64,
to ensure no memory overflow
*/
if ((pRet = (LPBYTE) malloc( 2*uLength)) == NULL)
return FALSE;
memset( pRet, 0, 2*uLength);
// Base64 encode data and returns the number of bytes written
if ((nLengthB64 = EVP_EncodeBlock( pRet, pBuffer, uLength)) < 0)
{
free( pRet);
return FALSE;
}
// Put base64 encoded result into string
for (int nIndex = 0; nIndex<nLengthB64; nIndex++)
{
csBase64.AppendFormat( _T( "%c"), pRet[nIndex]);
}
free( pRet);
return TRUE;
}
catch (CException *pEx)
{
pEx->Delete();
if (pRet != NULL)
free( pRet);
return FALSE;
}
}
LPBYTE <API key> base64_decode( LPCTSTR lpstrBase64, UINT *uLength)
{
LPBYTE pRet = NULL;
int nOutLength;
ASSERT( lpstrBase64);
try
{
/* The exact amount of decoded data is 3 * inlen / 4, minus 1
if the input ends with "=" and minus another 1 if the input
ends with "==".
However, we allocated the size of base64 data for decoded data,
to ensure no memory overflow
*/
// Ensure lpstrBase64 contains base64 encoded data
nOutLength = _tcslen( lpstrBase64);
if (nOutLength < 2)
// Buffer to small, not base 64 encoded
return NULL;
if (lpstrBase64[nOutLength-1] != '=')
// Not ending with =, not base64 encoded
return NULL;
if ((pRet = (LPBYTE) malloc( nOutLength)) == NULL)
return NULL;
memset( pRet, 0, nOutLength);
if ((nOutLength = EVP_DecodeBlock( pRet, (LPBYTE) LPCSTR( GetAnsiFromUnicode( lpstrBase64)), nOutLength)) < 0)
{
free( pRet);
return NULL;
}
*uLength = nOutLength;
return pRet;
}
catch (CException *pEx)
{
pEx->Delete();
if (pRet != NULL)
free( pRet);
return NULL;
}
}
BOOL <API key> is_printable( CString myString)
{
BOOL bPrintable = TRUE;
CStringA myAnsiString = GetAnsiFromUnicode( myString);
for (int i=0; i<myAnsiString.GetLength(); i++)
{
if (!isprint( myAnsiString.GetAt( i)))
bPrintable = FALSE;
}
return bPrintable;
} |
package com.frinika.sequencer.gui.menu;
import static com.frinika.localization.CurrentLocale.getMessage;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import com.frinika.sequencer.gui.ProjectFrame;
public class <API key> extends AbstractAction {
private static final long serialVersionUID = 1L;
private ProjectFrame project;
public <API key>(ProjectFrame project) {
super(getMessage("sequencer.project.<API key>"));
this.project = project;
}
public void actionPerformed(ActionEvent arg0) {
// project.
String prefix = "*";
this.project.getProjectContainer().getProjectLane().displayStructure(prefix,
System.out);
}
} |
/** \file iksolver/intern/IK_Solver.cpp
* \ingroup iksolver
*/
#include "../extern/IK_solver.h"
#include "IK_QJacobianSolver.h"
#include "IK_QSegment.h"
#include "IK_QTask.h"
#include <list>
using namespace std;
class IK_QSolver {
public:
IK_QSolver() : root(NULL) {
}
IK_QJacobianSolver solver;
IK_QSegment *root;
std::list<IK_QTask *> tasks;
};
// FIXME: locks still result in small "residual" changes to the locked axes...
static IK_QSegment *CreateSegment(int flag, bool translate)
{
int ndof = 0;
ndof += (flag & IK_XDOF) ? 1 : 0;
ndof += (flag & IK_YDOF) ? 1 : 0;
ndof += (flag & IK_ZDOF) ? 1 : 0;
IK_QSegment *seg;
if (ndof == 0)
return NULL;
else if (ndof == 1) {
int axis;
if (flag & IK_XDOF) axis = 0;
else if (flag & IK_YDOF) axis = 1;
else axis = 2;
if (translate)
seg = new <API key>(axis);
else
seg = new IK_QRevoluteSegment(axis);
}
else if (ndof == 2) {
int axis1, axis2;
if (flag & IK_XDOF) {
axis1 = 0;
axis2 = (flag & IK_YDOF) ? 1 : 2;
}
else {
axis1 = 1;
axis2 = 2;
}
if (translate)
seg = new <API key>(axis1, axis2);
else {
if (axis1 + axis2 == 2)
seg = new IK_QSwingSegment();
else
seg = new IK_QElbowSegment((axis1 == 0) ? 0 : 2);
}
}
else {
if (translate)
seg = new <API key>();
else
seg = new <API key>();
}
return seg;
}
IK_Segment *IK_CreateSegment(int flag)
{
IK_QSegment *rot = CreateSegment(flag, false);
IK_QSegment *trans = CreateSegment(flag >> 3, true);
IK_QSegment *seg;
if (rot == NULL && trans == NULL)
seg = new IK_QNullSegment();
else if (rot == NULL)
seg = trans;
else {
seg = rot;
// make it seem from the interface as if the rotation and translation
// segment are one
if (trans) {
seg->SetComposite(trans);
trans->SetParent(seg);
}
}
return seg;
}
void IK_FreeSegment(IK_Segment *seg)
{
IK_QSegment *qseg = (IK_QSegment *)seg;
if (qseg->Composite())
delete qseg->Composite();
delete qseg;
}
void IK_SetParent(IK_Segment *seg, IK_Segment *parent)
{
IK_QSegment *qseg = (IK_QSegment *)seg;
IK_QSegment *qparent = (IK_QSegment *)parent;
if (qparent && qparent->Composite())
qseg->SetParent(qparent->Composite());
else
qseg->SetParent(qparent);
}
void IK_SetTransform(IK_Segment *seg, float start[3], float rest[][3], float basis[][3], float length)
{
IK_QSegment *qseg = (IK_QSegment *)seg;
MT_Vector3 mstart(start);
// convert from blender column major to moto row major
MT_Matrix3x3 mbasis(basis[0][0], basis[1][0], basis[2][0],
basis[0][1], basis[1][1], basis[2][1],
basis[0][2], basis[1][2], basis[2][2]);
MT_Matrix3x3 mrest(rest[0][0], rest[1][0], rest[2][0],
rest[0][1], rest[1][1], rest[2][1],
rest[0][2], rest[1][2], rest[2][2]);
MT_Scalar mlength(length);
if (qseg->Composite()) {
MT_Vector3 cstart(0, 0, 0);
MT_Matrix3x3 cbasis;
cbasis.setIdentity();
qseg->SetTransform(mstart, mrest, mbasis, 0.0);
qseg->Composite()->SetTransform(cstart, cbasis, cbasis, mlength);
}
else
qseg->SetTransform(mstart, mrest, mbasis, mlength);
}
void IK_SetLimit(IK_Segment *seg, IK_SegmentAxis axis, float lmin, float lmax)
{
IK_QSegment *qseg = (IK_QSegment *)seg;
if (axis >= IK_TRANS_X) {
if (!qseg->Translational()) {
if (qseg->Composite() && qseg->Composite()->Translational())
qseg = qseg->Composite();
else
return;
}
if (axis == IK_TRANS_X) axis = IK_X;
else if (axis == IK_TRANS_Y) axis = IK_Y;
else axis = IK_Z;
}
qseg->SetLimit(axis, lmin, lmax);
}
void IK_SetStiffness(IK_Segment *seg, IK_SegmentAxis axis, float stiffness)
{
if (stiffness < 0.0f)
return;
if (stiffness > (1.0 - <API key>))
stiffness = (1.0 - <API key>);
IK_QSegment *qseg = (IK_QSegment *)seg;
MT_Scalar weight = 1.0f - stiffness;
if (axis >= IK_TRANS_X) {
if (!qseg->Translational()) {
if (qseg->Composite() && qseg->Composite()->Translational())
qseg = qseg->Composite();
else
return;
}
if (axis == IK_TRANS_X) axis = IK_X;
else if (axis == IK_TRANS_Y) axis = IK_Y;
else axis = IK_Z;
}
qseg->SetWeight(axis, weight);
}
void IK_GetBasisChange(IK_Segment *seg, float basis_change[][3])
{
IK_QSegment *qseg = (IK_QSegment *)seg;
if (qseg->Translational() && qseg->Composite())
qseg = qseg->Composite();
const MT_Matrix3x3& change = qseg->BasisChange();
// convert from moto row major to blender column major
basis_change[0][0] = (float)change[0][0];
basis_change[1][0] = (float)change[0][1];
basis_change[2][0] = (float)change[0][2];
basis_change[0][1] = (float)change[1][0];
basis_change[1][1] = (float)change[1][1];
basis_change[2][1] = (float)change[1][2];
basis_change[0][2] = (float)change[2][0];
basis_change[1][2] = (float)change[2][1];
basis_change[2][2] = (float)change[2][2];
}
void <API key>(IK_Segment *seg, float *translation_change)
{
IK_QSegment *qseg = (IK_QSegment *)seg;
if (!qseg->Translational() && qseg->Composite())
qseg = qseg->Composite();
const MT_Vector3& change = qseg->TranslationChange();
translation_change[0] = (float)change[0];
translation_change[1] = (float)change[1];
translation_change[2] = (float)change[2];
}
IK_Solver *IK_CreateSolver(IK_Segment *root)
{
if (root == NULL)
return NULL;
IK_QSolver *solver = new IK_QSolver();
solver->root = (IK_QSegment *)root;
return (IK_Solver *)solver;
}
void IK_FreeSolver(IK_Solver *solver)
{
if (solver == NULL)
return;
IK_QSolver *qsolver = (IK_QSolver *)solver;
std::list<IK_QTask *>& tasks = qsolver->tasks;
std::list<IK_QTask *>::iterator task;
for (task = tasks.begin(); task != tasks.end(); task++)
delete (*task);
delete qsolver;
}
void IK_SolverAddGoal(IK_Solver *solver, IK_Segment *tip, float goal[3], float weight)
{
if (solver == NULL || tip == NULL)
return;
IK_QSolver *qsolver = (IK_QSolver *)solver;
IK_QSegment *qtip = (IK_QSegment *)tip;
// in case of composite segment the second segment is the tip
if (qtip->Composite())
qtip = qtip->Composite();
MT_Vector3 pos(goal);
IK_QTask *ee = new IK_QPositionTask(true, qtip, pos);
ee->SetWeight(weight);
qsolver->tasks.push_back(ee);
}
void <API key>(IK_Solver *solver, IK_Segment *tip, float goal[][3], float weight)
{
if (solver == NULL || tip == NULL)
return;
IK_QSolver *qsolver = (IK_QSolver *)solver;
IK_QSegment *qtip = (IK_QSegment *)tip;
// in case of composite segment the second segment is the tip
if (qtip->Composite())
qtip = qtip->Composite();
// convert from blender column major to moto row major
MT_Matrix3x3 rot(goal[0][0], goal[1][0], goal[2][0],
goal[0][1], goal[1][1], goal[2][1],
goal[0][2], goal[1][2], goal[2][2]);
IK_QTask *orient = new IK_QOrientationTask(true, qtip, rot);
orient->SetWeight(weight);
qsolver->tasks.push_back(orient);
}
void <API key>(IK_Solver *solver, IK_Segment *tip, float goal[3], float polegoal[3], float poleangle, int getangle)
{
if (solver == NULL || tip == NULL)
return;
IK_QSolver *qsolver = (IK_QSolver *)solver;
IK_QSegment *qtip = (IK_QSegment *)tip;
// in case of composite segment the second segment is the tip
if (qtip->Composite())
qtip = qtip->Composite();
MT_Vector3 qgoal(goal);
MT_Vector3 qpolegoal(polegoal);
qsolver->solver.<API key>(
qtip, qgoal, qpolegoal, poleangle, getangle);
}
float <API key>(IK_Solver *solver)
{
if (solver == NULL)
return 0.0f;
IK_QSolver *qsolver = (IK_QSolver *)solver;
return qsolver->solver.GetPoleAngle();
}
#if 0
static void <API key>(IK_Solver *solver, IK_Segment *root, float goal[3], float weight)
{
if (solver == NULL || root == NULL)
return;
IK_QSolver *qsolver = (IK_QSolver *)solver;
IK_QSegment *qroot = (IK_QSegment *)root;
// convert from blender column major to moto row major
MT_Vector3 center(goal);
IK_QTask *com = new <API key>(true, qroot, center);
com->SetWeight(weight);
qsolver->tasks.push_back(com);
}
#endif
int IK_Solve(IK_Solver *solver, float tolerance, int max_iterations)
{
if (solver == NULL)
return 0;
IK_QSolver *qsolver = (IK_QSolver *)solver;
IK_QSegment *root = qsolver->root;
IK_QJacobianSolver& jacobian = qsolver->solver;
std::list<IK_QTask *>& tasks = qsolver->tasks;
MT_Scalar tol = tolerance;
if (!jacobian.Setup(root, tasks))
return 0;
bool result = jacobian.Solve(root, tasks, tol, max_iterations);
return ((result) ? 1 : 0);
} |
#include <linux/module.h>
#include <linux/reboot.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <linux/slab.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_cmnd.h>
#include "3w-sas.h"
/* Globals */
#define TW_DRIVER_VERSION "3.26.02.000"
static DEFINE_MUTEX(twl_chrdev_mutex);
static TW_Device_Extension *<API key>[TW_MAX_SLOT];
static unsigned int <API key>;
static int twl_major = -1;
extern struct timezone sys_tz;
/* Module parameters */
MODULE_AUTHOR ("LSI");
MODULE_DESCRIPTION ("LSI 3ware SAS/SATA-RAID Linux Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(TW_DRIVER_VERSION);
static int use_msi;
module_param(use_msi, int, S_IRUGO);
MODULE_PARM_DESC(use_msi, "Use Message Signaled Interrupts. Default: 0");
/* Function prototypes */
static int <API key>(TW_Device_Extension *tw_dev, int ioctl_reset);
/* Functions */
/* This function returns AENs through sysfs */
static ssize_t twl_sysfs_aen_read(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *outbuf, loff_t offset, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct Scsi_Host *shost = class_to_shost(dev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)shost->hostdata;
unsigned long flags = 0;
ssize_t ret;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
spin_lock_irqsave(tw_dev->host->host_lock, flags);
ret = <API key>(outbuf, count, &offset, tw_dev->event_queue[0], sizeof(TW_Event) * TW_Q_LENGTH);
<API key>(tw_dev->host->host_lock, flags);
return ret;
} /* End twl_sysfs_aen_read() */
/* aen_read sysfs attribute initializer */
static struct bin_attribute <API key> = {
.attr = {
.name = "3ware_aen_read",
.mode = S_IRUSR,
},
.size = 0,
.read = twl_sysfs_aen_read
};
/* This function returns driver compatibility info through sysfs */
static ssize_t <API key>(struct file *filp, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *outbuf, loff_t offset, size_t count)
{
struct device *dev = container_of(kobj, struct device, kobj);
struct Scsi_Host *shost = class_to_shost(dev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)shost->hostdata;
unsigned long flags = 0;
ssize_t ret;
if (!capable(CAP_SYS_ADMIN))
return -EACCES;
spin_lock_irqsave(tw_dev->host->host_lock, flags);
ret = <API key>(outbuf, count, &offset, &tw_dev->tw_compat_info, sizeof(<API key>));
<API key>(tw_dev->host->host_lock, flags);
return ret;
} /* End <API key>() */
/* compat_info sysfs attribute initializer */
static struct bin_attribute <API key> = {
.attr = {
.name = "3ware_compat_info",
.mode = S_IRUSR,
},
.size = 0,
.read = <API key>
};
/* Show some statistics about the card */
static ssize_t twl_show_stats(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct Scsi_Host *host = class_to_shost(dev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
unsigned long flags = 0;
ssize_t len;
spin_lock_irqsave(tw_dev->host->host_lock, flags);
len = snprintf(buf, PAGE_SIZE, "3w-sas Driver version: %s\n"
"Current commands posted: %4d\n"
"Max commands posted: %4d\n"
"Last sgl length: %4d\n"
"Max sgl length: %4d\n"
"Last sector count: %4d\n"
"Max sector count: %4d\n"
"SCSI Host Resets: %4d\n"
"AEN's: %4d\n",
TW_DRIVER_VERSION,
tw_dev-><API key>,
tw_dev-><API key>,
tw_dev->sgl_entries,
tw_dev->max_sgl_entries,
tw_dev->sector_count,
tw_dev->max_sector_count,
tw_dev->num_resets,
tw_dev->aen_count);
<API key>(tw_dev->host->host_lock, flags);
return len;
} /* End twl_show_stats() */
/* This function will set a devices queue depth */
static int <API key>(struct scsi_device *sdev, int queue_depth,
int reason)
{
if (reason != SCSI_QDEPTH_DEFAULT)
return -EOPNOTSUPP;
if (queue_depth > TW_Q_LENGTH-2)
queue_depth = TW_Q_LENGTH-2;
<API key>(sdev, MSG_ORDERED_TAG, queue_depth);
return queue_depth;
} /* End <API key>() */
/* stats sysfs attribute initializer */
static struct device_attribute twl_host_stats_attr = {
.attr = {
.name = "3ware_stats",
.mode = S_IRUGO,
},
.show = twl_show_stats
};
/* Host attributes initializer */
static struct device_attribute *twl_host_attrs[] = {
&twl_host_stats_attr,
NULL,
};
/* This function will look up an AEN severity string */
static char *<API key>(unsigned char severity_code)
{
char *retval = NULL;
if ((severity_code < (unsigned char) <API key>) ||
(severity_code > (unsigned char) <API key>))
goto out;
retval = <API key>[severity_code];
out:
return retval;
} /* End <API key>() */
/* This function will queue an event */
static void twl_aen_queue_event(TW_Device_Extension *tw_dev, <API key> *header)
{
u32 local_time;
struct timeval time;
TW_Event *event;
unsigned short aen;
char host[16];
char *error_str;
tw_dev->aen_count++;
/* Fill out event info */
event = tw_dev->event_queue[tw_dev->error_index];
host[0] = '\0';
if (tw_dev->host)
sprintf(host, " scsi%d:", tw_dev->host->host_no);
aen = le16_to_cpu(header->status_block.error);
memset(event, 0, sizeof(TW_Event));
event->severity = TW_SEV_OUT(header->status_block.severity__reserved);
do_gettimeofday(&time);
local_time = (u32)(time.tv_sec - (sys_tz.tz_minuteswest * 60));
event->time_stamp_sec = local_time;
event->aen_code = aen;
event->retrieved = <API key>;
event->sequence_id = tw_dev->error_sequence_id;
tw_dev->error_sequence_id++;
/* Check for embedded error string */
error_str = &(header->err_specific_desc[strlen(header->err_specific_desc)+1]);
header->err_specific_desc[sizeof(header->err_specific_desc) - 1] = '\0';
event->parameter_len = strlen(header->err_specific_desc);
memcpy(event->parameter_data, header->err_specific_desc, event->parameter_len + 1 + strlen(error_str));
if (event->severity != <API key>)
printk(KERN_WARNING "3w-sas:%s AEN: %s (0x%02X:0x%04X): %s:%s.\n",
host,
<API key>(TW_SEV_OUT(header->status_block.severity__reserved)),
<API key>, aen, error_str,
header->err_specific_desc);
else
tw_dev->aen_count
tw_dev->error_index = (tw_dev->error_index + 1 ) % TW_Q_LENGTH;
} /* End twl_aen_queue_event() */
/* This function will attempt to post a command packet to the board */
static int <API key>(TW_Device_Extension *tw_dev, int request_id)
{
dma_addr_t command_que_value;
command_que_value = tw_dev->command_packet_phys[request_id];
command_que_value += TW_COMMAND_OFFSET;
/* First write upper 4 bytes */
writel((u32)((u64)command_que_value >> 32), TWL_HIBQPH_REG_ADDR(tw_dev));
/* Then the lower 4 bytes */
writel((u32)(command_que_value | TWL_PULL_MODE), TWL_HIBQPL_REG_ADDR(tw_dev));
tw_dev->state[request_id] = TW_S_POSTED;
tw_dev-><API key>++;
if (tw_dev-><API key> > tw_dev-><API key>)
tw_dev-><API key> = tw_dev-><API key>;
return 0;
} /* End <API key>() */
/* This function will perform a pci-dma mapping for a scatter gather list */
static int <API key>(TW_Device_Extension *tw_dev, int request_id)
{
int use_sg;
struct scsi_cmnd *cmd = tw_dev->srb[request_id];
use_sg = scsi_dma_map(cmd);
if (!use_sg)
return 0;
else if (use_sg < 0) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1, "Failed to map scatter gather list");
return 0;
}
cmd->SCp.phase = TW_PHASE_SGLIST;
cmd->SCp.have_data_in = use_sg;
return use_sg;
} /* End <API key>() */
/* This function hands scsi cdb's to the firmware */
static int <API key>(TW_Device_Extension *tw_dev, int request_id, char *cdb, int use_sg, TW_SG_Entry_ISO *sglistarg)
{
TW_Command_Full *full_command_packet;
TW_Command_Apache *command_packet;
int i, sg_count;
struct scsi_cmnd *srb = NULL;
struct scatterlist *sglist = NULL, *sg;
int retval = 1;
if (tw_dev->srb[request_id]) {
srb = tw_dev->srb[request_id];
if (scsi_sglist(srb))
sglist = scsi_sglist(srb);
}
/* Initialize command packet */
full_command_packet = tw_dev->command_packet_virt[request_id];
full_command_packet->header.header_desc.size_header = 128;
full_command_packet->header.status_block.error = 0;
full_command_packet->header.status_block.severity__reserved = 0;
command_packet = &full_command_packet->command.newcommand;
command_packet->status = 0;
command_packet->opcode__reserved = TW_OPRES_IN(0, TW_OP_EXECUTE_SCSI);
/* We forced 16 byte cdb use earlier */
if (!cdb)
memcpy(command_packet->cdb, srb->cmnd, TW_MAX_CDB_LEN);
else
memcpy(command_packet->cdb, cdb, TW_MAX_CDB_LEN);
if (srb) {
command_packet->unit = srb->device->id;
command_packet->request_id__lunl =
cpu_to_le16(TW_REQ_LUN_IN(srb->device->lun, request_id));
} else {
command_packet->request_id__lunl =
cpu_to_le16(TW_REQ_LUN_IN(0, request_id));
command_packet->unit = 0;
}
command_packet->sgl_offset = 16;
if (!sglistarg) {
/* Map sglist from scsi layer to cmd packet */
if (scsi_sg_count(srb)) {
sg_count = <API key>(tw_dev, request_id);
if (sg_count == 0)
goto out;
scsi_for_each_sg(srb, sg, sg_count, i) {
command_packet->sg_list[i].address = TW_CPU_TO_SGL(sg_dma_address(sg));
command_packet->sg_list[i].length = TW_CPU_TO_SGL(sg_dma_len(sg));
}
command_packet->sgl_entries__lunh = cpu_to_le16(TW_REQ_LUN_IN((srb->device->lun >> 4), scsi_sg_count(tw_dev->srb[request_id])));
}
} else {
/* Internal cdb post */
for (i = 0; i < use_sg; i++) {
command_packet->sg_list[i].address = TW_CPU_TO_SGL(sglistarg[i].address);
command_packet->sg_list[i].length = TW_CPU_TO_SGL(sglistarg[i].length);
}
command_packet->sgl_entries__lunh = cpu_to_le16(TW_REQ_LUN_IN(0, use_sg));
}
/* Update some stats */
if (srb) {
tw_dev->sector_count = scsi_bufflen(srb) / 512;
if (tw_dev->sector_count > tw_dev->max_sector_count)
tw_dev->max_sector_count = tw_dev->sector_count;
tw_dev->sgl_entries = scsi_sg_count(srb);
if (tw_dev->sgl_entries > tw_dev->max_sgl_entries)
tw_dev->max_sgl_entries = tw_dev->sgl_entries;
}
/* Now post the command to the board */
retval = <API key>(tw_dev, request_id);
out:
return retval;
} /* End <API key>() */
/* This function will read the aen queue from the isr */
static int twl_aen_read_queue(TW_Device_Extension *tw_dev, int request_id)
{
char cdb[TW_MAX_CDB_LEN];
TW_SG_Entry_ISO sglist[1];
TW_Command_Full *full_command_packet;
int retval = 1;
full_command_packet = tw_dev->command_packet_virt[request_id];
memset(full_command_packet, 0, sizeof(TW_Command_Full));
/* Initialize cdb */
memset(&cdb, 0, TW_MAX_CDB_LEN);
cdb[0] = REQUEST_SENSE; /* opcode */
cdb[4] = <API key>; /* allocation length */
/* Initialize sglist */
memset(&sglist, 0, sizeof(TW_SG_Entry_ISO));
sglist[0].length = TW_SECTOR_SIZE;
sglist[0].address = tw_dev->generic_buffer_phys[request_id];
/* Mark internal command */
tw_dev->srb[request_id] = NULL;
/* Now post the command packet */
if (<API key>(tw_dev, request_id, cdb, 1, sglist)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x2, "Post failed while reading AEN queue");
goto out;
}
retval = 0;
out:
return retval;
} /* End twl_aen_read_queue() */
/* This function will sync firmware time with the host time */
static void twl_aen_sync_time(TW_Device_Extension *tw_dev, int request_id)
{
u32 schedulertime;
struct timeval utc;
TW_Command_Full *full_command_packet;
TW_Command *command_packet;
TW_Param_Apache *param;
u32 local_time;
/* Fill out the command packet */
full_command_packet = tw_dev->command_packet_virt[request_id];
memset(full_command_packet, 0, sizeof(TW_Command_Full));
command_packet = &full_command_packet->command.oldcommand;
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_SET_PARAM);
command_packet->request_id = request_id;
command_packet->byte8_offset.param.sgl[0].address = TW_CPU_TO_SGL(tw_dev->generic_buffer_phys[request_id]);
command_packet->byte8_offset.param.sgl[0].length = TW_CPU_TO_SGL(TW_SECTOR_SIZE);
command_packet->size = TW_COMMAND_SIZE;
command_packet->byte6_offset.parameter_count = cpu_to_le16(1);
/* Setup the param */
param = (TW_Param_Apache *)tw_dev->generic_buffer_virt[request_id];
memset(param, 0, TW_SECTOR_SIZE);
param->table_id = cpu_to_le16(TW_TIMEKEEP_TABLE | 0x8000); /* Controller time keep table */
param->parameter_id = cpu_to_le16(0x3); /* SchedulerTime */
param-><API key> = cpu_to_le16(4);
/* Convert system time in UTC to local time seconds since last
Sunday 12:00AM */
do_gettimeofday(&utc);
local_time = (u32)(utc.tv_sec - (sys_tz.tz_minuteswest * 60));
schedulertime = local_time - (3 * 86400);
schedulertime = cpu_to_le32(schedulertime % 604800);
memcpy(param->data, &schedulertime, sizeof(u32));
/* Mark internal command */
tw_dev->srb[request_id] = NULL;
/* Now post the command */
<API key>(tw_dev, request_id);
} /* End twl_aen_sync_time() */
/* This function will assign an available request id */
static void twl_get_request_id(TW_Device_Extension *tw_dev, int *request_id)
{
*request_id = tw_dev->free_queue[tw_dev->free_head];
tw_dev->free_head = (tw_dev->free_head + 1) % TW_Q_LENGTH;
tw_dev->state[*request_id] = TW_S_STARTED;
} /* End twl_get_request_id() */
/* This function will free a request id */
static void twl_free_request_id(TW_Device_Extension *tw_dev, int request_id)
{
tw_dev->free_queue[tw_dev->free_tail] = request_id;
tw_dev->state[request_id] = TW_S_FINISHED;
tw_dev->free_tail = (tw_dev->free_tail + 1) % TW_Q_LENGTH;
} /* End twl_free_request_id() */
/* This function will complete an aen request from the isr */
static int twl_aen_complete(TW_Device_Extension *tw_dev, int request_id)
{
TW_Command_Full *full_command_packet;
TW_Command *command_packet;
<API key> *header;
unsigned short aen;
int retval = 1;
header = (<API key> *)tw_dev->generic_buffer_virt[request_id];
tw_dev-><API key>
aen = le16_to_cpu(header->status_block.error);
full_command_packet = tw_dev->command_packet_virt[request_id];
command_packet = &full_command_packet->command.oldcommand;
/* First check for internal completion of set param for time sync */
if (TW_OP_OUT(command_packet->opcode__sgloffset) == TW_OP_SET_PARAM) {
/* Keep reading the queue in case there are more aen's */
if (twl_aen_read_queue(tw_dev, request_id))
goto out2;
else {
retval = 0;
goto out;
}
}
switch (aen) {
case TW_AEN_QUEUE_EMPTY:
/* Quit reading the queue if this is the last one */
break;
case <API key>:
twl_aen_sync_time(tw_dev, request_id);
retval = 0;
goto out;
default:
twl_aen_queue_event(tw_dev, header);
/* If there are more aen's, keep reading the queue */
if (twl_aen_read_queue(tw_dev, request_id))
goto out2;
else {
retval = 0;
goto out;
}
}
retval = 0;
out2:
tw_dev->state[request_id] = TW_S_COMPLETED;
twl_free_request_id(tw_dev, request_id);
clear_bit(<API key>, &tw_dev->flags);
out:
return retval;
} /* End twl_aen_complete() */
/* This function will poll for a response */
static int twl_poll_response(TW_Device_Extension *tw_dev, int request_id, int seconds)
{
unsigned long before;
dma_addr_t mfa;
u32 regh, regl;
u32 response;
int retval = 1;
int found = 0;
before = jiffies;
while (!found) {
if (sizeof(dma_addr_t) > 4) {
regh = readl(TWL_HOBQPH_REG_ADDR(tw_dev));
regl = readl(TWL_HOBQPL_REG_ADDR(tw_dev));
mfa = ((u64)regh << 32) | regl;
} else
mfa = readl(TWL_HOBQPL_REG_ADDR(tw_dev));
response = (u32)mfa;
if (TW_RESID_OUT(response) == request_id)
found = 1;
if (time_after(jiffies, before + HZ * seconds))
goto out;
msleep(50);
}
retval = 0;
out:
return retval;
} /* End twl_poll_response() */
/* This function will drain the aen queue */
static int twl_aen_drain_queue(TW_Device_Extension *tw_dev, int no_check_reset)
{
int request_id = 0;
char cdb[TW_MAX_CDB_LEN];
TW_SG_Entry_ISO sglist[1];
int finished = 0, count = 0;
TW_Command_Full *full_command_packet;
<API key> *header;
unsigned short aen;
int first_reset = 0, queue = 0, retval = 1;
if (no_check_reset)
first_reset = 0;
else
first_reset = 1;
full_command_packet = tw_dev->command_packet_virt[request_id];
memset(full_command_packet, 0, sizeof(TW_Command_Full));
/* Initialize cdb */
memset(&cdb, 0, TW_MAX_CDB_LEN);
cdb[0] = REQUEST_SENSE; /* opcode */
cdb[4] = <API key>; /* allocation length */
/* Initialize sglist */
memset(&sglist, 0, sizeof(TW_SG_Entry_ISO));
sglist[0].length = TW_SECTOR_SIZE;
sglist[0].address = tw_dev->generic_buffer_phys[request_id];
/* Mark internal command */
tw_dev->srb[request_id] = NULL;
do {
/* Send command to the board */
if (<API key>(tw_dev, request_id, cdb, 1, sglist)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x3, "Error posting request sense");
goto out;
}
/* Now poll for completion */
if (twl_poll_response(tw_dev, request_id, 30)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x4, "No valid response while draining AEN queue");
tw_dev-><API key>
goto out;
}
tw_dev-><API key>
header = (<API key> *)tw_dev->generic_buffer_virt[request_id];
aen = le16_to_cpu(header->status_block.error);
queue = 0;
count++;
switch (aen) {
case TW_AEN_QUEUE_EMPTY:
if (first_reset != 1)
goto out;
else
finished = 1;
break;
case TW_AEN_SOFT_RESET:
if (first_reset == 0)
first_reset = 1;
else
queue = 1;
break;
case <API key>:
break;
default:
queue = 1;
}
/* Now queue an event info */
if (queue)
twl_aen_queue_event(tw_dev, header);
} while ((finished == 0) && (count < TW_MAX_AEN_DRAIN));
if (count == TW_MAX_AEN_DRAIN)
goto out;
retval = 0;
out:
tw_dev->state[request_id] = TW_S_INITIAL;
return retval;
} /* End twl_aen_drain_queue() */
/* This function will allocate memory and check if it is correctly aligned */
static int twl_allocate_memory(TW_Device_Extension *tw_dev, int size, int which)
{
int i;
dma_addr_t dma_handle;
unsigned long *cpu_addr;
int retval = 1;
cpu_addr = <API key>(tw_dev->tw_pci_dev, size*TW_Q_LENGTH, &dma_handle);
if (!cpu_addr) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x5, "Memory allocation failed");
goto out;
}
memset(cpu_addr, 0, size*TW_Q_LENGTH);
for (i = 0; i < TW_Q_LENGTH; i++) {
switch(which) {
case 0:
tw_dev->command_packet_phys[i] = dma_handle+(i*size);
tw_dev->command_packet_virt[i] = (TW_Command_Full *)((unsigned char *)cpu_addr + (i*size));
break;
case 1:
tw_dev->generic_buffer_phys[i] = dma_handle+(i*size);
tw_dev->generic_buffer_virt[i] = (unsigned long *)((unsigned char *)cpu_addr + (i*size));
break;
case 2:
tw_dev->sense_buffer_phys[i] = dma_handle+(i*size);
tw_dev->sense_buffer_virt[i] = (<API key> *)((unsigned char *)cpu_addr + (i*size));
break;
}
}
retval = 0;
out:
return retval;
} /* End twl_allocate_memory() */
/* This function will load the request id and various sgls for ioctls */
static void twl_load_sgl(TW_Device_Extension *tw_dev, TW_Command_Full *full_command_packet, int request_id, dma_addr_t dma_handle, int length)
{
TW_Command *oldcommand;
TW_Command_Apache *newcommand;
TW_SG_Entry_ISO *sgl;
unsigned int pae = 0;
if ((sizeof(long) < 8) && (sizeof(dma_addr_t) > 4))
pae = 1;
if (TW_OP_OUT(full_command_packet->command.newcommand.opcode__reserved) == TW_OP_EXECUTE_SCSI) {
newcommand = &full_command_packet->command.newcommand;
newcommand->request_id__lunl =
cpu_to_le16(TW_REQ_LUN_IN(TW_LUN_OUT(newcommand->request_id__lunl), request_id));
if (length) {
newcommand->sg_list[0].address = TW_CPU_TO_SGL(dma_handle + sizeof(TW_Ioctl_Buf_Apache) - 1);
newcommand->sg_list[0].length = TW_CPU_TO_SGL(length);
}
newcommand->sgl_entries__lunh =
cpu_to_le16(TW_REQ_LUN_IN(TW_LUN_OUT(newcommand->sgl_entries__lunh), length ? 1 : 0));
} else {
oldcommand = &full_command_packet->command.oldcommand;
oldcommand->request_id = request_id;
if (TW_SGL_OUT(oldcommand->opcode__sgloffset)) {
/* Load the sg list */
sgl = (TW_SG_Entry_ISO *)((u32 *)oldcommand+oldcommand->size - (sizeof(TW_SG_Entry_ISO)/4) + pae + (sizeof(dma_addr_t) > 4 ? 1 : 0));
sgl->address = TW_CPU_TO_SGL(dma_handle + sizeof(TW_Ioctl_Buf_Apache) - 1);
sgl->length = TW_CPU_TO_SGL(length);
oldcommand->size += pae;
oldcommand->size += sizeof(dma_addr_t) > 4 ? 1 : 0;
}
}
} /* End twl_load_sgl() */
/* This function handles ioctl for the character device
This interface is used by smartmontools open source software */
static long twl_chrdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
long timeout;
unsigned long *cpu_addr, <API key> = 0, flags = 0;
dma_addr_t dma_handle;
int request_id = 0;
<API key> driver_command;
struct inode *inode = file->f_dentry->d_inode;
TW_Ioctl_Buf_Apache *tw_ioctl;
TW_Command_Full *full_command_packet;
TW_Device_Extension *tw_dev = <API key>[iminor(inode)];
int retval = -EFAULT;
void __user *argp = (void __user *)arg;
mutex_lock(&twl_chrdev_mutex);
/* Only let one of these through at a time */
if (<API key>(&tw_dev->ioctl_lock)) {
retval = -EINTR;
goto out;
}
/* First copy down the driver command */
if (copy_from_user(&driver_command, argp, sizeof(<API key>)))
goto out2;
/* Check data buffer size */
if (driver_command.buffer_length > TW_MAX_SECTORS * 2048) {
retval = -EINVAL;
goto out2;
}
/* Hardware can only do multiple of 512 byte transfers */
<API key> = (driver_command.buffer_length + 511) & ~511;
/* Now allocate ioctl buf memory */
cpu_addr = dma_alloc_coherent(&tw_dev->tw_pci_dev->dev, <API key>+sizeof(TW_Ioctl_Buf_Apache) - 1, &dma_handle, GFP_KERNEL);
if (!cpu_addr) {
retval = -ENOMEM;
goto out2;
}
tw_ioctl = (TW_Ioctl_Buf_Apache *)cpu_addr;
/* Now copy down the entire ioctl */
if (copy_from_user(tw_ioctl, argp, driver_command.buffer_length + sizeof(TW_Ioctl_Buf_Apache) - 1))
goto out3;
/* See which ioctl we are doing */
switch (cmd) {
case <API key>:
spin_lock_irqsave(tw_dev->host->host_lock, flags);
twl_get_request_id(tw_dev, &request_id);
/* Flag internal command */
tw_dev->srb[request_id] = NULL;
/* Flag chrdev ioctl */
tw_dev->chrdev_request_id = request_id;
full_command_packet = (TW_Command_Full *)&tw_ioctl->firmware_command;
/* Load request id and sglist for both command types */
twl_load_sgl(tw_dev, full_command_packet, request_id, dma_handle, <API key>);
memcpy(tw_dev->command_packet_virt[request_id], &(tw_ioctl->firmware_command), sizeof(TW_Command_Full));
/* Now post the command packet to the controller */
<API key>(tw_dev, request_id);
<API key>(tw_dev->host->host_lock, flags);
timeout = <API key>*HZ;
/* Now wait for command to complete */
timeout = wait_event_timeout(tw_dev->ioctl_wqueue, tw_dev->chrdev_request_id == <API key>, timeout);
/* We timed out, and didn't get an interrupt */
if (tw_dev->chrdev_request_id != <API key>) {
/* Now we need to reset the board */
printk(KERN_WARNING "3w-sas: scsi%d: WARNING: (0x%02X:0x%04X): Character ioctl (0x%x) timed out, resetting card.\n",
tw_dev->host->host_no, TW_DRIVER, 0x6,
cmd);
retval = -EIO;
<API key>(tw_dev, 1);
goto out3;
}
/* Now copy in the command packet response */
memcpy(&(tw_ioctl->firmware_command), tw_dev->command_packet_virt[request_id], sizeof(TW_Command_Full));
/* Now complete the io */
spin_lock_irqsave(tw_dev->host->host_lock, flags);
tw_dev-><API key>
tw_dev->state[request_id] = TW_S_COMPLETED;
twl_free_request_id(tw_dev, request_id);
<API key>(tw_dev->host->host_lock, flags);
break;
default:
retval = -ENOTTY;
goto out3;
}
/* Now copy the entire response to userspace */
if (copy_to_user(argp, tw_ioctl, sizeof(TW_Ioctl_Buf_Apache) + driver_command.buffer_length - 1) == 0)
retval = 0;
out3:
/* Now free ioctl buf memory */
dma_free_coherent(&tw_dev->tw_pci_dev->dev, <API key>+sizeof(TW_Ioctl_Buf_Apache) - 1, cpu_addr, dma_handle);
out2:
mutex_unlock(&tw_dev->ioctl_lock);
out:
mutex_unlock(&twl_chrdev_mutex);
return retval;
} /* End twl_chrdev_ioctl() */
/* This function handles open for the character device */
static int twl_chrdev_open(struct inode *inode, struct file *file)
{
unsigned int minor_number;
int retval = -ENODEV;
if (!capable(CAP_SYS_ADMIN)) {
retval = -EACCES;
goto out;
}
minor_number = iminor(inode);
if (minor_number >= <API key>)
goto out;
retval = 0;
out:
return retval;
} /* End twl_chrdev_open() */
/* File operations struct for character device */
static const struct file_operations twl_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = twl_chrdev_ioctl,
.open = twl_chrdev_open,
.release = NULL,
.llseek = noop_llseek,
};
/* This function passes sense data from firmware to scsi layer */
static int twl_fill_sense(TW_Device_Extension *tw_dev, int i, int request_id, int copy_sense, int print_host)
{
<API key> *header;
TW_Command_Full *full_command_packet;
unsigned short error;
char *error_str;
int retval = 1;
header = tw_dev->sense_buffer_virt[i];
full_command_packet = tw_dev->command_packet_virt[request_id];
/* Get embedded firmware error string */
error_str = &(header->err_specific_desc[strlen(header->err_specific_desc) + 1]);
/* Don't print error for Logical unit not supported during rollcall */
error = le16_to_cpu(header->status_block.error);
if ((error != <API key>) && (error != <API key>) && (error != <API key>)) {
if (print_host)
printk(KERN_WARNING "3w-sas: scsi%d: ERROR: (0x%02X:0x%04X): %s:%s.\n",
tw_dev->host->host_no,
<API key>,
header->status_block.error,
error_str,
header->err_specific_desc);
else
printk(KERN_WARNING "3w-sas: ERROR: (0x%02X:0x%04X): %s:%s.\n",
<API key>,
header->status_block.error,
error_str,
header->err_specific_desc);
}
if (copy_sense) {
memcpy(tw_dev->srb[request_id]->sense_buffer, header->sense_data, <API key>);
tw_dev->srb[request_id]->result = (full_command_packet->command.newcommand.status << 1);
goto out;
}
out:
return retval;
} /* End twl_fill_sense() */
/* This function will free up device extension resources */
static void <API key>(TW_Device_Extension *tw_dev)
{
if (tw_dev->command_packet_virt[0])
pci_free_consistent(tw_dev->tw_pci_dev,
sizeof(TW_Command_Full)*TW_Q_LENGTH,
tw_dev->command_packet_virt[0],
tw_dev->command_packet_phys[0]);
if (tw_dev->generic_buffer_virt[0])
pci_free_consistent(tw_dev->tw_pci_dev,
TW_SECTOR_SIZE*TW_Q_LENGTH,
tw_dev->generic_buffer_virt[0],
tw_dev->generic_buffer_phys[0]);
if (tw_dev->sense_buffer_virt[0])
pci_free_consistent(tw_dev->tw_pci_dev,
sizeof(<API key>)*
TW_Q_LENGTH,
tw_dev->sense_buffer_virt[0],
tw_dev->sense_buffer_phys[0]);
kfree(tw_dev->event_queue[0]);
} /* End <API key>() */
/* This function will get parameter table entries from the firmware */
static void *twl_get_param(TW_Device_Extension *tw_dev, int request_id, int table_id, int parameter_id, int <API key>)
{
TW_Command_Full *full_command_packet;
TW_Command *command_packet;
TW_Param_Apache *param;
void *retval = NULL;
/* Setup the command packet */
full_command_packet = tw_dev->command_packet_virt[request_id];
memset(full_command_packet, 0, sizeof(TW_Command_Full));
command_packet = &full_command_packet->command.oldcommand;
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = TW_COMMAND_SIZE;
command_packet->request_id = request_id;
command_packet->byte6_offset.block_count = cpu_to_le16(1);
/* Now setup the param */
param = (TW_Param_Apache *)tw_dev->generic_buffer_virt[request_id];
memset(param, 0, TW_SECTOR_SIZE);
param->table_id = cpu_to_le16(table_id | 0x8000);
param->parameter_id = cpu_to_le16(parameter_id);
param-><API key> = cpu_to_le16(<API key>);
command_packet->byte8_offset.param.sgl[0].address = TW_CPU_TO_SGL(tw_dev->generic_buffer_phys[request_id]);
command_packet->byte8_offset.param.sgl[0].length = TW_CPU_TO_SGL(TW_SECTOR_SIZE);
/* Post the command packet to the board */
<API key>(tw_dev, request_id);
/* Poll for completion */
if (twl_poll_response(tw_dev, request_id, 30))
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x7, "No valid response during get param")
else
retval = (void *)&(param->data[0]);
tw_dev-><API key>
tw_dev->state[request_id] = TW_S_INITIAL;
return retval;
} /* End twl_get_param() */
/* This function will send an initconnection command to controller */
static int twl_initconnection(TW_Device_Extension *tw_dev, int message_credits,
u32 set_features, unsigned short current_fw_srl,
unsigned short current_fw_arch_id,
unsigned short current_fw_branch,
unsigned short current_fw_build,
unsigned short *fw_on_ctlr_srl,
unsigned short *fw_on_ctlr_arch_id,
unsigned short *fw_on_ctlr_branch,
unsigned short *fw_on_ctlr_build,
u32 *init_connect_result)
{
TW_Command_Full *full_command_packet;
TW_Initconnect *tw_initconnect;
int request_id = 0, retval = 1;
/* Initialize InitConnection command packet */
full_command_packet = tw_dev->command_packet_virt[request_id];
memset(full_command_packet, 0, sizeof(TW_Command_Full));
full_command_packet->header.header_desc.size_header = 128;
tw_initconnect = (TW_Initconnect *)&full_command_packet->command.oldcommand;
tw_initconnect->opcode__reserved = TW_OPRES_IN(0, <API key>);
tw_initconnect->request_id = request_id;
tw_initconnect->message_credits = cpu_to_le16(message_credits);
tw_initconnect->features = set_features;
/* Turn on 64-bit sgl support if we need to */
tw_initconnect->features |= sizeof(dma_addr_t) > 4 ? 1 : 0;
tw_initconnect->features = cpu_to_le32(tw_initconnect->features);
if (set_features & <API key>) {
tw_initconnect->size = <API key>;
tw_initconnect->fw_srl = cpu_to_le16(current_fw_srl);
tw_initconnect->fw_arch_id = cpu_to_le16(current_fw_arch_id);
tw_initconnect->fw_branch = cpu_to_le16(current_fw_branch);
tw_initconnect->fw_build = cpu_to_le16(current_fw_build);
} else
tw_initconnect->size = <API key>;
/* Send command packet to the board */
<API key>(tw_dev, request_id);
/* Poll for completion */
if (twl_poll_response(tw_dev, request_id, 30)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x8, "No valid response during init connection");
} else {
if (set_features & <API key>) {
*fw_on_ctlr_srl = le16_to_cpu(tw_initconnect->fw_srl);
*fw_on_ctlr_arch_id = le16_to_cpu(tw_initconnect->fw_arch_id);
*fw_on_ctlr_branch = le16_to_cpu(tw_initconnect->fw_branch);
*fw_on_ctlr_build = le16_to_cpu(tw_initconnect->fw_build);
*init_connect_result = le32_to_cpu(tw_initconnect->result);
}
retval = 0;
}
tw_dev-><API key>
tw_dev->state[request_id] = TW_S_INITIAL;
return retval;
} /* End twl_initconnection() */
/* This function will initialize the fields of a device extension */
static int <API key>(TW_Device_Extension *tw_dev)
{
int i, retval = 1;
/* Initialize command packet buffers */
if (twl_allocate_memory(tw_dev, sizeof(TW_Command_Full), 0)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x9, "Command packet memory allocation failed");
goto out;
}
/* Initialize generic buffer */
if (twl_allocate_memory(tw_dev, TW_SECTOR_SIZE, 1)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xa, "Generic memory allocation failed");
goto out;
}
/* Allocate sense buffers */
if (twl_allocate_memory(tw_dev, sizeof(<API key>), 2)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xb, "Sense buffer allocation failed");
goto out;
}
/* Allocate event info space */
tw_dev->event_queue[0] = kcalloc(TW_Q_LENGTH, sizeof(TW_Event), GFP_KERNEL);
if (!tw_dev->event_queue[0]) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xc, "Event info memory allocation failed");
goto out;
}
for (i = 0; i < TW_Q_LENGTH; i++) {
tw_dev->event_queue[i] = (TW_Event *)((unsigned char *)tw_dev->event_queue[0] + (i * sizeof(TW_Event)));
tw_dev->free_queue[i] = i;
tw_dev->state[i] = TW_S_INITIAL;
}
tw_dev->free_head = TW_Q_START;
tw_dev->free_tail = TW_Q_START;
tw_dev->error_sequence_id = 1;
tw_dev->chrdev_request_id = <API key>;
mutex_init(&tw_dev->ioctl_lock);
init_waitqueue_head(&tw_dev->ioctl_wqueue);
retval = 0;
out:
return retval;
} /* End <API key>() */
/* This function will perform a pci-dma unmap */
static void twl_unmap_scsi_data(TW_Device_Extension *tw_dev, int request_id)
{
struct scsi_cmnd *cmd = tw_dev->srb[request_id];
if (cmd->SCp.phase == TW_PHASE_SGLIST)
scsi_dma_unmap(cmd);
} /* End twl_unmap_scsi_data() */
/* This function will handle attention interrupts */
static int <API key>(TW_Device_Extension *tw_dev)
{
int retval = 1;
u32 request_id, doorbell;
/* Read doorbell status */
doorbell = readl(TWL_HOBDB_REG_ADDR(tw_dev));
/* Check for controller errors */
if (doorbell & <API key>) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xd, "Microcontroller Error: clearing");
goto out;
}
/* Check if we need to perform an AEN drain */
if (doorbell & <API key>) {
if (!(test_and_set_bit(<API key>, &tw_dev->flags))) {
twl_get_request_id(tw_dev, &request_id);
if (twl_aen_read_queue(tw_dev, request_id)) {
tw_dev->state[request_id] = TW_S_COMPLETED;
twl_free_request_id(tw_dev, request_id);
clear_bit(<API key>, &tw_dev->flags);
}
}
}
retval = 0;
out:
/* Clear doorbell interrupt */
<API key>(tw_dev);
/* Make sure the clear was flushed by reading it back */
readl(TWL_HOBDBC_REG_ADDR(tw_dev));
return retval;
} /* End <API key>() */
/* Interrupt service routine */
static irqreturn_t twl_interrupt(int irq, void *dev_instance)
{
TW_Device_Extension *tw_dev = (TW_Device_Extension *)dev_instance;
int i, handled = 0, error = 0;
dma_addr_t mfa = 0;
u32 reg, regl, regh, response, request_id = 0;
struct scsi_cmnd *cmd;
TW_Command_Full *full_command_packet;
spin_lock(tw_dev->host->host_lock);
/* Read host interrupt status */
reg = readl(TWL_HISTAT_REG_ADDR(tw_dev));
/* Check if this is our interrupt, otherwise bail */
if (!(reg & <API key>))
goto twl_interrupt_bail;
handled = 1;
/* If we are resetting, bail */
if (test_bit(TW_IN_RESET, &tw_dev->flags))
goto twl_interrupt_bail;
/* Attention interrupt */
if (reg & <API key>) {
if (<API key>(tw_dev)) {
TWL_MASK_INTERRUPTS(tw_dev);
goto twl_interrupt_bail;
}
}
/* Response interrupt */
while (reg & <API key>) {
if (sizeof(dma_addr_t) > 4) {
regh = readl(TWL_HOBQPH_REG_ADDR(tw_dev));
regl = readl(TWL_HOBQPL_REG_ADDR(tw_dev));
mfa = ((u64)regh << 32) | regl;
} else
mfa = readl(TWL_HOBQPL_REG_ADDR(tw_dev));
error = 0;
response = (u32)mfa;
/* Check for command packet error */
if (!TW_NOTMFA_OUT(response)) {
for (i=0;i<TW_Q_LENGTH;i++) {
if (tw_dev->sense_buffer_phys[i] == mfa) {
request_id = le16_to_cpu(tw_dev->sense_buffer_virt[i]->header_desc.request_id);
if (tw_dev->srb[request_id] != NULL)
error = twl_fill_sense(tw_dev, i, request_id, 1, 1);
else {
/* Skip ioctl error prints */
if (request_id != tw_dev->chrdev_request_id)
error = twl_fill_sense(tw_dev, i, request_id, 0, 1);
else
memcpy(tw_dev->command_packet_virt[request_id], tw_dev->sense_buffer_virt[i], sizeof(<API key>));
}
/* Now re-post the sense buffer */
writel((u32)((u64)tw_dev->sense_buffer_phys[i] >> 32), TWL_HOBQPH_REG_ADDR(tw_dev));
writel((u32)tw_dev->sense_buffer_phys[i], TWL_HOBQPL_REG_ADDR(tw_dev));
break;
}
}
} else
request_id = TW_RESID_OUT(response);
full_command_packet = tw_dev->command_packet_virt[request_id];
/* Check for correct state */
if (tw_dev->state[request_id] != TW_S_POSTED) {
if (tw_dev->srb[request_id] != NULL) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xe, "Received a request id that wasn't posted");
TWL_MASK_INTERRUPTS(tw_dev);
goto twl_interrupt_bail;
}
}
/* Check for internal command completion */
if (tw_dev->srb[request_id] == NULL) {
if (request_id != tw_dev->chrdev_request_id) {
if (twl_aen_complete(tw_dev, request_id))
TW_PRINTK(tw_dev->host, TW_DRIVER, 0xf, "Error completing AEN during attention interrupt");
} else {
tw_dev->chrdev_request_id = <API key>;
wake_up(&tw_dev->ioctl_wqueue);
}
} else {
cmd = tw_dev->srb[request_id];
if (!error)
cmd->result = (DID_OK << 16);
/* Report residual bytes for single sgl */
if ((scsi_sg_count(cmd) <= 1) && (full_command_packet->command.newcommand.status == 0)) {
if (full_command_packet->command.newcommand.sg_list[0].length < scsi_bufflen(tw_dev->srb[request_id]))
scsi_set_resid(cmd, scsi_bufflen(cmd) - full_command_packet->command.newcommand.sg_list[0].length);
}
/* Now complete the io */
tw_dev->state[request_id] = TW_S_COMPLETED;
twl_free_request_id(tw_dev, request_id);
tw_dev-><API key>
tw_dev->srb[request_id]->scsi_done(tw_dev->srb[request_id]);
twl_unmap_scsi_data(tw_dev, request_id);
}
/* Check for another response interrupt */
reg = readl(TWL_HISTAT_REG_ADDR(tw_dev));
}
twl_interrupt_bail:
spin_unlock(tw_dev->host->host_lock);
return IRQ_RETVAL(handled);
} /* End twl_interrupt() */
/* This function will poll for a register change */
static int twl_poll_register(TW_Device_Extension *tw_dev, void *reg, u32 value, u32 result, int seconds)
{
unsigned long before;
int retval = 1;
u32 reg_value;
reg_value = readl(reg);
before = jiffies;
while ((reg_value & value) != result) {
reg_value = readl(reg);
if (time_after(jiffies, before + HZ * seconds))
goto out;
msleep(50);
}
retval = 0;
out:
return retval;
} /* End twl_poll_register() */
/* This function will reset a controller */
static int twl_reset_sequence(TW_Device_Extension *tw_dev, int soft_reset)
{
int retval = 1;
int i = 0;
u32 status = 0;
unsigned short fw_on_ctlr_srl = 0, fw_on_ctlr_arch_id = 0;
unsigned short fw_on_ctlr_branch = 0, fw_on_ctlr_build = 0;
u32 init_connect_result = 0;
int tries = 0;
int do_soft_reset = soft_reset;
while (tries < TW_MAX_RESET_TRIES) {
/* Do a soft reset if one is needed */
if (do_soft_reset) {
TWL_SOFT_RESET(tw_dev);
/* Make sure controller is in a good state */
if (twl_poll_register(tw_dev, TWL_SCRPD3_REG_ADDR(tw_dev), <API key>, 0x0, 30)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x10, "Controller never went non-ready during reset sequence");
tries++;
continue;
}
if (twl_poll_register(tw_dev, TWL_SCRPD3_REG_ADDR(tw_dev), <API key>, <API key>, 60)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x11, "Controller not ready during reset sequence");
tries++;
continue;
}
}
/* Initconnect */
if (twl_initconnection(tw_dev, <API key>,
<API key>, <API key>,
TW_9750_ARCH_ID, <API key>,
<API key>, &fw_on_ctlr_srl,
&fw_on_ctlr_arch_id, &fw_on_ctlr_branch,
&fw_on_ctlr_build, &init_connect_result)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x12, "Initconnection failed while checking SRL");
do_soft_reset = 1;
tries++;
continue;
}
/* Load sense buffers */
while (i < TW_Q_LENGTH) {
writel((u32)((u64)tw_dev->sense_buffer_phys[i] >> 32), TWL_HOBQPH_REG_ADDR(tw_dev));
writel((u32)tw_dev->sense_buffer_phys[i], TWL_HOBQPL_REG_ADDR(tw_dev));
/* Check status for over-run after each write */
status = readl(TWL_STATUS_REG_ADDR(tw_dev));
if (!(status & <API key>))
i++;
}
/* Now check status */
status = readl(TWL_STATUS_REG_ADDR(tw_dev));
if (status) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x13, "Bad controller status after loading sense buffers");
do_soft_reset = 1;
tries++;
continue;
}
/* Drain the AEN queue */
if (twl_aen_drain_queue(tw_dev, soft_reset)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x14, "AEN drain failed during reset sequence");
do_soft_reset = 1;
tries++;
continue;
}
/* Load rest of compatibility struct */
strncpy(tw_dev->tw_compat_info.driver_version, TW_DRIVER_VERSION, strlen(TW_DRIVER_VERSION));
tw_dev->tw_compat_info.driver_srl_high = <API key>;
tw_dev->tw_compat_info.driver_branch_high = <API key>;
tw_dev->tw_compat_info.driver_build_high = <API key>;
tw_dev->tw_compat_info.driver_srl_low = TW_BASE_FW_SRL;
tw_dev->tw_compat_info.driver_branch_low = TW_BASE_FW_BRANCH;
tw_dev->tw_compat_info.driver_build_low = TW_BASE_FW_BUILD;
tw_dev->tw_compat_info.fw_on_ctlr_srl = fw_on_ctlr_srl;
tw_dev->tw_compat_info.fw_on_ctlr_branch = fw_on_ctlr_branch;
tw_dev->tw_compat_info.fw_on_ctlr_build = fw_on_ctlr_build;
/* If we got here, controller is in a good state */
retval = 0;
goto out;
}
out:
return retval;
} /* End twl_reset_sequence() */
/* This function will reset a device extension */
static int <API key>(TW_Device_Extension *tw_dev, int ioctl_reset)
{
int i = 0, retval = 1;
unsigned long flags = 0;
/* Block SCSI requests while we are resetting */
if (ioctl_reset)
scsi_block_requests(tw_dev->host);
set_bit(TW_IN_RESET, &tw_dev->flags);
TWL_MASK_INTERRUPTS(tw_dev);
<API key>(tw_dev);
spin_lock_irqsave(tw_dev->host->host_lock, flags);
/* Abort all requests that are in progress */
for (i = 0; i < TW_Q_LENGTH; i++) {
if ((tw_dev->state[i] != TW_S_FINISHED) &&
(tw_dev->state[i] != TW_S_INITIAL) &&
(tw_dev->state[i] != TW_S_COMPLETED)) {
if (tw_dev->srb[i]) {
tw_dev->srb[i]->result = (DID_RESET << 16);
tw_dev->srb[i]->scsi_done(tw_dev->srb[i]);
twl_unmap_scsi_data(tw_dev, i);
}
}
}
/* Reset queues and counts */
for (i = 0; i < TW_Q_LENGTH; i++) {
tw_dev->free_queue[i] = i;
tw_dev->state[i] = TW_S_INITIAL;
}
tw_dev->free_head = TW_Q_START;
tw_dev->free_tail = TW_Q_START;
tw_dev-><API key> = 0;
<API key>(tw_dev->host->host_lock, flags);
if (twl_reset_sequence(tw_dev, 1))
goto out;
<API key>(tw_dev);
clear_bit(TW_IN_RESET, &tw_dev->flags);
tw_dev->chrdev_request_id = <API key>;
retval = 0;
out:
if (ioctl_reset)
<API key>(tw_dev->host);
return retval;
} /* End <API key>() */
/* This funciton returns unit geometry in cylinders/heads/sectors */
static int twl_scsi_biosparam(struct scsi_device *sdev, struct block_device *bdev, sector_t capacity, int geom[])
{
int heads, sectors;
TW_Device_Extension *tw_dev;
tw_dev = (TW_Device_Extension *)sdev->host->hostdata;
if (capacity >= 0x200000) {
heads = 255;
sectors = 63;
} else {
heads = 64;
sectors = 32;
}
geom[0] = heads;
geom[1] = sectors;
geom[2] = sector_div(capacity, heads * sectors); /* cylinders */
return 0;
} /* End twl_scsi_biosparam() */
/* This is the new scsi eh reset function */
static int twl_scsi_eh_reset(struct scsi_cmnd *SCpnt)
{
TW_Device_Extension *tw_dev = NULL;
int retval = FAILED;
tw_dev = (TW_Device_Extension *)SCpnt->device->host->hostdata;
tw_dev->num_resets++;
sdev_printk(KERN_WARNING, SCpnt->device,
"WARNING: (0x%02X:0x%04X): Command (0x%x) timed out, resetting card.\n",
TW_DRIVER, 0x2c, SCpnt->cmnd[0]);
/* Make sure we are not issuing an ioctl or resetting from ioctl */
mutex_lock(&tw_dev->ioctl_lock);
/* Now reset the card and some of the device extension data */
if (<API key>(tw_dev, 0)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x15, "Controller reset failed during scsi host reset");
goto out;
}
retval = SUCCESS;
out:
mutex_unlock(&tw_dev->ioctl_lock);
return retval;
} /* End twl_scsi_eh_reset() */
/* This is the main scsi queue function to handle scsi opcodes */
static int twl_scsi_queue_lck(struct scsi_cmnd *SCpnt, void (*done)(struct scsi_cmnd *))
{
int request_id, retval;
TW_Device_Extension *tw_dev = (TW_Device_Extension *)SCpnt->device->host->hostdata;
/* If we are resetting due to timed out ioctl, report as busy */
if (test_bit(TW_IN_RESET, &tw_dev->flags)) {
retval = <API key>;
goto out;
}
/* Save done function into scsi_cmnd struct */
SCpnt->scsi_done = done;
/* Get a free request id */
twl_get_request_id(tw_dev, &request_id);
/* Save the scsi command for use by the ISR */
tw_dev->srb[request_id] = SCpnt;
/* Initialize phase to zero */
SCpnt->SCp.phase = TW_PHASE_INITIAL;
retval = <API key>(tw_dev, request_id, NULL, 0, NULL);
if (retval) {
tw_dev->state[request_id] = TW_S_COMPLETED;
twl_free_request_id(tw_dev, request_id);
SCpnt->result = (DID_ERROR << 16);
done(SCpnt);
retval = 0;
}
out:
return retval;
} /* End twl_scsi_queue() */
static DEF_SCSI_QCMD(twl_scsi_queue)
/* This function tells the controller to shut down */
static void __twl_shutdown(TW_Device_Extension *tw_dev)
{
/* Disable interrupts */
TWL_MASK_INTERRUPTS(tw_dev);
/* Free up the IRQ */
free_irq(tw_dev->tw_pci_dev->irq, tw_dev);
printk(KERN_WARNING "3w-sas: Shutting down host %d.\n", tw_dev->host->host_no);
/* Tell the card we are shutting down */
if (twl_initconnection(tw_dev, 1, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x16, "Connection shutdown failed");
} else {
printk(KERN_WARNING "3w-sas: Shutdown complete.\n");
}
/* Clear doorbell interrupt just before exit */
<API key>(tw_dev);
} /* End __twl_shutdown() */
/* Wrapper for __twl_shutdown */
static void twl_shutdown(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev;
if (!host)
return;
tw_dev = (TW_Device_Extension *)host->hostdata;
if (tw_dev->online)
__twl_shutdown(tw_dev);
} /* End twl_shutdown() */
/* This function configures unit settings when a unit is coming on-line */
static int twl_slave_configure(struct scsi_device *sdev)
{
/* Force 60 second timeout */
<API key>(sdev->request_queue, 60 * HZ);
return 0;
} /* End twl_slave_configure() */
/* scsi_host_template initializer */
static struct scsi_host_template driver_template = {
.module = THIS_MODULE,
.name = "3w-sas",
.queuecommand = twl_scsi_queue,
.<API key> = twl_scsi_eh_reset,
.bios_param = twl_scsi_biosparam,
.change_queue_depth = <API key>,
.can_queue = TW_Q_LENGTH-2,
.slave_configure = twl_slave_configure,
.this_id = -1,
.sg_tablesize = <API key>,
.max_sectors = TW_MAX_SECTORS,
.cmd_per_lun = TW_MAX_CMDS_PER_LUN,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = twl_host_attrs,
.emulated = 1
};
/* This function will probe and initialize a card */
static int __devinit twl_probe(struct pci_dev *pdev, const struct pci_device_id *dev_id)
{
struct Scsi_Host *host = NULL;
TW_Device_Extension *tw_dev;
int retval = -ENODEV;
int *ptr_phycount, phycount=0;
retval = pci_enable_device(pdev);
if (retval) {
TW_PRINTK(host, TW_DRIVER, 0x17, "Failed to enable pci device");
goto out_disable_device;
}
pci_set_master(pdev);
pci_try_set_mwi(pdev);
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))
|| <API key>(pdev, DMA_BIT_MASK(64)))
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
|| <API key>(pdev, DMA_BIT_MASK(32))) {
TW_PRINTK(host, TW_DRIVER, 0x18, "Failed to set dma mask");
retval = -ENODEV;
goto out_disable_device;
}
host = scsi_host_alloc(&driver_template, sizeof(TW_Device_Extension));
if (!host) {
TW_PRINTK(host, TW_DRIVER, 0x19, "Failed to allocate memory for device extension");
retval = -ENOMEM;
goto out_disable_device;
}
tw_dev = shost_priv(host);
/* Save values to device extension */
tw_dev->host = host;
tw_dev->tw_pci_dev = pdev;
if (<API key>(tw_dev)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1a, "Failed to initialize device extension");
goto <API key>;
}
/* Request IO regions */
retval = pci_request_regions(pdev, "3w-sas");
if (retval) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1b, "Failed to get mem region");
goto <API key>;
}
/* Save base address, use region 1 */
tw_dev->base_addr = pci_iomap(pdev, 1, 0);
if (!tw_dev->base_addr) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1c, "Failed to ioremap");
goto <API key>;
}
/* Disable interrupts on the card */
TWL_MASK_INTERRUPTS(tw_dev);
/* Initialize the card */
if (twl_reset_sequence(tw_dev, 0)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1d, "Controller reset failed during probe");
goto out_iounmap;
}
/* Set host specific parameters */
host->max_id = TW_MAX_UNITS;
host->max_cmd_len = TW_MAX_CDB_LEN;
host->max_lun = TW_MAX_LUNS;
host->max_channel = 0;
/* Register the card with the kernel SCSI layer */
retval = scsi_add_host(host, &pdev->dev);
if (retval) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1e, "scsi add host failed");
goto out_iounmap;
}
pci_set_drvdata(pdev, host);
printk(KERN_WARNING "3w-sas: scsi%d: Found an LSI 3ware %s Controller at 0x%llx, IRQ: %d.\n",
host->host_no,
(char *)twl_get_param(tw_dev, 1, TW_VERSION_TABLE,
TW_PARAM_MODEL, <API key>),
(u64)pci_resource_start(pdev, 1), pdev->irq);
ptr_phycount = twl_get_param(tw_dev, 2, <API key>,
TW_PARAM_PHYCOUNT, <API key>);
if (ptr_phycount)
phycount = le32_to_cpu(*(int *)ptr_phycount);
printk(KERN_WARNING "3w-sas: scsi%d: Firmware %s, BIOS %s, Phys: %d.\n",
host->host_no,
(char *)twl_get_param(tw_dev, 1, TW_VERSION_TABLE,
TW_PARAM_FWVER, <API key>),
(char *)twl_get_param(tw_dev, 2, TW_VERSION_TABLE,
TW_PARAM_BIOSVER, <API key>),
phycount);
/* Try to enable MSI */
if (use_msi && !pci_enable_msi(pdev))
set_bit(TW_USING_MSI, &tw_dev->flags);
/* Now setup the interrupt handler */
retval = request_irq(pdev->irq, twl_interrupt, IRQF_SHARED, "3w-sas", tw_dev);
if (retval) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x1f, "Error requesting IRQ");
goto out_remove_host;
}
<API key>[<API key>] = tw_dev;
<API key>++;
/* Re-enable interrupts on the card */
<API key>(tw_dev);
/* Finally, scan the host */
scsi_scan_host(host);
/* Add sysfs binary files */
if (<API key>(&host->shost_dev.kobj, &<API key>))
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x20, "Failed to create sysfs binary file: 3ware_aen_read");
if (<API key>(&host->shost_dev.kobj, &<API key>))
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x21, "Failed to create sysfs binary file: 3ware_compat_info");
if (twl_major == -1) {
if ((twl_major = register_chrdev (0, "twl", &twl_fops)) < 0)
TW_PRINTK(host, TW_DRIVER, 0x22, "Failed to register character device");
}
tw_dev->online = 1;
return 0;
out_remove_host:
if (test_bit(TW_USING_MSI, &tw_dev->flags))
pci_disable_msi(pdev);
scsi_remove_host(host);
out_iounmap:
iounmap(tw_dev->base_addr);
<API key>:
pci_release_regions(pdev);
<API key>:
<API key>(tw_dev);
scsi_host_put(host);
out_disable_device:
pci_disable_device(pdev);
return retval;
} /* End twl_probe() */
/* This function is called to remove a device */
static void twl_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev;
if (!host)
return;
tw_dev = (TW_Device_Extension *)host->hostdata;
if (!tw_dev->online)
return;
/* Remove sysfs binary files */
<API key>(&host->shost_dev.kobj, &<API key>);
<API key>(&host->shost_dev.kobj, &<API key>);
scsi_remove_host(tw_dev->host);
/* Unregister character device */
if (twl_major >= 0) {
unregister_chrdev(twl_major, "twl");
twl_major = -1;
}
/* Shutdown the card */
__twl_shutdown(tw_dev);
/* Disable MSI if enabled */
if (test_bit(TW_USING_MSI, &tw_dev->flags))
pci_disable_msi(pdev);
/* Free IO remapping */
iounmap(tw_dev->base_addr);
/* Free up the mem region */
pci_release_regions(pdev);
/* Free up device extension resources */
<API key>(tw_dev);
scsi_host_put(tw_dev->host);
pci_disable_device(pdev);
<API key>
} /* End twl_remove() */
#ifdef CONFIG_PM
/* This function is called on PCI suspend */
static int twl_suspend(struct pci_dev *pdev, pm_message_t state)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
printk(KERN_WARNING "3w-sas: Suspending host %d.\n", tw_dev->host->host_no);
/* Disable interrupts */
TWL_MASK_INTERRUPTS(tw_dev);
free_irq(tw_dev->tw_pci_dev->irq, tw_dev);
/* Tell the card we are shutting down */
if (twl_initconnection(tw_dev, 1, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL)) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x23, "Connection shutdown failed during suspend");
} else {
printk(KERN_WARNING "3w-sas: Suspend complete.\n");
}
/* Clear doorbell interrupt */
<API key>(tw_dev);
pci_save_state(pdev);
pci_disable_device(pdev);
pci_set_power_state(pdev, pci_choose_state(pdev, state));
return 0;
} /* End twl_suspend() */
/* This function is called on PCI resume */
static int twl_resume(struct pci_dev *pdev)
{
int retval = 0;
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
printk(KERN_WARNING "3w-sas: Resuming host %d.\n", tw_dev->host->host_no);
pci_set_power_state(pdev, PCI_D0);
pci_enable_wake(pdev, PCI_D0, 0);
pci_restore_state(pdev);
retval = pci_enable_device(pdev);
if (retval) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x24, "Enable device failed during resume");
return retval;
}
pci_set_master(pdev);
pci_try_set_mwi(pdev);
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64))
|| <API key>(pdev, DMA_BIT_MASK(64)))
if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
|| <API key>(pdev, DMA_BIT_MASK(32))) {
TW_PRINTK(host, TW_DRIVER, 0x25, "Failed to set dma mask during resume");
retval = -ENODEV;
goto out_disable_device;
}
/* Initialize the card */
if (twl_reset_sequence(tw_dev, 0)) {
retval = -ENODEV;
goto out_disable_device;
}
/* Now setup the interrupt handler */
retval = request_irq(pdev->irq, twl_interrupt, IRQF_SHARED, "3w-sas", tw_dev);
if (retval) {
TW_PRINTK(tw_dev->host, TW_DRIVER, 0x26, "Error requesting IRQ during resume");
retval = -ENODEV;
goto out_disable_device;
}
/* Now enable MSI if enabled */
if (test_bit(TW_USING_MSI, &tw_dev->flags))
pci_enable_msi(pdev);
/* Re-enable interrupts on the card */
<API key>(tw_dev);
printk(KERN_WARNING "3w-sas: Resume complete.\n");
return 0;
out_disable_device:
scsi_remove_host(host);
pci_disable_device(pdev);
return retval;
} /* End twl_resume() */
#endif
/* PCI Devices supported by this driver */
static struct pci_device_id twl_pci_tbl[] __devinitdata = {
{ PCI_VDEVICE(3WARE, <API key>) },
{ }
};
MODULE_DEVICE_TABLE(pci, twl_pci_tbl);
/* pci_driver initializer */
static struct pci_driver twl_driver = {
.name = "3w-sas",
.id_table = twl_pci_tbl,
.probe = twl_probe,
.remove = twl_remove,
#ifdef CONFIG_PM
.suspend = twl_suspend,
.resume = twl_resume,
#endif
.shutdown = twl_shutdown
};
/* This function is called on driver initialization */
static int __init twl_init(void)
{
printk(KERN_INFO "LSI 3ware SAS/SATA-RAID Controller device driver for Linux v%s.\n", TW_DRIVER_VERSION);
return pci_register_driver(&twl_driver);
} /* End twl_init() */
/* This function is called on driver exit */
static void __exit twl_exit(void)
{
<API key>(&twl_driver);
} /* End twl_exit() */
module_init(twl_init);
module_exit(twl_exit); |
package de.iritgo.openmetix.exporter.gui;
import de.iritgo.openmetix.app.gui.<API key>;
import de.iritgo.openmetix.app.gui.<API key>;
import de.iritgo.openmetix.app.instrument.<API key>;
import de.iritgo.openmetix.core.Engine;
import de.iritgo.openmetix.core.gui.GUIPane;
import de.iritgo.openmetix.core.iobject.IObject;
import de.iritgo.openmetix.exporter.minmidmax.<API key>;
import de.iritgo.openmetix.framework.client.command.ShowDialog;
import de.iritgo.openmetix.framework.command.CommandTools;
import org.swixml.SwingEngine;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.<API key>;
import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.<API key>;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
public class ExporterWizard
extends <API key>
implements <API key>, <API key>
{
public class ComboBoxItem
{
public String id;
public String text;
public ComboBoxItem (String id)
{
this.id = id;
text = Engine.instance ().getResourceService ().<API key> (id);
if (text.startsWith ("!"))
{
text = text.substring (1, text.length () - 1);
}
}
public String toString ()
{
return text;
}
}
public class SensorItem
{
public String name;
public long stationId;
public long sensorId;
public SensorItem (String name, long stationId, long sensorId)
{
this.name = name;
this.stationId = stationId;
this.sensorId = sensorId;
}
public String toString ()
{
return name;
}
}
private SimpleDateFormat fullDateFormat;
private <API key> yearsStartModel;
private <API key> yearsStopModel;
private <API key> yearModel;
private <API key> seasonsModel;
private <API key> monthsStartModel;
private <API key> monthsStopModel;
private <API key> monthModel;
private <API key> decadeModel;
private <API key> daysStartModel;
private <API key> daysStopModel;
private <API key> dayModel;
private <API key> hoursStartModel;
private <API key> hoursStopModel;
private <API key> hourModel;
public JComboBox listYearsStart;
public JComboBox listYearsStop;
public JComboBox listYear;
public JComboBox listSeasons;
public JComboBox listMonthsStart;
public JComboBox listMonthsStop;
public JComboBox listMonth;
public JComboBox listDecade;
public JComboBox listDaysStart;
public JComboBox listDaysStop;
public JComboBox listDay;
public JComboBox listHoursStart;
public JComboBox listHoursStop;
public JComboBox listHour;
/** The station an sensor selector. */
public <API key> <API key>;
/** The absolute filename. */
public JTextField filename;
/** The sensor list. */
public JList sensorList;
/** The sensor model. */
public DefaultListModel sensorModel;
/**
* Create a new <API key>
*/
public ExporterWizard ()
{
super("ExporterWizard");
fullDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
}
/**
* Return a sample of the data object that is displayed in this gui pane.
*
* @return The sample oject.
*/
public IObject getSampleObject ()
{
return null;
}
/**
* Return a clone of this gui pane.
*
* @return The gui pane clone.
*/
public GUIPane cloneGUIPane ()
{
return new ExporterWizard();
}
/**
* Initialize the gui. Subclasses should override this method to create a
* custom gui.
*/
public void initGUI ()
{
super.initGUI ();
try
{
JPanel panel =
(JPanel) new SwingEngine(this).render (
getClass ().getResource ("/swixml/ExporterWizard.xml"));
content.add (
panel, createConstraints (0, 0, 1, 1, GridBagConstraints.BOTH, 100, 100, null));
}
catch (Exception x)
{
}
yearsStartModel = new <API key>();
yearsStopModel = new <API key>();
yearModel = new <API key>();
seasonsModel = new <API key>();
monthsStartModel = new <API key>();
monthsStopModel = new <API key>();
monthModel = new <API key>();
decadeModel = new <API key>();
daysStartModel = new <API key>();
daysStopModel = new <API key>();
dayModel = new <API key>();
hoursStartModel = new <API key>();
hoursStopModel = new <API key>();
hourModel = new <API key>();
updateComboBoxModel ();
listYearsStart.setModel (yearsStartModel);
listYearsStart.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listYearsStart.setEnabled (true);
listYearsStop.setEnabled (true);
listSeasons.setEnabled (false);
listMonthsStart.setEnabled (false);
listMonthsStop.setEnabled (false);
listMonth.setEnabled (false);
listYear.setEnabled (true);
}
else
{
listYear.setEnabled (false);
listSeasons.setEnabled (true);
listMonthsStart.setEnabled (true);
listMonthsStop.setEnabled (true);
listMonth.setEnabled (true);
}
}
}
});
listYearsStop.setModel (yearsStopModel);
listYearsStop.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listYearsStart.setEnabled (true);
listYearsStop.setEnabled (true);
listSeasons.setEnabled (false);
listMonthsStart.setEnabled (false);
listMonthsStop.setEnabled (false);
listMonth.setEnabled (false);
listYear.setEnabled (true);
}
else
{
listYear.setEnabled (false);
listSeasons.setEnabled (true);
listMonthsStart.setEnabled (true);
listMonthsStop.setEnabled (true);
listMonth.setEnabled (true);
}
}
}
});
listYear.setModel (yearModel);
listYear.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listYearsStart.setEnabled (true);
listYearsStop.setEnabled (true);
listSeasons.setEnabled (false);
listMonthsStart.setEnabled (false);
listMonthsStop.setEnabled (false);
listMonth.setEnabled (false);
}
else
{
listYearsStart.setEnabled (false);
listYearsStop.setEnabled (false);
listSeasons.setEnabled (true);
listMonthsStart.setEnabled (true);
listMonthsStop.setEnabled (true);
listMonth.setEnabled (true);
}
}
}
});
listSeasons.setModel (seasonsModel);
listSeasons.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listMonthsStart.setEnabled (true);
listMonthsStop.setEnabled (true);
listMonth.setEnabled (true);
}
else
{
listMonthsStart.setEnabled (false);
listMonthsStop.setEnabled (false);
listMonth.setEnabled (false);
}
}
}
});
listSeasons.setEnabled (false);
listMonthsStart.setModel (monthsStartModel);
listMonthsStart.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listSeasons.setEnabled (true);
listMonth.setEnabled (true);
}
else
{
listSeasons.setEnabled (false);
listMonth.setEnabled (false);
}
}
}
});
listMonthsStart.setEnabled (false);
listMonthsStop.setModel (monthsStopModel);
listMonthsStop.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listSeasons.setEnabled (true);
listMonth.setEnabled (true);
}
else
{
listSeasons.setEnabled (false);
listMonth.setEnabled (false);
}
}
}
});
listMonthsStop.setEnabled (false);
listMonth.setModel (monthModel);
listMonth.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listMonthsStart.setEnabled (true);
listMonthsStop.setEnabled (true);
listDaysStart.setEnabled (false);
listDaysStop.setEnabled (false);
listDecade.setEnabled (false);
listDay.setEnabled (false);
}
else
{
listMonthsStart.setEnabled (false);
listMonthsStop.setEnabled (false);
listDaysStart.setEnabled (true);
listDaysStop.setEnabled (true);
listDecade.setEnabled (true);
listDay.setEnabled (true);
}
}
}
});
listMonth.setEnabled (false);
listDecade.setModel (decadeModel);
listDecade.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listDaysStart.setEnabled (true);
listDaysStop.setEnabled (true);
listDay.setEnabled (true);
}
else
{
listDaysStart.setEnabled (false);
listDaysStop.setEnabled (false);
listDay.setEnabled (false);
}
}
}
});
listDecade.setEnabled (false);
listDaysStart.setModel (daysStartModel);
listDaysStart.setEnabled (false);
listDaysStart.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listDecade.setEnabled (true);
listDay.setEnabled (true);
}
else
{
listDecade.setEnabled (false);
listDay.setEnabled (false);
}
}
}
});
listDaysStop.setModel (daysStopModel);
listDaysStop.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listDecade.setEnabled (true);
listDay.setEnabled (true);
}
else
{
listDecade.setEnabled (false);
listDay.setEnabled (false);
}
}
}
});
listDaysStop.setEnabled (false);
listDay.setModel (dayModel);
listDay.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listDaysStart.setEnabled (true);
listDaysStop.setEnabled (true);
listDecade.setEnabled (true);
listHoursStart.setEnabled (false);
listHoursStop.setEnabled (false);
listHour.setEnabled (false);
}
else
{
listDaysStart.setEnabled (false);
listDaysStop.setEnabled (false);
listDecade.setEnabled (false);
listHoursStart.setEnabled (true);
listHoursStop.setEnabled (true);
listHour.setEnabled (true);
}
}
}
});
listDay.setEnabled (false);
listHoursStart.setModel (hoursStartModel);
listHoursStart.setEnabled (false);
listHoursStart.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listHour.setEnabled (true);
}
else
{
listHour.setEnabled (false);
}
}
}
});
listHoursStop.setModel (hoursStopModel);
listHoursStop.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listHour.setEnabled (true);
}
else
{
listHour.setEnabled (false);
}
}
}
});
listHoursStop.setEnabled (false);
listHour.setModel (hourModel);
listHour.addItemListener (
new ItemListener()
{
public void itemStateChanged (ItemEvent e)
{
if (e.getStateChange () == ItemEvent.SELECTED)
{
if (((ComboBoxItem) e.getItem ()).id.equals ("exporterwizard.dummy"))
{
listHoursStart.setEnabled (true);
listHoursStop.setEnabled (true);
}
else
{
listHoursStart.setEnabled (false);
listHoursStop.setEnabled (false);
}
}
}
});
listHour.setEnabled (false);
sensorModel = new DefaultListModel();
sensorList.setModel (sensorModel);
<API key>.update ();
super.loadFromObject ();
}
/**
* Load the gui values from the data object attributes.
*/
public void loadFromObject ()
{
super.loadFromObject ();
}
/**
* Store the current gui values into the data object attributes.
*/
public void storeToObject ()
{
}
/**
* A sensor was selected from the list.
*
* @param event The list selection event.
*/
public void valueChanged (ListSelectionEvent event)
{
}
/**
* Update the list of item for the combobox dateYear
*/
public void updateComboBoxModel ()
{
yearsStartModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
yearsStopModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
yearModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
for (int i = 1900; i <= 2050; i++)
{
yearsStartModel.addElement (new ComboBoxItem("" + i));
yearsStopModel.addElement (new ComboBoxItem("" + i));
yearModel.addElement (new ComboBoxItem("" + i));
}
seasonsModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
seasonsModel.addElement (new ComboBoxItem("winter"));
seasonsModel.addElement (new ComboBoxItem("spring"));
seasonsModel.addElement (new ComboBoxItem("summer"));
seasonsModel.addElement (new ComboBoxItem("harvest"));
monthsStartModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
monthsStopModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
monthModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
monthsStartModel.addElement (new ComboBoxItem("january"));
monthsStopModel.addElement (new ComboBoxItem("january"));
monthModel.addElement (new ComboBoxItem("january"));
monthsStartModel.addElement (new ComboBoxItem("february"));
monthsStopModel.addElement (new ComboBoxItem("february"));
monthModel.addElement (new ComboBoxItem("february"));
monthsStartModel.addElement (new ComboBoxItem("march"));
monthsStopModel.addElement (new ComboBoxItem("march"));
monthModel.addElement (new ComboBoxItem("march"));
monthsStartModel.addElement (new ComboBoxItem("april"));
monthsStopModel.addElement (new ComboBoxItem("april"));
monthModel.addElement (new ComboBoxItem("april"));
monthsStartModel.addElement (new ComboBoxItem("may"));
monthsStopModel.addElement (new ComboBoxItem("may"));
monthModel.addElement (new ComboBoxItem("may"));
monthsStartModel.addElement (new ComboBoxItem("june"));
monthsStopModel.addElement (new ComboBoxItem("june"));
monthModel.addElement (new ComboBoxItem("june"));
monthsStartModel.addElement (new ComboBoxItem("july"));
monthsStopModel.addElement (new ComboBoxItem("july"));
monthModel.addElement (new ComboBoxItem("july"));
monthsStartModel.addElement (new ComboBoxItem("august"));
monthsStopModel.addElement (new ComboBoxItem("august"));
monthModel.addElement (new ComboBoxItem("august"));
monthsStartModel.addElement (new ComboBoxItem("september"));
monthsStopModel.addElement (new ComboBoxItem("september"));
monthModel.addElement (new ComboBoxItem("september"));
monthsStartModel.addElement (new ComboBoxItem("october"));
monthsStopModel.addElement (new ComboBoxItem("october"));
monthModel.addElement (new ComboBoxItem("october"));
monthsStopModel.addElement (new ComboBoxItem("november"));
monthsStartModel.addElement (new ComboBoxItem("november"));
monthModel.addElement (new ComboBoxItem("november"));
monthsStartModel.addElement (new ComboBoxItem("december"));
monthsStopModel.addElement (new ComboBoxItem("december"));
monthModel.addElement (new ComboBoxItem("december"));
decadeModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
decadeModel.addElement (new ComboBoxItem("1dc"));
decadeModel.addElement (new ComboBoxItem("2dc"));
decadeModel.addElement (new ComboBoxItem("3dc"));
decadeModel.addElement (new ComboBoxItem("4dc"));
daysStartModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
daysStopModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
dayModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
for (int i = 1; i <= 31; i++)
{
daysStartModel.addElement (new ComboBoxItem("" + i));
daysStopModel.addElement (new ComboBoxItem("" + i));
dayModel.addElement (new ComboBoxItem("" + i));
}
hoursStartModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
hoursStopModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
hourModel.addElement (new ComboBoxItem("exporterwizard.dummy"));
for (int i = 0; i <= 24; i++)
{
hoursStartModel.addElement (new ComboBoxItem("" + i));
hoursStopModel.addElement (new ComboBoxItem("" + i));
hourModel.addElement (new ComboBoxItem("" + i));
}
}
/**
* Add a new sensor to the instrument.
*/
public Action sensorAcceptAction =
new AbstractAction()
{
public void actionPerformed (ActionEvent e)
{
sensorModel.addElement (
new SensorItem(
<API key>.<API key> () + " - " +
<API key>.<API key> (),
<API key>.<API key> (),
<API key>.getSelectedSensorId ()));
sensorList.repaint ();
}
};
/**
* Delete a sensor from the instrument.
*/
public Action delSensorAction =
new AbstractAction()
{
public void actionPerformed (ActionEvent e)
{
int index = sensorList.getSelectedIndex ();
if (index != -1)
{
sensorModel.remove (index);
}
}
};
/**
* Send the action for the eporter.
*/
public Action okAction =
new AbstractAction()
{
public void actionPerformed (ActionEvent e)
{
LinkedList o = new LinkedList();
for (int i = 0; i < sensorModel.size (); ++i)
{
SensorItem s = (SensorItem) sensorModel.get (i);
o.add (new Long(s.sensorId));
}
Date startDate = null;
Date stopDate = null;
int startYear = 0;
int stopYear = 0;
try
{
int year = 0;
int monthStart = 1;
int monthStop = 12;
int monthDayStart = 1;
int monthDayStop = 31;
int month = 0;
int day = 0;
int hoursStart = 6;
int hoursStop = 6;
int hour = 0;
if (listYearsStart.isEnabled ())
{
year =
Integer.valueOf (((ComboBoxItem) listYearsStop.getSelectedItem ()).id)
.intValue ();
startYear =
Integer.valueOf (((ComboBoxItem) listYearsStart.getSelectedItem ()).id)
.intValue ();
stopYear =
Integer.valueOf (((ComboBoxItem) listYearsStop.getSelectedItem ()).id)
.intValue ();
startDate = fullDateFormat.parse ("01.01." + year + " 6:00");
stopDate = fullDateFormat.parse ("31.12." + year + " 6:00");
}
if (
listYear.isEnabled () &&
(! ((ComboBoxItem) listYear.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
year =
Integer.valueOf (((ComboBoxItem) listYear.getSelectedItem ()).id)
.intValue ();
startDate =
fullDateFormat.parse (
monthDayStart + "." + monthStart + "." + year + " 6:00");
stopDate =
fullDateFormat.parse (
monthDayStop + "." + monthStop + "." + year + " 6:00");
}
if (
listSeasons.isEnabled () &&
(! ((ComboBoxItem) listSeasons.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
if (((ComboBoxItem) listSeasons.getSelectedItem ()).id.equals ("winter"))
{
startDate = fullDateFormat.parse ("01.12." + (year - 1) + " 6:00");
stopDate = fullDateFormat.parse ("01.03." + year + " 6:00");
}
if (((ComboBoxItem) listSeasons.getSelectedItem ()).id.equals ("spring"))
{
startDate = fullDateFormat.parse ("01.03." + year + " 6:00");
stopDate = fullDateFormat.parse ("01.06." + year + " 6:00");
}
if (((ComboBoxItem) listSeasons.getSelectedItem ()).id.equals ("summer"))
{
startDate = fullDateFormat.parse ("01.06." + year + " 6:00");
stopDate = fullDateFormat.parse ("01.09." + year + " 6:00");
}
if (((ComboBoxItem) listSeasons.getSelectedItem ()).id.equals ("harvest"))
{
startDate = fullDateFormat.parse ("01.09." + year + " 6:00");
stopDate = fullDateFormat.parse ("01.12." + year + " 6:00");
}
}
if (
listMonthsStart.isEnabled () &&
(! ((ComboBoxItem) listMonthsStart.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
monthStart = listMonthsStart.getSelectedIndex ();
monthStop = listMonthsStop.getSelectedIndex ();
startDate =
fullDateFormat.parse ("01." + monthStart + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("01." + monthStop + "." + year + " 6:00");
}
if (
listMonth.isEnabled () &&
(! ((ComboBoxItem) listMonth.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
month = listMonth.getSelectedIndex ();
startDate = fullDateFormat.parse ("01." + month + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("31." + month + "." + year + " 6:00");
}
if (
listDecade.isEnabled () &&
(! ((ComboBoxItem) listDecade.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
if (((ComboBoxItem) listDecade.getSelectedItem ()).id.equals ("1dc"))
{
startDate = fullDateFormat.parse ("01." + month + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("08." + month + "." + year + " 6:00");
}
if (((ComboBoxItem) listDecade.getSelectedItem ()).id.equals ("2dc"))
{
startDate = fullDateFormat.parse ("08." + month + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("16." + month + "." + year + " 6:00");
}
if (((ComboBoxItem) listDecade.getSelectedItem ()).id.equals ("3dc"))
{
startDate = fullDateFormat.parse ("16." + month + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("24." + month + "." + year + " 6:00");
}
if (((ComboBoxItem) listDecade.getSelectedItem ()).id.equals ("4dc"))
{
startDate = fullDateFormat.parse ("24." + month + "." + year + " 6:00");
stopDate = fullDateFormat.parse ("31." + month + "." + year + " 6:00");
}
}
if (
listDaysStart.isEnabled () &&
(! ((ComboBoxItem) listDaysStart.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
monthDayStart =
Integer.valueOf (((ComboBoxItem) listDaysStart.getSelectedItem ()).id)
.intValue ();
monthDayStop =
Integer.valueOf (((ComboBoxItem) listDaysStop.getSelectedItem ()).id)
.intValue ();
startDate =
fullDateFormat.parse (
monthDayStart + "." + month + "." + year + " 6:00");
stopDate =
fullDateFormat.parse (
monthDayStop + "." + month + "." + year + " 6:00");
}
if (
listDay.isEnabled () &&
(! ((ComboBoxItem) listDay.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
day = Integer.valueOf (((ComboBoxItem) listDay.getSelectedItem ()).id)
.intValue ();
monthDayStart = day;
monthDayStop = day;
startDate = fullDateFormat.parse (day + "." + month + "." + year + " 6:00");
stopDate =
fullDateFormat.parse ((day + 1) + "." + month + "." + year + " 6:00");
}
if (
listHoursStart.isEnabled () &&
(! ((ComboBoxItem) listHoursStart.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
hoursStart =
Integer.valueOf (((ComboBoxItem) listHoursStart.getSelectedItem ()).id)
.intValue ();
hoursStop =
Integer.valueOf (((ComboBoxItem) listHoursStop.getSelectedItem ()).id)
.intValue ();
startDate =
fullDateFormat.parse (
monthDayStart + "." + month + "." + year + " " + hoursStart +
":00");
stopDate =
fullDateFormat.parse (
monthDayStop + "." + month + "." + year + " " + hoursStart + ":00");
}
if (
listHour.isEnabled () &&
(! ((ComboBoxItem) listHour.getSelectedItem ()).id.equals (
"exporterwizard.dummy")))
{
hour =
Integer.valueOf (((ComboBoxItem) listHour.getSelectedItem ()).id)
.intValue ();
startDate =
fullDateFormat.parse (
monthDayStart + "." + month + "." + year + " " + hour + ":00");
stopDate =
fullDateFormat.parse (
monthDayStop + "." + month + "." + year + " " + hour + ":60");
}
}
catch (Exception x)
{
System.out.println (x);
}
if (o.size () == 0)
{
JOptionPane.showMessageDialog (
content,
Engine.instance ().getResourceService ().<API key> (
"exportwizard.sensorerror"), "Metix", JOptionPane.OK_OPTION);
return;
}
if (startDate == null)
{
JOptionPane.showMessageDialog (
content,
Engine.instance ().getResourceService ().<API key> (
"exportwizard.timeerror"), "Metix", JOptionPane.OK_OPTION);
return;
}
CommandTools.performAsync (new ShowDialog("MinMidMaxResult"));
<API key> mc = new <API key>();
mc.setSensorList (o);
mc.setStartDate (startDate.getTime ());
mc.setStopDate (stopDate.getTime ());
mc.setStartYear ((long) startYear);
mc.setStopYear ((long) stopYear);
CommandTools.performAsync (mc);
display.close ();
}
};
/**
* Cancel the instrument configuration and close the
* configurator.
*/
public Action cancelAction =
new AbstractAction()
{
public void actionPerformed (ActionEvent e)
{
display.close ();
}
};
} |
package com.sun.tools.internal.xjc.reader.xmlschema.bindinfo;
import java.util.Collection;
import java.util.Collections;
import com.sun.codemodel.internal.JCodeModel;
import com.sun.tools.internal.xjc.reader.Ring;
import com.sun.tools.internal.xjc.reader.xmlschema.BGMBuilder;
import com.sun.xml.internal.bind.annotation.XmlLocation;
import com.sun.xml.internal.xsom.XSComponent;
import org.xml.sax.Locator;
/**
* Abstract partial implementation of {@link BIDeclaration}
*
* @author
* Kohsuke Kawaguchi (kohsuke.kawaguchi@sun.com)
*/
abstract class <API key> implements BIDeclaration {
@Deprecated // eventually delete this in favor of using JAXB
protected <API key>(Locator loc) {
this.loc = loc;
}
protected <API key>() {}
@XmlLocation
Locator loc; // set by JAXB
public Locator getLocation() { return loc; }
protected BindInfo parent;
public void setParent(BindInfo p) { this.parent=p; }
protected final XSComponent getOwner() {
return parent.getOwner();
}
protected final BGMBuilder getBuilder() {
return parent.getBuilder();
}
protected final JCodeModel getCodeModel() {
return Ring.get(JCodeModel.class);
}
private boolean isAcknowledged = false;
public final boolean isAcknowledged() { return isAcknowledged; }
public void onSetOwner() {
}
public Collection<BIDeclaration> getChildren() {
return Collections.emptyList();
}
public void markAsAcknowledged() {
isAcknowledged = true;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.