repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
gjms2000/mixerp | src/FrontEnd/MixERP.Net.FrontEnd/Modules/BackOffice/CustomFields.ascx.cs | 1053 | /********************************************************************************
Copyright (C) MixERP Inc. (http://mixof.org).
This file is part of MixERP.
MixERP is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, version 2 of the License.
MixERP is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MixERP. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************************/
using System;
using MixERP.Net.FrontEnd.Base;
namespace MixERP.Net.Core.Modules.BackOffice
{
public partial class CustomFields : MixERPUserControl
{
public override void OnControlLoad(object sender, EventArgs e)
{
}
}
} | gpl-2.0 |
carlobar/uclinux_leon3_UD | user/pppd/freebsd-2.0/if_ppp.c | 35795 | /*
* if_ppp.c - Point-to-Point Protocol (PPP) Asynchronous driver.
*
* Copyright (c) 1989 Carnegie Mellon University.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by Carnegie Mellon University. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Drew D. Perkins
* Carnegie Mellon University
* 4910 Forbes Ave.
* Pittsburgh, PA 15213
* (412) 268-8576
* [email protected]
*
* Based on:
* @(#)if_sl.c 7.6.1.2 (Berkeley) 2/15/89
*
* Copyright (c) 1987 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* Serial Line interface
*
* Rick Adams
* Center for Seismic Studies
* 1300 N 17th Street, Suite 1450
* Arlington, Virginia 22209
* (703)276-7900
* [email protected]
* seismo!rick
*
* Pounded on heavily by Chris Torek ([email protected], umcp-cs!chris).
* Converted to 4.3BSD Beta by Chris Torek.
* Other changes made at Berkeley, based in part on code by Kirk Smith.
*
* Converted to 4.3BSD+ 386BSD by Brad Parker ([email protected])
* Added VJ tcp header compression; more unified ioctls
*
* Extensively modified by Paul Mackerras ([email protected]).
* Cleaned up a lot of the mbuf-related code to fix bugs that
* caused system crashes and packet corruption. Changed pppstart
* so that it doesn't just give up with a collision if the whole
* packet doesn't fit in the output ring buffer.
*
* Added priority queueing for interactive IP packets, following
* the model of if_sl.c, plus hooks for bpf.
* Paul Mackerras ([email protected]).
*/
/* $Id: if_ppp.c,v 1.1.1.1 1999/11/22 03:47:53 christ Exp $ */
/* from if_sl.c,v 1.11 84/10/04 12:54:47 rick Exp */
/* from NetBSD: if_ppp.c,v 1.15.2.2 1994/07/28 05:17:58 cgd Exp */
#include "ppp.h"
#if NPPP > 0
#define VJC
#define PPP_COMPRESS
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/proc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/kernel.h>
#include <sys/time.h>
#include <sys/malloc.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/netisr.h>
#include <net/route.h>
#ifdef PPP_FILTER
#include <net/bpf.h>
#endif
#if INET
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/in_var.h>
#include <netinet/ip.h>
#endif
#include "bpfilter.h"
#if NBPFILTER > 0
#include <net/bpf.h>
#endif
#ifdef VJC
#include <net/pppcompress.h>
#endif
#include <net/ppp_defs.h>
#include <net/if_ppp.h>
#include <net/if_pppvar.h>
#include <machine/cpu.h>
#define splsoftnet splnet
#ifndef NETISR_PPP
/* This definition should be moved to net/netisr.h */
#define NETISR_PPP 26 /* PPP software interrupt */
#endif
#ifdef PPP_COMPRESS
#define PACKETPTR struct mbuf *
#include <net/ppp-comp.h>
#endif
static int pppsioctl __P((struct ifnet *, int, caddr_t));
static void ppp_requeue __P((struct ppp_softc *));
static void ppp_ccp __P((struct ppp_softc *, struct mbuf *m, int rcvd));
static void ppp_ccp_closed __P((struct ppp_softc *));
static void ppp_inproc __P((struct ppp_softc *, struct mbuf *));
static void pppdumpm __P((struct mbuf *m0));
/*
* Some useful mbuf macros not in mbuf.h.
*/
#define M_IS_CLUSTER(m) ((m)->m_flags & M_EXT)
#define M_DATASTART(m) \
(M_IS_CLUSTER(m) ? (m)->m_ext.ext_buf : \
(m)->m_flags & M_PKTHDR ? (m)->m_pktdat : (m)->m_dat)
#define M_DATASIZE(m) \
(M_IS_CLUSTER(m) ? (m)->m_ext.ext_size : \
(m)->m_flags & M_PKTHDR ? MHLEN: MLEN)
/*
* We steal two bits in the mbuf m_flags, to mark high-priority packets
* for output, and received packets following lost/corrupted packets.
*/
#define M_HIGHPRI 0x2000 /* output packet for sc_fastq */
#define M_ERRMARK 0x4000 /* steal a bit in mbuf m_flags */
#ifdef PPP_COMPRESS
/*
* List of compressors we know about.
* We leave some space so maybe we can modload compressors.
*/
extern struct compressor ppp_bsd_compress;
extern struct compressor ppp_deflate, ppp_deflate_draft;
struct compressor *ppp_compressors[8] = {
#if DO_BSD_COMPRESS
&ppp_bsd_compress,
#endif
#if DO_DEFLATE
&ppp_deflate,
&ppp_deflate_draft,
#endif
NULL
};
#endif /* PPP_COMPRESS */
TEXT_SET(pseudo_set, pppattach);
/*
* Called from boot code to establish ppp interfaces.
*/
void
pppattach()
{
register struct ppp_softc *sc;
register int i = 0;
extern void (*netisrs[])__P((void));
for (sc = ppp_softc; i < NPPP; sc++) {
sc->sc_if.if_name = "ppp";
sc->sc_if.if_unit = i++;
sc->sc_if.if_mtu = PPP_MTU;
sc->sc_if.if_flags = IFF_POINTOPOINT | IFF_MULTICAST;
sc->sc_if.if_type = IFT_PPP;
sc->sc_if.if_hdrlen = PPP_HDRLEN;
sc->sc_if.if_ioctl = pppsioctl;
sc->sc_if.if_output = pppoutput;
sc->sc_if.if_snd.ifq_maxlen = IFQ_MAXLEN;
sc->sc_inq.ifq_maxlen = IFQ_MAXLEN;
sc->sc_fastq.ifq_maxlen = IFQ_MAXLEN;
sc->sc_rawq.ifq_maxlen = IFQ_MAXLEN;
if_attach(&sc->sc_if);
#if NBPFILTER > 0
bpfattach(&sc->sc_bpf, &sc->sc_if, DLT_PPP, PPP_HDRLEN);
#endif
}
netisrs[NETISR_PPP] = pppintr;
}
/*
* Allocate a ppp interface unit and initialize it.
*/
struct ppp_softc *
pppalloc(pid)
pid_t pid;
{
int nppp, i;
struct ppp_softc *sc;
for (nppp = 0, sc = ppp_softc; nppp < NPPP; nppp++, sc++)
if (sc->sc_xfer == pid) {
sc->sc_xfer = 0;
return sc;
}
for (nppp = 0, sc = ppp_softc; nppp < NPPP; nppp++, sc++)
if (sc->sc_devp == NULL)
break;
if (nppp >= NPPP)
return NULL;
sc->sc_flags = 0;
sc->sc_mru = PPP_MRU;
sc->sc_relinq = NULL;
bzero((char *)&sc->sc_stats, sizeof(sc->sc_stats));
#ifdef VJC
MALLOC(sc->sc_comp, struct vjcompress *, sizeof(struct vjcompress),
M_DEVBUF, M_NOWAIT);
if (sc->sc_comp)
vj_compress_init(sc->sc_comp, -1);
#endif
#ifdef PPP_COMPRESS
sc->sc_xc_state = NULL;
sc->sc_rc_state = NULL;
#endif /* PPP_COMPRESS */
for (i = 0; i < NUM_NP; ++i)
sc->sc_npmode[i] = NPMODE_ERROR;
sc->sc_npqueue = NULL;
sc->sc_npqtail = &sc->sc_npqueue;
sc->sc_last_sent = sc->sc_last_recv = time.tv_sec;
return sc;
}
/*
* Deallocate a ppp unit. Must be called at splsoftnet or higher.
*/
void
pppdealloc(sc)
struct ppp_softc *sc;
{
struct mbuf *m;
if_down(&sc->sc_if);
sc->sc_if.if_flags &= ~(IFF_UP|IFF_RUNNING);
sc->sc_devp = NULL;
sc->sc_xfer = 0;
for (;;) {
IF_DEQUEUE(&sc->sc_rawq, m);
if (m == NULL)
break;
m_freem(m);
}
for (;;) {
IF_DEQUEUE(&sc->sc_inq, m);
if (m == NULL)
break;
m_freem(m);
}
for (;;) {
IF_DEQUEUE(&sc->sc_fastq, m);
if (m == NULL)
break;
m_freem(m);
}
while ((m = sc->sc_npqueue) != NULL) {
sc->sc_npqueue = m->m_nextpkt;
m_freem(m);
}
if (sc->sc_togo != NULL) {
m_freem(sc->sc_togo);
sc->sc_togo = NULL;
}
#ifdef PPP_COMPRESS
ppp_ccp_closed(sc);
sc->sc_xc_state = NULL;
sc->sc_rc_state = NULL;
#endif /* PPP_COMPRESS */
#ifdef PPP_FILTER
if (sc->sc_pass_filt.bf_insns != 0) {
FREE(sc->sc_pass_filt.bf_insns, M_DEVBUF);
sc->sc_pass_filt.bf_insns = 0;
sc->sc_pass_filt.bf_len = 0;
}
if (sc->sc_active_filt.bf_insns != 0) {
FREE(sc->sc_active_filt.bf_insns, M_DEVBUF);
sc->sc_active_filt.bf_insns = 0;
sc->sc_active_filt.bf_len = 0;
}
#endif /* PPP_FILTER */
#ifdef VJC
if (sc->sc_comp != 0) {
FREE(sc->sc_comp, M_DEVBUF);
sc->sc_comp = 0;
}
#endif
}
/*
* Ioctl routine for generic ppp devices.
*/
int
pppioctl(sc, cmd, data, flag, p)
struct ppp_softc *sc;
int cmd;
caddr_t data;
int flag;
struct proc *p;
{
int s, error, flags, mru, nb, npx;
struct ppp_option_data *odp;
struct compressor **cp;
struct npioctl *npi;
time_t t;
#ifdef PPP_FILTER
struct bpf_program *bp, *nbp;
struct bpf_insn *newcode, *oldcode;
int newcodelen;
#endif /* PPP_FILTER */
#ifdef PPP_COMPRESS
u_char ccp_option[CCP_MAX_OPTION_LENGTH];
#endif
switch (cmd) {
case FIONREAD:
*(int *)data = sc->sc_inq.ifq_len;
break;
case PPPIOCGUNIT:
*(int *)data = sc->sc_if.if_unit;
break;
case PPPIOCGFLAGS:
*(u_int *)data = sc->sc_flags;
break;
case PPPIOCSFLAGS:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
flags = *(int *)data & SC_MASK;
s = splsoftnet();
#ifdef PPP_COMPRESS
if (sc->sc_flags & SC_CCP_OPEN && !(flags & SC_CCP_OPEN))
ppp_ccp_closed(sc);
#endif
splimp();
sc->sc_flags = (sc->sc_flags & ~SC_MASK) | flags;
splx(s);
break;
case PPPIOCSMRU:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
mru = *(int *)data;
if (mru >= PPP_MRU && mru <= PPP_MAXMRU)
sc->sc_mru = mru;
break;
case PPPIOCGMRU:
*(int *)data = sc->sc_mru;
break;
#ifdef VJC
case PPPIOCSMAXCID:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
if (sc->sc_comp) {
s = splsoftnet();
vj_compress_init(sc->sc_comp, *(int *)data);
splx(s);
}
break;
#endif
case PPPIOCXFERUNIT:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
sc->sc_xfer = p->p_pid;
break;
#ifdef PPP_COMPRESS
case PPPIOCSCOMPRESS:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
odp = (struct ppp_option_data *) data;
nb = odp->length;
if (nb > sizeof(ccp_option))
nb = sizeof(ccp_option);
if ((error = copyin(odp->ptr, ccp_option, nb)) != 0)
return (error);
if (ccp_option[1] < 2) /* preliminary check on the length byte */
return (EINVAL);
for (cp = ppp_compressors; *cp != NULL; ++cp)
if ((*cp)->compress_proto == ccp_option[0]) {
/*
* Found a handler for the protocol - try to allocate
* a compressor or decompressor.
*/
error = 0;
if (odp->transmit) {
s = splsoftnet();
if (sc->sc_xc_state != NULL)
(*sc->sc_xcomp->comp_free)(sc->sc_xc_state);
sc->sc_xcomp = *cp;
sc->sc_xc_state = (*cp)->comp_alloc(ccp_option, nb);
if (sc->sc_xc_state == NULL) {
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: comp_alloc failed\n",
sc->sc_if.if_unit);
error = ENOBUFS;
}
splimp();
sc->sc_flags &= ~SC_COMP_RUN;
splx(s);
} else {
s = splsoftnet();
if (sc->sc_rc_state != NULL)
(*sc->sc_rcomp->decomp_free)(sc->sc_rc_state);
sc->sc_rcomp = *cp;
sc->sc_rc_state = (*cp)->decomp_alloc(ccp_option, nb);
if (sc->sc_rc_state == NULL) {
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: decomp_alloc failed\n",
sc->sc_if.if_unit);
error = ENOBUFS;
}
splimp();
sc->sc_flags &= ~SC_DECOMP_RUN;
splx(s);
}
return (error);
}
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: no compressor for [%x %x %x], %x\n",
sc->sc_if.if_unit, ccp_option[0], ccp_option[1],
ccp_option[2], nb);
return (EINVAL); /* no handler found */
#endif /* PPP_COMPRESS */
case PPPIOCGNPMODE:
case PPPIOCSNPMODE:
npi = (struct npioctl *) data;
switch (npi->protocol) {
case PPP_IP:
npx = NP_IP;
break;
default:
return EINVAL;
}
if (cmd == PPPIOCGNPMODE) {
npi->mode = sc->sc_npmode[npx];
} else {
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
return (error);
if (npi->mode != sc->sc_npmode[npx]) {
s = splsoftnet();
sc->sc_npmode[npx] = npi->mode;
if (npi->mode != NPMODE_QUEUE) {
ppp_requeue(sc);
(*sc->sc_start)(sc);
}
splx(s);
}
}
break;
case PPPIOCGIDLE:
s = splsoftnet();
t = time.tv_sec;
((struct ppp_idle *)data)->xmit_idle = t - sc->sc_last_sent;
((struct ppp_idle *)data)->recv_idle = t - sc->sc_last_recv;
splx(s);
break;
#ifdef PPP_FILTER
case PPPIOCSPASS:
case PPPIOCSACTIVE:
nbp = (struct bpf_program *) data;
if ((unsigned) nbp->bf_len > BPF_MAXINSNS)
return EINVAL;
newcodelen = nbp->bf_len * sizeof(struct bpf_insn);
if (newcodelen != 0) {
MALLOC(newcode, struct bpf_insn *, newcodelen, M_DEVBUF, M_WAITOK);
if (newcode == 0) {
return EINVAL; /* or sumpin */
}
if ((error = copyin((caddr_t)nbp->bf_insns, (caddr_t)newcode,
newcodelen)) != 0) {
FREE(newcode, M_DEVBUF);
return error;
}
if (!bpf_validate(newcode, nbp->bf_len)) {
FREE(newcode, M_DEVBUF);
return EINVAL;
}
} else
newcode = 0;
bp = (cmd == PPPIOCSPASS)? &sc->sc_pass_filt: &sc->sc_active_filt;
oldcode = bp->bf_insns;
s = splimp();
bp->bf_len = nbp->bf_len;
bp->bf_insns = newcode;
splx(s);
if (oldcode != 0)
FREE(oldcode, M_DEVBUF);
break;
#endif
default:
return (-1);
}
return (0);
}
/*
* Process an ioctl request to the ppp network interface.
*/
static int
pppsioctl(ifp, cmd, data)
register struct ifnet *ifp;
int cmd;
caddr_t data;
{
struct proc *p = curproc; /* XXX */
register struct ppp_softc *sc = &ppp_softc[ifp->if_unit];
register struct ifaddr *ifa = (struct ifaddr *)data;
register struct ifreq *ifr = (struct ifreq *)data;
struct ppp_stats *psp;
#ifdef PPP_COMPRESS
struct ppp_comp_stats *pcp;
#endif
int s = splimp(), error = 0;
switch (cmd) {
case SIOCSIFFLAGS:
if ((ifp->if_flags & IFF_RUNNING) == 0)
ifp->if_flags &= ~IFF_UP;
break;
case SIOCSIFADDR:
if (ifa->ifa_addr->sa_family != AF_INET)
error = EAFNOSUPPORT;
break;
case SIOCSIFDSTADDR:
if (ifa->ifa_addr->sa_family != AF_INET)
error = EAFNOSUPPORT;
break;
case SIOCSIFMTU:
if ((error = suser(p->p_ucred, &p->p_acflag)) != 0)
break;
sc->sc_if.if_mtu = ifr->ifr_mtu;
break;
case SIOCGIFMTU:
ifr->ifr_mtu = sc->sc_if.if_mtu;
break;
case SIOCADDMULTI:
case SIOCDELMULTI:
if (ifr == 0) {
error = EAFNOSUPPORT;
break;
}
switch(ifr->ifr_addr.sa_family) {
#ifdef INET
case AF_INET:
break;
#endif
default:
error = EAFNOSUPPORT;
break;
}
break;
case SIOCGPPPSTATS:
psp = &((struct ifpppstatsreq *) data)->stats;
bzero(psp, sizeof(*psp));
psp->p = sc->sc_stats;
#if defined(VJC) && !defined(SL_NO_STATS)
if (sc->sc_comp) {
psp->vj.vjs_packets = sc->sc_comp->sls_packets;
psp->vj.vjs_compressed = sc->sc_comp->sls_compressed;
psp->vj.vjs_searches = sc->sc_comp->sls_searches;
psp->vj.vjs_misses = sc->sc_comp->sls_misses;
psp->vj.vjs_uncompressedin = sc->sc_comp->sls_uncompressedin;
psp->vj.vjs_compressedin = sc->sc_comp->sls_compressedin;
psp->vj.vjs_errorin = sc->sc_comp->sls_errorin;
psp->vj.vjs_tossed = sc->sc_comp->sls_tossed;
}
#endif /* VJC */
break;
#ifdef PPP_COMPRESS
case SIOCGPPPCSTATS:
pcp = &((struct ifpppcstatsreq *) data)->stats;
bzero(pcp, sizeof(*pcp));
if (sc->sc_xc_state != NULL)
(*sc->sc_xcomp->comp_stat)(sc->sc_xc_state, &pcp->c);
if (sc->sc_rc_state != NULL)
(*sc->sc_rcomp->decomp_stat)(sc->sc_rc_state, &pcp->d);
break;
#endif /* PPP_COMPRESS */
default:
error = EINVAL;
}
splx(s);
return (error);
}
/*
* Queue a packet. Start transmission if not active.
* Packet is placed in Information field of PPP frame.
*/
int
pppoutput(ifp, m0, dst, rtp)
struct ifnet *ifp;
struct mbuf *m0;
struct sockaddr *dst;
struct rtentry *rtp;
{
register struct ppp_softc *sc = &ppp_softc[ifp->if_unit];
int protocol, address, control;
u_char *cp;
int s, error;
struct ip *ip;
struct ifqueue *ifq;
enum NPmode mode;
int len;
struct mbuf *m;
if (sc->sc_devp == NULL || (ifp->if_flags & IFF_RUNNING) == 0
|| ((ifp->if_flags & IFF_UP) == 0 && dst->sa_family != AF_UNSPEC)) {
error = ENETDOWN; /* sort of */
goto bad;
}
/*
* Compute PPP header.
*/
m0->m_flags &= ~M_HIGHPRI;
switch (dst->sa_family) {
#ifdef INET
case AF_INET:
address = PPP_ALLSTATIONS;
control = PPP_UI;
protocol = PPP_IP;
mode = sc->sc_npmode[NP_IP];
/*
* If this packet has the "low delay" bit set in the IP header,
* put it on the fastq instead.
*/
ip = mtod(m0, struct ip *);
if (ip->ip_tos & IPTOS_LOWDELAY)
m0->m_flags |= M_HIGHPRI;
break;
#endif
case AF_UNSPEC:
address = PPP_ADDRESS(dst->sa_data);
control = PPP_CONTROL(dst->sa_data);
protocol = PPP_PROTOCOL(dst->sa_data);
mode = NPMODE_PASS;
break;
default:
printf("ppp%d: af%d not supported\n", ifp->if_unit, dst->sa_family);
error = EAFNOSUPPORT;
goto bad;
}
/*
* Drop this packet, or return an error, if necessary.
*/
if (mode == NPMODE_ERROR) {
error = ENETDOWN;
goto bad;
}
if (mode == NPMODE_DROP) {
error = 0;
goto bad;
}
/*
* Add PPP header. If no space in first mbuf, allocate another.
* (This assumes M_LEADINGSPACE is always 0 for a cluster mbuf.)
*/
if (M_LEADINGSPACE(m0) < PPP_HDRLEN) {
m0 = m_prepend(m0, PPP_HDRLEN, M_DONTWAIT);
if (m0 == 0) {
error = ENOBUFS;
goto bad;
}
m0->m_len = 0;
} else
m0->m_data -= PPP_HDRLEN;
cp = mtod(m0, u_char *);
*cp++ = address;
*cp++ = control;
*cp++ = protocol >> 8;
*cp++ = protocol & 0xff;
m0->m_len += PPP_HDRLEN;
len = 0;
for (m = m0; m != 0; m = m->m_next)
len += m->m_len;
if (sc->sc_flags & SC_LOG_OUTPKT) {
printf("ppp%d output: ", ifp->if_unit);
pppdumpm(m0);
}
if ((protocol & 0x8000) == 0) {
#ifdef PPP_FILTER
/*
* Apply the pass and active filters to the packet,
* but only if it is a data packet.
*/
*mtod(m0, u_char *) = 1; /* indicates outbound */
if (sc->sc_pass_filt.bf_insns != 0
&& bpf_filter(sc->sc_pass_filt.bf_insns, (u_char *) m0,
len, 0) == 0) {
error = 0; /* drop this packet */
goto bad;
}
/*
* Update the time we sent the most recent packet.
*/
if (sc->sc_active_filt.bf_insns == 0
|| bpf_filter(sc->sc_active_filt.bf_insns, (u_char *) m0, len, 0))
sc->sc_last_sent = time.tv_sec;
*mtod(m0, u_char *) = address;
#else
/*
* Update the time we sent the most recent data packet.
*/
sc->sc_last_sent = time.tv_sec;
#endif /* PPP_FILTER */
}
#if NBPFILTER > 0
/*
* See if bpf wants to look at the packet.
*/
if (sc->sc_bpf)
bpf_mtap(sc->sc_bpf, m0);
#endif
/*
* Put the packet on the appropriate queue.
*/
s = splsoftnet();
if (mode == NPMODE_QUEUE) {
/* XXX we should limit the number of packets on this queue */
*sc->sc_npqtail = m0;
m0->m_nextpkt = NULL;
sc->sc_npqtail = &m0->m_nextpkt;
} else {
ifq = (m0->m_flags & M_HIGHPRI)? &sc->sc_fastq: &ifp->if_snd;
if (IF_QFULL(ifq) && dst->sa_family != AF_UNSPEC) {
IF_DROP(ifq);
splx(s);
sc->sc_if.if_oerrors++;
sc->sc_stats.ppp_oerrors++;
error = ENOBUFS;
goto bad;
}
IF_ENQUEUE(ifq, m0);
(*sc->sc_start)(sc);
}
ifp->if_lastchange = time;
ifp->if_opackets++;
ifp->if_obytes += len;
splx(s);
return (0);
bad:
m_freem(m0);
return (error);
}
/*
* After a change in the NPmode for some NP, move packets from the
* npqueue to the send queue or the fast queue as appropriate.
* Should be called at splsoftnet.
*/
static void
ppp_requeue(sc)
struct ppp_softc *sc;
{
struct mbuf *m, **mpp;
struct ifqueue *ifq;
enum NPmode mode;
for (mpp = &sc->sc_npqueue; (m = *mpp) != NULL; ) {
switch (PPP_PROTOCOL(mtod(m, u_char *))) {
case PPP_IP:
mode = sc->sc_npmode[NP_IP];
break;
default:
mode = NPMODE_PASS;
}
switch (mode) {
case NPMODE_PASS:
/*
* This packet can now go on one of the queues to be sent.
*/
*mpp = m->m_nextpkt;
m->m_nextpkt = NULL;
ifq = (m->m_flags & M_HIGHPRI)? &sc->sc_fastq: &sc->sc_if.if_snd;
if (IF_QFULL(ifq)) {
IF_DROP(ifq);
sc->sc_if.if_oerrors++;
sc->sc_stats.ppp_oerrors++;
} else
IF_ENQUEUE(ifq, m);
break;
case NPMODE_DROP:
case NPMODE_ERROR:
*mpp = m->m_nextpkt;
m_freem(m);
break;
case NPMODE_QUEUE:
mpp = &m->m_nextpkt;
break;
}
}
sc->sc_npqtail = mpp;
}
/*
* Transmitter has finished outputting some stuff;
* remember to call sc->sc_start later at splsoftnet.
*/
void
ppp_restart(sc)
struct ppp_softc *sc;
{
int s = splimp();
sc->sc_flags &= ~SC_TBUSY;
schednetisr(NETISR_PPP);
splx(s);
}
/*
* Get a packet to send. This procedure is intended to be called at
* splsoftnet, since it may involve time-consuming operations such as
* applying VJ compression, packet compression, address/control and/or
* protocol field compression to the packet.
*/
struct mbuf *
ppp_dequeue(sc)
struct ppp_softc *sc;
{
struct mbuf *m, *mp;
u_char *cp;
int address, control, protocol;
/*
* Grab a packet to send: first try the fast queue, then the
* normal queue.
*/
IF_DEQUEUE(&sc->sc_fastq, m);
if (m == NULL)
IF_DEQUEUE(&sc->sc_if.if_snd, m);
if (m == NULL)
return NULL;
++sc->sc_stats.ppp_opackets;
/*
* Extract the ppp header of the new packet.
* The ppp header will be in one mbuf.
*/
cp = mtod(m, u_char *);
address = PPP_ADDRESS(cp);
control = PPP_CONTROL(cp);
protocol = PPP_PROTOCOL(cp);
switch (protocol) {
case PPP_IP:
#ifdef VJC
/*
* If the packet is a TCP/IP packet, see if we can compress it.
*/
if ((sc->sc_flags & SC_COMP_TCP) && sc->sc_comp != NULL) {
struct ip *ip;
int type;
mp = m;
ip = (struct ip *) (cp + PPP_HDRLEN);
if (mp->m_len <= PPP_HDRLEN) {
mp = mp->m_next;
if (mp == NULL)
break;
ip = mtod(mp, struct ip *);
}
/* this code assumes the IP/TCP header is in one non-shared mbuf */
if (ip->ip_p == IPPROTO_TCP) {
type = vj_compress_tcp(mp, ip, sc->sc_comp,
!(sc->sc_flags & SC_NO_TCP_CCID));
switch (type) {
case TYPE_UNCOMPRESSED_TCP:
protocol = PPP_VJC_UNCOMP;
break;
case TYPE_COMPRESSED_TCP:
protocol = PPP_VJC_COMP;
cp = mtod(m, u_char *);
cp[0] = address; /* header has moved */
cp[1] = control;
cp[2] = 0;
break;
}
cp[3] = protocol; /* update protocol in PPP header */
}
}
#endif /* VJC */
break;
#ifdef PPP_COMPRESS
case PPP_CCP:
ppp_ccp(sc, m, 0);
break;
#endif /* PPP_COMPRESS */
}
#ifdef PPP_COMPRESS
if (protocol != PPP_LCP && protocol != PPP_CCP
&& sc->sc_xc_state && (sc->sc_flags & SC_COMP_RUN)) {
struct mbuf *mcomp = NULL;
int slen, clen;
slen = 0;
for (mp = m; mp != NULL; mp = mp->m_next)
slen += mp->m_len;
clen = (*sc->sc_xcomp->compress)
(sc->sc_xc_state, &mcomp, m, slen, sc->sc_if.if_mtu + PPP_HDRLEN);
if (mcomp != NULL) {
if (sc->sc_flags & SC_CCP_UP) {
/* Send the compressed packet instead of the original. */
m_freem(m);
m = mcomp;
cp = mtod(m, u_char *);
protocol = cp[3];
} else {
/* Can't transmit compressed packets until CCP is up. */
m_freem(mcomp);
}
}
}
#endif /* PPP_COMPRESS */
/*
* Compress the address/control and protocol, if possible.
*/
if (sc->sc_flags & SC_COMP_AC && address == PPP_ALLSTATIONS &&
control == PPP_UI && protocol != PPP_ALLSTATIONS &&
protocol != PPP_LCP) {
/* can compress address/control */
m->m_data += 2;
m->m_len -= 2;
}
if (sc->sc_flags & SC_COMP_PROT && protocol < 0xFF) {
/* can compress protocol */
if (mtod(m, u_char *) == cp) {
cp[2] = cp[1]; /* move address/control up */
cp[1] = cp[0];
}
++m->m_data;
--m->m_len;
}
return m;
}
/*
* Software interrupt routine, called at splsoftnet.
*/
void
pppintr()
{
struct ppp_softc *sc;
int i, s, s2;
struct mbuf *m;
sc = ppp_softc;
s = splsoftnet();
for (i = 0; i < NPPP; ++i, ++sc) {
if (!(sc->sc_flags & SC_TBUSY)
&& (sc->sc_if.if_snd.ifq_head || sc->sc_fastq.ifq_head)) {
s2 = splimp();
sc->sc_flags |= SC_TBUSY;
splx(s2);
(*sc->sc_start)(sc);
}
for (;;) {
s2 = splimp();
IF_DEQUEUE(&sc->sc_rawq, m);
splx(s2);
if (m == NULL)
break;
ppp_inproc(sc, m);
}
}
splx(s);
}
#ifdef PPP_COMPRESS
/*
* Handle a CCP packet. `rcvd' is 1 if the packet was received,
* 0 if it is about to be transmitted.
*/
static void
ppp_ccp(sc, m, rcvd)
struct ppp_softc *sc;
struct mbuf *m;
int rcvd;
{
u_char *dp, *ep;
struct mbuf *mp;
int slen, s;
/*
* Get a pointer to the data after the PPP header.
*/
if (m->m_len <= PPP_HDRLEN) {
mp = m->m_next;
if (mp == NULL)
return;
dp = (mp != NULL)? mtod(mp, u_char *): NULL;
} else {
mp = m;
dp = mtod(mp, u_char *) + PPP_HDRLEN;
}
ep = mtod(mp, u_char *) + mp->m_len;
if (dp + CCP_HDRLEN > ep)
return;
slen = CCP_LENGTH(dp);
if (dp + slen > ep) {
if (sc->sc_flags & SC_DEBUG)
printf("if_ppp/ccp: not enough data in mbuf (%p+%x > %p+%x)\n",
dp, slen, mtod(mp, u_char *), mp->m_len);
return;
}
switch (CCP_CODE(dp)) {
case CCP_CONFREQ:
case CCP_TERMREQ:
case CCP_TERMACK:
/* CCP must be going down - disable compression */
if (sc->sc_flags & SC_CCP_UP) {
s = splimp();
sc->sc_flags &= ~(SC_CCP_UP | SC_COMP_RUN | SC_DECOMP_RUN);
splx(s);
}
break;
case CCP_CONFACK:
if (sc->sc_flags & SC_CCP_OPEN && !(sc->sc_flags & SC_CCP_UP)
&& slen >= CCP_HDRLEN + CCP_OPT_MINLEN
&& slen >= CCP_OPT_LENGTH(dp + CCP_HDRLEN) + CCP_HDRLEN) {
if (!rcvd) {
/* we're agreeing to send compressed packets. */
if (sc->sc_xc_state != NULL
&& (*sc->sc_xcomp->comp_init)
(sc->sc_xc_state, dp + CCP_HDRLEN, slen - CCP_HDRLEN,
sc->sc_if.if_unit, 0, sc->sc_flags & SC_DEBUG)) {
s = splimp();
sc->sc_flags |= SC_COMP_RUN;
splx(s);
}
} else {
/* peer is agreeing to send compressed packets. */
if (sc->sc_rc_state != NULL
&& (*sc->sc_rcomp->decomp_init)
(sc->sc_rc_state, dp + CCP_HDRLEN, slen - CCP_HDRLEN,
sc->sc_if.if_unit, 0, sc->sc_mru,
sc->sc_flags & SC_DEBUG)) {
s = splimp();
sc->sc_flags |= SC_DECOMP_RUN;
sc->sc_flags &= ~(SC_DC_ERROR | SC_DC_FERROR);
splx(s);
}
}
}
break;
case CCP_RESETACK:
if (sc->sc_flags & SC_CCP_UP) {
if (!rcvd) {
if (sc->sc_xc_state && (sc->sc_flags & SC_COMP_RUN))
(*sc->sc_xcomp->comp_reset)(sc->sc_xc_state);
} else {
if (sc->sc_rc_state && (sc->sc_flags & SC_DECOMP_RUN)) {
(*sc->sc_rcomp->decomp_reset)(sc->sc_rc_state);
s = splimp();
sc->sc_flags &= ~SC_DC_ERROR;
splx(s);
}
}
}
break;
}
}
/*
* CCP is down; free (de)compressor state if necessary.
*/
static void
ppp_ccp_closed(sc)
struct ppp_softc *sc;
{
if (sc->sc_xc_state) {
(*sc->sc_xcomp->comp_free)(sc->sc_xc_state);
sc->sc_xc_state = NULL;
}
if (sc->sc_rc_state) {
(*sc->sc_rcomp->decomp_free)(sc->sc_rc_state);
sc->sc_rc_state = NULL;
}
}
#endif /* PPP_COMPRESS */
/*
* PPP packet input routine.
* The caller has checked and removed the FCS and has inserted
* the address/control bytes and the protocol high byte if they
* were omitted.
*/
void
ppppktin(sc, m, lost)
struct ppp_softc *sc;
struct mbuf *m;
int lost;
{
int s = splimp();
if (lost)
m->m_flags |= M_ERRMARK;
IF_ENQUEUE(&sc->sc_rawq, m);
schednetisr(NETISR_PPP);
splx(s);
}
/*
* Process a received PPP packet, doing decompression as necessary.
* Should be called at splsoftnet.
*/
#define COMPTYPE(proto) ((proto) == PPP_VJC_COMP? TYPE_COMPRESSED_TCP: \
TYPE_UNCOMPRESSED_TCP)
static void
ppp_inproc(sc, m)
struct ppp_softc *sc;
struct mbuf *m;
{
struct ifnet *ifp = &sc->sc_if;
struct ifqueue *inq;
int s, ilen, xlen, proto, rv;
u_char *cp, adrs, ctrl;
struct mbuf *mp, *dmp = NULL;
u_char *iphdr;
u_int hlen;
sc->sc_stats.ppp_ipackets++;
if (sc->sc_flags & SC_LOG_INPKT) {
ilen = 0;
for (mp = m; mp != NULL; mp = mp->m_next)
ilen += mp->m_len;
printf("ppp%d: got %d bytes\n", ifp->if_unit, ilen);
pppdumpm(m);
}
cp = mtod(m, u_char *);
adrs = PPP_ADDRESS(cp);
ctrl = PPP_CONTROL(cp);
proto = PPP_PROTOCOL(cp);
if (m->m_flags & M_ERRMARK) {
m->m_flags &= ~M_ERRMARK;
s = splimp();
sc->sc_flags |= SC_VJ_RESET;
splx(s);
}
#ifdef PPP_COMPRESS
/*
* Decompress this packet if necessary, update the receiver's
* dictionary, or take appropriate action on a CCP packet.
*/
if (proto == PPP_COMP && sc->sc_rc_state && (sc->sc_flags & SC_DECOMP_RUN)
&& !(sc->sc_flags & SC_DC_ERROR) && !(sc->sc_flags & SC_DC_FERROR)) {
/* decompress this packet */
rv = (*sc->sc_rcomp->decompress)(sc->sc_rc_state, m, &dmp);
if (rv == DECOMP_OK) {
m_freem(m);
if (dmp == NULL) {
/* no error, but no decompressed packet produced */
return;
}
m = dmp;
cp = mtod(m, u_char *);
proto = PPP_PROTOCOL(cp);
} else {
/*
* An error has occurred in decompression.
* Pass the compressed packet up to pppd, which may take
* CCP down or issue a Reset-Req.
*/
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: decompress failed %d\n", ifp->if_unit, rv);
s = splimp();
sc->sc_flags |= SC_VJ_RESET;
if (rv == DECOMP_ERROR)
sc->sc_flags |= SC_DC_ERROR;
else
sc->sc_flags |= SC_DC_FERROR;
splx(s);
}
} else {
if (sc->sc_rc_state && (sc->sc_flags & SC_DECOMP_RUN)) {
(*sc->sc_rcomp->incomp)(sc->sc_rc_state, m);
}
if (proto == PPP_CCP) {
ppp_ccp(sc, m, 1);
}
}
#endif
ilen = 0;
for (mp = m; mp != NULL; mp = mp->m_next)
ilen += mp->m_len;
#ifdef VJC
if (sc->sc_flags & SC_VJ_RESET) {
/*
* If we've missed a packet, we must toss subsequent compressed
* packets which don't have an explicit connection ID.
*/
if (sc->sc_comp)
vj_uncompress_tcp(NULL, 0, TYPE_ERROR, sc->sc_comp);
s = splimp();
sc->sc_flags &= ~SC_VJ_RESET;
splx(s);
}
/*
* See if we have a VJ-compressed packet to uncompress.
*/
if (proto == PPP_VJC_COMP) {
if ((sc->sc_flags & SC_REJ_COMP_TCP) || sc->sc_comp == 0)
goto bad;
xlen = vj_uncompress_tcp_core(cp + PPP_HDRLEN, m->m_len - PPP_HDRLEN,
ilen - PPP_HDRLEN, TYPE_COMPRESSED_TCP,
sc->sc_comp, &iphdr, &hlen);
if (xlen <= 0) {
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: VJ uncompress failed on type comp\n",
ifp->if_unit);
goto bad;
}
/* Copy the PPP and IP headers into a new mbuf. */
MGETHDR(mp, M_DONTWAIT, MT_DATA);
if (mp == NULL)
goto bad;
mp->m_len = 0;
mp->m_next = NULL;
if (hlen + PPP_HDRLEN > MHLEN) {
MCLGET(mp, M_DONTWAIT);
if (M_TRAILINGSPACE(mp) < hlen + PPP_HDRLEN) {
m_freem(mp);
goto bad; /* lose if big headers and no clusters */
}
}
cp = mtod(mp, u_char *);
cp[0] = adrs;
cp[1] = ctrl;
cp[2] = 0;
cp[3] = PPP_IP;
proto = PPP_IP;
bcopy(iphdr, cp + PPP_HDRLEN, hlen);
mp->m_len = hlen + PPP_HDRLEN;
/*
* Trim the PPP and VJ headers off the old mbuf
* and stick the new and old mbufs together.
*/
m->m_data += PPP_HDRLEN + xlen;
m->m_len -= PPP_HDRLEN + xlen;
if (m->m_len <= M_TRAILINGSPACE(mp)) {
bcopy(mtod(m, u_char *), mtod(mp, u_char *) + mp->m_len, m->m_len);
mp->m_len += m->m_len;
MFREE(m, mp->m_next);
} else
mp->m_next = m;
m = mp;
ilen += hlen - xlen;
} else if (proto == PPP_VJC_UNCOMP) {
if ((sc->sc_flags & SC_REJ_COMP_TCP) || sc->sc_comp == 0)
goto bad;
xlen = vj_uncompress_tcp_core(cp + PPP_HDRLEN, m->m_len - PPP_HDRLEN,
ilen - PPP_HDRLEN, TYPE_UNCOMPRESSED_TCP,
sc->sc_comp, &iphdr, &hlen);
if (xlen < 0) {
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: VJ uncompress failed on type uncomp\n",
ifp->if_unit);
goto bad;
}
proto = PPP_IP;
cp[3] = PPP_IP;
}
#endif /* VJC */
/*
* If the packet will fit in a header mbuf, don't waste a
* whole cluster on it.
*/
if (ilen <= MHLEN && M_IS_CLUSTER(m)) {
MGETHDR(mp, M_DONTWAIT, MT_DATA);
if (mp != NULL) {
m_copydata(m, 0, ilen, mtod(mp, caddr_t));
m_freem(m);
m = mp;
m->m_len = ilen;
}
}
m->m_pkthdr.len = ilen;
m->m_pkthdr.rcvif = ifp;
if ((proto & 0x8000) == 0) {
#ifdef PPP_FILTER
/*
* See whether we want to pass this packet, and
* if it counts as link activity.
*/
adrs = *mtod(m, u_char *); /* save address field */
*mtod(m, u_char *) = 0; /* indicate inbound */
if (sc->sc_pass_filt.bf_insns != 0
&& bpf_filter(sc->sc_pass_filt.bf_insns, (u_char *) m,
ilen, 0) == 0) {
/* drop this packet */
m_freem(m);
return;
}
if (sc->sc_active_filt.bf_insns == 0
|| bpf_filter(sc->sc_active_filt.bf_insns, (u_char *) m, ilen, 0))
sc->sc_last_recv = time.tv_sec;
*mtod(m, u_char *) = adrs;
#else
/*
* Record the time that we received this packet.
*/
sc->sc_last_recv = time.tv_sec;
#endif /* PPP_FILTER */
}
#if NBPFILTER > 0
/* See if bpf wants to look at the packet. */
if (sc->sc_bpf)
bpf_mtap(sc->sc_bpf, m);
#endif
rv = 0;
switch (proto) {
#ifdef INET
case PPP_IP:
/*
* IP packet - take off the ppp header and pass it up to IP.
*/
if ((ifp->if_flags & IFF_UP) == 0
|| sc->sc_npmode[NP_IP] != NPMODE_PASS) {
/* interface is down - drop the packet. */
m_freem(m);
return;
}
m->m_pkthdr.len -= PPP_HDRLEN;
m->m_data += PPP_HDRLEN;
m->m_len -= PPP_HDRLEN;
schednetisr(NETISR_IP);
inq = &ipintrq;
break;
#endif
default:
/*
* Some other protocol - place on input queue for read().
*/
inq = &sc->sc_inq;
rv = 1;
break;
}
/*
* Put the packet on the appropriate input queue.
*/
s = splimp();
if (IF_QFULL(inq)) {
IF_DROP(inq);
splx(s);
if (sc->sc_flags & SC_DEBUG)
printf("ppp%d: input queue full\n", ifp->if_unit);
ifp->if_iqdrops++;
goto bad;
}
IF_ENQUEUE(inq, m);
splx(s);
ifp->if_ipackets++;
ifp->if_ibytes += ilen;
ifp->if_lastchange = time;
if (rv)
(*sc->sc_ctlp)(sc);
return;
bad:
m_freem(m);
sc->sc_if.if_ierrors++;
sc->sc_stats.ppp_ierrors++;
}
#define MAX_DUMP_BYTES 128
static void
pppdumpm(m0)
struct mbuf *m0;
{
char buf[3*MAX_DUMP_BYTES+4];
char *bp = buf;
struct mbuf *m;
static char digits[] = "0123456789abcdef";
for (m = m0; m; m = m->m_next) {
int l = m->m_len;
u_char *rptr = (u_char *)m->m_data;
while (l--) {
if (bp > buf + sizeof(buf) - 4)
goto done;
*bp++ = digits[*rptr >> 4]; /* convert byte to ascii hex */
*bp++ = digits[*rptr++ & 0xf];
}
if (m->m_next) {
if (bp > buf + sizeof(buf) - 3)
goto done;
*bp++ = '|';
} else
*bp++ = ' ';
}
done:
if (m)
*bp++ = '>';
*bp = 0;
printf("%s\n", buf);
}
#endif /* NPPP > 0 */
| gpl-2.0 |
TEAM-Gummy/kernel_oppo_msm8974 | drivers/mmc/card/block.c | 87783 | /*
* Block driver for media (i.e., flash cards)
*
* Copyright 2002 Hewlett-Packard Company
* Copyright 2005-2008 Pierre Ossman
*
* Use consistent with the GNU GPL is permitted,
* provided that this copyright notice is
* preserved in its entirety in all copies and derived works.
*
* HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
* AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
* FITNESS FOR ANY PARTICULAR PURPOSE.
*
* Many thanks to Alessandro Rubini and Jonathan Corbet!
*
* Author: Andrew Christian
* 28 May 2002
*/
#include <linux/moduleparam.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/hdreg.h>
#include <linux/kdev_t.h>
#include <linux/blkdev.h>
#include <linux/mutex.h>
#include <linux/scatterlist.h>
#include <linux/string_helpers.h>
#include <linux/delay.h>
#include <linux/capability.h>
#include <linux/compat.h>
#include <linux/pm_runtime.h>
#include <linux/mmc/ioctl.h>
#include <linux/mmc/card.h>
#include <linux/mmc/host.h>
#include <linux/mmc/mmc.h>
#include <linux/mmc/sd.h>
#include <asm/uaccess.h>
#include "queue.h"
#ifdef CONFIG_VENDOR_EDIT
//[email protected], 2013/10/24, Add for eMMC and DDR device information
#include <mach/device_info.h>
#include <linux/pcb_version.h>
#endif /* VENDOR_EDIT */
MODULE_ALIAS("mmc:block");
#ifdef MODULE_PARAM_PREFIX
#undef MODULE_PARAM_PREFIX
#endif
#define MODULE_PARAM_PREFIX "mmcblk."
#define INAND_CMD38_ARG_EXT_CSD 113
#define INAND_CMD38_ARG_ERASE 0x00
#define INAND_CMD38_ARG_TRIM 0x01
#define INAND_CMD38_ARG_SECERASE 0x80
#define INAND_CMD38_ARG_SECTRIM1 0x81
#define INAND_CMD38_ARG_SECTRIM2 0x88
#define MMC_BLK_TIMEOUT_MS (30 * 1000) /* 30 sec timeout */
#define MMC_SANITIZE_REQ_TIMEOUT 240000 /* msec */
#define mmc_req_rel_wr(req) (((req->cmd_flags & REQ_FUA) || \
(req->cmd_flags & REQ_META)) && \
(rq_data_dir(req) == WRITE))
#define PACKED_CMD_VER 0x01
#define PACKED_CMD_WR 0x02
#define PACKED_TRIGGER_MAX_ELEMENTS 5000
#define MMC_BLK_UPDATE_STOP_REASON(stats, reason) \
do { \
if (stats->enabled) \
stats->pack_stop_reason[reason]++; \
} while (0)
#define PCKD_TRGR_INIT_MEAN_POTEN 17
#define PCKD_TRGR_POTEN_LOWER_BOUND 5
#define PCKD_TRGR_URGENT_PENALTY 2
#define PCKD_TRGR_LOWER_BOUND 5
#define PCKD_TRGR_PRECISION_MULTIPLIER 100
static DEFINE_MUTEX(block_mutex);
/*
* The defaults come from config options but can be overriden by module
* or bootarg options.
*/
static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
/*
* We've only got one major, so number of mmcblk devices is
* limited to 256 / number of minors per device.
*/
static int max_devices;
/* 256 minors, so at most 256 separate devices */
static DECLARE_BITMAP(dev_use, 256);
static DECLARE_BITMAP(name_use, 256);
/*
* There is one mmc_blk_data per slot.
*/
struct mmc_blk_data {
spinlock_t lock;
struct gendisk *disk;
struct mmc_queue queue;
struct list_head part;
unsigned int flags;
#define MMC_BLK_CMD23 (1 << 0) /* Can do SET_BLOCK_COUNT for multiblock */
#define MMC_BLK_REL_WR (1 << 1) /* MMC Reliable write support */
unsigned int usage;
unsigned int read_only;
unsigned int part_type;
unsigned int name_idx;
unsigned int reset_done;
#define MMC_BLK_READ BIT(0)
#define MMC_BLK_WRITE BIT(1)
#define MMC_BLK_DISCARD BIT(2)
#define MMC_BLK_SECDISCARD BIT(3)
/*
* Only set in main mmc_blk_data associated
* with mmc_card with mmc_set_drvdata, and keeps
* track of the current selected device partition.
*/
unsigned int part_curr;
struct device_attribute force_ro;
struct device_attribute power_ro_lock;
struct device_attribute num_wr_reqs_to_start_packing;
struct device_attribute bkops_check_threshold;
struct device_attribute no_pack_for_random;
int area_type;
};
static DEFINE_MUTEX(open_lock);
enum {
MMC_PACKED_N_IDX = -1,
MMC_PACKED_N_ZERO,
MMC_PACKED_N_SINGLE,
};
module_param(perdev_minors, int, 0444);
MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md);
static int get_card_status(struct mmc_card *card, u32 *status, int retries);
static inline void mmc_blk_clear_packed(struct mmc_queue_req *mqrq)
{
mqrq->packed_cmd = MMC_PACKED_NONE;
mqrq->packed_num = MMC_PACKED_N_ZERO;
}
static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
{
struct mmc_blk_data *md;
mutex_lock(&open_lock);
md = disk->private_data;
if (md && md->usage == 0)
md = NULL;
if (md)
md->usage++;
mutex_unlock(&open_lock);
return md;
}
static inline int mmc_get_devidx(struct gendisk *disk)
{
int devidx = disk->first_minor / perdev_minors;
return devidx;
}
static void mmc_blk_put(struct mmc_blk_data *md)
{
mutex_lock(&open_lock);
md->usage--;
if (md->usage == 0) {
int devidx = mmc_get_devidx(md->disk);
blk_cleanup_queue(md->queue.queue);
__clear_bit(devidx, dev_use);
put_disk(md->disk);
kfree(md);
}
mutex_unlock(&open_lock);
}
static ssize_t power_ro_lock_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card;
int locked = 0;
if (!md)
return -EINVAL;
card = md->queue.card;
if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
locked = 2;
else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
locked = 1;
ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
return ret;
}
static ssize_t power_ro_lock_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
int ret;
struct mmc_blk_data *md, *part_md;
struct mmc_card *card;
unsigned long set;
if (kstrtoul(buf, 0, &set))
return -EINVAL;
if (set != 1)
return count;
md = mmc_blk_get(dev_to_disk(dev));
if (!md)
return -EINVAL;
card = md->queue.card;
mmc_rpm_hold(card->host, &card->dev);
mmc_claim_host(card->host);
ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
card->ext_csd.boot_ro_lock |
EXT_CSD_BOOT_WP_B_PWR_WP_EN,
card->ext_csd.part_time);
if (ret)
pr_err("%s: Locking boot partition ro until next power on failed: %d\n", md->disk->disk_name, ret);
else
card->ext_csd.boot_ro_lock |= EXT_CSD_BOOT_WP_B_PWR_WP_EN;
mmc_release_host(card->host);
mmc_rpm_release(card->host, &card->dev);
if (!ret) {
pr_info("%s: Locking boot partition ro until next power on\n",
md->disk->disk_name);
set_disk_ro(md->disk, 1);
list_for_each_entry(part_md, &md->part, part)
if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
set_disk_ro(part_md->disk, 1);
}
}
mmc_blk_put(md);
return count;
}
static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
int ret;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
if (!md)
return -EINVAL;
ret = snprintf(buf, PAGE_SIZE, "%d",
get_disk_ro(dev_to_disk(dev)) ^
md->read_only);
mmc_blk_put(md);
return ret;
}
static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
int ret;
char *end;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
unsigned long set = simple_strtoul(buf, &end, 0);
if (!md)
return -EINVAL;
if (end == buf) {
ret = -EINVAL;
goto out;
}
set_disk_ro(dev_to_disk(dev), set || md->read_only);
ret = count;
out:
mmc_blk_put(md);
return ret;
}
static ssize_t
num_wr_reqs_to_start_packing_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
int num_wr_reqs_to_start_packing;
int ret;
if (!md)
return -EINVAL;
num_wr_reqs_to_start_packing = md->queue.num_wr_reqs_to_start_packing;
ret = snprintf(buf, PAGE_SIZE, "%d\n", num_wr_reqs_to_start_packing);
mmc_blk_put(md);
return ret;
}
static ssize_t
num_wr_reqs_to_start_packing_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card;
int ret = count;
if (!md)
return -EINVAL;
card = md->queue.card;
if (!card) {
ret = -EINVAL;
goto exit;
}
sscanf(buf, "%d", &value);
if (value >= 0) {
md->queue.num_wr_reqs_to_start_packing =
min_t(int, value, (int)card->ext_csd.max_packed_writes);
pr_debug("%s: trigger to pack: new value = %d",
mmc_hostname(card->host),
md->queue.num_wr_reqs_to_start_packing);
} else {
pr_err("%s: value %d is not valid. old value remains = %d",
mmc_hostname(card->host), value,
md->queue.num_wr_reqs_to_start_packing);
ret = -EINVAL;
}
exit:
mmc_blk_put(md);
return ret;
}
static ssize_t
bkops_check_threshold_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card;
int ret;
if (!md)
return -EINVAL;
card = md->queue.card;
if (!card)
ret = -EINVAL;
else
ret = snprintf(buf, PAGE_SIZE, "%d\n",
card->bkops_info.size_percentage_to_queue_delayed_work);
mmc_blk_put(md);
return ret;
}
static ssize_t
bkops_check_threshold_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card;
unsigned int card_size;
int ret = count;
if (!md)
return -EINVAL;
card = md->queue.card;
if (!card) {
ret = -EINVAL;
goto exit;
}
sscanf(buf, "%d", &value);
if ((value <= 0) || (value >= 100)) {
ret = -EINVAL;
goto exit;
}
card_size = (unsigned int)get_capacity(md->disk);
if (card_size <= 0) {
ret = -EINVAL;
goto exit;
}
card->bkops_info.size_percentage_to_queue_delayed_work = value;
card->bkops_info.min_sectors_to_queue_delayed_work =
(card_size * value) / 100;
pr_debug("%s: size_percentage = %d, min_sectors = %d",
mmc_hostname(card->host),
card->bkops_info.size_percentage_to_queue_delayed_work,
card->bkops_info.min_sectors_to_queue_delayed_work);
exit:
mmc_blk_put(md);
return count;
}
static ssize_t
no_pack_for_random_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
int ret;
if (!md)
return -EINVAL;
ret = snprintf(buf, PAGE_SIZE, "%d\n", md->queue.no_pack_for_random);
mmc_blk_put(md);
return ret;
}
static ssize_t
no_pack_for_random_store(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
int value;
struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
struct mmc_card *card;
int ret = count;
if (!md)
return -EINVAL;
card = md->queue.card;
if (!card) {
ret = -EINVAL;
goto exit;
}
sscanf(buf, "%d", &value);
if (value < 0) {
pr_err("%s: value %d is not valid. old value remains = %d",
mmc_hostname(card->host), value,
md->queue.no_pack_for_random);
ret = -EINVAL;
goto exit;
}
md->queue.no_pack_for_random = (value > 0) ? true : false;
pr_debug("%s: no_pack_for_random: new value = %d",
mmc_hostname(card->host),
md->queue.no_pack_for_random);
exit:
mmc_blk_put(md);
return ret;
}
static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
{
struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
int ret = -ENXIO;
mutex_lock(&block_mutex);
if (md) {
if (md->usage == 2)
check_disk_change(bdev);
ret = 0;
if ((mode & FMODE_WRITE) && md->read_only) {
mmc_blk_put(md);
ret = -EROFS;
}
}
mutex_unlock(&block_mutex);
return ret;
}
static int mmc_blk_release(struct gendisk *disk, fmode_t mode)
{
struct mmc_blk_data *md = disk->private_data;
mutex_lock(&block_mutex);
mmc_blk_put(md);
mutex_unlock(&block_mutex);
return 0;
}
static int
mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
{
geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
geo->heads = 4;
geo->sectors = 16;
return 0;
}
struct mmc_blk_ioc_data {
struct mmc_ioc_cmd ic;
unsigned char *buf;
u64 buf_bytes;
};
static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
struct mmc_ioc_cmd __user *user)
{
struct mmc_blk_ioc_data *idata;
int err;
idata = kzalloc(sizeof(*idata), GFP_KERNEL);
if (!idata) {
err = -ENOMEM;
goto out;
}
if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
err = -EFAULT;
goto idata_err;
}
idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
err = -EOVERFLOW;
goto idata_err;
}
if (!idata->buf_bytes)
return idata;
idata->buf = kzalloc(idata->buf_bytes, GFP_KERNEL);
if (!idata->buf) {
err = -ENOMEM;
goto idata_err;
}
if (copy_from_user(idata->buf, (void __user *)(unsigned long)
idata->ic.data_ptr, idata->buf_bytes)) {
err = -EFAULT;
goto copy_err;
}
return idata;
copy_err:
kfree(idata->buf);
idata_err:
kfree(idata);
out:
return ERR_PTR(err);
}
static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
u32 retries_max)
{
int err;
u32 retry_count = 0;
if (!status || !retries_max)
return -EINVAL;
do {
err = get_card_status(card, status, 5);
if (err)
break;
if (!R1_STATUS(*status) &&
(R1_CURRENT_STATE(*status) != R1_STATE_PRG))
break; /* RPMB programming operation complete */
/*
* Rechedule to give the MMC device a chance to continue
* processing the previous command without being polled too
* frequently.
*/
usleep_range(1000, 5000);
} while (++retry_count < retries_max);
if (retry_count == retries_max)
err = -EPERM;
return err;
}
static int mmc_blk_ioctl_cmd(struct block_device *bdev,
struct mmc_ioc_cmd __user *ic_ptr)
{
struct mmc_blk_ioc_data *idata;
struct mmc_blk_data *md;
struct mmc_card *card;
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct mmc_request mrq = {NULL};
struct scatterlist sg;
int err;
/*
* The caller must have CAP_SYS_RAWIO, and must be calling this on the
* whole block device, not on a partition. This prevents overspray
* between sibling partitions.
*/
if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
return -EPERM;
idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
if (IS_ERR(idata))
return PTR_ERR(idata);
md = mmc_blk_get(bdev->bd_disk);
if (!md) {
err = -EINVAL;
goto blk_err;
}
card = md->queue.card;
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto cmd_done;
}
cmd.opcode = idata->ic.opcode;
cmd.arg = idata->ic.arg;
cmd.flags = idata->ic.flags;
if (idata->buf_bytes) {
data.sg = &sg;
data.sg_len = 1;
data.blksz = idata->ic.blksz;
data.blocks = idata->ic.blocks;
sg_init_one(data.sg, idata->buf, idata->buf_bytes);
if (idata->ic.write_flag)
data.flags = MMC_DATA_WRITE;
else
data.flags = MMC_DATA_READ;
/* data.flags must already be set before doing this. */
mmc_set_data_timeout(&data, card);
/* Allow overriding the timeout_ns for empirical tuning. */
if (idata->ic.data_timeout_ns)
data.timeout_ns = idata->ic.data_timeout_ns;
if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
/*
* Pretend this is a data transfer and rely on the
* host driver to compute timeout. When all host
* drivers support cmd.cmd_timeout for R1B, this
* can be changed to:
*
* mrq.data = NULL;
* cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
*/
data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
}
mrq.data = &data;
}
mrq.cmd = &cmd;
mmc_rpm_hold(card->host, &card->dev);
mmc_claim_host(card->host);
err = mmc_blk_part_switch(card, md);
if (err)
goto cmd_rel_host;
if (idata->ic.is_acmd) {
err = mmc_app_cmd(card->host, card);
if (err)
goto cmd_rel_host;
}
mmc_wait_for_req(card->host, &mrq);
if (cmd.error) {
dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
__func__, cmd.error);
err = cmd.error;
goto cmd_rel_host;
}
if (data.error) {
dev_err(mmc_dev(card->host), "%s: data error %d\n",
__func__, data.error);
err = data.error;
goto cmd_rel_host;
}
/*
* According to the SD specs, some commands require a delay after
* issuing the command.
*/
if (idata->ic.postsleep_min_us)
usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
if (copy_to_user(&(ic_ptr->response), cmd.resp, sizeof(cmd.resp))) {
err = -EFAULT;
goto cmd_rel_host;
}
if (!idata->ic.write_flag) {
if (copy_to_user((void __user *)(unsigned long) idata->ic.data_ptr,
idata->buf, idata->buf_bytes)) {
err = -EFAULT;
goto cmd_rel_host;
}
}
cmd_rel_host:
mmc_release_host(card->host);
mmc_rpm_release(card->host, &card->dev);
cmd_done:
mmc_blk_put(md);
blk_err:
kfree(idata->buf);
kfree(idata);
return err;
}
struct mmc_blk_ioc_rpmb_data {
struct mmc_blk_ioc_data *data[MMC_IOC_MAX_RPMB_CMD];
};
static struct mmc_blk_ioc_rpmb_data *mmc_blk_ioctl_rpmb_copy_from_user(
struct mmc_ioc_rpmb __user *user)
{
struct mmc_blk_ioc_rpmb_data *idata;
int err, i;
idata = kzalloc(sizeof(*idata), GFP_KERNEL);
if (!idata) {
err = -ENOMEM;
goto out;
}
for (i = 0; i < MMC_IOC_MAX_RPMB_CMD; i++) {
idata->data[i] = mmc_blk_ioctl_copy_from_user(&(user->cmds[i]));
if (IS_ERR(idata->data[i])) {
err = PTR_ERR(idata->data[i]);
goto copy_err;
}
}
return idata;
copy_err:
while (--i >= 0) {
kfree(idata->data[i]->buf);
kfree(idata->data[i]);
}
kfree(idata);
out:
return ERR_PTR(err);
}
static int mmc_blk_ioctl_rpmb_cmd(struct block_device *bdev,
struct mmc_ioc_rpmb __user *ic_ptr)
{
struct mmc_blk_ioc_rpmb_data *idata;
struct mmc_blk_data *md;
struct mmc_card *card;
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct mmc_request mrq = {NULL};
struct scatterlist sg;
int err = 0, i = 0;
u32 status = 0;
/* The caller must have CAP_SYS_RAWIO */
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
md = mmc_blk_get(bdev->bd_disk);
/* make sure this is a rpmb partition */
if ((!md) || (!(md->area_type & MMC_BLK_DATA_AREA_RPMB))) {
err = -EINVAL;
return err;
}
idata = mmc_blk_ioctl_rpmb_copy_from_user(ic_ptr);
if (IS_ERR(idata)) {
err = PTR_ERR(idata);
goto cmd_done;
}
card = md->queue.card;
if (IS_ERR(card)) {
err = PTR_ERR(card);
goto idata_free;
}
mmc_rpm_hold(card->host, &card->dev);
mmc_claim_host(card->host);
err = mmc_blk_part_switch(card, md);
if (err)
goto cmd_rel_host;
for (i = 0; i < MMC_IOC_MAX_RPMB_CMD; i++) {
struct mmc_blk_ioc_data *curr_data;
struct mmc_ioc_cmd *curr_cmd;
curr_data = idata->data[i];
curr_cmd = &curr_data->ic;
if (!curr_cmd->opcode)
break;
cmd.opcode = curr_cmd->opcode;
cmd.arg = curr_cmd->arg;
cmd.flags = curr_cmd->flags;
if (curr_data->buf_bytes) {
data.sg = &sg;
data.sg_len = 1;
data.blksz = curr_cmd->blksz;
data.blocks = curr_cmd->blocks;
sg_init_one(data.sg, curr_data->buf,
curr_data->buf_bytes);
if (curr_cmd->write_flag)
data.flags = MMC_DATA_WRITE;
else
data.flags = MMC_DATA_READ;
/* data.flags must already be set before doing this. */
mmc_set_data_timeout(&data, card);
/*
* Allow overriding the timeout_ns for empirical tuning.
*/
if (curr_cmd->data_timeout_ns)
data.timeout_ns = curr_cmd->data_timeout_ns;
mrq.data = &data;
}
mrq.cmd = &cmd;
err = mmc_set_blockcount(card, data.blocks,
curr_cmd->write_flag & (1 << 31));
if (err)
goto cmd_rel_host;
mmc_wait_for_req(card->host, &mrq);
if (cmd.error) {
dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
__func__, cmd.error);
err = cmd.error;
goto cmd_rel_host;
}
if (data.error) {
dev_err(mmc_dev(card->host), "%s: data error %d\n",
__func__, data.error);
err = data.error;
goto cmd_rel_host;
}
if (copy_to_user(&(ic_ptr->cmds[i].response), cmd.resp,
sizeof(cmd.resp))) {
err = -EFAULT;
goto cmd_rel_host;
}
if (!curr_cmd->write_flag) {
if (copy_to_user((void __user *)(unsigned long)
curr_cmd->data_ptr,
curr_data->buf,
curr_data->buf_bytes)) {
err = -EFAULT;
goto cmd_rel_host;
}
}
/*
* Ensure RPMB command has completed by polling CMD13
* "Send Status".
*/
err = ioctl_rpmb_card_status_poll(card, &status, 5);
if (err)
dev_err(mmc_dev(card->host),
"%s: Card Status=0x%08X, error %d\n",
__func__, status, err);
}
cmd_rel_host:
mmc_release_host(card->host);
mmc_rpm_release(card->host, &card->dev);
idata_free:
for (i = 0; i < MMC_IOC_MAX_RPMB_CMD; i++) {
kfree(idata->data[i]->buf);
kfree(idata->data[i]);
}
kfree(idata);
cmd_done:
mmc_blk_put(md);
return err;
}
static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
int ret = -EINVAL;
if (cmd == MMC_IOC_CMD)
ret = mmc_blk_ioctl_cmd(bdev, (struct mmc_ioc_cmd __user *)arg);
if (cmd == MMC_IOC_RPMB_CMD)
ret = mmc_blk_ioctl_rpmb_cmd(bdev,
(struct mmc_ioc_rpmb __user *)arg);
return ret;
}
#ifdef CONFIG_COMPAT
static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
}
#endif
static const struct block_device_operations mmc_bdops = {
.open = mmc_blk_open,
.release = mmc_blk_release,
.getgeo = mmc_blk_getgeo,
.owner = THIS_MODULE,
.ioctl = mmc_blk_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = mmc_blk_compat_ioctl,
#endif
};
static inline int mmc_blk_part_switch(struct mmc_card *card,
struct mmc_blk_data *md)
{
int ret;
struct mmc_blk_data *main_md = mmc_get_drvdata(card);
if ((main_md->part_curr == md->part_type) &&
(card->part_curr == md->part_type))
return 0;
if (mmc_card_mmc(card)) {
u8 part_config = card->ext_csd.part_config;
part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
part_config |= md->part_type;
ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_PART_CONFIG, part_config,
card->ext_csd.part_time);
if (ret)
return ret;
card->ext_csd.part_config = part_config;
card->part_curr = md->part_type;
}
main_md->part_curr = md->part_type;
return 0;
}
static u32 mmc_sd_num_wr_blocks(struct mmc_card *card)
{
int err;
u32 result;
__be32 *blocks;
struct mmc_request mrq = {NULL};
struct mmc_command cmd = {0};
struct mmc_data data = {0};
struct scatterlist sg;
cmd.opcode = MMC_APP_CMD;
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 0);
if (err)
return (u32)-1;
if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
return (u32)-1;
memset(&cmd, 0, sizeof(struct mmc_command));
cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
cmd.arg = 0;
cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
data.blksz = 4;
data.blocks = 1;
data.flags = MMC_DATA_READ;
data.sg = &sg;
data.sg_len = 1;
mmc_set_data_timeout(&data, card);
mrq.cmd = &cmd;
mrq.data = &data;
blocks = kmalloc(4, GFP_KERNEL);
if (!blocks)
return (u32)-1;
sg_init_one(&sg, blocks, 4);
mmc_wait_for_req(card->host, &mrq);
result = ntohl(*blocks);
kfree(blocks);
if (cmd.error || data.error)
result = (u32)-1;
return result;
}
static int send_stop(struct mmc_card *card, u32 *status)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_STOP_TRANSMISSION;
cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, 5);
if (err == 0)
*status = cmd.resp[0];
return err;
}
static int get_card_status(struct mmc_card *card, u32 *status, int retries)
{
struct mmc_command cmd = {0};
int err;
cmd.opcode = MMC_SEND_STATUS;
if (!mmc_host_is_spi(card->host))
cmd.arg = card->rca << 16;
cmd.flags = MMC_RSP_SPI_R2 | MMC_RSP_R1 | MMC_CMD_AC;
err = mmc_wait_for_cmd(card->host, &cmd, retries);
if (err == 0)
*status = cmd.resp[0];
return err;
}
#define ERR_NOMEDIUM 3
#define ERR_RETRY 2
#define ERR_ABORT 1
#define ERR_CONTINUE 0
static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
bool status_valid, u32 status)
{
switch (error) {
case -EILSEQ:
/* response crc error, retry the r/w cmd */
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "response CRC error",
name, status);
return ERR_RETRY;
case -ETIMEDOUT:
pr_err("%s: %s sending %s command, card status %#x\n",
req->rq_disk->disk_name, "timed out", name, status);
/* If the status cmd initially failed, retry the r/w cmd */
if (!status_valid) {
pr_err("%s: status not valid, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
/*
* If it was a r/w cmd crc error, or illegal command
* (eg, issued in wrong state) then retry - we should
* have corrected the state problem above.
*/
if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) {
pr_err("%s: command error, retrying timeout\n", req->rq_disk->disk_name);
return ERR_RETRY;
}
/* Otherwise abort the command */
pr_err("%s: not retrying timeout\n", req->rq_disk->disk_name);
return ERR_ABORT;
default:
/* We don't understand the error code the driver gave us */
pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
req->rq_disk->disk_name, error, status);
return ERR_ABORT;
}
}
/*
* Initial r/w and stop cmd error recovery.
* We don't know whether the card received the r/w cmd or not, so try to
* restore things back to a sane state. Essentially, we do this as follows:
* - Obtain card status. If the first attempt to obtain card status fails,
* the status word will reflect the failed status cmd, not the failed
* r/w cmd. If we fail to obtain card status, it suggests we can no
* longer communicate with the card.
* - Check the card state. If the card received the cmd but there was a
* transient problem with the response, it might still be in a data transfer
* mode. Try to send it a stop command. If this fails, we can't recover.
* - If the r/w cmd failed due to a response CRC error, it was probably
* transient, so retry the cmd.
* - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
* - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
* illegal cmd, retry.
* Otherwise we don't understand what happened, so abort.
*/
static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
struct mmc_blk_request *brq, int *ecc_err)
{
bool prev_cmd_status_valid = true;
u32 status, stop_status = 0;
int err, retry;
if (mmc_card_removed(card))
return ERR_NOMEDIUM;
/*
* Try to get card status which indicates both the card state
* and why there was no response. If the first attempt fails,
* we can't be sure the returned status is for the r/w command.
*/
for (retry = 2; retry >= 0; retry--) {
err = get_card_status(card, &status, 0);
if (!err)
break;
prev_cmd_status_valid = false;
pr_err("%s: error %d sending status command, %sing\n",
req->rq_disk->disk_name, err, retry ? "retry" : "abort");
}
/* We couldn't get a response from the card. Give up. */
if (err) {
/* Check if the card is removed */
if (mmc_detect_card_removed(card->host))
return ERR_NOMEDIUM;
return ERR_ABORT;
}
/* Flag ECC errors */
if ((status & R1_CARD_ECC_FAILED) ||
(brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
(brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
*ecc_err = 1;
/*
* Check the current card state. If it is in some data transfer
* mode, tell it to stop (and hopefully transition back to TRAN.)
*/
if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
R1_CURRENT_STATE(status) == R1_STATE_RCV) {
err = send_stop(card, &stop_status);
if (err)
pr_err("%s: error %d sending stop command\n",
req->rq_disk->disk_name, err);
/*
* If the stop cmd also timed out, the card is probably
* not present, so abort. Other errors are bad news too.
*/
if (err)
return ERR_ABORT;
if (stop_status & R1_CARD_ECC_FAILED)
*ecc_err = 1;
}
/* Check for set block count errors */
if (brq->sbc.error)
return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
prev_cmd_status_valid, status);
/* Check for r/w command errors */
if (brq->cmd.error)
return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
prev_cmd_status_valid, status);
/* Data errors */
if (!brq->stop.error)
return ERR_CONTINUE;
/* Now for stop errors. These aren't fatal to the transfer. */
pr_err("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->stop.error,
brq->cmd.resp[0], status);
/*
* Subsitute in our own stop status as this will give the error
* state which happened during the execution of the r/w command.
*/
if (stop_status) {
brq->stop.resp[0] = stop_status;
brq->stop.error = 0;
}
return ERR_CONTINUE;
}
static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
int type)
{
int err;
if (md->reset_done & type)
return -EEXIST;
md->reset_done |= type;
err = mmc_hw_reset(host);
/* Ensure we switch back to the correct partition */
if (err != -EOPNOTSUPP) {
struct mmc_blk_data *main_md = mmc_get_drvdata(host->card);
int part_err;
main_md->part_curr = main_md->part_type;
part_err = mmc_blk_part_switch(host->card, md);
if (part_err) {
/*
* We have failed to get back into the correct
* partition, so we need to abort the whole request.
*/
return -ENODEV;
}
}
return err;
}
static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
{
md->reset_done &= ~type;
}
static int mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_DISCARD;
if (!mmc_can_erase(card)) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (card->ext_csd.bkops_en)
card->bkops_info.sectors_changed += blk_rq_sectors(req);
if (mmc_can_discard(card))
arg = MMC_DISCARD_ARG;
else if (mmc_can_trim(card))
arg = MMC_TRIM_ARG;
else
arg = MMC_ERASE_ARG;
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_TRIM_ARG ?
INAND_CMD38_ARG_TRIM :
INAND_CMD38_ARG_ERASE,
0);
if (err)
goto out;
}
err = mmc_erase(card, from, nr, arg);
out:
if (err == -EIO && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
unsigned int from, nr, arg;
int err = 0, type = MMC_BLK_SECDISCARD;
if (!(mmc_can_secure_erase_trim(card))) {
err = -EOPNOTSUPP;
goto out;
}
from = blk_rq_pos(req);
nr = blk_rq_sectors(req);
if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr))
arg = MMC_SECURE_TRIM1_ARG;
else
arg = MMC_SECURE_ERASE_ARG;
retry:
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
arg == MMC_SECURE_TRIM1_ARG ?
INAND_CMD38_ARG_SECTRIM1 :
INAND_CMD38_ARG_SECERASE,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, arg);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
if (arg == MMC_SECURE_TRIM1_ARG) {
if (card->quirks & MMC_QUIRK_INAND_CMD38) {
err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
INAND_CMD38_ARG_EXT_CSD,
INAND_CMD38_ARG_SECTRIM2,
0);
if (err)
goto out_retry;
}
err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
if (err == -EIO)
goto out_retry;
if (err)
goto out;
}
out_retry:
if (err && !mmc_blk_reset(md, card->host, type))
goto retry;
if (!err)
mmc_blk_reset_success(md, type);
out:
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_sanitize_rq(struct mmc_queue *mq,
struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
int err = 0;
BUG_ON(!card);
BUG_ON(!card->host);
if (!(mmc_can_sanitize(card) &&
(card->host->caps2 & MMC_CAP2_SANITIZE))) {
pr_warning("%s: %s - SANITIZE is not supported\n",
mmc_hostname(card->host), __func__);
err = -EOPNOTSUPP;
goto out;
}
pr_debug("%s: %s - SANITIZE IN PROGRESS...\n",
mmc_hostname(card->host), __func__);
err = mmc_switch_ignore_timeout(card, EXT_CSD_CMD_SET_NORMAL,
EXT_CSD_SANITIZE_START, 1,
MMC_SANITIZE_REQ_TIMEOUT);
if (err)
pr_err("%s: %s - mmc_switch() with "
"EXT_CSD_SANITIZE_START failed. err=%d\n",
mmc_hostname(card->host), __func__, err);
pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host),
__func__);
out:
blk_end_request(req, err, blk_rq_bytes(req));
return err ? 0 : 1;
}
static int mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
{
struct mmc_blk_data *md = mq->data;
struct request_queue *q = mq->queue;
struct mmc_card *card = md->queue.card;
int ret = 0;
ret = mmc_flush_cache(card);
if (ret == -ETIMEDOUT) {
pr_info("%s: requeue flush request after timeout", __func__);
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, req);
spin_unlock_irq(q->queue_lock);
ret = 0;
goto exit;
} else if (ret) {
pr_err("%s: notify flush error to upper layers", __func__);
ret = -EIO;
}
blk_end_request_all(req, ret);
exit:
return ret ? 0 : 1;
}
/*
* Reformat current write as a reliable write, supporting
* both legacy and the enhanced reliable write MMC cards.
* In each transfer we'll handle only as much as a single
* reliable write can handle, thus finish the request in
* partial completions.
*/
static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
struct mmc_card *card,
struct request *req)
{
if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
/* Legacy mode imposes restrictions on transfers. */
if (!IS_ALIGNED(brq->cmd.arg, card->ext_csd.rel_sectors))
brq->data.blocks = 1;
if (brq->data.blocks > card->ext_csd.rel_sectors)
brq->data.blocks = card->ext_csd.rel_sectors;
else if (brq->data.blocks < card->ext_csd.rel_sectors)
brq->data.blocks = 1;
}
}
#ifdef CONFIG_VENDOR_EDIT
//[email protected], 2013/12/28, Add for solve QT bug(ID:390597): Bad micro SD card cause the phone to suspend/wakeup abnormal
static int bad_micro_sd_card = 0;
#endif /* VENDOR_EDIT */
#define CMD_ERRORS \
(R1_OUT_OF_RANGE | /* Command argument out of range */ \
R1_ADDRESS_ERROR | /* Misaligned address */ \
R1_BLOCK_LEN_ERROR | /* Transferred block length incorrect */\
R1_WP_VIOLATION | /* Tried to write to protected block */ \
R1_CC_ERROR | /* Card controller error */ \
R1_ERROR) /* General/unknown error */
static int mmc_blk_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct mmc_blk_request *brq = &mq_mrq->brq;
struct request *req = mq_mrq->req;
int ecc_err = 0;
/*
* sbc.error indicates a problem with the set block count
* command. No data will have been transferred.
*
* cmd.error indicates a problem with the r/w command. No
* data will have been transferred.
*
* stop.error indicates a problem with the stop command. Data
* may have been transferred, or may still be transferring.
*/
if (brq->sbc.error || brq->cmd.error || brq->stop.error ||
brq->data.error) {
#ifdef CONFIG_VENDOR_EDIT
//[email protected], 2013/12/28, Add for solve QT bug(ID:390597): Bad micro SD card cause the phone to suspend/wakeup abnormal
if ((card->host->index == 1) && bad_micro_sd_card) {
if (req) {
printk(KERN_ERR"%s: bad sd card had been detected, return MMC_BLK_ABORT\n", __func__);
return MMC_BLK_ABORT;
}
}
#endif /* VENDOR_EDIT */
switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err)) {
case ERR_RETRY:
return MMC_BLK_RETRY;
case ERR_ABORT:
return MMC_BLK_ABORT;
case ERR_NOMEDIUM:
return MMC_BLK_NOMEDIUM;
case ERR_CONTINUE:
break;
}
}
/*
* Check for errors relating to the execution of the
* initial command - such as address errors. No data
* has been transferred.
*/
if (brq->cmd.resp[0] & CMD_ERRORS) {
pr_err("%s: r/w command failed, status = %#x\n",
req->rq_disk->disk_name, brq->cmd.resp[0]);
return MMC_BLK_ABORT;
}
/*
* Everything else is either success, or a data error of some
* kind. If it was a write, we may have transitioned to
* program mode, which we have to wait for it to complete.
*/
if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
u32 status;
unsigned long timeout;
timeout = jiffies + msecs_to_jiffies(MMC_BLK_TIMEOUT_MS);
do {
int err = get_card_status(card, &status, 5);
if (err) {
pr_err("%s: error %d requesting status\n",
req->rq_disk->disk_name, err);
return MMC_BLK_CMD_ERR;
}
/* Timeout if the device never becomes ready for data
* and never leaves the program state.
*/
if (time_after(jiffies, timeout)) {
pr_err("%s: Card stuck in programming state!"\
" %s %s\n", mmc_hostname(card->host),
req->rq_disk->disk_name, __func__);
return MMC_BLK_CMD_ERR;
}
/*
* Some cards mishandle the status bits,
* so make sure to check both the busy
* indication and the card state.
*/
} while (!(status & R1_READY_FOR_DATA) ||
(R1_CURRENT_STATE(status) == R1_STATE_PRG));
}
if (brq->data.error) {
pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
req->rq_disk->disk_name, brq->data.error,
(unsigned)blk_rq_pos(req),
(unsigned)blk_rq_sectors(req),
brq->cmd.resp[0], brq->stop.resp[0]);
#ifdef CONFIG_VENDOR_EDIT
//[email protected], 2013/12/28, Add for solve QT bug(ID:390597): Bad micro SD card cause the phone to suspend/wakeup abnormal
if ((card->host->index == 1)
&& (rq_data_dir(req) == READ)) {
bad_micro_sd_card = 1;
printk(KERN_ERR"%s: bad sd card had been detected.\n", __func__);
}
#endif /* VENDOR_EDIT */
if (rq_data_dir(req) == READ) {
if (ecc_err)
return MMC_BLK_ECC_ERR;
return MMC_BLK_DATA_ERR;
} else {
return MMC_BLK_CMD_ERR;
}
}
if (!brq->data.bytes_xfered)
return MMC_BLK_RETRY;
if (mq_mrq->packed_cmd != MMC_PACKED_NONE) {
if (unlikely(brq->data.blocks << 9 != brq->data.bytes_xfered))
return MMC_BLK_PARTIAL;
else
return MMC_BLK_SUCCESS;
}
if (blk_rq_bytes(req) != brq->data.bytes_xfered)
return MMC_BLK_PARTIAL;
return MMC_BLK_SUCCESS;
}
/*
* mmc_blk_reinsert_req() - re-insert request back to the scheduler
* @areq: request to re-insert.
*
* Request may be packed or single. When fails to reinsert request, it will be
* requeued to the the dispatch queue.
*/
static void mmc_blk_reinsert_req(struct mmc_async_req *areq)
{
struct request *prq;
int ret = 0;
struct mmc_queue_req *mq_rq;
struct request_queue *q;
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
q = mq_rq->req->q;
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
while (!list_empty(&mq_rq->packed_list)) {
/* return requests in reverse order */
prq = list_entry_rq(mq_rq->packed_list.prev);
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
ret = blk_reinsert_request(q, prq);
if (ret) {
blk_requeue_request(q, prq);
spin_unlock_irq(q->queue_lock);
goto reinsert_error;
}
spin_unlock_irq(q->queue_lock);
}
} else {
spin_lock_irq(q->queue_lock);
ret = blk_reinsert_request(q, mq_rq->req);
if (ret)
blk_requeue_request(q, mq_rq->req);
spin_unlock_irq(q->queue_lock);
}
return;
reinsert_error:
pr_err("%s: blk_reinsert_request() failed (%d)",
mq_rq->req->rq_disk->disk_name, ret);
/*
* -EIO will be reported for this request and rest of packed_list.
* Urgent request will be proceeded anyway, while upper layer
* responsibility to re-send failed requests
*/
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, prq);
spin_unlock_irq(q->queue_lock);
}
}
/*
* mmc_blk_update_interrupted_req() - update of the stopped request
* @card: the MMC card associated with the request.
* @areq: interrupted async request.
*
* Get stopped request state from card and update successfully done part of
* the request by setting packed_fail_idx. The packed_fail_idx is index of
* first uncompleted request in packed request list, for non-packed request
* packed_fail_idx remains unchanged.
*
* Returns: MMC_BLK_SUCCESS for success, MMC_BLK_ABORT otherwise
*/
static int mmc_blk_update_interrupted_req(struct mmc_card *card,
struct mmc_async_req *areq)
{
int ret = MMC_BLK_SUCCESS;
u8 *ext_csd;
int correctly_done;
struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct request *prq;
u8 req_index = 0;
if (mq_rq->packed_cmd == MMC_PACKED_NONE)
return MMC_BLK_SUCCESS;
ext_csd = kmalloc(512, GFP_KERNEL);
if (!ext_csd)
return MMC_BLK_ABORT;
/* get correctly programmed sectors number from card */
ret = mmc_send_ext_csd(card, ext_csd);
if (ret) {
pr_err("%s: error %d reading ext_csd\n",
mmc_hostname(card->host), ret);
ret = MMC_BLK_ABORT;
goto exit;
}
correctly_done = card->ext_csd.data_sector_size *
(ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 0] << 0 |
ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 1] << 8 |
ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 2] << 16 |
ext_csd[EXT_CSD_CORRECTLY_PRG_SECTORS_NUM + 3] << 24);
/*
* skip packed command header (1 sector) included by the counter but not
* actually written to the NAND
*/
if (correctly_done >= card->ext_csd.data_sector_size)
correctly_done -= card->ext_csd.data_sector_size;
list_for_each_entry(prq, &mq_rq->packed_list, queuelist) {
if ((correctly_done - (int)blk_rq_bytes(prq)) < 0) {
/* prq is not successfull */
mq_rq->packed_fail_idx = req_index;
break;
}
correctly_done -= blk_rq_bytes(prq);
req_index++;
}
exit:
kfree(ext_csd);
return ret;
}
static int mmc_blk_packed_err_check(struct mmc_card *card,
struct mmc_async_req *areq)
{
struct mmc_queue_req *mq_rq = container_of(areq, struct mmc_queue_req,
mmc_active);
struct request *req = mq_rq->req;
int err, check, status;
u8 ext_csd[512];
mq_rq->packed_retries--;
check = mmc_blk_err_check(card, areq);
err = get_card_status(card, &status, 0);
if (err) {
pr_err("%s: error %d sending status command\n",
req->rq_disk->disk_name, err);
return MMC_BLK_ABORT;
}
if (status & R1_EXCEPTION_EVENT) {
err = mmc_send_ext_csd(card, ext_csd);
if (err) {
pr_err("%s: error %d sending ext_csd\n",
req->rq_disk->disk_name, err);
return MMC_BLK_ABORT;
}
if ((ext_csd[EXT_CSD_EXP_EVENTS_STATUS] &
EXT_CSD_PACKED_FAILURE) &&
(ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
EXT_CSD_PACKED_GENERIC_ERROR)) {
if (ext_csd[EXT_CSD_PACKED_CMD_STATUS] &
EXT_CSD_PACKED_INDEXED_ERROR) {
mq_rq->packed_fail_idx =
ext_csd[EXT_CSD_PACKED_FAILURE_INDEX] - 1;
return MMC_BLK_PARTIAL;
}
}
}
return check;
}
static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
int disable_multi,
struct mmc_queue *mq)
{
u32 readcmd, writecmd;
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct mmc_blk_data *md = mq->data;
bool do_data_tag;
/*
* Reliable writes are used to implement Forced Unit Access and
* REQ_META accesses, and are supported only on MMCs.
*
* XXX: this really needs a good explanation of why REQ_META
* is treated special.
*/
bool do_rel_wr = ((req->cmd_flags & REQ_FUA) ||
(req->cmd_flags & REQ_META)) &&
(rq_data_dir(req) == WRITE) &&
(md->flags & MMC_BLK_REL_WR);
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->stop.opcode = MMC_STOP_TRANSMISSION;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
brq->data.blocks = blk_rq_sectors(req);
brq->data.fault_injected = false;
/*
* The block layer doesn't support all sector count
* restrictions, so we need to be prepared for too big
* requests.
*/
if (brq->data.blocks > card->host->max_blk_count)
brq->data.blocks = card->host->max_blk_count;
if (brq->data.blocks > 1) {
/*
* After a read error, we redo the request one sector
* at a time in order to accurately determine which
* sectors can be read successfully.
*/
if (disable_multi)
brq->data.blocks = 1;
/* Some controllers can't do multiblock reads due to hw bugs */
if (card->host->caps2 & MMC_CAP2_NO_MULTI_READ &&
rq_data_dir(req) == READ)
brq->data.blocks = 1;
}
if (brq->data.blocks > 1 || do_rel_wr) {
/* SPI multiblock writes terminate using a special
* token, not a STOP_TRANSMISSION request.
*/
if (!mmc_host_is_spi(card->host) ||
rq_data_dir(req) == READ)
brq->mrq.stop = &brq->stop;
readcmd = MMC_READ_MULTIPLE_BLOCK;
writecmd = MMC_WRITE_MULTIPLE_BLOCK;
} else {
brq->mrq.stop = NULL;
readcmd = MMC_READ_SINGLE_BLOCK;
writecmd = MMC_WRITE_BLOCK;
}
if (rq_data_dir(req) == READ) {
brq->cmd.opcode = readcmd;
brq->data.flags |= MMC_DATA_READ;
} else {
brq->cmd.opcode = writecmd;
brq->data.flags |= MMC_DATA_WRITE;
}
if (do_rel_wr)
mmc_apply_rel_rw(brq, card, req);
/*
* Data tag is used only during writing meta data to speed
* up write and any subsequent read of this meta data
*/
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(req->cmd_flags & REQ_META) &&
(rq_data_dir(req) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/*
* Pre-defined multi-block transfers are preferable to
* open ended-ones (and necessary for reliable writes).
* However, it is not sufficient to just send CMD23,
* and avoid the final CMD12, as on an error condition
* CMD12 (stop) needs to be sent anyway. This, coupled
* with Auto-CMD23 enhancements provided by some
* hosts, means that the complexity of dealing
* with this is best left to the host. If CMD23 is
* supported by card and host, we'll fill sbc in and let
* the host deal with handling it correctly. This means
* that for hosts that don't expose MMC_CAP_CMD23, no
* change of behavior will be observed.
*
* N.B: Some MMC cards experience perf degradation.
* We'll avoid using CMD23-bounded multiblock writes for
* these, while retaining features like reliable writes.
*/
if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
(do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
do_data_tag)) {
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = brq->data.blocks |
(do_rel_wr ? (1 << 31) : 0) |
(do_data_tag ? (1 << 29) : 0);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->mrq.sbc = &brq->sbc;
}
mmc_set_data_timeout(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
/*
* Adjust the sg list so it is the same size as the
* request.
*/
if (brq->data.blocks != blk_rq_sectors(req)) {
int i, data_size = brq->data.blocks << 9;
struct scatterlist *sg;
for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
data_size -= sg->length;
if (data_size <= 0) {
sg->length += data_size;
i++;
break;
}
}
brq->data.sg_len = i;
}
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.cmd_flags = req->cmd_flags;
if (mq->err_check_fn)
mqrq->mmc_active.err_check = mq->err_check_fn;
else
mqrq->mmc_active.err_check = mmc_blk_err_check;
mqrq->mmc_active.reinsert_req = mmc_blk_reinsert_req;
mqrq->mmc_active.update_interrupted_req =
mmc_blk_update_interrupted_req;
mmc_queue_bounce_pre(mqrq);
}
/**
* mmc_blk_disable_wr_packing() - disables packing mode
* @mq: MMC queue.
*
*/
void mmc_blk_disable_wr_packing(struct mmc_queue *mq)
{
if (mq) {
mq->wr_packing_enabled = false;
mq->num_of_potential_packed_wr_reqs = 0;
}
}
EXPORT_SYMBOL(mmc_blk_disable_wr_packing);
static int get_packed_trigger(int potential, struct mmc_card *card,
struct request *req, int curr_trigger)
{
static int num_mean_elements = 1;
static unsigned long mean_potential = PCKD_TRGR_INIT_MEAN_POTEN;
unsigned int trigger = curr_trigger;
unsigned int pckd_trgr_upper_bound = card->ext_csd.max_packed_writes;
/* scale down the upper bound to 75% */
pckd_trgr_upper_bound = (pckd_trgr_upper_bound * 3) / 4;
/*
* since the most common calls for this function are with small
* potential write values and since we don't want these calls to affect
* the packed trigger, set a lower bound and ignore calls with
* potential lower than that bound
*/
if (potential <= PCKD_TRGR_POTEN_LOWER_BOUND)
return trigger;
/*
* this is to prevent integer overflow in the following calculation:
* once every PACKED_TRIGGER_MAX_ELEMENTS reset the algorithm
*/
if (num_mean_elements > PACKED_TRIGGER_MAX_ELEMENTS) {
num_mean_elements = 1;
mean_potential = PCKD_TRGR_INIT_MEAN_POTEN;
}
/*
* get next mean value based on previous mean value and current
* potential packed writes. Calculation is as follows:
* mean_pot[i+1] =
* ((mean_pot[i] * num_mean_elem) + potential)/(num_mean_elem + 1)
*/
mean_potential *= num_mean_elements;
/*
* add num_mean_elements so that the division of two integers doesn't
* lower mean_potential too much
*/
if (potential > mean_potential)
mean_potential += num_mean_elements;
mean_potential += potential;
/* this is for gaining more precision when dividing two integers */
mean_potential *= PCKD_TRGR_PRECISION_MULTIPLIER;
/* this completes the mean calculation */
mean_potential /= ++num_mean_elements;
mean_potential /= PCKD_TRGR_PRECISION_MULTIPLIER;
/*
* if current potential packed writes is greater than the mean potential
* then the heuristic is that the following workload will contain many
* write requests, therefore we lower the packed trigger. In the
* opposite case we want to increase the trigger in order to get less
* packing events.
*/
if (potential >= mean_potential)
trigger = (trigger <= PCKD_TRGR_LOWER_BOUND) ?
PCKD_TRGR_LOWER_BOUND : trigger - 1;
else
trigger = (trigger >= pckd_trgr_upper_bound) ?
pckd_trgr_upper_bound : trigger + 1;
/*
* an urgent read request indicates a packed list being interrupted
* by this read, therefore we aim for less packing, hence the trigger
* gets increased
*/
if (req && (req->cmd_flags & REQ_URGENT) && (rq_data_dir(req) == READ))
trigger += PCKD_TRGR_URGENT_PENALTY;
return trigger;
}
static void mmc_blk_write_packing_control(struct mmc_queue *mq,
struct request *req)
{
struct mmc_host *host = mq->card->host;
int data_dir;
if (!(host->caps2 & MMC_CAP2_PACKED_WR))
return;
/* Support for the write packing on eMMC 4.5 or later */
if (mq->card->ext_csd.rev <= 5)
return;
/*
* In case the packing control is not supported by the host, it should
* not have an effect on the write packing. Therefore we have to enable
* the write packing
*/
if (!(host->caps2 & MMC_CAP2_PACKED_WR_CONTROL)) {
mq->wr_packing_enabled = true;
return;
}
if (!req || (req && (req->cmd_flags & REQ_FLUSH))) {
if (mq->num_of_potential_packed_wr_reqs >
mq->num_wr_reqs_to_start_packing)
mq->wr_packing_enabled = true;
mq->num_wr_reqs_to_start_packing =
get_packed_trigger(mq->num_of_potential_packed_wr_reqs,
mq->card, req,
mq->num_wr_reqs_to_start_packing);
mq->num_of_potential_packed_wr_reqs = 0;
return;
}
data_dir = rq_data_dir(req);
if (data_dir == READ) {
mmc_blk_disable_wr_packing(mq);
mq->num_wr_reqs_to_start_packing =
get_packed_trigger(mq->num_of_potential_packed_wr_reqs,
mq->card, req,
mq->num_wr_reqs_to_start_packing);
mq->num_of_potential_packed_wr_reqs = 0;
mq->wr_packing_enabled = false;
return;
} else if (data_dir == WRITE) {
mq->num_of_potential_packed_wr_reqs++;
}
if (mq->num_of_potential_packed_wr_reqs >
mq->num_wr_reqs_to_start_packing)
mq->wr_packing_enabled = true;
}
struct mmc_wr_pack_stats *mmc_blk_get_packed_statistics(struct mmc_card *card)
{
if (!card)
return NULL;
return &card->wr_pack_stats;
}
EXPORT_SYMBOL(mmc_blk_get_packed_statistics);
void mmc_blk_init_packed_statistics(struct mmc_card *card)
{
int max_num_of_packed_reqs = 0;
if (!card || !card->wr_pack_stats.packing_events)
return;
max_num_of_packed_reqs = card->ext_csd.max_packed_writes;
spin_lock(&card->wr_pack_stats.lock);
memset(card->wr_pack_stats.packing_events, 0,
(max_num_of_packed_reqs + 1) *
sizeof(*card->wr_pack_stats.packing_events));
memset(&card->wr_pack_stats.pack_stop_reason, 0,
sizeof(card->wr_pack_stats.pack_stop_reason));
card->wr_pack_stats.enabled = true;
spin_unlock(&card->wr_pack_stats.lock);
}
EXPORT_SYMBOL(mmc_blk_init_packed_statistics);
static u8 mmc_blk_prep_packed_list(struct mmc_queue *mq, struct request *req)
{
struct request_queue *q = mq->queue;
struct mmc_card *card = mq->card;
struct request *cur = req, *next = NULL;
struct mmc_blk_data *md = mq->data;
bool en_rel_wr = card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN;
unsigned int req_sectors = 0, phys_segments = 0;
unsigned int max_blk_count, max_phys_segs;
u8 put_back = 0;
u8 max_packed_rw = 0;
u8 reqs = 0;
struct mmc_wr_pack_stats *stats = &card->wr_pack_stats;
mmc_blk_clear_packed(mq->mqrq_cur);
if (!(md->flags & MMC_BLK_CMD23) ||
!card->ext_csd.packed_event_en)
goto no_packed;
if (!mq->wr_packing_enabled)
goto no_packed;
if ((rq_data_dir(cur) == WRITE) &&
(card->host->caps2 & MMC_CAP2_PACKED_WR))
max_packed_rw = card->ext_csd.max_packed_writes;
if (max_packed_rw == 0)
goto no_packed;
if (mmc_req_rel_wr(cur) &&
(md->flags & MMC_BLK_REL_WR) &&
!en_rel_wr)
goto no_packed;
if (mmc_large_sec(card) &&
!IS_ALIGNED(blk_rq_sectors(cur), 8))
goto no_packed;
if (cur->cmd_flags & REQ_FUA)
goto no_packed;
max_blk_count = min(card->host->max_blk_count,
card->host->max_req_size >> 9);
if (unlikely(max_blk_count > 0xffff))
max_blk_count = 0xffff;
max_phys_segs = queue_max_segments(q);
req_sectors += blk_rq_sectors(cur);
phys_segments += cur->nr_phys_segments;
if (rq_data_dir(cur) == WRITE) {
req_sectors++;
phys_segments++;
}
spin_lock(&stats->lock);
while (reqs < max_packed_rw - 1) {
spin_lock_irq(q->queue_lock);
next = blk_fetch_request(q);
spin_unlock_irq(q->queue_lock);
if (!next) {
MMC_BLK_UPDATE_STOP_REASON(stats, EMPTY_QUEUE);
break;
}
if (mmc_large_sec(card) &&
!IS_ALIGNED(blk_rq_sectors(next), 8)) {
MMC_BLK_UPDATE_STOP_REASON(stats, LARGE_SEC_ALIGN);
put_back = 1;
break;
}
if (next->cmd_flags & REQ_DISCARD ||
next->cmd_flags & REQ_FLUSH) {
MMC_BLK_UPDATE_STOP_REASON(stats, FLUSH_OR_DISCARD);
put_back = 1;
break;
}
if (next->cmd_flags & REQ_FUA) {
MMC_BLK_UPDATE_STOP_REASON(stats, FUA);
put_back = 1;
break;
}
if (rq_data_dir(cur) != rq_data_dir(next)) {
MMC_BLK_UPDATE_STOP_REASON(stats, WRONG_DATA_DIR);
put_back = 1;
break;
}
if (mmc_req_rel_wr(next) &&
(md->flags & MMC_BLK_REL_WR) &&
!en_rel_wr) {
MMC_BLK_UPDATE_STOP_REASON(stats, REL_WRITE);
put_back = 1;
break;
}
req_sectors += blk_rq_sectors(next);
if (req_sectors > max_blk_count) {
if (stats->enabled)
stats->pack_stop_reason[EXCEEDS_SECTORS]++;
put_back = 1;
break;
}
phys_segments += next->nr_phys_segments;
if (phys_segments > max_phys_segs) {
MMC_BLK_UPDATE_STOP_REASON(stats, EXCEEDS_SEGMENTS);
put_back = 1;
break;
}
if (mq->no_pack_for_random) {
if ((blk_rq_pos(cur) + blk_rq_sectors(cur)) !=
blk_rq_pos(next)) {
MMC_BLK_UPDATE_STOP_REASON(stats, RANDOM);
put_back = 1;
break;
}
}
if (rq_data_dir(next) == WRITE) {
mq->num_of_potential_packed_wr_reqs++;
if (card->ext_csd.bkops_en)
card->bkops_info.sectors_changed +=
blk_rq_sectors(next);
}
list_add_tail(&next->queuelist, &mq->mqrq_cur->packed_list);
cur = next;
reqs++;
}
if (put_back) {
spin_lock_irq(q->queue_lock);
blk_requeue_request(q, next);
spin_unlock_irq(q->queue_lock);
}
if (stats->enabled) {
if (reqs + 1 <= card->ext_csd.max_packed_writes)
stats->packing_events[reqs + 1]++;
if (reqs + 1 == max_packed_rw)
MMC_BLK_UPDATE_STOP_REASON(stats, THRESHOLD);
}
spin_unlock(&stats->lock);
if (reqs > 0) {
list_add(&req->queuelist, &mq->mqrq_cur->packed_list);
mq->mqrq_cur->packed_num = ++reqs;
mq->mqrq_cur->packed_retries = reqs;
return reqs;
}
no_packed:
mmc_blk_clear_packed(mq->mqrq_cur);
return 0;
}
static void mmc_blk_packed_hdr_wrq_prep(struct mmc_queue_req *mqrq,
struct mmc_card *card,
struct mmc_queue *mq)
{
struct mmc_blk_request *brq = &mqrq->brq;
struct request *req = mqrq->req;
struct request *prq;
struct mmc_blk_data *md = mq->data;
bool do_rel_wr, do_data_tag;
u32 *packed_cmd_hdr = mqrq->packed_cmd_hdr;
u8 i = 1;
mqrq->packed_cmd = MMC_PACKED_WRITE;
mqrq->packed_blocks = 0;
mqrq->packed_fail_idx = MMC_PACKED_N_IDX;
memset(packed_cmd_hdr, 0, sizeof(mqrq->packed_cmd_hdr));
packed_cmd_hdr[0] = (mqrq->packed_num << 16) |
(PACKED_CMD_WR << 8) | PACKED_CMD_VER;
/*
* Argument for each entry of packed group
*/
list_for_each_entry(prq, &mqrq->packed_list, queuelist) {
do_rel_wr = mmc_req_rel_wr(prq) && (md->flags & MMC_BLK_REL_WR);
do_data_tag = (card->ext_csd.data_tag_unit_size) &&
(prq->cmd_flags & REQ_META) &&
(rq_data_dir(prq) == WRITE) &&
((brq->data.blocks * brq->data.blksz) >=
card->ext_csd.data_tag_unit_size);
/* Argument of CMD23 */
packed_cmd_hdr[(i * 2)] =
(do_rel_wr ? MMC_CMD23_ARG_REL_WR : 0) |
(do_data_tag ? MMC_CMD23_ARG_TAG_REQ : 0) |
blk_rq_sectors(prq);
/* Argument of CMD18 or CMD25 */
packed_cmd_hdr[((i * 2)) + 1] =
mmc_card_blockaddr(card) ?
blk_rq_pos(prq) : blk_rq_pos(prq) << 9;
mqrq->packed_blocks += blk_rq_sectors(prq);
i++;
}
memset(brq, 0, sizeof(struct mmc_blk_request));
brq->mrq.cmd = &brq->cmd;
brq->mrq.data = &brq->data;
brq->mrq.sbc = &brq->sbc;
brq->mrq.stop = &brq->stop;
brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
brq->sbc.arg = MMC_CMD23_ARG_PACKED | (mqrq->packed_blocks + 1);
brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
brq->cmd.opcode = MMC_WRITE_MULTIPLE_BLOCK;
brq->cmd.arg = blk_rq_pos(req);
if (!mmc_card_blockaddr(card))
brq->cmd.arg <<= 9;
brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
brq->data.blksz = 512;
brq->data.blocks = mqrq->packed_blocks + 1;
brq->data.flags |= MMC_DATA_WRITE;
brq->data.fault_injected = false;
brq->stop.opcode = MMC_STOP_TRANSMISSION;
brq->stop.arg = 0;
brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
mmc_set_data_timeout(&brq->data, card);
brq->data.sg = mqrq->sg;
brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
mqrq->mmc_active.mrq = &brq->mrq;
mqrq->mmc_active.cmd_flags = req->cmd_flags;
/*
* This is intended for packed commands tests usage - in case these
* functions are not in use the respective pointers are NULL
*/
if (mq->err_check_fn)
mqrq->mmc_active.err_check = mq->err_check_fn;
else
mqrq->mmc_active.err_check = mmc_blk_packed_err_check;
if (mq->packed_test_fn)
mq->packed_test_fn(mq->queue, mqrq);
mqrq->mmc_active.reinsert_req = mmc_blk_reinsert_req;
mqrq->mmc_active.update_interrupted_req =
mmc_blk_update_interrupted_req;
mmc_queue_bounce_pre(mqrq);
}
static int mmc_blk_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
struct mmc_blk_request *brq, struct request *req,
int ret)
{
struct mmc_queue_req *mq_rq;
mq_rq = container_of(brq, struct mmc_queue_req, brq);
/*
* If this is an SD card and we're writing, we can first
* mark the known good sectors as ok.
*
* If the card is not SD, we can still ok written sectors
* as reported by the controller (which might be less than
* the real number of written sectors, but never more).
*/
if (mmc_card_sd(card)) {
u32 blocks;
if (!brq->data.fault_injected) {
blocks = mmc_sd_num_wr_blocks(card);
if (blocks != (u32)-1)
ret = blk_end_request(req, 0, blocks << 9);
} else
ret = blk_end_request(req, 0, brq->data.bytes_xfered);
} else {
if (mq_rq->packed_cmd == MMC_PACKED_NONE)
ret = blk_end_request(req, 0, brq->data.bytes_xfered);
}
return ret;
}
static int mmc_blk_end_packed_req(struct mmc_queue_req *mq_rq)
{
struct request *prq;
int idx = mq_rq->packed_fail_idx, i = 0;
int ret = 0;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
if (idx == i) {
/* retry from error index */
mq_rq->packed_num -= idx;
mq_rq->req = prq;
ret = 1;
if (mq_rq->packed_num == MMC_PACKED_N_SINGLE) {
list_del_init(&prq->queuelist);
mmc_blk_clear_packed(mq_rq);
}
return ret;
}
list_del_init(&prq->queuelist);
blk_end_request(prq, 0, blk_rq_bytes(prq));
i++;
}
mmc_blk_clear_packed(mq_rq);
return ret;
}
static void mmc_blk_abort_packed_req(struct mmc_queue_req *mq_rq,
unsigned int cmd_flags)
{
struct request *prq;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.next);
list_del_init(&prq->queuelist);
prq->cmd_flags |= cmd_flags;
blk_end_request(prq, -EIO, blk_rq_bytes(prq));
}
mmc_blk_clear_packed(mq_rq);
}
static void mmc_blk_revert_packed_req(struct mmc_queue *mq,
struct mmc_queue_req *mq_rq)
{
struct request *prq;
struct request_queue *q = mq->queue;
while (!list_empty(&mq_rq->packed_list)) {
prq = list_entry_rq(mq_rq->packed_list.prev);
if (prq->queuelist.prev != &mq_rq->packed_list) {
list_del_init(&prq->queuelist);
spin_lock_irq(q->queue_lock);
blk_requeue_request(mq->queue, prq);
spin_unlock_irq(q->queue_lock);
} else {
list_del_init(&prq->queuelist);
}
}
mmc_blk_clear_packed(mq_rq);
}
static int mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *rqc)
{
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_blk_request *brq = &mq->mqrq_cur->brq;
int ret = 1, disable_multi = 0, retry = 0, type;
enum mmc_blk_status status;
struct mmc_queue_req *mq_rq;
struct request *req;
struct mmc_async_req *areq;
const u8 packed_num = 2;
u8 reqs = 0;
if (!rqc && !mq->mqrq_prev->req)
return 0;
if (rqc) {
if ((card->ext_csd.bkops_en) && (rq_data_dir(rqc) == WRITE))
card->bkops_info.sectors_changed += blk_rq_sectors(rqc);
reqs = mmc_blk_prep_packed_list(mq, rqc);
}
do {
if (rqc) {
if (reqs >= packed_num)
mmc_blk_packed_hdr_wrq_prep(mq->mqrq_cur,
card, mq);
else
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
areq = &mq->mqrq_cur->mmc_active;
} else
areq = NULL;
areq = mmc_start_req(card->host, areq, (int *) &status);
if (!areq) {
if (status == MMC_BLK_NEW_REQUEST)
mq->flags |= MMC_QUEUE_NEW_REQUEST;
return 0;
}
mq_rq = container_of(areq, struct mmc_queue_req, mmc_active);
brq = &mq_rq->brq;
req = mq_rq->req;
type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
mmc_queue_bounce_post(mq_rq);
switch (status) {
case MMC_BLK_URGENT:
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
/* complete successfully transmitted part */
if (mmc_blk_end_packed_req(mq_rq))
/* process for not transmitted part */
mmc_blk_reinsert_req(areq);
} else {
mmc_blk_reinsert_req(areq);
}
mq->flags |= MMC_QUEUE_URGENT_REQUEST;
ret = 0;
break;
case MMC_BLK_URGENT_DONE:
case MMC_BLK_SUCCESS:
case MMC_BLK_PARTIAL:
/*
* A block was successfully transferred.
*/
mmc_blk_reset_success(md, type);
if (mq_rq->packed_cmd != MMC_PACKED_NONE) {
ret = mmc_blk_end_packed_req(mq_rq);
break;
} else {
ret = blk_end_request(req, 0,
brq->data.bytes_xfered);
}
/*
* If the blk_end_request function returns non-zero even
* though all data has been transferred and no errors
* were returned by the host controller, it's a bug.
*/
if (status == MMC_BLK_SUCCESS && ret) {
pr_err("%s BUG rq_tot %d d_xfer %d\n",
__func__, blk_rq_bytes(req),
brq->data.bytes_xfered);
rqc = NULL;
goto cmd_abort;
}
break;
case MMC_BLK_CMD_ERR:
ret = mmc_blk_cmd_err(md, card, brq, req, ret);
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_RETRY:
if (retry++ < 5)
break;
/* Fall through */
case MMC_BLK_ABORT:
if (!mmc_blk_reset(md, card->host, type))
break;
goto cmd_abort;
case MMC_BLK_DATA_ERR: {
int err;
err = mmc_blk_reset(md, card->host, type);
if (!err)
break;
if (err == -ENODEV ||
mq_rq->packed_cmd != MMC_PACKED_NONE)
goto cmd_abort;
/* Fall through */
}
case MMC_BLK_ECC_ERR:
if (brq->data.blocks > 1) {
/* Redo read one sector at a time */
pr_warning("%s: retrying using single block read\n",
req->rq_disk->disk_name);
disable_multi = 1;
break;
}
/*
* After an error, we redo I/O one sector at a
* time, so we only reach here after trying to
* read a single sector.
*/
ret = blk_end_request(req, -EIO,
brq->data.blksz);
if (!ret)
goto start_new_req;
break;
case MMC_BLK_NOMEDIUM:
goto cmd_abort;
default:
pr_err("%s:%s: Unhandled return value (%d)",
req->rq_disk->disk_name,
__func__, status);
goto cmd_abort;
}
if (ret) {
if (mq_rq->packed_cmd == MMC_PACKED_NONE) {
/*
* In case of a incomplete request
* prepare it again and resend.
*/
mmc_blk_rw_rq_prep(mq_rq, card,
disable_multi, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
} else {
if (!mq_rq->packed_retries)
goto cmd_abort;
mmc_blk_packed_hdr_wrq_prep(mq_rq, card, mq);
mmc_start_req(card->host,
&mq_rq->mmc_active, NULL);
}
}
} while (ret);
return 1;
cmd_abort:
if (mq_rq->packed_cmd == MMC_PACKED_NONE) {
if (mmc_card_removed(card))
req->cmd_flags |= REQ_QUIET;
while (ret)
ret = blk_end_request(req, -EIO,
blk_rq_cur_bytes(req));
} else {
mmc_blk_abort_packed_req(mq_rq, 0);
}
start_new_req:
if (rqc) {
if (mmc_card_removed(card)) {
if (mq_rq->packed_cmd == MMC_PACKED_NONE) {
rqc->cmd_flags |= REQ_QUIET;
blk_end_request_all(rqc, -EIO);
} else {
mmc_blk_abort_packed_req(mq_rq, REQ_QUIET);
}
} else {
/* If current request is packed, it needs to put back */
if (mq_rq->packed_cmd != MMC_PACKED_NONE)
mmc_blk_revert_packed_req(mq, mq->mqrq_cur);
mmc_blk_rw_rq_prep(mq->mqrq_cur, card, 0, mq);
mmc_start_req(card->host,
&mq->mqrq_cur->mmc_active,
NULL);
}
}
return 0;
}
static int mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
{
int ret;
struct mmc_blk_data *md = mq->data;
struct mmc_card *card = md->queue.card;
struct mmc_host *host = card->host;
unsigned long flags;
if (req && !mq->mqrq_prev->req) {
mmc_rpm_hold(host, &card->dev);
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
if (mmc_bus_needs_resume(card->host)) {
mmc_resume_bus(card->host);
}
#endif
/* claim host only for the first request */
mmc_claim_host(card->host);
if (card->ext_csd.bkops_en)
mmc_stop_bkops(card);
}
#ifdef CONFIG_VENDOR_EDIT
//[email protected], 2013/12/28, Add for solve QT bug(ID:390597): Bad micro SD card cause the phone to suspend/wakeup abnormal
if ((card->host->index == 1) && bad_micro_sd_card) {
if (req) {
blk_end_request_all(req, -EIO);
printk(KERN_ERR"%s: bad sd card had been detected. do nothing.\n", __func__);
ret = -EIO;
goto out;
}
}
#endif /* VENDOR_EDIT */
ret = mmc_blk_part_switch(card, md);
if (ret) {
if (req) {
blk_end_request_all(req, -EIO);
}
ret = 0;
goto out;
}
mmc_blk_write_packing_control(mq, req);
mq->flags &= ~MMC_QUEUE_NEW_REQUEST;
mq->flags &= ~MMC_QUEUE_URGENT_REQUEST;
if (req && req->cmd_flags & REQ_SANITIZE) {
/* complete ongoing async transfer before issuing sanitize */
if (card->host && card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = mmc_blk_issue_sanitize_rq(mq, req);
} else if (req && req->cmd_flags & REQ_DISCARD) {
/* complete ongoing async transfer before issuing discard */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
if (req->cmd_flags & REQ_SECURE &&
!(card->quirks & MMC_QUIRK_SEC_ERASE_TRIM_BROKEN))
ret = mmc_blk_issue_secdiscard_rq(mq, req);
else
ret = mmc_blk_issue_discard_rq(mq, req);
} else if (req && req->cmd_flags & REQ_FLUSH) {
/* complete ongoing async transfer before issuing flush */
if (card->host->areq)
mmc_blk_issue_rw_rq(mq, NULL);
ret = mmc_blk_issue_flush(mq, req);
} else {
if (!req && host->areq) {
spin_lock_irqsave(&host->context_info.lock, flags);
host->context_info.is_waiting_last_req = true;
spin_unlock_irqrestore(&host->context_info.lock, flags);
}
ret = mmc_blk_issue_rw_rq(mq, req);
}
out:
/*
* packet burst is over, when one of the following occurs:
* - no more requests and new request notification is not in progress
* - urgent notification in progress and current request is not urgent
* (all existing requests completed or reinserted to the block layer)
*/
if ((!req && !(mq->flags & MMC_QUEUE_NEW_REQUEST)) ||
((mq->flags & MMC_QUEUE_URGENT_REQUEST) &&
!(mq->mqrq_cur->req->cmd_flags &
MMC_REQ_NOREINSERT_MASK))) {
if (mmc_card_need_bkops(card))
mmc_start_bkops(card, false);
/* release host only when there are no more requests */
mmc_release_host(card->host);
mmc_rpm_release(host, &card->dev);
}
return ret;
}
static inline int mmc_blk_readonly(struct mmc_card *card)
{
return mmc_card_readonly(card) ||
!(card->csd.cmdclass & CCC_BLOCK_WRITE);
}
static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
struct device *parent,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
struct mmc_blk_data *md;
int devidx, ret;
unsigned int percentage =
BKOPS_SIZE_PERCENTAGE_TO_QUEUE_DELAYED_WORK;
devidx = find_first_zero_bit(dev_use, max_devices);
if (devidx >= max_devices)
return ERR_PTR(-ENOSPC);
__set_bit(devidx, dev_use);
md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
if (!md) {
ret = -ENOMEM;
goto out;
}
/*
* !subname implies we are creating main mmc_blk_data that will be
* associated with mmc_card with mmc_set_drvdata. Due to device
* partitions, devidx will not coincide with a per-physical card
* index anymore so we keep track of a name index.
*/
if (!subname) {
md->name_idx = find_first_zero_bit(name_use, max_devices);
__set_bit(md->name_idx, name_use);
} else
md->name_idx = ((struct mmc_blk_data *)
dev_to_disk(parent)->private_data)->name_idx;
md->area_type = area_type;
/*
* Set the read-only status based on the supported commands
* and the write protect switch.
*/
md->read_only = mmc_blk_readonly(card);
md->disk = alloc_disk(perdev_minors);
if (md->disk == NULL) {
ret = -ENOMEM;
goto err_kfree;
}
spin_lock_init(&md->lock);
INIT_LIST_HEAD(&md->part);
md->usage = 1;
ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
if (ret)
goto err_putdisk;
md->queue.issue_fn = mmc_blk_issue_rq;
md->queue.data = md;
md->disk->major = MMC_BLOCK_MAJOR;
md->disk->first_minor = devidx * perdev_minors;
md->disk->fops = &mmc_bdops;
md->disk->private_data = md;
md->disk->queue = md->queue.queue;
md->disk->driverfs_dev = parent;
set_disk_ro(md->disk, md->read_only || default_ro);
md->disk->flags = GENHD_FL_EXT_DEVT;
if (area_type & MMC_BLK_DATA_AREA_RPMB)
md->disk->flags |= GENHD_FL_NO_PART_SCAN;
/*
* As discussed on lkml, GENHD_FL_REMOVABLE should:
*
* - be set for removable media with permanent block devices
* - be unset for removable block devices with permanent media
*
* Since MMC block devices clearly fall under the second
* case, we do not set GENHD_FL_REMOVABLE. Userspace
* should use the block device creation/destruction hotplug
* messages to tell when the card is present.
*/
snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
"mmcblk%d%s", md->name_idx, subname ? subname : "");
blk_queue_logical_block_size(md->queue.queue, 512);
set_capacity(md->disk, size);
card->bkops_info.size_percentage_to_queue_delayed_work = percentage;
card->bkops_info.min_sectors_to_queue_delayed_work =
((unsigned int)size * percentage) / 100;
if (mmc_host_cmd23(card->host)) {
if (mmc_card_mmc(card) ||
(mmc_card_sd(card) &&
card->scr.cmds & SD_SCR_CMD23_SUPPORT))
md->flags |= MMC_BLK_CMD23;
}
if (mmc_card_mmc(card) &&
md->flags & MMC_BLK_CMD23 &&
((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
card->ext_csd.rel_sectors)) {
md->flags |= MMC_BLK_REL_WR;
blk_queue_flush(md->queue.queue, REQ_FLUSH | REQ_FUA);
}
return md;
err_putdisk:
put_disk(md->disk);
err_kfree:
if (!subname)
__clear_bit(md->name_idx, name_use);
kfree(md);
out:
__clear_bit(devidx, dev_use);
return ERR_PTR(ret);
}
static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
{
sector_t size;
struct mmc_blk_data *md;
if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
/*
* The EXT_CSD sector count is in number or 512 byte
* sectors.
*/
size = card->ext_csd.sectors;
} else {
/*
* The CSD capacity field is in units of read_blkbits.
* set_capacity takes units of 512 bytes.
*/
size = card->csd.capacity << (card->csd.read_blkbits - 9);
}
md = mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
MMC_BLK_DATA_AREA_MAIN);
return md;
}
static int mmc_blk_alloc_part(struct mmc_card *card,
struct mmc_blk_data *md,
unsigned int part_type,
sector_t size,
bool default_ro,
const char *subname,
int area_type)
{
char cap_str[10];
struct mmc_blk_data *part_md;
part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
subname, area_type);
if (IS_ERR(part_md))
return PTR_ERR(part_md);
part_md->part_type = part_type;
list_add(&part_md->part, &md->part);
string_get_size((u64)get_capacity(part_md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s partition %u %s\n",
part_md->disk->disk_name, mmc_card_id(card),
mmc_card_name(card), part_md->part_type, cap_str);
return 0;
}
/* MMC Physical partitions consist of two boot partitions and
* up to four general purpose partitions.
* For each partition enabled in EXT_CSD a block device will be allocatedi
* to provide access to the partition.
*/
static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
{
int idx, ret = 0;
if (!mmc_card_mmc(card))
return 0;
for (idx = 0; idx < card->nr_parts; idx++) {
if (card->part[idx].size) {
ret = mmc_blk_alloc_part(card, md,
card->part[idx].part_cfg,
card->part[idx].size >> 9,
card->part[idx].force_ro,
card->part[idx].name,
card->part[idx].area_type);
if (ret)
return ret;
}
}
return ret;
}
static void mmc_blk_remove_req(struct mmc_blk_data *md)
{
struct mmc_card *card;
if (md) {
card = md->queue.card;
device_remove_file(disk_to_dev(md->disk),
&md->num_wr_reqs_to_start_packing);
if (md->disk->flags & GENHD_FL_UP) {
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
card->ext_csd.boot_ro_lockable)
device_remove_file(disk_to_dev(md->disk),
&md->power_ro_lock);
/* Stop new requests from getting into the queue */
del_gendisk(md->disk);
}
/* Then flush out any already in there */
mmc_cleanup_queue(&md->queue);
mmc_blk_put(md);
}
}
static void mmc_blk_remove_parts(struct mmc_card *card,
struct mmc_blk_data *md)
{
struct list_head *pos, *q;
struct mmc_blk_data *part_md;
__clear_bit(md->name_idx, name_use);
list_for_each_safe(pos, q, &md->part) {
part_md = list_entry(pos, struct mmc_blk_data, part);
list_del(pos);
mmc_blk_remove_req(part_md);
}
}
static int mmc_add_disk(struct mmc_blk_data *md)
{
int ret;
struct mmc_card *card = md->queue.card;
add_disk(md->disk);
md->force_ro.show = force_ro_show;
md->force_ro.store = force_ro_store;
sysfs_attr_init(&md->force_ro.attr);
md->force_ro.attr.name = "force_ro";
md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
if (ret)
goto force_ro_fail;
if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
card->ext_csd.boot_ro_lockable) {
umode_t mode;
if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
mode = S_IRUGO;
else
mode = S_IRUGO | S_IWUSR;
md->power_ro_lock.show = power_ro_lock_show;
md->power_ro_lock.store = power_ro_lock_store;
sysfs_attr_init(&md->power_ro_lock.attr);
md->power_ro_lock.attr.mode = mode;
md->power_ro_lock.attr.name =
"ro_lock_until_next_power_on";
ret = device_create_file(disk_to_dev(md->disk),
&md->power_ro_lock);
if (ret)
goto power_ro_lock_fail;
}
md->num_wr_reqs_to_start_packing.show =
num_wr_reqs_to_start_packing_show;
md->num_wr_reqs_to_start_packing.store =
num_wr_reqs_to_start_packing_store;
sysfs_attr_init(&md->num_wr_reqs_to_start_packing.attr);
md->num_wr_reqs_to_start_packing.attr.name =
"num_wr_reqs_to_start_packing";
md->num_wr_reqs_to_start_packing.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md->num_wr_reqs_to_start_packing);
if (ret)
goto num_wr_reqs_to_start_packing_fail;
md->bkops_check_threshold.show = bkops_check_threshold_show;
md->bkops_check_threshold.store = bkops_check_threshold_store;
sysfs_attr_init(&md->bkops_check_threshold.attr);
md->bkops_check_threshold.attr.name = "bkops_check_threshold";
md->bkops_check_threshold.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md->bkops_check_threshold);
if (ret)
goto bkops_check_threshold_fails;
md->no_pack_for_random.show = no_pack_for_random_show;
md->no_pack_for_random.store = no_pack_for_random_store;
sysfs_attr_init(&md->no_pack_for_random.attr);
md->no_pack_for_random.attr.name = "no_pack_for_random";
md->no_pack_for_random.attr.mode = S_IRUGO | S_IWUSR;
ret = device_create_file(disk_to_dev(md->disk),
&md->no_pack_for_random);
if (ret)
goto no_pack_for_random_fails;
return ret;
no_pack_for_random_fails:
device_remove_file(disk_to_dev(md->disk),
&md->bkops_check_threshold);
bkops_check_threshold_fails:
device_remove_file(disk_to_dev(md->disk),
&md->num_wr_reqs_to_start_packing);
num_wr_reqs_to_start_packing_fail:
device_remove_file(disk_to_dev(md->disk), &md->power_ro_lock);
power_ro_lock_fail:
device_remove_file(disk_to_dev(md->disk), &md->force_ro);
force_ro_fail:
del_gendisk(md->disk);
return ret;
}
static const struct mmc_fixup blk_fixups[] =
{
MMC_FIXUP("SEM02G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM04G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM08G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM16G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
MMC_FIXUP("SEM32G", CID_MANFID_SANDISK, 0x100, add_quirk,
MMC_QUIRK_INAND_CMD38),
/*
* Some MMC cards experience performance degradation with CMD23
* instead of CMD12-bounded multiblock transfers. For now we'll
* black list what's bad...
* - Certain Toshiba cards.
*
* N.B. This doesn't affect SD cards.
*/
MMC_FIXUP("MMC08G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC16G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
MMC_FIXUP("MMC32G", CID_MANFID_TOSHIBA, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BLK_NO_CMD23),
/*
* Some Micron MMC cards needs longer data read timeout than
* indicated in CSD.
*/
MMC_FIXUP(CID_NAME_ANY, CID_MANFID_MICRON, 0x200, add_quirk_mmc,
MMC_QUIRK_LONG_READ_TIME),
/* Some INAND MCP devices advertise incorrect timeout values */
MMC_FIXUP("SEM04G", 0x45, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_INAND_DATA_TIMEOUT),
/*
* On these Samsung MoviNAND parts, performing secure erase or
* secure trim can result in unrecoverable corruption due to a
* firmware bug.
*/
MMC_FIXUP("M8G2FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MAG4FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MBG8FA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("MCGAFA", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VAL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("KYL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP("VZL00M", CID_MANFID_SAMSUNG, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_SEC_ERASE_TRIM_BROKEN),
MMC_FIXUP(CID_NAME_ANY, CID_MANFID_HYNIX, CID_OEMID_ANY, add_quirk_mmc,
MMC_QUIRK_BROKEN_DATA_TIMEOUT),
END_FIXUP
};
static int mmc_blk_probe(struct mmc_card *card)
{
struct mmc_blk_data *md, *part_md;
char cap_str[10];
#ifdef CONFIG_OPPO_DEVICE_INFO
//[email protected], 2013/10/24, Add for eMMC and DDR device information
char * manufacturerid;
struct manufacture_info ddr_info_1 = {
.version = "EDFA164A2PB",
.manufacture = "ELPIDA",
};
struct manufacture_info ddr_info_2 = {
.version = "K3QF7F70DM",
.manufacture = "SAMSUNG",
};
#endif /* VENDOR_EDIT */
/*
* Check that the card supports the command class(es) we need.
*/
if (!(card->csd.cmdclass & CCC_BLOCK_READ))
return -ENODEV;
#ifdef CONFIG_OPPO_DEVICE_INFO
//[email protected], 2013/10/24, Add for eMMC and DDR device information
switch (card->cid.manfid) {
case 0x11:
manufacturerid = "TOSHIBA";
break;
case 0x15:
manufacturerid = "SAMSUNG";
break;
case 0x45:
manufacturerid = "SANDISK";
break;
default:
manufacturerid = "unknown";
break;
}
if (!strcmp(mmc_card_id(card), "mmc0:0001")) {
register_device_proc("emmc", mmc_card_name(card), manufacturerid);
if (get_pcb_version() < HW_VERSION__20)
register_device_proc("ddr", ddr_info_1.version, ddr_info_1.manufacture);
else
register_device_proc("ddr", ddr_info_2.version, ddr_info_2.manufacture);
}
#endif /* VENDOR_EDIT */
md = mmc_blk_alloc(card);
if (IS_ERR(md))
return PTR_ERR(md);
string_get_size((u64)get_capacity(md->disk) << 9, STRING_UNITS_2,
cap_str, sizeof(cap_str));
pr_info("%s: %s %s %s %s\n",
md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
cap_str, md->read_only ? "(ro)" : "");
if (mmc_blk_alloc_parts(card, md))
goto out;
mmc_set_drvdata(card, md);
mmc_fixup_device(card, blk_fixups);
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
mmc_set_bus_resume_policy(card->host, 1);
#endif
if (mmc_add_disk(md))
goto out;
list_for_each_entry(part_md, &md->part, part) {
if (mmc_add_disk(part_md))
goto out;
}
return 0;
out:
mmc_blk_remove_parts(card, md);
mmc_blk_remove_req(md);
return 0;
}
static void mmc_blk_remove(struct mmc_card *card)
{
struct mmc_blk_data *md = mmc_get_drvdata(card);
mmc_blk_remove_parts(card, md);
mmc_claim_host(card->host);
mmc_blk_part_switch(card, md);
mmc_release_host(card->host);
mmc_blk_remove_req(md);
mmc_set_drvdata(card, NULL);
#ifdef CONFIG_MMC_BLOCK_DEFERRED_RESUME
mmc_set_bus_resume_policy(card->host, 0);
#endif
}
static void mmc_blk_shutdown(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
int rc;
/* Silent the block layer */
if (md) {
rc = mmc_queue_suspend(&md->queue, 1);
if (rc)
goto suspend_error;
list_for_each_entry(part_md, &md->part, part) {
rc = mmc_queue_suspend(&part_md->queue, 1);
if (rc)
goto suspend_error;
}
}
/* send power off notification */
if (mmc_card_mmc(card)) {
mmc_rpm_hold(card->host, &card->dev);
mmc_claim_host(card->host);
mmc_stop_bkops(card);
mmc_release_host(card->host);
mmc_send_long_pon(card);
mmc_rpm_release(card->host, &card->dev);
}
return;
suspend_error:
pr_err("%s: mmc_queue_suspend returned error = %d",
mmc_hostname(card->host), rc);
}
#ifdef CONFIG_PM
static int mmc_blk_suspend(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
int rc = 0;
if (md) {
rc = mmc_queue_suspend(&md->queue, 0);
if (rc)
goto out;
list_for_each_entry(part_md, &md->part, part) {
rc = mmc_queue_suspend(&part_md->queue, 0);
if (rc)
goto out_resume;
}
}
goto out;
out_resume:
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
out:
return rc;
}
static int mmc_blk_resume(struct mmc_card *card)
{
struct mmc_blk_data *part_md;
struct mmc_blk_data *md = mmc_get_drvdata(card);
if (md) {
/*
* Resume involves the card going into idle state,
* so current partition is always the main one.
*/
md->part_curr = md->part_type;
mmc_queue_resume(&md->queue);
list_for_each_entry(part_md, &md->part, part) {
mmc_queue_resume(&part_md->queue);
}
}
return 0;
}
#else
#define mmc_blk_suspend NULL
#define mmc_blk_resume NULL
#endif
static struct mmc_driver mmc_driver = {
.drv = {
.name = "mmcblk",
},
.probe = mmc_blk_probe,
.remove = mmc_blk_remove,
.suspend = mmc_blk_suspend,
.resume = mmc_blk_resume,
.shutdown = mmc_blk_shutdown,
};
static int __init mmc_blk_init(void)
{
int res;
if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
pr_info("mmcblk: using %d minors per device\n", perdev_minors);
max_devices = 256 / perdev_minors;
res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
if (res)
goto out;
res = mmc_register_driver(&mmc_driver);
if (res)
goto out2;
return 0;
out2:
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
out:
return res;
}
static void __exit mmc_blk_exit(void)
{
mmc_unregister_driver(&mmc_driver);
unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
}
module_init(mmc_blk_init);
module_exit(mmc_blk_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
| gpl-2.0 |
zioproto/SDK.UBNT.v5.5 | feeds/packages/Xorg/xorg/driver/xf86-video-nv/Makefile | 2088 | #
# Copyright (C) 2007 OpenWrt.org
#
# This is free software, licensed under the GNU General Public License v2.
# See /LICENSE for more information.
#
# [email protected]
include $(TOPDIR)/rules.mk
PKG_BASE_NAME:=xf86
PKG_NAME:=xf86-video-nv
PKG_RELEASE:=3
PKG_VERSION:=2.1.12
PKG_SOURCE_URL:=http://xorg.freedesktop.org/releases/X11R7.4/src/driver
PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
PKG_BUILD_DIR=$(BUILD_DIR)/Xorg/$(_CATEGORY)/${PKG_NAME}-$(PKG_VERSION)/
PKG_MD5SUM:=42f12a36d7afc26c817e8e8f5c8b7274
include $(INCLUDE_DIR)/package.mk
define Package/xf86-video-nv
SECTION:=xorg-driver
CATEGORY:=Xorg
SUBMENU:=driver
DEPENDS:=+xserver-xorg
TITLE:=xf86-video-nv
URL:=http://xorg.freedesktop.org/
endef
define Build/InstallDev
DESTDIR="$(1)" $(MAKE) -C $(PKG_BUILD_DIR)/ $(MAKE_FLAGS) install
endef
EXTRA_CPPFLAGS= -I$(STAGING_DIR)/usr/include/xorg \
-I$(STAGING_DIR)/usr/include/X11/ \
-I$(STAGING_DIR)/usr/include/ \
-I$(STAGING_DIR)/include/
EXTRA_CFLAGS+= $(EXTRA_CPPFLAGS)
acvar=$(subst -,_,$(subst .,_,$(subst /,_,$(1))))
CONFIGURE_VARS +=DRI_CFLAGS="-I$(STAGING_DIR)/usr/include/X11/dri/" ac_cv_file__usr_share_sgml_X11_defs_ent=yes \
sdkdir=$(STAGING_DIR)
define Build/Configure
(cd $(PKG_BUILD_DIR)/$(CONFIGURE_PATH); \
if [ -x $(CONFIGURE_CMD) ]; then \
$(CP) $(SCRIPT_DIR)/config.{guess,sub} $(PKG_BUILD_DIR)/ && \
$(foreach a,dri.h sarea.h dristruct.h exa.h damage.h,export ac_cv_file_$(call acvar,$(STAGING_DIR)/usr/include/xorg/$(a))=yes;) \
sed -i "s|sdkdir=.*|sdkdir=$(STAGING_DIR)/usr/include/xorg|g" $(PKG_BUILD_DIR)/configure ;\
$(CONFIGURE_VARS) \
$(CONFIGURE_CMD) \
$(CONFIGURE_ARGS_XTRA) \
$(CONFIGURE_ARGS) \
CPPFLAGS="$(EXTRA_CPPFLAGS)" ;\
fi \
)
endef
define Build/Compile
make -C $(PKG_BUILD_DIR)
DESTDIR=$(PKG_INSTALL_DIR) $(MAKE) -C $(PKG_BUILD_DIR) $(MAKE_FLAGS) install
find $(PKG_INSTALL_DIR) -name *a | xargs rm -rf
endef
define Package/xf86-video-nv/install
$(INSTALL_DIR) $(1)/usr/lib/
$(CP) $(PKG_INSTALL_DIR)/usr/lib/* $(1)/usr/lib/
endef
$(eval $(call BuildPackage,xf86-video-nv))
| gpl-2.0 |
tanya-guza/abiword | plugins/mathview/xp/gr_Abi_CharArea.cpp | 2657 | /* AbiWord
* Copyright (C) 2004 Luca Padovani <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "gr_Graphics.h"
#include "gr_Abi_CharArea.h"
#include "gr_Abi_RenderingContext.h"
GR_Abi_CharArea::GR_Abi_CharArea(GR_Graphics* graphics, GR_Font* f, const scaled& /*size*/, UT_UCS4Char c)
: m_pFont(f), m_ch(c)
{
#if 0
UT_ASSERT(graphics);
graphics->setFont(m_pFont);
m_box = BoundingBox(GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->measureUnRemappedChar(m_ch)),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontAscent()),
GR_Abi_RenderingContext::fromAbiLayoutUnits(graphics->getFontDescent()));
#else
UT_ASSERT(f);
UT_Rect glyphRect;
graphics->setFont(m_pFont);
f->glyphBox(m_ch, glyphRect, graphics);
GR_Abi_RenderingContext Context(graphics);
#if 0
fprintf(stderr, "getting glyph %d\n glyphBox [left=%d,width=%d,top=%d,height=%d]\n measureUnremappedChar=%d\n measureUnremappedCharForCache=%d\n ftlu=%f\n tdu=%f\n tlu=%f\n size=%d\n", c,
glyphRect.left, glyphRect.width, glyphRect.top, glyphRect.height,
graphics->measureUnRemappedChar(m_ch),
f->measureUnremappedCharForCache(m_ch),
graphics->ftluD(1.0),
graphics->tduD(1.0),
graphics->tluD(1.0),
size.getValue());
#endif
m_box = BoundingBox(Context.fromAbiLayoutUnits(glyphRect.width + glyphRect.left),
Context.fromAbiLayoutUnits(glyphRect.top),
Context.fromAbiLayoutUnits(glyphRect.height - glyphRect.top));
#endif
}
GR_Abi_CharArea::~GR_Abi_CharArea()
{ }
BoundingBox
GR_Abi_CharArea::box() const
{
return m_box;
}
scaled
GR_Abi_CharArea::leftEdge() const
{
return 0;
}
scaled
GR_Abi_CharArea::rightEdge() const
{
return m_box.width;
}
void
GR_Abi_CharArea::render(RenderingContext& c, const scaled& x, const scaled& y) const
{
GR_Abi_RenderingContext& context = dynamic_cast<GR_Abi_RenderingContext&>(c);
context.drawChar(x, y, m_pFont, m_ch);
//context.drawBox(x, y, m_box);
}
| gpl-2.0 |
Alexpux/GCC | gcc/testsuite/gcc.target/i386/avx512dq-vbroadcasti32x2-2.c | 1145 | /* { dg-do run } */
/* { dg-options "-O2 -mavx512dq -DAVX512DQ" } */
/* { dg-require-effective-target avx512dq } */
#include "avx512f-helper.h"
#define SIZE (AVX512F_LEN / 32)
#include "avx512f-mask-type.h"
void
CALC (int *r, int *s)
{
int i;
for (i = 0; i < SIZE; i++)
{
r[i] = s[i % 2];
}
}
void
TEST (void)
{
int i, sign;
UNION_TYPE (AVX512F_LEN, i_d) res1, res2, res3;
UNION_TYPE (128, i_d) src;
MASK_TYPE mask = SIZE | 123;
int res_ref[SIZE];
sign = -1;
for (i = 0; i < 4; i++)
{
src.a[i] = 34 * i * sign;
sign = sign * -1;
}
for (i = 0; i < SIZE; i++)
res2.a[i] = DEFAULT_VALUE;
res1.x = INTRINSIC (_broadcast_i32x2) (src.x);
res2.x = INTRINSIC (_mask_broadcast_i32x2) (res2.x, mask, src.x);
res3.x = INTRINSIC (_maskz_broadcast_i32x2) (mask, src.x);
CALC (res_ref, src.a);
if (UNION_CHECK (AVX512F_LEN, i_d) (res1, res_ref))
abort ();
MASK_MERGE (i_d) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_d) (res2, res_ref))
abort ();
MASK_ZERO (i_d) (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, i_d) (res3, res_ref))
abort ();
}
| gpl-2.0 |
404pnf/d7sites | sites/csc.fltrp.com/themes/standard/omega/omega/templates/zone.tpl.php | 1173 | <?php
/**
* @file
* Default theme implementation to display a region.
*
* Available variables:
* - $regions: Renderable array of regions associated with this zone
* - $enabled: Flag to detect if the zone was enabled/disabled via theme settings
* - $wrapper: Flag set to display a full browser width wrapper around the
* container zone allowing items/backgrounds to be themed outside the
* 960pixel container size.
* - $zid: the zone id of the zone being rendered. This is a text value.
* - $container_width: the container width (12, 16, 24) of the zone
* - $attributes: a string containing the relevant class & id data for a container
*
* Helper Variables
* - $attributes_array: an array of attributes for the container zone
*
* @see template_preprocess()
* @see template_preprocess_zone()
* @see template_process()
* @see template_process_zone()
*/
?>
<?php if($enabled && $populated): ?>
<?php if($wrapper): ?><div id="<?php print $zid;?>-outer-wrapper" class="clearfix"><?php endif; ?>
<div <?php print $attributes; ?>>
<?php print render($regions); ?>
</div>
<?php if($wrapper): ?></div><?php endif; ?>
<?php endif; ?> | gpl-2.0 |
geopython/QGIS | src/core/raster/qgsrasterfilewriter.h | 12940 | /***************************************************************************
qgsrasterfilewriter.h
---------------------
begin : July 2012
copyright : (C) 2012 by Marco Hugentobler
email : marco dot hugentobler at sourcepole dot ch
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef QGSRASTERFILEWRITER_H
#define QGSRASTERFILEWRITER_H
#include "qgis_core.h"
#include "qgscoordinatereferencesystem.h"
#include <QDomDocument>
#include <QDomElement>
#include <QString>
#include <QStringList>
#include "qgsraster.h"
class QgsRasterBlockFeedback;
class QgsRasterIterator;
class QgsRasterPipe;
class QgsRectangle;
class QgsRasterDataProvider;
class QgsRasterInterface;
/**
* \ingroup core
* The raster file writer which allows you to save a raster to a new file.
*/
class CORE_EXPORT QgsRasterFileWriter
{
public:
enum Mode
{
Raw = 0, //!< Raw data
Image = 1 //!< Rendered image
};
enum WriterError
{
NoError = 0,
SourceProviderError = 1,
DestProviderError = 2,
CreateDatasourceError = 3,
WriteError = 4,
NoDataConflict = 5, //!< Internal error if a value used for 'no data' was found in input
WriteCanceled = 6, //!< Writing was manually canceled
};
/**
* Options for sorting and filtering raster formats.
* \since QGIS 3.0
*/
enum RasterFormatOption
{
SortRecommended = 1 << 1, //!< Use recommended sort order, with extremely commonly used formats listed first
};
Q_DECLARE_FLAGS( RasterFormatOptions, RasterFormatOption )
QgsRasterFileWriter( const QString &outputUrl );
/**
* Create a raster file with one band without initializing the pixel data.
* Returned provider may be used to initialize the raster using writeBlock() calls.
* Ownership of the returned provider is passed to the caller.
* \returns Instance of data provider in editing mode (on success) or nullptr on error.
* \note Does not work with tiled mode enabled.
* \since QGIS 3.0
*/
QgsRasterDataProvider *createOneBandRaster( Qgis::DataType dataType,
int width, int height,
const QgsRectangle &extent,
const QgsCoordinateReferenceSystem &crs ) SIP_FACTORY;
/**
* Create a raster file with given number of bands without initializing the pixel data.
* Returned provider may be used to initialize the raster using writeBlock() calls.
* Ownership of the returned provider is passed to the caller.
* \returns Instance of data provider in editing mode (on success) or nullptr on error.
* \note Does not work with tiled mode enabled.
* \since QGIS 3.0
*/
QgsRasterDataProvider *createMultiBandRaster( Qgis::DataType dataType,
int width, int height,
const QgsRectangle &extent,
const QgsCoordinateReferenceSystem &crs,
int nBands ) SIP_FACTORY;
/**
* Write raster file
\param pipe raster pipe
\param nCols number of output columns
\param nRows number of output rows (or -1 to automatically calculate row number to have square pixels)
\param outputExtent extent to output
\param crs crs to reproject to
\param feedback optional feedback object for progress reports
*/
WriterError writeRaster( const QgsRasterPipe *pipe, int nCols, int nRows, const QgsRectangle &outputExtent,
const QgsCoordinateReferenceSystem &crs, QgsRasterBlockFeedback *feedback = nullptr );
/**
* Returns the output URL for the raster.
* \since QGIS 3.0
*/
QString outputUrl() const { return mOutputUrl; }
void setOutputFormat( const QString &format ) { mOutputFormat = format; }
QString outputFormat() const { return mOutputFormat; }
void setOutputProviderKey( const QString &key ) { mOutputProviderKey = key; }
QString outputProviderKey() const { return mOutputProviderKey; }
void setTiledMode( bool t ) { mTiledMode = t; }
bool tiledMode() const { return mTiledMode; }
void setMaxTileWidth( int w ) { mMaxTileWidth = w; }
int maxTileWidth() const { return mMaxTileWidth; }
QgsRaster::RasterBuildPyramids buildPyramidsFlag() const { return mBuildPyramidsFlag; }
void setBuildPyramidsFlag( QgsRaster::RasterBuildPyramids f ) { mBuildPyramidsFlag = f; }
QList< int > pyramidsList() const { return mPyramidsList; }
void setPyramidsList( const QList< int > &list ) { mPyramidsList = list; }
QString pyramidsResampling() const { return mPyramidsResampling; }
void setPyramidsResampling( const QString &str ) { mPyramidsResampling = str; }
QgsRaster::RasterPyramidsFormat pyramidsFormat() const { return mPyramidsFormat; }
void setPyramidsFormat( QgsRaster::RasterPyramidsFormat f ) { mPyramidsFormat = f; }
void setMaxTileHeight( int h ) { mMaxTileHeight = h; }
int maxTileHeight() const { return mMaxTileHeight; }
void setCreateOptions( const QStringList &list ) { mCreateOptions = list; }
QStringList createOptions() const { return mCreateOptions; }
void setPyramidsConfigOptions( const QStringList &list ) { mPyramidsConfigOptions = list; }
QStringList pyramidsConfigOptions() const { return mPyramidsConfigOptions; }
//! Creates a filter for an GDAL driver key
static QString filterForDriver( const QString &driverName );
/**
* Details of available filters and formats.
* \since QGIS 3.0
*/
struct FilterFormatDetails
{
//! Unique driver name
QString driverName;
//! Filter string for file picker dialogs
QString filterString;
};
/**
* Returns a list or pairs, with format filter string as first element and GDAL format key as second element.
* Relies on GDAL_DMD_EXTENSIONS metadata, if it is empty corresponding driver will be skipped even if supported.
*
* The \a options argument can be used to control the sorting and filtering of
* returned formats.
*
* \see supportedFormatExtensions()
*/
static QList< QgsRasterFileWriter::FilterFormatDetails > supportedFiltersAndFormats( RasterFormatOptions options = SortRecommended );
/**
* Returns a list of file extensions for supported formats.
*
* The \a options argument can be used to control the sorting and filtering of
* returned formats.
*
* \see supportedFiltersAndFormats()
* \since QGIS 3.0
*/
static QStringList supportedFormatExtensions( RasterFormatOptions options = SortRecommended );
/**
* Returns the GDAL driver name for a specified file \a extension. E.g. the
* driver name for the ".tif" extension is "GTiff".
* If no suitable drivers are found then an empty string is returned.
*
* Note that this method works for all GDAL drivers, including those without create support
* (and which are not supported by QgsRasterFileWriter).
*
* \since QGIS 3.0
*/
static QString driverForExtension( const QString &extension );
/**
* Returns a list of known file extensions for the given GDAL driver \a format.
* E.g. returns "tif", "tiff" for the format "GTiff".
*
* If no matching format driver is found an empty list will be returned.
*
* Note that this method works for all GDAL drivers, including those without create support
* (and which are not supported by QgsRasterFileWriter).
*
* \since QGIS 3.0
*/
static QStringList extensionsForFormat( const QString &format );
private:
QgsRasterFileWriter(); //forbidden
WriterError writeDataRaster( const QgsRasterPipe *pipe, QgsRasterIterator *iter, int nCols, int nRows, const QgsRectangle &outputExtent,
const QgsCoordinateReferenceSystem &crs, QgsRasterBlockFeedback *feedback = nullptr );
// Helper method used by previous one
WriterError writeDataRaster( const QgsRasterPipe *pipe,
QgsRasterIterator *iter,
int nCols, int nRows,
const QgsRectangle &outputExtent,
const QgsCoordinateReferenceSystem &crs,
Qgis::DataType destDataType,
const QList<bool> &destHasNoDataValueList,
const QList<double> &destNoDataValueList,
QgsRasterDataProvider *destProvider,
QgsRasterBlockFeedback *feedback = nullptr );
WriterError writeImageRaster( QgsRasterIterator *iter, int nCols, int nRows, const QgsRectangle &outputExtent,
const QgsCoordinateReferenceSystem &crs,
QgsRasterBlockFeedback *feedback = nullptr );
/**
* \brief Initialize vrt member variables
* \param xSize width of vrt
* \param ySize height of vrt
* \param crs coordinate system of vrt
* \param geoTransform optional array of transformation matrix values
* \param type datatype of vrt
* \param destHasNoDataValueList true if destination has no data value, indexed from 0
* \param destNoDataValueList no data value, indexed from 0
*/
void createVRT( int xSize, int ySize, const QgsCoordinateReferenceSystem &crs, double *geoTransform, Qgis::DataType type, const QList<bool> &destHasNoDataValueList, const QList<double> &destNoDataValueList );
//write vrt document to disk
bool writeVRT( const QString &file );
//add file entry to vrt
void addToVRT( const QString &filename, int band, int xSize, int ySize, int xOffset, int yOffset );
void buildPyramids( const QString &filename, QgsRasterDataProvider *destProviderIn = nullptr );
//! Create provider and datasource for a part image (vrt mode)
QgsRasterDataProvider *createPartProvider( const QgsRectangle &extent, int nCols, int iterCols, int iterRows,
int iterLeft, int iterTop,
const QString &outputUrl, int fileIndex, int nBands, Qgis::DataType type,
const QgsCoordinateReferenceSystem &crs );
/**
* \brief Init VRT (for tiled mode) or create global output provider (single-file mode)
* \param nCols number of tile columns
* \param nRows number of tile rows
* \param crs coordinate system of vrt
* \param geoTransform optional array of transformation matrix values
* \param nBands number of bands
* \param type datatype of vrt
* \param destHasNoDataValueList true if destination has no data value, indexed from 0
* \param destNoDataValueList no data value, indexed from 0
*/
QgsRasterDataProvider *initOutput( int nCols, int nRows,
const QgsCoordinateReferenceSystem &crs, double *geoTransform, int nBands,
Qgis::DataType type,
const QList<bool> &destHasNoDataValueList = QList<bool>(), const QList<double> &destNoDataValueList = QList<double>() );
//! Calculate nRows, geotransform and pixel size for output
void globalOutputParameters( const QgsRectangle &extent, int nCols, int &nRows, double *geoTransform, double &pixelSize );
QString partFileName( int fileIndex );
QString vrtFileName();
Mode mMode = Raw;
QString mOutputUrl;
QString mOutputProviderKey = QStringLiteral( "gdal" );
QString mOutputFormat = QStringLiteral( "GTiff" );
QStringList mCreateOptions;
QgsCoordinateReferenceSystem mOutputCRS;
//! False: Write one file, true: create a directory and add the files numbered
bool mTiledMode = false;
double mMaxTileWidth = 500;
double mMaxTileHeight = 500;
QList< int > mPyramidsList;
QString mPyramidsResampling = QStringLiteral( "AVERAGE" );
QgsRaster::RasterBuildPyramids mBuildPyramidsFlag = QgsRaster::PyramidsFlagNo;
QgsRaster::RasterPyramidsFormat mPyramidsFormat = QgsRaster::PyramidsGTiff;
QStringList mPyramidsConfigOptions;
QDomDocument mVRTDocument;
QList<QDomElement> mVRTBands;
QgsRasterBlockFeedback *mFeedback = nullptr;
const QgsRasterPipe *mPipe = nullptr;
const QgsRasterInterface *mInput = nullptr;
};
#endif // QGSRASTERFILEWRITER_H
| gpl-2.0 |
vFiv/spring-oauth-server | src/main/java/cc/wdcy/domain/AbstractDomain.java | 1925 | package cc.wdcy.domain;
import cc.wdcy.infrastructure.DateUtils;
import cc.wdcy.domain.shared.GuidGenerator;
import java.io.Serializable;
import java.util.Date;
/**
* @author Shengzhao Li
*/
public abstract class AbstractDomain implements Serializable {
/**
* Database id
*/
protected int id;
protected boolean archived;
/**
* Domain business guid.
*/
protected String guid = GuidGenerator.generate();
/**
* The domain create time.
*/
protected Date createTime = DateUtils.now();
public AbstractDomain() {
}
public int id() {
return id;
}
public void id(int id) {
this.id = id;
}
public boolean archived() {
return archived;
}
public AbstractDomain archived(boolean archived) {
this.archived = archived;
return this;
}
public String guid() {
return guid;
}
public void guid(String guid) {
this.guid = guid;
}
public Date createTime() {
return createTime;
}
public boolean isNewly() {
return id == 0;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof AbstractDomain)) {
return false;
}
AbstractDomain that = (AbstractDomain) o;
return guid.equals(that.guid);
}
@Override
public int hashCode() {
return guid.hashCode();
}
//For subclass override it
public void saveOrUpdate() {
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("{id=").append(id);
sb.append(", archived=").append(archived);
sb.append(", guid='").append(guid).append('\'');
sb.append(", createTime=").append(createTime);
sb.append('}');
return sb.toString();
}
} | gpl-2.0 |
johannes-mueller/ardour | libs/ardour/analyser.cc | 3246 | /*
Copyright (C) 2008 Paul Davis
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "ardour/analyser.h"
#include "ardour/audiofilesource.h"
#include "ardour/rc_configuration.h"
#include "ardour/session_event.h"
#include "ardour/transient_detector.h"
#include "pbd/compose.h"
#include "pbd/error.h"
#include "pbd/i18n.h"
using namespace std;
using namespace ARDOUR;
using namespace PBD;
Analyser* Analyser::the_analyser = 0;
Glib::Threads::Mutex Analyser::analysis_active_lock;
Glib::Threads::Mutex Analyser::analysis_queue_lock;
Glib::Threads::Cond Analyser::SourcesToAnalyse;
list<boost::weak_ptr<Source> > Analyser::analysis_queue;
Analyser::Analyser ()
{
}
Analyser::~Analyser ()
{
}
static void
analyser_work ()
{
Analyser::work ();
}
void
Analyser::init ()
{
Glib::Threads::Thread::create (sigc::ptr_fun (analyser_work));
}
void
Analyser::queue_source_for_analysis (boost::shared_ptr<Source> src, bool force)
{
if (!src->can_be_analysed()) {
return;
}
if (!force && src->has_been_analysed()) {
return;
}
Glib::Threads::Mutex::Lock lm (analysis_queue_lock);
analysis_queue.push_back (boost::weak_ptr<Source>(src));
SourcesToAnalyse.broadcast ();
}
void
Analyser::work ()
{
SessionEvent::create_per_thread_pool ("Analyser", 64);
while (true) {
analysis_queue_lock.lock ();
wait:
if (analysis_queue.empty()) {
SourcesToAnalyse.wait (analysis_queue_lock);
}
if (analysis_queue.empty()) {
goto wait;
}
boost::shared_ptr<Source> src (analysis_queue.front().lock());
analysis_queue.pop_front();
analysis_queue_lock.unlock ();
boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (src);
if (afs && afs->length(afs->timeline_position())) {
Glib::Threads::Mutex::Lock lm (analysis_active_lock);
analyse_audio_file_source (afs);
}
}
}
void
Analyser::analyse_audio_file_source (boost::shared_ptr<AudioFileSource> src)
{
AnalysisFeatureList results;
try {
TransientDetector td (src->sample_rate());
td.set_sensitivity (3, Config->get_transient_sensitivity()); // "General purpose"
if (td.run (src->get_transients_path(), src.get(), 0, results) == 0) {
src->set_been_analysed (true);
} else {
src->set_been_analysed (false);
}
} catch (...) {
error << string_compose(_("Transient Analysis failed for %1."), _("Audio File Source")) << endmsg;;
src->set_been_analysed (false);
return;
}
}
void
Analyser::flush ()
{
Glib::Threads::Mutex::Lock lq (analysis_queue_lock);
Glib::Threads::Mutex::Lock la (analysis_active_lock);
analysis_queue.clear();
}
| gpl-2.0 |
thanhtrantv/car-wp | wp-content/themes/goodstore/templates/widgets/jaw_ecommerce_widget.php | 3151 | <?php global $woocommerce, $yith_wcwl; ?>
<?php
$instance = jaw_template_get_var('instance');
?>
<ul>
<?php if (isset($instance['login_show']) && $instance['login_show'] == '1') { ?>
<li class="top-bar-login-content" aria-haspopup="true">
<?php
$myaccount_page_id = get_option('woocommerce_myaccount_page_id');
$myaccount_page_url = '';
if ($myaccount_page_id) {
$myaccount_page_url = get_permalink($myaccount_page_id);
}
if (is_user_logged_in()) {
$text = __('My account', 'jawtemplates');
} else {
$text = __('Log in', 'jawtemplates');
}
?>
<a href="<?php echo $myaccount_page_url; ?>">
<span class="topbar-title-icon icon-user-icon2"></span>
<span class="topbar-title-text">
<?php echo $text; ?>
</span>
</a>
<?php
$class = '';
if (class_exists('WooCommerce') && is_user_logged_in()) {
$class = 'woo-menu';
}
?>
<div class="top-bar-login-form <?php echo $class; ?>">
<?php echo jaw_get_template_part('login', array('header', 'top_bar')); ?>
<?php if (get_option('users_can_register') && !is_user_logged_in()) : ?>
<p class="regiter-button">
<?php
if (class_exists('WooCommerce') && get_option('woocommerce_enable_myaccount_registration') == 'yes') {
$register_link = get_permalink($myaccount_page_id);
} else {
$register_link = esc_url(wp_registration_url());
}
?>
<?php echo apply_filters('register', sprintf('<a class="btnregiter" href="%s">%s</a>', $register_link, __('Register', 'jawtemplates'))); ?>
</p>
<?php endif; ?>
</div>
</li>
<?php } ?>
<?php if (is_plugin_active('yith-woocommerce-wishlist/init.php') && class_exists('WooCommerce')) { ?>
<?php if (isset($instance['wishlist_show']) && $instance['wishlist_show'] == '1') { ?>
<li class="wishlist-contents">
<a href="<?php echo $yith_wcwl->get_wishlist_url(); ?>">
<span class="topbar-title-icon icon-wishlist-icon"></span>
<span class="topbar-title-text">
<?php _e('Wishlist', 'jawtemplates'); ?>
</span>
</a>
</li>
<?php } ?>
<?php } ?>
<?php if (class_exists('WooCommerce')) { ?>
<?php if (isset($instance['cart_show']) && $instance['cart_show'] == '1') { ?>
<li class="woo-bar-woo-cart woocommerce-page " aria-haspopup="true">
<?php echo jaw_get_template_part('woo_cart', array('widgets', 'ecommerce_widget')); ?>
</li>
<?php } ?>
<?php } ?>
</ul>
| gpl-2.0 |
ybbxk/xavl2tp | ipv6aaa.c | 14259 | /*
* Layer Two Tunnelling Protocol Daemon
* Copyright (C) 1998 Adtran, Inc.
* Copyright (C) 2002 Jeff McAdams
*
* Mark Spencer
*
* This software is distributed under the terms
* of the GPL, which you should have received
* along with this source.
*
* Authorization, Accounting, and Access control
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <errno.h>
#include "l2tp.h"
extern void bufferDump (char *, int);
/* FIXME: Accounting? */
extern struct addr_ent *uaddr[ADDR_HASH_SIZE];
//RY: start, THis function is not used
/*
static int ip_used (unsigned int addr)
{
struct addr_ent *tmp;
tmp = uaddr[addr % ADDR_HASH_SIZE];
while (tmp)
{
if (tmp->addr == addr)
return -1;
tmp = tmp->next;
}
return 0;
}
*/
//RY: end
//TODO: implement wrt to ipv6
/*
unsigned int get_addr6 (struct iprange6 *ipr)
{
unsigned int x, y;
int status;
struct iprange6 *ipr2;
while (ipr)
{
if (ipr->sense == SENSE_ALLOW)
for (x = ntohl (ipr->start); x <= ntohl (ipr->end); x++)
{
// Found an IP in an ALLOW range, check to be sure it is
//consistant through the remaining regions
if (!ip_used (x))
{
status = SENSE_ALLOW;
ipr2 = ipr->next;
while (ipr2)
{
if ((x >= ntohl (ipr2->start))
&& (x <= ntohl (ipr2->end)))
status = ipr2->sense;
ipr2 = ipr2->next;
}
y = htonl (x);
if (status == SENSE_ALLOW)
return y;
}
};
ipr = ipr->next;
}
return 0;
}*/
//TODO: need to chekc the urpose, till then use original
//int get_secret (char *us, char *them, unsigned char *secret, int size)
//{
// FILE *f;
// char buf[STRLEN];
// char *u, *t, *s;
// int num = 0;
// f = fopen (gconfig.authfile, "r");
// if (!f)
// {
// l2tp_log (LOG_WARNING, "%s : Unable to open '%s' for authentication\n",
// __FUNCTION__, gconfig.authfile);
// return 0;
// }
// while (!feof (f))
// {
// num++;
// fgets (buf, sizeof (buf), f);
// if (feof (f))
// break;
// /* Strip comments */
// for (t = buf; *t; t++)
// *t = ((*t == '#') || (*t == ';')) ? 0 : *t;
// /* Strip trailing whitespace */
// for (t = buf + strlen (buf) - 1; (t >= buf) && (*t < 33); t--)
// *t = 0;
// if (!strlen (buf))
// continue; /* Empty line */
// u = buf;
// while (*u && (*u < 33))
// u++;
// /* us */
// if (!*u)
// {
// l2tp_log (LOG_WARNING,
// "%s: Invalid authentication info (no us), line %d\n",
// __FUNCTION__, num);
// continue;
// }
// t = u;
// while (*t > 32)
// t++;
// *(t++) = 0;
// while (*t && (*t < 33))
// t++;
// /* them */
// if (!*t)
// {
// l2tp_log (LOG_WARNING,
// "%s: Invalid authentication info (nothem), line %d\n",
// __FUNCTION__, num);
// continue;
// }
// s = t;
// while (*s > 33)
// s++;
// *(s++) = 0;
// while (*s && (*s < 33))
// s++;
// if (!*s)
// {
// l2tp_log (LOG_WARNING,
// "%s: Invalid authentication info (no secret), line %d\n",
// __FUNCTION__, num);
// continue;
// }
// if ((!strcasecmp (u, us) || !strcasecmp (u, "*")) &&
// (!strcasecmp (t, them) || !strcasecmp (t, "*")))
// {
//#ifdef DEBUG_AUTH
// l2tp_log (LOG_DEBUG,
// "%s: we are '%s', they are '%s', secret is '%s'\n",
// __FUNCTION__, u, t, s);
//#endif
// strncpy ((char *)secret, s, size);
// fclose(f);
// return -1;
// }
// }
// fclose(f);
// return 0;
//}
int handle_challenge6 (struct tunnel6 *t, struct challenge *chal)
{
char *us;
char *them;
if (!t->lns && !t->lac)
{
l2tp_log (LOG_DEBUG, "%s: No lns6 or LAC to handle challenge!\n",
__FUNCTION__);
return -1;
}
#ifdef DEBUG_AUTH
l2tp_log (LOG_DEBUG, "%s: making response for tunnel6: %d\n", __FUNCTION__,
t->ourtid);
#endif
if (t->lns)
{
if (t->lns->hostname[0])
us = t->lns->hostname;
else
us = hostname;
if (t->lns->peername[0])
them = t->lns->peername;
else
them = t->hostname;
}
else
{
if (t->lac->hostname[0])
us = t->lac->hostname;
else
us = hostname;
if (t->lac->peername[0])
them = t->lac->peername;
else
them = t->hostname;
}
if (!get_secret (us, them, chal->secret, sizeof (chal->secret)))
{
l2tp_log (LOG_DEBUG, "%s: no secret found for us='%s' and them='%s'\n",
__FUNCTION__, us, them);
return -1;
}
#if DEBUG_AUTH
l2tp_log (LOG_DEBUG, "*%s: Here comes the chal->ss:\n", __FUNCTION__);
bufferDump (&chal->ss, 1);
l2tp_log (LOG_DEBUG, "%s: Here comes the secret\n", __FUNCTION__);
bufferDump (chal->secret, strlen (chal->secret));
l2tp_log (LOG_DEBUG, "%s: Here comes the challenge\n", __FUNCTION__);
bufferDump (chal->challenge, chal->chal_len);
#endif
memset (chal->response, 0, MD_SIG_SIZE);
MD5Init (&chal->md5);
MD5Update (&chal->md5, &chal->ss, 1);
MD5Update (&chal->md5, chal->secret, strlen ((char *)chal->secret));
MD5Update (&chal->md5, chal->challenge, chal->chal_len);
MD5Final (chal->response, &chal->md5);
#ifdef DEBUG_AUTH
l2tp_log (LOG_DEBUG, "response is %X%X%X%X to '%s' and %X%X%X%X, %d\n",
*((int *) &chal->response[0]),
*((int *) &chal->response[4]),
*((int *) &chal->response[8]),
*((int *) &chal->response[12]),
chal->secret,
*((int *) &chal->challenge[0]),
*((int *) &chal->challenge[4]),
*((int *) &chal->challenge[8]),
*((int *) &chal->challenge[12]), chal->ss);
#endif
chal->state = STATE_CHALLENGED;
return 0;
}
struct lns6 *get_lns6 (struct tunnel6 *t)
{
/*
* Look through our list of LNS's and
* find a reasonable lns6 for this call
* if one is available
*/
struct lns6 *lns6;
struct iprange6 *ipr;
int allow, checkdefault = 0;
/* If access control is disabled, we give the default
otherwise, we give nothing */
allow = 0;
lns6 = lnslist6;
if (!lns6)
{
lns6 = deflns6;
checkdefault = -1;
}
while (lns6)
{
ipr = lns6->lacs;
while (ipr)
{
//TODO: need to change with respect to iprange
//RY: for testing this has been eliminated
/*
if ((ntohl (t->peer.sin6_addr.s6_addr16) >= ntohl (ipr->start)) &&
(ntohl (t->peer.sin6_addr.s6_addr16) <= ntohl (ipr->end)))
*/
{
#ifdef DEBUG_AAA
l2tp_log (LOG_DEBUG,
"get_lns6: Rule %s to %s, sense %s matched %s\n",
IPADDY6 (ipr->start), IPADDY6 (ipr->end),
(ipr->sense ? "allow" : "deny"), IPADDY6 (t->peer.sin_addr.s_addr));
#endif
allow = ipr->sense;
}
ipr = ipr->next;
}
if (allow)
return lns6;
lns6 = lns6->next;
if (!lns6 && !checkdefault)
{
lns6 = deflns6;
checkdefault = -1;
}
}
if (gconfig.accesscontrol)
return NULL;
else
return deflns6;
}
#ifdef DEBUG_HIDDEN
void print_md5 (void *md5)
{
int *i = (int *) md5;
l2tp_log (LOG_DEBUG, "%X%X%X%X\n", i[0], i[1], i[2], i[3], i[4]);
}
inline void print_challenge (struct challenge *chal)
{
l2tp_log (LOG_DEBUG, "vector: ");
print_md5 (chal->vector);
l2tp_log (LOG_DEBUG, "secret: %s\n", chal->secret);
}
#endif
void encrypt_avp6 (struct buffer6 *buf, _u16 len, struct tunnel6 *t)
{
/* Encrypts an AVP of len, at data. We assume there
are two "spare bytes" before the data pointer,l but otherwise
this is just a normal AVP that is about to be returned from
an avpsend routine */
struct avp_hdr *new_hdr =
(struct avp_hdr *) (buf->start + buf->len - len);
struct avp_hdr *old_hdr =
(struct avp_hdr *) (buf->start + buf->len - len + 2);
_u16 length, flags, attr; /* New length, old flags */
unsigned char *ptr, *end;
int cnt;
unsigned char digest[MD_SIG_SIZE];
unsigned char *previous_segment;
/* FIXME: Should I pad more randomly? Right now I pad to nearest 16 bytes */
length =
((len - sizeof (struct avp_hdr) + 1) / 16 + 1) * 16 +
sizeof (struct avp_hdr);
flags = htons (old_hdr->length) & 0xF000;
new_hdr->length = htons (length | flags | HBIT);
new_hdr->vendorid = old_hdr->vendorid;
new_hdr->attr = attr = old_hdr->attr;
/* This is really the length field of the hidden sub-format */
old_hdr->attr = htons (len - sizeof (struct avp_hdr));
/* Okay, now we've rewritten the header, as it should be. Let's start
encrypting the actual data now */
buf->len -= len;
buf->len += length;
/* Back to the beginning of real data, including the original length AVP */
MD5Init (&t->chal_them.md5);
MD5Update (&t->chal_them.md5, (void *) &attr, 2);
MD5Update (&t->chal_them.md5, t->chal_them.secret,
strlen ((char *)t->chal_them.secret));
MD5Update (&t->chal_them.md5, t->chal_them.vector, VECTOR_SIZE);
MD5Final (digest, &t->chal_them.md5);
/* Though not a "MUST" in the spec, our subformat length is always a multiple of 16 */
ptr = ((unsigned char *) new_hdr) + sizeof (struct avp_hdr);
end = ((unsigned char *) new_hdr) + length;
previous_segment = ptr;
while (ptr < end)
{
#if DEBUG_HIDDEN
l2tp_log (LOG_DEBUG, "%s: The digest to be XOR'ed\n", __FUNCTION__);
bufferDump (digest, MD_SIG_SIZE);
l2tp_log (LOG_DEBUG, "%s: The plaintext to be XOR'ed\n", __FUNCTION__);
bufferDump (ptr, MD_SIG_SIZE);
#endif
for (cnt = 0; cnt < MD_SIG_SIZE; cnt++, ptr++)
{
*ptr = *ptr ^ digest[cnt];
}
#if DEBUG_HIDDEN
l2tp_log (LOG_DEBUG, "%s: The result of XOR\n", __FUNCTION__);
bufferDump (previous_segment, MD_SIG_SIZE);
#endif
if (ptr < end)
{
MD5Init (&t->chal_them.md5);
MD5Update (&t->chal_them.md5, t->chal_them.secret,
strlen ((char *)t->chal_them.secret));
MD5Update (&t->chal_them.md5, previous_segment, MD_SIG_SIZE);
MD5Final (digest, &t->chal_them.md5);
}
previous_segment = ptr;
}
}
int decrypt_avp6 (char *buf, struct tunnel6 *t)
{
/* Decrypts a hidden AVP pointed to by buf. The
new header will be exptected to be two characters
offset from the old */
int cnt = 0;
int len, olen, flags;
unsigned char digest[MD_SIG_SIZE];
char *ptr, *end;
_u16 attr;
struct avp_hdr *old_hdr = (struct avp_hdr *) buf;
struct avp_hdr *new_hdr = (struct avp_hdr *) (buf + 2);
int saved_segment_len; /* maybe less 16; may be used if the cipher is longer than 16 octets */
unsigned char saved_segment[MD_SIG_SIZE];
ptr = ((char *) old_hdr) + sizeof (struct avp_hdr);
olen = old_hdr->length & 0x0FFF;
end = buf + olen;
if (!t->chal_us.vector)
{
l2tp_log (LOG_DEBUG,
"decrypt_avp: Hidden bit set, but no random vector specified!\n");
return -EINVAL;
}
/* First, let's decrypt all the data. We're not guaranteed
that it will be padded to a 16 byte boundary, so we
have to be more careful than when encrypting */
attr = ntohs (old_hdr->attr);
MD5Init (&t->chal_us.md5);
MD5Update (&t->chal_us.md5, (void *) &attr, 2);
MD5Update (&t->chal_us.md5, t->chal_us.secret,
strlen ((char *)t->chal_us.secret));
MD5Update (&t->chal_us.md5, t->chal_us.vector, t->chal_us.vector_len);
MD5Final (digest, &t->chal_us.md5);
#ifdef DEBUG_HIDDEN
l2tp_log (LOG_DEBUG, "attribute is %d and challenge is: ", attr);
print_challenge (&t->chal_us);
l2tp_log (LOG_DEBUG, "md5 is: ");
print_md5 (digest);
#endif
while (ptr < end)
{
if (cnt >= MD_SIG_SIZE)
{
MD5Init (&t->chal_us.md5);
MD5Update (&t->chal_us.md5, t->chal_us.secret,
strlen ((char *)t->chal_us.secret));
MD5Update (&t->chal_us.md5, saved_segment, MD_SIG_SIZE);
MD5Final (digest, &t->chal_us.md5);
cnt = 0;
}
/* at the beginning of each segment, we save the current segment (16 octets or less) of cipher
* so that the next round of MD5 (if there is a next round) hash could use it
*/
if (cnt == 0)
{
saved_segment_len =
(end - ptr < MD_SIG_SIZE) ? (end - ptr) : MD_SIG_SIZE;
memcpy (saved_segment, ptr, saved_segment_len);
}
*ptr = *ptr ^ digest[cnt++];
ptr++;
}
/* Hopefully we're all nice and decrypted now. Let's rewrite the header.
First save the old flags, and get the new stuff */
flags = old_hdr->length & 0xF000 & ~HBIT;
len = ntohs (new_hdr->attr) + sizeof (struct avp_hdr);
if (len > olen - 2)
{
l2tp_log (LOG_DEBUG,
"decrypt_avp: Decrypted length is too long (%d > %d)\n", len,
olen - 2);
return -EINVAL;
}
new_hdr->attr = old_hdr->attr;
new_hdr->vendorid = old_hdr->vendorid;
new_hdr->length = len | flags;
return 0;
}
| gpl-2.0 |
petrofcikmatus/wp-blog | wp-content/themes/sketch/index.php | 1208 | <?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package Sketch
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'content', get_post_format() );
?>
<?php endwhile; ?>
<?php sketch_paging_nav(); ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?> | gpl-2.0 |
liuyanghejerry/qtextended | qtopiacore/qt/src/gui/painting/qtransform.h | 10039 | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
****************************************************************************/
#ifndef QTRANSFORM_H
#define QTRANSFORM_H
#include <QtGui/qmatrix.h>
#include <QtGui/qpainterpath.h>
#include <QtGui/qpolygon.h>
#include <QtGui/qregion.h>
#include <QtGui/qwindowdefs.h>
#include <QtCore/qline.h>
#include <QtCore/qpoint.h>
#include <QtCore/qrect.h>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
class QVariant;
class Q_GUI_EXPORT QTransform
{
Q_ENUMS(TransformationType)
public:
enum TransformationType {
TxNone = 0x00,
TxTranslate = 0x01,
TxScale = 0x02,
TxRotate = 0x04,
TxShear = 0x08,
TxProject = 0x10
};
QTransform();
QTransform(qreal h11, qreal h12, qreal h13,
qreal h21, qreal h22, qreal h23,
qreal h31, qreal h32, qreal h33 = 1.0);
QTransform(qreal h11, qreal h12, qreal h13,
qreal h21, qreal h22, qreal h23);
explicit QTransform(const QMatrix &mtx);
bool isAffine() const;
bool isIdentity() const;
bool isInvertible() const;
bool isScaling() const;
bool isRotating() const;
bool isTranslating() const;
TransformationType type() const;
inline qreal determinant() const;
qreal det() const;
qreal m11() const;
qreal m12() const;
qreal m13() const;
qreal m21() const;
qreal m22() const;
qreal m23() const;
qreal m31() const;
qreal m32() const;
qreal m33() const;
qreal dx() const;
qreal dy() const;
void setMatrix(qreal m11, qreal m12, qreal m13,
qreal m21, qreal m22, qreal m23,
qreal m31, qreal m32, qreal m33);
QTransform inverted(bool *invertible = 0) const;
QTransform adjoint() const;
QTransform transposed() const;
QTransform &translate(qreal dx, qreal dy);
QTransform &scale(qreal sx, qreal sy);
QTransform &shear(qreal sh, qreal sv);
QTransform &rotate(qreal a, Qt::Axis axis = Qt::ZAxis);
QTransform &rotateRadians(qreal a, Qt::Axis axis = Qt::ZAxis);
static bool squareToQuad(const QPolygonF &square, QTransform &result);
static bool quadToSquare(const QPolygonF &quad, QTransform &result);
static bool quadToQuad(const QPolygonF &one,
const QPolygonF &two,
QTransform &result);
bool operator==(const QTransform &) const;
bool operator!=(const QTransform &) const;
QTransform &operator*=(const QTransform &);
QTransform operator*(const QTransform &o) const;
QTransform &operator=(const QTransform &);
operator QVariant() const;
void reset();
QPoint map(const QPoint &p) const;
QPointF map(const QPointF &p) const;
QLine map(const QLine &l) const;
QLineF map(const QLineF &l) const;
QPolygonF map(const QPolygonF &a) const;
QPolygon map(const QPolygon &a) const;
QRegion map(const QRegion &r) const;
QPainterPath map(const QPainterPath &p) const;
QPolygon mapToPolygon(const QRect &r) const;
QRect mapRect(const QRect &) const;
QRectF mapRect(const QRectF &) const;
void map(int x, int y, int *tx, int *ty) const;
void map(qreal x, qreal y, qreal *tx, qreal *ty) const;
const QMatrix &toAffine() const;
QTransform &operator*=(qreal div);
QTransform &operator/=(qreal div);
QTransform &operator+=(qreal div);
QTransform &operator-=(qreal div);
private:
QMatrix affine;
qreal m_13;
qreal m_23;
qreal m_33;
mutable uint m_type : 5;
mutable uint m_dirty : 5;
class Private;
Private *d;
};
Q_DECLARE_TYPEINFO(QTransform, Q_MOVABLE_TYPE);
/******* inlines *****/
inline bool QTransform::isAffine() const
{
return qFuzzyCompare(m_13 + 1, 1) && qFuzzyCompare(m_23 + 1, 1);
}
inline bool QTransform::isIdentity() const
{
#define qFZ qFuzzyCompare
return qFZ(affine._m11, 1) && qFZ(affine._m12 + 1, 1) && qFZ(m_13 + 1, 1)
&& qFZ(affine._m21 + 1, 1) && qFZ(affine._m22, 1) && qFZ(m_23 + 1, 1)
&& qFZ(affine._dx + 1, 1) && qFZ(affine._dy + 1, 1) && qFZ(m_33, 1);
#undef qFZ
}
inline bool QTransform::isInvertible() const
{
return !qFuzzyCompare(determinant() + 1, 1);
}
inline bool QTransform::isScaling() const
{
return !qFuzzyCompare(affine._m11, 1) ||
!qFuzzyCompare(affine._m22, 1);
}
inline bool QTransform::isRotating() const
{
return !qFuzzyCompare(affine._m12 + 1, 1) ||
!qFuzzyCompare(affine._m21 + 1, 1);
}
inline bool QTransform::isTranslating() const
{
return !qFuzzyCompare(affine._dx + 1, 1) ||
!qFuzzyCompare(affine._dy + 1, 1);
}
inline qreal QTransform::determinant() const
{
return affine._m11*(m_33*affine._m22-affine._dy*m_23) -
affine._m21*(m_33*affine._m12-affine._dy*m_13)+affine._dx*(m_23*affine._m12-affine._m22*m_13);
}
inline qreal QTransform::det() const
{
return determinant();
}
inline qreal QTransform::m11() const
{
return affine._m11;
}
inline qreal QTransform::m12() const
{
return affine._m12;
}
inline qreal QTransform::m13() const
{
return m_13;
}
inline qreal QTransform::m21() const
{
return affine._m21;
}
inline qreal QTransform::m22() const
{
return affine._m22;
}
inline qreal QTransform::m23() const
{
return m_23;
}
inline qreal QTransform::m31() const
{
return affine._dx;
}
inline qreal QTransform::m32() const
{
return affine._dy;
}
inline qreal QTransform::m33() const
{
return m_33;
}
inline qreal QTransform::dx() const
{
return affine._dx;
}
inline qreal QTransform::dy() const
{
return affine._dy;
}
inline QTransform &QTransform::operator*=(qreal num)
{
affine._m11 *= num;
affine._m12 *= num;
m_13 *= num;
affine._m21 *= num;
affine._m22 *= num;
m_23 *= num;
affine._dx *= num;
affine._dy *= num;
m_33 *= num;
m_dirty |= TxScale;
return *this;
}
inline QTransform &QTransform::operator/=(qreal div)
{
div = 1/div;
return operator*=(div);
}
inline QTransform &QTransform::operator+=(qreal num)
{
affine._m11 += num;
affine._m12 += num;
m_13 += num;
affine._m21 += num;
affine._m22 += num;
m_23 += num;
affine._dx += num;
affine._dy += num;
m_33 += num;
m_dirty |= TxProject;
return *this;
}
inline QTransform &QTransform::operator-=(qreal num)
{
affine._m11 -= num;
affine._m12 -= num;
m_13 -= num;
affine._m21 -= num;
affine._m22 -= num;
m_23 -= num;
affine._dx -= num;
affine._dy -= num;
m_33 -= num;
m_dirty |= TxProject;
return *this;
}
/****** stream functions *******************/
Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTransform &);
Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTransform &);
#ifndef QT_NO_DEBUG_STREAM
Q_GUI_EXPORT QDebug operator<<(QDebug, const QTransform &);
#endif
/****** end stream functions *******************/
// mathematical semantics
Q_GUI_EXPORT_INLINE QPoint operator*(const QPoint &p, const QTransform &m)
{ return m.map(p); }
Q_GUI_EXPORT_INLINE QPointF operator*(const QPointF &p, const QTransform &m)
{ return m.map(p); }
Q_GUI_EXPORT_INLINE QLineF operator*(const QLineF &l, const QTransform &m)
{ return m.map(l); }
Q_GUI_EXPORT_INLINE QLine operator*(const QLine &l, const QTransform &m)
{ return m.map(l); }
Q_GUI_EXPORT_INLINE QPolygon operator *(const QPolygon &a, const QTransform &m)
{ return m.map(a); }
Q_GUI_EXPORT_INLINE QPolygonF operator *(const QPolygonF &a, const QTransform &m)
{ return m.map(a); }
Q_GUI_EXPORT_INLINE QRegion operator *(const QRegion &r, const QTransform &m)
{ return m.map(r); }
Q_GUI_EXPORT_INLINE QPainterPath operator *(const QPainterPath &p, const QTransform &m)
{ return m.map(p); }
Q_GUI_EXPORT_INLINE QTransform operator *(const QTransform &a, qreal n)
{ QTransform t(a); t *= n; return t; }
Q_GUI_EXPORT_INLINE QTransform operator /(const QTransform &a, qreal n)
{ QTransform t(a); t /= n; return t; }
Q_GUI_EXPORT_INLINE QTransform operator +(const QTransform &a, qreal n)
{ QTransform t(a); t += n; return t; }
Q_GUI_EXPORT_INLINE QTransform operator -(const QTransform &a, qreal n)
{ QTransform t(a); t -= n; return t; }
QT_END_NAMESPACE
QT_END_HEADER
#endif
| gpl-2.0 |
RJRetro/mame | src/lib/netlist/devices/nld_legacy.cpp | 1191 | // license:GPL-2.0+
// copyright-holders:Couriersud
/*
* nld_legacy.c
*
*/
#include "nld_legacy.h"
#include "nl_setup.h"
NETLIB_NAMESPACE_DEVICES_START()
NETLIB_START(nicRSFF)
{
register_input("S", m_S);
register_input("R", m_R);
register_output("Q", m_Q);
register_output("QQ", m_QQ);
}
NETLIB_RESET(nicRSFF)
{
m_Q.initial(0);
m_QQ.initial(1);
}
NETLIB_UPDATE(nicRSFF)
{
if (!INPLOGIC(m_S))
{
OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(20));
OUTLOGIC(m_QQ, 0, NLTIME_FROM_NS(20));
}
else if (!INPLOGIC(m_R))
{
OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(20));
OUTLOGIC(m_QQ, 1, NLTIME_FROM_NS(20));
}
}
NETLIB_START(nicDelay)
{
register_input("1", m_I);
register_output("2", m_Q);
register_param("L_TO_H", m_L_to_H, 10);
register_param("H_TO_L", m_H_to_L, 10);
save(NLNAME(m_last));
}
NETLIB_RESET(nicDelay)
{
m_Q.initial(0);
}
NETLIB_UPDATE_PARAM(nicDelay)
{
}
NETLIB_UPDATE(nicDelay)
{
netlist_sig_t nval = INPLOGIC(m_I);
if (nval && !m_last)
{
// L_to_H
OUTLOGIC(m_Q, 1, NLTIME_FROM_NS(m_L_to_H.Value()));
}
else if (!nval && m_last)
{
// H_to_L
OUTLOGIC(m_Q, 0, NLTIME_FROM_NS(m_H_to_L.Value()));
}
m_last = nval;
}
NETLIB_NAMESPACE_DEVICES_END()
| gpl-2.0 |
FilipBE/qtextended | qtopiacore/qt/mkspecs/qws/solaris-generic-g++/qplatformdefs.h | 1811 | /****************************************************************************
**
** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information ([email protected])
**
** This file is part of the qmake spec of the Qt Toolkit.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License versions 2.0 or 3.0 as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information
** to ensure GNU General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html. In addition, as a special
** exception, Nokia gives you certain additional rights. These rights
** are described in the Nokia Qt GPL Exception version 1.3, included in
** the file GPL_EXCEPTION.txt in this package.
**
** Qt for Windows(R) Licensees
** As a special exception, Nokia, as the sole copyright holder for Qt
** Designer, grants users of the Qt/Eclipse Integration plug-in the
** right for the Qt/Eclipse Integration to link to functionality
** provided by Qt Designer and its related libraries.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
****************************************************************************/
#include "../../solaris-g++/qplatformdefs.h"
| gpl-2.0 |
QiuLihua83/linux-2.6.10 | arch/i386/kernel/srat.c | 12625 | /*
* Some of the code in this file has been gleaned from the 64 bit
* discontigmem support code base.
*
* Copyright (C) 2002, IBM Corp.
*
* All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
* NON INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* Send feedback to Pat Gaughen <[email protected]>
*/
#include <linux/config.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <linux/mmzone.h>
#include <linux/acpi.h>
#include <linux/nodemask.h>
#include <asm/srat.h>
/*
* proximity macros and definitions
*/
#define NODE_ARRAY_INDEX(x) ((x) / 8) /* 8 bits/char */
#define NODE_ARRAY_OFFSET(x) ((x) % 8) /* 8 bits/char */
#define BMAP_SET(bmap, bit) ((bmap)[NODE_ARRAY_INDEX(bit)] |= 1 << NODE_ARRAY_OFFSET(bit))
#define BMAP_TEST(bmap, bit) ((bmap)[NODE_ARRAY_INDEX(bit)] & (1 << NODE_ARRAY_OFFSET(bit)))
#define MAX_PXM_DOMAINS 256 /* 1 byte and no promises about values */
/* bitmap length; _PXM is at most 255 */
#define PXM_BITMAP_LEN (MAX_PXM_DOMAINS / 8)
static u8 pxm_bitmap[PXM_BITMAP_LEN]; /* bitmap of proximity domains */
#define MAX_CHUNKS_PER_NODE 4
#define MAXCHUNKS (MAX_CHUNKS_PER_NODE * MAX_NUMNODES)
struct node_memory_chunk_s {
unsigned long start_pfn;
unsigned long end_pfn;
u8 pxm; // proximity domain of node
u8 nid; // which cnode contains this chunk?
u8 bank; // which mem bank on this node
};
static struct node_memory_chunk_s node_memory_chunk[MAXCHUNKS];
static int num_memory_chunks; /* total number of memory chunks */
static int zholes_size_init;
static unsigned long zholes_size[MAX_NUMNODES * MAX_NR_ZONES];
extern unsigned long node_start_pfn[], node_end_pfn[];
extern void * boot_ioremap(unsigned long, unsigned long);
/* Identify CPU proximity domains */
static void __init parse_cpu_affinity_structure(char *p)
{
struct acpi_table_processor_affinity *cpu_affinity =
(struct acpi_table_processor_affinity *) p;
if (!cpu_affinity->flags.enabled)
return; /* empty entry */
/* mark this node as "seen" in node bitmap */
BMAP_SET(pxm_bitmap, cpu_affinity->proximity_domain);
printk("CPU 0x%02X in proximity domain 0x%02X\n",
cpu_affinity->apic_id, cpu_affinity->proximity_domain);
}
/*
* Identify memory proximity domains and hot-remove capabilities.
* Fill node memory chunk list structure.
*/
static void __init parse_memory_affinity_structure (char *sratp)
{
unsigned long long paddr, size;
unsigned long start_pfn, end_pfn;
u8 pxm;
struct node_memory_chunk_s *p, *q, *pend;
struct acpi_table_memory_affinity *memory_affinity =
(struct acpi_table_memory_affinity *) sratp;
if (!memory_affinity->flags.enabled)
return; /* empty entry */
/* mark this node as "seen" in node bitmap */
BMAP_SET(pxm_bitmap, memory_affinity->proximity_domain);
/* calculate info for memory chunk structure */
paddr = memory_affinity->base_addr_hi;
paddr = (paddr << 32) | memory_affinity->base_addr_lo;
size = memory_affinity->length_hi;
size = (size << 32) | memory_affinity->length_lo;
start_pfn = paddr >> PAGE_SHIFT;
end_pfn = (paddr + size) >> PAGE_SHIFT;
pxm = memory_affinity->proximity_domain;
if (num_memory_chunks >= MAXCHUNKS) {
printk("Too many mem chunks in SRAT. Ignoring %lld MBytes at %llx\n",
size/(1024*1024), paddr);
return;
}
/* Insertion sort based on base address */
pend = &node_memory_chunk[num_memory_chunks];
for (p = &node_memory_chunk[0]; p < pend; p++) {
if (start_pfn < p->start_pfn)
break;
}
if (p < pend) {
for (q = pend; q >= p; q--)
*(q + 1) = *q;
}
p->start_pfn = start_pfn;
p->end_pfn = end_pfn;
p->pxm = pxm;
num_memory_chunks++;
printk("Memory range 0x%lX to 0x%lX (type 0x%X) in proximity domain 0x%02X %s\n",
start_pfn, end_pfn,
memory_affinity->memory_type,
memory_affinity->proximity_domain,
(memory_affinity->flags.hot_pluggable ?
"enabled and removable" : "enabled" ) );
}
#if MAX_NR_ZONES != 3
#error "MAX_NR_ZONES != 3, chunk_to_zone requires review"
#endif
/* Take a chunk of pages from page frame cstart to cend and count the number
* of pages in each zone, returned via zones[].
*/
static __init void chunk_to_zones(unsigned long cstart, unsigned long cend,
unsigned long *zones)
{
unsigned long max_dma;
extern unsigned long max_low_pfn;
int z;
unsigned long rend;
/* FIXME: MAX_DMA_ADDRESS and max_low_pfn are trying to provide
* similarly scoped information and should be handled in a consistant
* manner.
*/
max_dma = virt_to_phys((char *)MAX_DMA_ADDRESS) >> PAGE_SHIFT;
/* Split the hole into the zones in which it falls. Repeatedly
* take the segment in which the remaining hole starts, round it
* to the end of that zone.
*/
memset(zones, 0, MAX_NR_ZONES * sizeof(long));
while (cstart < cend) {
if (cstart < max_dma) {
z = ZONE_DMA;
rend = (cend < max_dma)? cend : max_dma;
} else if (cstart < max_low_pfn) {
z = ZONE_NORMAL;
rend = (cend < max_low_pfn)? cend : max_low_pfn;
} else {
z = ZONE_HIGHMEM;
rend = cend;
}
zones[z] += rend - cstart;
cstart = rend;
}
}
/* Parse the ACPI Static Resource Affinity Table */
static int __init acpi20_parse_srat(struct acpi_table_srat *sratp)
{
u8 *start, *end, *p;
int i, j, nid;
u8 pxm_to_nid_map[MAX_PXM_DOMAINS];/* _PXM to logical node ID map */
u8 nid_to_pxm_map[MAX_NUMNODES];/* logical node ID to _PXM map */
start = (u8 *)(&(sratp->reserved) + 1); /* skip header */
p = start;
end = (u8 *)sratp + sratp->header.length;
memset(pxm_bitmap, 0, sizeof(pxm_bitmap)); /* init proximity domain bitmap */
memset(node_memory_chunk, 0, sizeof(node_memory_chunk));
memset(zholes_size, 0, sizeof(zholes_size));
/* -1 in these maps means not available */
memset(pxm_to_nid_map, -1, sizeof(pxm_to_nid_map));
memset(nid_to_pxm_map, -1, sizeof(nid_to_pxm_map));
num_memory_chunks = 0;
while (p < end) {
switch (*p) {
case ACPI_SRAT_PROCESSOR_AFFINITY:
parse_cpu_affinity_structure(p);
break;
case ACPI_SRAT_MEMORY_AFFINITY:
parse_memory_affinity_structure(p);
break;
default:
printk("ACPI 2.0 SRAT: unknown entry skipped: type=0x%02X, len=%d\n", p[0], p[1]);
break;
}
p += p[1];
if (p[1] == 0) {
printk("acpi20_parse_srat: Entry length value is zero;"
" can't parse any further!\n");
break;
}
}
if (num_memory_chunks == 0) {
printk("could not finy any ACPI SRAT memory areas.\n");
goto out_fail;
}
/* Calculate total number of nodes in system from PXM bitmap and create
* a set of sequential node IDs starting at zero. (ACPI doesn't seem
* to specify the range of _PXM values.)
*/
numnodes = 0; /* init total nodes in system */
for (i = 0; i < MAX_PXM_DOMAINS; i++) {
if (BMAP_TEST(pxm_bitmap, i)) {
pxm_to_nid_map[i] = numnodes;
nid_to_pxm_map[numnodes] = i;
node_set_online(numnodes);
++numnodes;
}
}
if (numnodes == 0)
BUG();
/* set cnode id in memory chunk structure */
for (i = 0; i < num_memory_chunks; i++)
node_memory_chunk[i].nid = pxm_to_nid_map[node_memory_chunk[i].pxm];
printk("pxm bitmap: ");
for (i = 0; i < sizeof(pxm_bitmap); i++) {
printk("%02X ", pxm_bitmap[i]);
}
printk("\n");
printk("Number of logical nodes in system = %d\n", numnodes);
printk("Number of memory chunks in system = %d\n", num_memory_chunks);
for (j = 0; j < num_memory_chunks; j++){
printk("chunk %d nid %d start_pfn %08lx end_pfn %08lx\n",
j, node_memory_chunk[j].nid,
node_memory_chunk[j].start_pfn,
node_memory_chunk[j].end_pfn);
}
/*calculate node_start_pfn/node_end_pfn arrays*/
for (nid = 0; nid < numnodes; nid++) {
int been_here_before = 0;
for (j = 0; j < num_memory_chunks; j++){
if (node_memory_chunk[j].nid == nid) {
if (been_here_before == 0) {
node_start_pfn[nid] = node_memory_chunk[j].start_pfn;
node_end_pfn[nid] = node_memory_chunk[j].end_pfn;
been_here_before = 1;
} else { /* We've found another chunk of memory for the node */
if (node_start_pfn[nid] < node_memory_chunk[j].start_pfn) {
node_end_pfn[nid] = node_memory_chunk[j].end_pfn;
}
}
}
}
}
return 1;
out_fail:
return 0;
}
int __init get_memcfg_from_srat(void)
{
struct acpi_table_header *header = NULL;
struct acpi_table_rsdp *rsdp = NULL;
struct acpi_table_rsdt *rsdt = NULL;
struct acpi_pointer *rsdp_address = NULL;
struct acpi_table_rsdt saved_rsdt;
int tables = 0;
int i = 0;
acpi_find_root_pointer(ACPI_PHYSICAL_ADDRESSING, rsdp_address);
if (rsdp_address->pointer_type == ACPI_PHYSICAL_POINTER) {
printk("%s: assigning address to rsdp\n", __FUNCTION__);
rsdp = (struct acpi_table_rsdp *)
(u32)rsdp_address->pointer.physical;
} else {
printk("%s: rsdp_address is not a physical pointer\n", __FUNCTION__);
goto out_err;
}
if (!rsdp) {
printk("%s: Didn't find ACPI root!\n", __FUNCTION__);
goto out_err;
}
printk(KERN_INFO "%.8s v%d [%.6s]\n", rsdp->signature, rsdp->revision,
rsdp->oem_id);
if (strncmp(rsdp->signature, RSDP_SIG,strlen(RSDP_SIG))) {
printk(KERN_WARNING "%s: RSDP table signature incorrect\n", __FUNCTION__);
goto out_err;
}
rsdt = (struct acpi_table_rsdt *)
boot_ioremap(rsdp->rsdt_address, sizeof(struct acpi_table_rsdt));
if (!rsdt) {
printk(KERN_WARNING
"%s: ACPI: Invalid root system description tables (RSDT)\n",
__FUNCTION__);
goto out_err;
}
header = & rsdt->header;
if (strncmp(header->signature, RSDT_SIG, strlen(RSDT_SIG))) {
printk(KERN_WARNING "ACPI: RSDT signature incorrect\n");
goto out_err;
}
/*
* The number of tables is computed by taking the
* size of all entries (header size minus total
* size of RSDT) divided by the size of each entry
* (4-byte table pointers).
*/
tables = (header->length - sizeof(struct acpi_table_header)) / 4;
if (!tables)
goto out_err;
memcpy(&saved_rsdt, rsdt, sizeof(saved_rsdt));
if (saved_rsdt.header.length > sizeof(saved_rsdt)) {
printk(KERN_WARNING "ACPI: Too big length in RSDT: %d\n",
saved_rsdt.header.length);
goto out_err;
}
printk("Begin SRAT table scan....\n");
for (i = 0; i < tables; i++) {
/* Map in header, then map in full table length. */
header = (struct acpi_table_header *)
boot_ioremap(saved_rsdt.entry[i], sizeof(struct acpi_table_header));
if (!header)
break;
header = (struct acpi_table_header *)
boot_ioremap(saved_rsdt.entry[i], header->length);
if (!header)
break;
if (strncmp((char *) &header->signature, "SRAT", 4))
continue;
/* we've found the srat table. don't need to look at any more tables */
return acpi20_parse_srat((struct acpi_table_srat *)header);
}
out_err:
printk("failed to get NUMA memory information from SRAT table\n");
return 0;
}
/* For each node run the memory list to determine whether there are
* any memory holes. For each hole determine which ZONE they fall
* into.
*
* NOTE#1: this requires knowledge of the zone boundries and so
* _cannot_ be performed before those are calculated in setup_memory.
*
* NOTE#2: we rely on the fact that the memory chunks are ordered by
* start pfn number during setup.
*/
static void __init get_zholes_init(void)
{
int nid;
int c;
int first;
unsigned long end = 0;
for (nid = 0; nid < numnodes; nid++) {
first = 1;
for (c = 0; c < num_memory_chunks; c++){
if (node_memory_chunk[c].nid == nid) {
if (first) {
end = node_memory_chunk[c].end_pfn;
first = 0;
} else {
/* Record any gap between this chunk
* and the previous chunk on this node
* against the zones it spans.
*/
chunk_to_zones(end,
node_memory_chunk[c].start_pfn,
&zholes_size[nid * MAX_NR_ZONES]);
}
}
}
}
}
unsigned long * __init get_zholes_size(int nid)
{
if (!zholes_size_init) {
zholes_size_init++;
get_zholes_init();
}
if((nid >= numnodes) | (nid >= MAX_NUMNODES))
printk("%s: nid = %d is invalid. numnodes = %d",
__FUNCTION__, nid, numnodes);
return &zholes_size[nid * MAX_NR_ZONES];
}
| gpl-2.0 |
friedrich420/N4-AEL-KERNEL-LOLLIPOP | kernel/trace/trace.c | 159675 | /*
* ring buffer based function tracer
*
* Copyright (C) 2007-2012 Steven Rostedt <[email protected]>
* Copyright (C) 2008 Ingo Molnar <[email protected]>
*
* Originally taken from the RT patch by:
* Arnaldo Carvalho de Melo <[email protected]>
*
* Based on code from the latency_tracer, that is:
* Copyright (C) 2004-2006 Ingo Molnar
* Copyright (C) 2004 Nadia Yvette Chambers
*/
#include <linux/ring_buffer.h>
#include <generated/utsrelease.h>
#include <linux/stacktrace.h>
#include <linux/writeback.h>
#include <linux/kallsyms.h>
#include <linux/seq_file.h>
#include <linux/notifier.h>
#include <linux/irqflags.h>
#include <linux/debugfs.h>
#include <linux/pagemap.h>
#include <linux/hardirq.h>
#include <linux/linkage.h>
#include <linux/uaccess.h>
#include <linux/kprobes.h>
#include <linux/ftrace.h>
#include <linux/module.h>
#include <linux/percpu.h>
#include <linux/splice.h>
#include <linux/kdebug.h>
#include <linux/string.h>
#include <linux/rwsem.h>
#include <linux/slab.h>
#include <linux/ctype.h>
#include <linux/init.h>
#include <linux/poll.h>
#include <linux/nmi.h>
#include <linux/fs.h>
#include <linux/sched/rt.h>
#include <linux/coresight-stm.h>
#include "trace.h"
#include "trace_output.h"
/*
* On boot up, the ring buffer is set to the minimum size, so that
* we do not waste memory on systems that are not using tracing.
*/
bool ring_buffer_expanded;
/*
* We need to change this state when a selftest is running.
* A selftest will lurk into the ring-buffer to count the
* entries inserted during the selftest although some concurrent
* insertions into the ring-buffer such as trace_printk could occurred
* at the same time, giving false positive or negative results.
*/
static bool __read_mostly tracing_selftest_running;
/*
* If a tracer is running, we do not want to run SELFTEST.
*/
bool __read_mostly tracing_selftest_disabled;
/* For tracers that don't implement custom flags */
static struct tracer_opt dummy_tracer_opt[] = {
{ }
};
static struct tracer_flags dummy_tracer_flags = {
.val = 0,
.opts = dummy_tracer_opt
};
static int dummy_set_flag(u32 old_flags, u32 bit, int set)
{
return 0;
}
/*
* To prevent the comm cache from being overwritten when no
* tracing is active, only save the comm when a trace event
* occurred.
*/
static DEFINE_PER_CPU(bool, trace_cmdline_save);
/*
* Kill all tracing for good (never come back).
* It is initialized to 1 but will turn to zero if the initialization
* of the tracer is successful. But that is the only place that sets
* this back to zero.
*/
static int tracing_disabled = 1;
DEFINE_PER_CPU(int, ftrace_cpu_disabled);
cpumask_var_t __read_mostly tracing_buffer_mask;
/*
* ftrace_dump_on_oops - variable to dump ftrace buffer on oops
*
* If there is an oops (or kernel panic) and the ftrace_dump_on_oops
* is set, then ftrace_dump is called. This will output the contents
* of the ftrace buffers to the console. This is very useful for
* capturing traces that lead to crashes and outputing it to a
* serial console.
*
* It is default off, but you can enable it with either specifying
* "ftrace_dump_on_oops" in the kernel command line, or setting
* /proc/sys/kernel/ftrace_dump_on_oops
* Set 1 if you want to dump buffers of all CPUs
* Set 2 if you want to dump the buffer of the CPU that triggered oops
*/
enum ftrace_dump_mode ftrace_dump_on_oops;
static int tracing_set_tracer(const char *buf);
#define MAX_TRACER_SIZE 100
static char bootup_tracer_buf[MAX_TRACER_SIZE] __initdata;
static char *default_bootup_tracer;
static bool allocate_snapshot;
static int __init set_cmdline_ftrace(char *str)
{
strlcpy(bootup_tracer_buf, str, MAX_TRACER_SIZE);
default_bootup_tracer = bootup_tracer_buf;
/* We are using ftrace early, expand it */
ring_buffer_expanded = true;
return 1;
}
__setup("ftrace=", set_cmdline_ftrace);
static int __init set_ftrace_dump_on_oops(char *str)
{
if (*str++ != '=' || !*str) {
ftrace_dump_on_oops = DUMP_ALL;
return 1;
}
if (!strcmp("orig_cpu", str)) {
ftrace_dump_on_oops = DUMP_ORIG;
return 1;
}
return 0;
}
__setup("ftrace_dump_on_oops", set_ftrace_dump_on_oops);
static int __init boot_alloc_snapshot(char *str)
{
allocate_snapshot = true;
/* We also need the main ring buffer expanded */
ring_buffer_expanded = true;
return 1;
}
__setup("alloc_snapshot", boot_alloc_snapshot);
static char trace_boot_options_buf[MAX_TRACER_SIZE] __initdata;
static char *trace_boot_options __initdata;
static int __init set_trace_boot_options(char *str)
{
strlcpy(trace_boot_options_buf, str, MAX_TRACER_SIZE);
trace_boot_options = trace_boot_options_buf;
return 0;
}
__setup("trace_options=", set_trace_boot_options);
unsigned long long ns2usecs(cycle_t nsec)
{
nsec += 500;
do_div(nsec, 1000);
return nsec;
}
/*
* The global_trace is the descriptor that holds the tracing
* buffers for the live tracing. For each CPU, it contains
* a link list of pages that will store trace entries. The
* page descriptor of the pages in the memory is used to hold
* the link list by linking the lru item in the page descriptor
* to each of the pages in the buffer per CPU.
*
* For each active CPU there is a data field that holds the
* pages for the buffer for that CPU. Each CPU has the same number
* of pages allocated for its buffer.
*/
static struct trace_array global_trace;
LIST_HEAD(ftrace_trace_arrays);
int trace_array_get(struct trace_array *this_tr)
{
struct trace_array *tr;
int ret = -ENODEV;
mutex_lock(&trace_types_lock);
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr == this_tr) {
tr->ref++;
ret = 0;
break;
}
}
mutex_unlock(&trace_types_lock);
return ret;
}
static void __trace_array_put(struct trace_array *this_tr)
{
WARN_ON(!this_tr->ref);
this_tr->ref--;
}
void trace_array_put(struct trace_array *this_tr)
{
mutex_lock(&trace_types_lock);
__trace_array_put(this_tr);
mutex_unlock(&trace_types_lock);
}
int filter_current_check_discard(struct ring_buffer *buffer,
struct ftrace_event_call *call, void *rec,
struct ring_buffer_event *event)
{
return filter_check_discard(call, rec, buffer, event);
}
EXPORT_SYMBOL_GPL(filter_current_check_discard);
cycle_t buffer_ftrace_now(struct trace_buffer *buf, int cpu)
{
u64 ts;
/* Early boot up does not have a buffer yet */
if (!buf->buffer)
return trace_clock_local();
ts = ring_buffer_time_stamp(buf->buffer, cpu);
ring_buffer_normalize_time_stamp(buf->buffer, cpu, &ts);
return ts;
}
cycle_t ftrace_now(int cpu)
{
return buffer_ftrace_now(&global_trace.trace_buffer, cpu);
}
/**
* tracing_is_enabled - Show if global_trace has been disabled
*
* Shows if the global trace has been enabled or not. It uses the
* mirror flag "buffer_disabled" to be used in fast paths such as for
* the irqsoff tracer. But it may be inaccurate due to races. If you
* need to know the accurate state, use tracing_is_on() which is a little
* slower, but accurate.
*/
int tracing_is_enabled(void)
{
/*
* For quick access (irqsoff uses this in fast path), just
* return the mirror variable of the state of the ring buffer.
* It's a little racy, but we don't really care.
*/
smp_rmb();
return !global_trace.buffer_disabled;
}
/*
* trace_buf_size is the size in bytes that is allocated
* for a buffer. Note, the number of bytes is always rounded
* to page size.
*
* This number is purposely set to a low number of 16384.
* If the dump on oops happens, it will be much appreciated
* to not have to wait for all that output. Anyway this can be
* boot time and run time configurable.
*/
#define TRACE_BUF_SIZE_DEFAULT 1441792UL /* 16384 * 88 (sizeof(entry)) */
static unsigned long trace_buf_size = TRACE_BUF_SIZE_DEFAULT;
/* trace_types holds a link list of available tracers. */
static struct tracer *trace_types __read_mostly;
/*
* trace_types_lock is used to protect the trace_types list.
*/
DEFINE_MUTEX(trace_types_lock);
/*
* serialize the access of the ring buffer
*
* ring buffer serializes readers, but it is low level protection.
* The validity of the events (which returns by ring_buffer_peek() ..etc)
* are not protected by ring buffer.
*
* The content of events may become garbage if we allow other process consumes
* these events concurrently:
* A) the page of the consumed events may become a normal page
* (not reader page) in ring buffer, and this page will be rewrited
* by events producer.
* B) The page of the consumed events may become a page for splice_read,
* and this page will be returned to system.
*
* These primitives allow multi process access to different cpu ring buffer
* concurrently.
*
* These primitives don't distinguish read-only and read-consume access.
* Multi read-only access are also serialized.
*/
#ifdef CONFIG_SMP
static DECLARE_RWSEM(all_cpu_access_lock);
static DEFINE_PER_CPU(struct mutex, cpu_access_lock);
static inline void trace_access_lock(int cpu)
{
if (cpu == RING_BUFFER_ALL_CPUS) {
/* gain it for accessing the whole ring buffer. */
down_write(&all_cpu_access_lock);
} else {
/* gain it for accessing a cpu ring buffer. */
/* Firstly block other trace_access_lock(RING_BUFFER_ALL_CPUS). */
down_read(&all_cpu_access_lock);
/* Secondly block other access to this @cpu ring buffer. */
mutex_lock(&per_cpu(cpu_access_lock, cpu));
}
}
static inline void trace_access_unlock(int cpu)
{
if (cpu == RING_BUFFER_ALL_CPUS) {
up_write(&all_cpu_access_lock);
} else {
mutex_unlock(&per_cpu(cpu_access_lock, cpu));
up_read(&all_cpu_access_lock);
}
}
static inline void trace_access_lock_init(void)
{
int cpu;
for_each_possible_cpu(cpu)
mutex_init(&per_cpu(cpu_access_lock, cpu));
}
#else
static DEFINE_MUTEX(access_lock);
static inline void trace_access_lock(int cpu)
{
(void)cpu;
mutex_lock(&access_lock);
}
static inline void trace_access_unlock(int cpu)
{
(void)cpu;
mutex_unlock(&access_lock);
}
static inline void trace_access_lock_init(void)
{
}
#endif
/* trace_flags holds trace_options default values */
unsigned long trace_flags = TRACE_ITER_PRINT_PARENT | TRACE_ITER_PRINTK |
TRACE_ITER_ANNOTATE | TRACE_ITER_CONTEXT_INFO | TRACE_ITER_SLEEP_TIME |
TRACE_ITER_GRAPH_TIME | TRACE_ITER_RECORD_CMD | TRACE_ITER_OVERWRITE |
TRACE_ITER_IRQ_INFO | TRACE_ITER_MARKERS | TRACE_ITER_FUNCTION;
void tracer_tracing_on(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
ring_buffer_record_on(tr->trace_buffer.buffer);
/*
* This flag is looked at when buffers haven't been allocated
* yet, or by some tracers (like irqsoff), that just want to
* know if the ring buffer has been disabled, but it can handle
* races of where it gets disabled but we still do a record.
* As the check is in the fast path of the tracers, it is more
* important to be fast than accurate.
*/
tr->buffer_disabled = 0;
/* Make the flag seen by readers */
smp_wmb();
}
/**
* tracing_on - enable tracing buffers
*
* This function enables tracing buffers that may have been
* disabled with tracing_off.
*/
void tracing_on(void)
{
tracer_tracing_on(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_on);
/**
* __trace_puts - write a constant string into the trace buffer.
* @ip: The address of the caller
* @str: The constant string to write
* @size: The size of the string.
*/
int __trace_puts(unsigned long ip, const char *str, int size)
{
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct print_entry *entry;
unsigned long irq_flags;
int alloc;
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
alloc = sizeof(*entry) + size + 2; /* possible \n added */
local_save_flags(irq_flags);
buffer = global_trace.trace_buffer.buffer;
event = trace_buffer_lock_reserve(buffer, TRACE_PRINT, alloc,
irq_flags, preempt_count());
if (!event)
return 0;
entry = ring_buffer_event_data(event);
entry->ip = ip;
memcpy(&entry->buf, str, size);
/* Add a newline if necessary */
if (entry->buf[size - 1] != '\n') {
entry->buf[size] = '\n';
entry->buf[size + 1] = '\0';
stm_log(OST_ENTITY_TRACE_PRINTK, entry->buf, size + 2);
} else {
entry->buf[size] = '\0';
stm_log(OST_ENTITY_TRACE_PRINTK, entry->buf, size + 1);
}
__buffer_unlock_commit(buffer, event);
return size;
}
EXPORT_SYMBOL_GPL(__trace_puts);
/**
* __trace_bputs - write the pointer to a constant string into trace buffer
* @ip: The address of the caller
* @str: The constant string to write to the buffer to
*/
int __trace_bputs(unsigned long ip, const char *str)
{
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct bputs_entry *entry;
unsigned long irq_flags;
int size = sizeof(struct bputs_entry);
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
local_save_flags(irq_flags);
buffer = global_trace.trace_buffer.buffer;
event = trace_buffer_lock_reserve(buffer, TRACE_BPUTS, size,
irq_flags, preempt_count());
if (!event)
return 0;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->str = str;
stm_log(OST_ENTITY_TRACE_PRINTK, entry->str, strlen(entry->str)+1);
__buffer_unlock_commit(buffer, event);
return 1;
}
EXPORT_SYMBOL_GPL(__trace_bputs);
#ifdef CONFIG_TRACER_SNAPSHOT
/**
* trace_snapshot - take a snapshot of the current buffer.
*
* This causes a swap between the snapshot buffer and the current live
* tracing buffer. You can use this to take snapshots of the live
* trace when some condition is triggered, but continue to trace.
*
* Note, make sure to allocate the snapshot with either
* a tracing_snapshot_alloc(), or by doing it manually
* with: echo 1 > /sys/kernel/debug/tracing/snapshot
*
* If the snapshot buffer is not allocated, it will stop tracing.
* Basically making a permanent snapshot.
*/
void tracing_snapshot(void)
{
struct trace_array *tr = &global_trace;
struct tracer *tracer = tr->current_trace;
unsigned long flags;
if (in_nmi()) {
internal_trace_puts("*** SNAPSHOT CALLED FROM NMI CONTEXT ***\n");
internal_trace_puts("*** snapshot is being ignored ***\n");
return;
}
if (!tr->allocated_snapshot) {
internal_trace_puts("*** SNAPSHOT NOT ALLOCATED ***\n");
internal_trace_puts("*** stopping trace here! ***\n");
tracing_off();
return;
}
/* Note, snapshot can not be used when the tracer uses it */
if (tracer->use_max_tr) {
internal_trace_puts("*** LATENCY TRACER ACTIVE ***\n");
internal_trace_puts("*** Can not use snapshot (sorry) ***\n");
return;
}
local_irq_save(flags);
update_max_tr(tr, current, smp_processor_id());
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(tracing_snapshot);
static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf,
struct trace_buffer *size_buf, int cpu_id);
static void set_buffer_entries(struct trace_buffer *buf, unsigned long val);
static int alloc_snapshot(struct trace_array *tr)
{
int ret;
if (!tr->allocated_snapshot) {
/* allocate spare buffer */
ret = resize_buffer_duplicate_size(&tr->max_buffer,
&tr->trace_buffer, RING_BUFFER_ALL_CPUS);
if (ret < 0)
return ret;
tr->allocated_snapshot = true;
}
return 0;
}
void free_snapshot(struct trace_array *tr)
{
/*
* We don't free the ring buffer. instead, resize it because
* The max_tr ring buffer has some state (e.g. ring->clock) and
* we want preserve it.
*/
ring_buffer_resize(tr->max_buffer.buffer, 1, RING_BUFFER_ALL_CPUS);
set_buffer_entries(&tr->max_buffer, 1);
tracing_reset_online_cpus(&tr->max_buffer);
tr->allocated_snapshot = false;
}
/**
* trace_snapshot_alloc - allocate and take a snapshot of the current buffer.
*
* This is similar to trace_snapshot(), but it will allocate the
* snapshot buffer if it isn't already allocated. Use this only
* where it is safe to sleep, as the allocation may sleep.
*
* This causes a swap between the snapshot buffer and the current live
* tracing buffer. You can use this to take snapshots of the live
* trace when some condition is triggered, but continue to trace.
*/
void tracing_snapshot_alloc(void)
{
struct trace_array *tr = &global_trace;
int ret;
ret = alloc_snapshot(tr);
if (WARN_ON(ret < 0))
return;
tracing_snapshot();
}
EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
#else
void tracing_snapshot(void)
{
WARN_ONCE(1, "Snapshot feature not enabled, but internal snapshot used");
}
EXPORT_SYMBOL_GPL(tracing_snapshot);
void tracing_snapshot_alloc(void)
{
/* Give warning */
tracing_snapshot();
}
EXPORT_SYMBOL_GPL(tracing_snapshot_alloc);
#endif /* CONFIG_TRACER_SNAPSHOT */
void tracer_tracing_off(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
ring_buffer_record_off(tr->trace_buffer.buffer);
/*
* This flag is looked at when buffers haven't been allocated
* yet, or by some tracers (like irqsoff), that just want to
* know if the ring buffer has been disabled, but it can handle
* races of where it gets disabled but we still do a record.
* As the check is in the fast path of the tracers, it is more
* important to be fast than accurate.
*/
tr->buffer_disabled = 1;
/* Make the flag seen by readers */
smp_wmb();
}
/**
* tracing_off - turn off tracing buffers
*
* This function stops the tracing buffers from recording data.
* It does not disable any overhead the tracers themselves may
* be causing. This function simply causes all recording to
* the ring buffers to fail.
*/
void tracing_off(void)
{
tracer_tracing_off(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_off);
/**
* tracer_tracing_is_on - show real state of ring buffer enabled
* @tr : the trace array to know if ring buffer is enabled
*
* Shows real state of the ring buffer if it is enabled or not.
*/
int tracer_tracing_is_on(struct trace_array *tr)
{
if (tr->trace_buffer.buffer)
return ring_buffer_record_is_on(tr->trace_buffer.buffer);
return !tr->buffer_disabled;
}
/**
* tracing_is_on - show state of ring buffers enabled
*/
int tracing_is_on(void)
{
return tracer_tracing_is_on(&global_trace);
}
EXPORT_SYMBOL_GPL(tracing_is_on);
static int __init set_buf_size(char *str)
{
unsigned long buf_size;
if (!str)
return 0;
buf_size = memparse(str, &str);
/* nr_entries can not be zero */
if (buf_size == 0)
return 0;
trace_buf_size = buf_size;
return 1;
}
__setup("trace_buf_size=", set_buf_size);
static int __init set_tracing_thresh(char *str)
{
unsigned long threshold;
int ret;
if (!str)
return 0;
ret = kstrtoul(str, 0, &threshold);
if (ret < 0)
return 0;
tracing_thresh = threshold * 1000;
return 1;
}
__setup("tracing_thresh=", set_tracing_thresh);
unsigned long nsecs_to_usecs(unsigned long nsecs)
{
return nsecs / 1000;
}
/* These must match the bit postions in trace_iterator_flags */
static const char *trace_options[] = {
"print-parent",
"sym-offset",
"sym-addr",
"verbose",
"raw",
"hex",
"bin",
"block",
"stacktrace",
"trace_printk",
"ftrace_preempt",
"branch",
"annotate",
"userstacktrace",
"sym-userobj",
"printk-msg-only",
"context-info",
"latency-format",
"sleep-time",
"graph-time",
"record-cmd",
"overwrite",
"disable_on_free",
"irq-info",
"markers",
"function-trace",
"print-tgid",
NULL
};
static struct {
u64 (*func)(void);
const char *name;
int in_ns; /* is this clock in nanoseconds? */
} trace_clocks[] = {
{ trace_clock_local, "local", 1 },
{ trace_clock_global, "global", 1 },
{ trace_clock_counter, "counter", 0 },
{ trace_clock_jiffies, "uptime", 0 },
{ trace_clock, "perf", 1 },
ARCH_TRACE_CLOCKS
};
/*
* trace_parser_get_init - gets the buffer for trace parser
*/
int trace_parser_get_init(struct trace_parser *parser, int size)
{
memset(parser, 0, sizeof(*parser));
parser->buffer = kmalloc(size, GFP_KERNEL);
if (!parser->buffer)
return 1;
parser->size = size;
return 0;
}
/*
* trace_parser_put - frees the buffer for trace parser
*/
void trace_parser_put(struct trace_parser *parser)
{
kfree(parser->buffer);
}
/*
* trace_get_user - reads the user input string separated by space
* (matched by isspace(ch))
*
* For each string found the 'struct trace_parser' is updated,
* and the function returns.
*
* Returns number of bytes read.
*
* See kernel/trace/trace.h for 'struct trace_parser' details.
*/
int trace_get_user(struct trace_parser *parser, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char ch;
size_t read = 0;
ssize_t ret;
if (!*ppos)
trace_parser_clear(parser);
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
/*
* The parser is not finished with the last write,
* continue reading the user input without skipping spaces.
*/
if (!parser->cont) {
/* skip white space */
while (cnt && isspace(ch)) {
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
}
/* only spaces were written */
if (isspace(ch)) {
*ppos += read;
ret = read;
goto out;
}
parser->idx = 0;
}
/* read the non-space input */
while (cnt && !isspace(ch)) {
if (parser->idx < parser->size - 1)
parser->buffer[parser->idx++] = ch;
else {
ret = -EINVAL;
goto out;
}
ret = get_user(ch, ubuf++);
if (ret)
goto out;
read++;
cnt--;
}
/* We either got finished input or we have to wait for another call. */
if (isspace(ch)) {
parser->buffer[parser->idx] = 0;
parser->cont = false;
} else if (parser->idx < parser->size - 1) {
parser->cont = true;
parser->buffer[parser->idx++] = ch;
} else {
ret = -EINVAL;
goto out;
}
*ppos += read;
ret = read;
out:
return ret;
}
ssize_t trace_seq_to_user(struct trace_seq *s, char __user *ubuf, size_t cnt)
{
int len;
int ret;
if (!cnt)
return 0;
if (s->len <= s->readpos)
return -EBUSY;
len = s->len - s->readpos;
if (cnt > len)
cnt = len;
ret = copy_to_user(ubuf, s->buffer + s->readpos, cnt);
if (ret == cnt)
return -EFAULT;
cnt -= ret;
s->readpos += cnt;
return cnt;
}
static ssize_t trace_seq_to_buffer(struct trace_seq *s, void *buf, size_t cnt)
{
int len;
if (s->len <= s->readpos)
return -EBUSY;
len = s->len - s->readpos;
if (cnt > len)
cnt = len;
memcpy(buf, s->buffer + s->readpos, cnt);
s->readpos += cnt;
return cnt;
}
/*
* ftrace_max_lock is used to protect the swapping of buffers
* when taking a max snapshot. The buffers themselves are
* protected by per_cpu spinlocks. But the action of the swap
* needs its own lock.
*
* This is defined as a arch_spinlock_t in order to help
* with performance when lockdep debugging is enabled.
*
* It is also used in other places outside the update_max_tr
* so it needs to be defined outside of the
* CONFIG_TRACER_MAX_TRACE.
*/
static arch_spinlock_t ftrace_max_lock =
(arch_spinlock_t)__ARCH_SPIN_LOCK_UNLOCKED;
unsigned long __read_mostly tracing_thresh;
#ifdef CONFIG_TRACER_MAX_TRACE
unsigned long __read_mostly tracing_max_latency;
/*
* Copy the new maximum trace into the separate maximum-trace
* structure. (this way the maximum trace is permanently saved,
* for later retrieval via /sys/kernel/debug/tracing/latency_trace)
*/
static void
__update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
struct trace_buffer *trace_buf = &tr->trace_buffer;
struct trace_buffer *max_buf = &tr->max_buffer;
struct trace_array_cpu *data = per_cpu_ptr(trace_buf->data, cpu);
struct trace_array_cpu *max_data = per_cpu_ptr(max_buf->data, cpu);
max_buf->cpu = cpu;
max_buf->time_start = data->preempt_timestamp;
max_data->saved_latency = tracing_max_latency;
max_data->critical_start = data->critical_start;
max_data->critical_end = data->critical_end;
memcpy(max_data->comm, tsk->comm, TASK_COMM_LEN);
max_data->pid = tsk->pid;
/*
* If tsk == current, then use current_uid(), as that does not use
* RCU. The irq tracer can be called out of RCU scope.
*/
if (tsk == current)
max_data->uid = current_uid();
else
max_data->uid = task_uid(tsk);
max_data->nice = tsk->static_prio - 20 - MAX_RT_PRIO;
max_data->policy = tsk->policy;
max_data->rt_priority = tsk->rt_priority;
/* record this tasks comm */
tracing_record_cmdline(tsk);
}
/**
* update_max_tr - snapshot all trace buffers from global_trace to max_tr
* @tr: tracer
* @tsk: the task with the latency
* @cpu: The cpu that initiated the trace.
*
* Flip the buffers between the @tr and the max_tr and record information
* about which task was the cause of this latency.
*/
void
update_max_tr(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
struct ring_buffer *buf;
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&ftrace_max_lock);
buf = tr->trace_buffer.buffer;
tr->trace_buffer.buffer = tr->max_buffer.buffer;
tr->max_buffer.buffer = buf;
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&ftrace_max_lock);
}
/**
* update_max_tr_single - only copy one trace over, and reset the rest
* @tr - tracer
* @tsk - task with the latency
* @cpu - the cpu of the buffer to copy.
*
* Flip the trace of a single CPU buffer between the @tr and the max_tr.
*/
void
update_max_tr_single(struct trace_array *tr, struct task_struct *tsk, int cpu)
{
int ret;
if (tr->stop_count)
return;
WARN_ON_ONCE(!irqs_disabled());
if (!tr->allocated_snapshot) {
/* Only the nop tracer should hit this when disabling */
WARN_ON_ONCE(tr->current_trace != &nop_trace);
return;
}
arch_spin_lock(&ftrace_max_lock);
ret = ring_buffer_swap_cpu(tr->max_buffer.buffer, tr->trace_buffer.buffer, cpu);
if (ret == -EBUSY) {
/*
* We failed to swap the buffer due to a commit taking
* place on this CPU. We fail to record, but we reset
* the max trace buffer (no one writes directly to it)
* and flag that it failed.
*/
trace_array_printk_buf(tr->max_buffer.buffer, _THIS_IP_,
"Failed to swap buffers due to commit in progress\n");
}
WARN_ON_ONCE(ret && ret != -EAGAIN && ret != -EBUSY);
__update_max_tr(tr, tsk, cpu);
arch_spin_unlock(&ftrace_max_lock);
}
#endif /* CONFIG_TRACER_MAX_TRACE */
static int default_wait_pipe(struct trace_iterator *iter)
{
/* Iterators are static, they should be filled or empty */
if (trace_buffer_iter(iter, iter->cpu_file))
return 0;
return ring_buffer_wait(iter->trace_buffer->buffer, iter->cpu_file);
}
#ifdef CONFIG_FTRACE_STARTUP_TEST
static int run_tracer_selftest(struct tracer *type)
{
struct trace_array *tr = &global_trace;
struct tracer *saved_tracer = tr->current_trace;
int ret;
if (!type->selftest || tracing_selftest_disabled)
return 0;
/*
* Run a selftest on this tracer.
* Here we reset the trace buffer, and set the current
* tracer to be this tracer. The tracer can then run some
* internal tracing to verify that everything is in order.
* If we fail, we do not register this tracer.
*/
tracing_reset_online_cpus(&tr->trace_buffer);
tr->current_trace = type;
#ifdef CONFIG_TRACER_MAX_TRACE
if (type->use_max_tr) {
/* If we expanded the buffers, make sure the max is expanded too */
if (ring_buffer_expanded)
ring_buffer_resize(tr->max_buffer.buffer, trace_buf_size,
RING_BUFFER_ALL_CPUS);
tr->allocated_snapshot = true;
}
#endif
/* the test is responsible for initializing and enabling */
pr_info("Testing tracer %s: ", type->name);
ret = type->selftest(type, tr);
/* the test is responsible for resetting too */
tr->current_trace = saved_tracer;
if (ret) {
printk(KERN_CONT "FAILED!\n");
/* Add the warning after printing 'FAILED' */
WARN_ON(1);
return -1;
}
/* Only reset on passing, to avoid touching corrupted buffers */
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
if (type->use_max_tr) {
tr->allocated_snapshot = false;
/* Shrink the max buffer again */
if (ring_buffer_expanded)
ring_buffer_resize(tr->max_buffer.buffer, 1,
RING_BUFFER_ALL_CPUS);
}
#endif
printk(KERN_CONT "PASSED\n");
return 0;
}
#else
static inline int run_tracer_selftest(struct tracer *type)
{
return 0;
}
#endif /* CONFIG_FTRACE_STARTUP_TEST */
/**
* register_tracer - register a tracer with the ftrace system.
* @type - the plugin for the tracer
*
* Register a new plugin tracer.
*/
int register_tracer(struct tracer *type)
{
struct tracer *t;
int ret = 0;
if (!type->name) {
pr_info("Tracer must have a name\n");
return -1;
}
if (strlen(type->name) >= MAX_TRACER_SIZE) {
pr_info("Tracer has a name longer than %d\n", MAX_TRACER_SIZE);
return -1;
}
mutex_lock(&trace_types_lock);
tracing_selftest_running = true;
for (t = trace_types; t; t = t->next) {
if (strcmp(type->name, t->name) == 0) {
/* already found */
pr_info("Tracer %s already registered\n",
type->name);
ret = -1;
goto out;
}
}
if (!type->set_flag)
type->set_flag = &dummy_set_flag;
if (!type->flags)
type->flags = &dummy_tracer_flags;
else
if (!type->flags->opts)
type->flags->opts = dummy_tracer_opt;
if (!type->wait_pipe)
type->wait_pipe = default_wait_pipe;
ret = run_tracer_selftest(type);
if (ret < 0)
goto out;
type->next = trace_types;
trace_types = type;
out:
tracing_selftest_running = false;
mutex_unlock(&trace_types_lock);
if (ret || !default_bootup_tracer)
goto out_unlock;
if (strncmp(default_bootup_tracer, type->name, MAX_TRACER_SIZE))
goto out_unlock;
printk(KERN_INFO "Starting tracer '%s'\n", type->name);
/* Do we want this tracer to start on bootup? */
tracing_set_tracer(type->name);
default_bootup_tracer = NULL;
/* disable other selftests, since this will break it. */
tracing_selftest_disabled = true;
#ifdef CONFIG_FTRACE_STARTUP_TEST
printk(KERN_INFO "Disabling FTRACE selftests due to running tracer '%s'\n",
type->name);
#endif
out_unlock:
return ret;
}
void tracing_reset(struct trace_buffer *buf, int cpu)
{
struct ring_buffer *buffer = buf->buffer;
if (!buffer)
return;
ring_buffer_record_disable(buffer);
/* Make sure all commits have finished */
synchronize_sched();
ring_buffer_reset_cpu(buffer, cpu);
ring_buffer_record_enable(buffer);
}
void tracing_reset_online_cpus(struct trace_buffer *buf)
{
struct ring_buffer *buffer = buf->buffer;
int cpu;
if (!buffer)
return;
ring_buffer_record_disable(buffer);
/* Make sure all commits have finished */
synchronize_sched();
buf->time_start = buffer_ftrace_now(buf, buf->cpu);
for_each_online_cpu(cpu)
ring_buffer_reset_cpu(buffer, cpu);
ring_buffer_record_enable(buffer);
}
/* Must have trace_types_lock held */
void tracing_reset_all_online_cpus(void)
{
struct trace_array *tr;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
tracing_reset_online_cpus(&tr->max_buffer);
#endif
}
}
#define SAVED_CMDLINES 128
#define NO_CMDLINE_MAP UINT_MAX
static unsigned map_pid_to_cmdline[PID_MAX_DEFAULT+1];
static unsigned map_cmdline_to_pid[SAVED_CMDLINES];
static char saved_cmdlines[SAVED_CMDLINES][TASK_COMM_LEN];
static unsigned saved_tgids[SAVED_CMDLINES];
static int cmdline_idx;
static arch_spinlock_t trace_cmdline_lock = __ARCH_SPIN_LOCK_UNLOCKED;
/* temporary disable recording */
static atomic_t trace_record_cmdline_disabled __read_mostly;
static void trace_init_cmdlines(void)
{
memset(&map_pid_to_cmdline, NO_CMDLINE_MAP, sizeof(map_pid_to_cmdline));
memset(&map_cmdline_to_pid, NO_CMDLINE_MAP, sizeof(map_cmdline_to_pid));
cmdline_idx = 0;
}
int is_tracing_stopped(void)
{
return global_trace.stop_count;
}
/**
* ftrace_off_permanent - disable all ftrace code permanently
*
* This should only be called when a serious anomally has
* been detected. This will turn off the function tracing,
* ring buffers, and other tracing utilites. It takes no
* locks and can be called from any context.
*/
void ftrace_off_permanent(void)
{
tracing_disabled = 1;
ftrace_stop();
tracing_off_permanent();
}
/**
* tracing_start - quick start of the tracer
*
* If tracing is enabled but was stopped by tracing_stop,
* this will start the tracer back up.
*/
void tracing_start(void)
{
struct ring_buffer *buffer;
unsigned long flags;
if (tracing_disabled)
return;
raw_spin_lock_irqsave(&global_trace.start_lock, flags);
if (--global_trace.stop_count) {
if (global_trace.stop_count < 0) {
/* Someone screwed up their debugging */
WARN_ON_ONCE(1);
global_trace.stop_count = 0;
}
goto out;
}
/* Prevent the buffers from switching */
arch_spin_lock(&ftrace_max_lock);
buffer = global_trace.trace_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
buffer = global_trace.max_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
#endif
arch_spin_unlock(&ftrace_max_lock);
out:
raw_spin_unlock_irqrestore(&global_trace.start_lock, flags);
}
static void tracing_start_tr(struct trace_array *tr)
{
struct ring_buffer *buffer;
unsigned long flags;
if (tracing_disabled)
return;
/* If global, we need to also start the max tracer */
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
return tracing_start();
raw_spin_lock_irqsave(&tr->start_lock, flags);
if (--tr->stop_count) {
if (tr->stop_count < 0) {
/* Someone screwed up their debugging */
WARN_ON_ONCE(1);
tr->stop_count = 0;
}
goto out;
}
buffer = tr->trace_buffer.buffer;
if (buffer)
ring_buffer_record_enable(buffer);
out:
raw_spin_unlock_irqrestore(&tr->start_lock, flags);
}
/**
* tracing_stop - quick stop of the tracer
*
* Light weight way to stop tracing. Use in conjunction with
* tracing_start.
*/
void tracing_stop(void)
{
struct ring_buffer *buffer;
unsigned long flags;
raw_spin_lock_irqsave(&global_trace.start_lock, flags);
if (global_trace.stop_count++)
goto out;
/* Prevent the buffers from switching */
arch_spin_lock(&ftrace_max_lock);
buffer = global_trace.trace_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
buffer = global_trace.max_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
#endif
arch_spin_unlock(&ftrace_max_lock);
out:
raw_spin_unlock_irqrestore(&global_trace.start_lock, flags);
}
static void tracing_stop_tr(struct trace_array *tr)
{
struct ring_buffer *buffer;
unsigned long flags;
/* If global, we need to also stop the max tracer */
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
return tracing_stop();
raw_spin_lock_irqsave(&tr->start_lock, flags);
if (tr->stop_count++)
goto out;
buffer = tr->trace_buffer.buffer;
if (buffer)
ring_buffer_record_disable(buffer);
out:
raw_spin_unlock_irqrestore(&tr->start_lock, flags);
}
void trace_stop_cmdline_recording(void);
static int trace_save_cmdline(struct task_struct *tsk)
{
unsigned pid, idx;
if (!tsk->pid || unlikely(tsk->pid > PID_MAX_DEFAULT))
return 0;
/*
* It's not the end of the world if we don't get
* the lock, but we also don't want to spin
* nor do we want to disable interrupts,
* so if we miss here, then better luck next time.
*/
if (!arch_spin_trylock(&trace_cmdline_lock))
return 0;
idx = map_pid_to_cmdline[tsk->pid];
if (idx == NO_CMDLINE_MAP) {
idx = (cmdline_idx + 1) % SAVED_CMDLINES;
/*
* Check whether the cmdline buffer at idx has a pid
* mapped. We are going to overwrite that entry so we
* need to clear the map_pid_to_cmdline. Otherwise we
* would read the new comm for the old pid.
*/
pid = map_cmdline_to_pid[idx];
if (pid != NO_CMDLINE_MAP)
map_pid_to_cmdline[pid] = NO_CMDLINE_MAP;
map_cmdline_to_pid[idx] = tsk->pid;
map_pid_to_cmdline[tsk->pid] = idx;
cmdline_idx = idx;
}
memcpy(&saved_cmdlines[idx], tsk->comm, TASK_COMM_LEN);
saved_tgids[idx] = tsk->tgid;
arch_spin_unlock(&trace_cmdline_lock);
return 1;
}
void trace_find_cmdline(int pid, char comm[])
{
unsigned map;
if (!pid) {
strcpy(comm, "<idle>");
return;
}
if (WARN_ON_ONCE(pid < 0)) {
strcpy(comm, "<XXX>");
return;
}
if (pid > PID_MAX_DEFAULT) {
strcpy(comm, "<...>");
return;
}
preempt_disable();
arch_spin_lock(&trace_cmdline_lock);
map = map_pid_to_cmdline[pid];
if (map != NO_CMDLINE_MAP)
strcpy(comm, saved_cmdlines[map]);
else
strcpy(comm, "<...>");
arch_spin_unlock(&trace_cmdline_lock);
preempt_enable();
}
int trace_find_tgid(int pid)
{
unsigned map;
int tgid;
preempt_disable();
arch_spin_lock(&trace_cmdline_lock);
map = map_pid_to_cmdline[pid];
if (map != NO_CMDLINE_MAP)
tgid = saved_tgids[map];
else
tgid = -1;
arch_spin_unlock(&trace_cmdline_lock);
preempt_enable();
return tgid;
}
void tracing_record_cmdline(struct task_struct *tsk)
{
if (atomic_read(&trace_record_cmdline_disabled) || !tracing_is_on())
return;
if (!__this_cpu_read(trace_cmdline_save))
return;
if (trace_save_cmdline(tsk))
__this_cpu_write(trace_cmdline_save, false);
}
void
tracing_generic_entry_update(struct trace_entry *entry, unsigned long flags,
int pc)
{
struct task_struct *tsk = current;
entry->preempt_count = pc & 0xff;
entry->pid = (tsk) ? tsk->pid : 0;
entry->flags =
#ifdef CONFIG_TRACE_IRQFLAGS_SUPPORT
(irqs_disabled_flags(flags) ? TRACE_FLAG_IRQS_OFF : 0) |
#else
TRACE_FLAG_IRQS_NOSUPPORT |
#endif
((pc & HARDIRQ_MASK) ? TRACE_FLAG_HARDIRQ : 0) |
((pc & SOFTIRQ_MASK) ? TRACE_FLAG_SOFTIRQ : 0) |
(need_resched() ? TRACE_FLAG_NEED_RESCHED : 0);
}
EXPORT_SYMBOL_GPL(tracing_generic_entry_update);
struct ring_buffer_event *
trace_buffer_lock_reserve(struct ring_buffer *buffer,
int type,
unsigned long len,
unsigned long flags, int pc)
{
struct ring_buffer_event *event;
event = ring_buffer_lock_reserve(buffer, len);
if (event != NULL) {
struct trace_entry *ent = ring_buffer_event_data(event);
tracing_generic_entry_update(ent, flags, pc);
ent->type = type;
}
return event;
}
void
__buffer_unlock_commit(struct ring_buffer *buffer, struct ring_buffer_event *event)
{
__this_cpu_write(trace_cmdline_save, true);
ring_buffer_unlock_commit(buffer, event);
}
static inline void
__trace_buffer_unlock_commit(struct ring_buffer *buffer,
struct ring_buffer_event *event,
unsigned long flags, int pc)
{
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(buffer, flags, 6, pc);
ftrace_trace_userstack(buffer, flags, pc);
}
void trace_buffer_unlock_commit(struct ring_buffer *buffer,
struct ring_buffer_event *event,
unsigned long flags, int pc)
{
__trace_buffer_unlock_commit(buffer, event, flags, pc);
}
EXPORT_SYMBOL_GPL(trace_buffer_unlock_commit);
struct ring_buffer_event *
trace_event_buffer_lock_reserve(struct ring_buffer **current_rb,
struct ftrace_event_file *ftrace_file,
int type, unsigned long len,
unsigned long flags, int pc)
{
*current_rb = ftrace_file->tr->trace_buffer.buffer;
return trace_buffer_lock_reserve(*current_rb,
type, len, flags, pc);
}
EXPORT_SYMBOL_GPL(trace_event_buffer_lock_reserve);
struct ring_buffer_event *
trace_current_buffer_lock_reserve(struct ring_buffer **current_rb,
int type, unsigned long len,
unsigned long flags, int pc)
{
*current_rb = global_trace.trace_buffer.buffer;
return trace_buffer_lock_reserve(*current_rb,
type, len, flags, pc);
}
EXPORT_SYMBOL_GPL(trace_current_buffer_lock_reserve);
void trace_current_buffer_unlock_commit(struct ring_buffer *buffer,
struct ring_buffer_event *event,
unsigned long flags, int pc)
{
__trace_buffer_unlock_commit(buffer, event, flags, pc);
}
EXPORT_SYMBOL_GPL(trace_current_buffer_unlock_commit);
void trace_buffer_unlock_commit_regs(struct ring_buffer *buffer,
struct ring_buffer_event *event,
unsigned long flags, int pc,
struct pt_regs *regs)
{
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack_regs(buffer, flags, 0, pc, regs);
ftrace_trace_userstack(buffer, flags, pc);
}
EXPORT_SYMBOL_GPL(trace_buffer_unlock_commit_regs);
void trace_current_buffer_discard_commit(struct ring_buffer *buffer,
struct ring_buffer_event *event)
{
ring_buffer_discard_commit(buffer, event);
}
EXPORT_SYMBOL_GPL(trace_current_buffer_discard_commit);
void
trace_function(struct trace_array *tr,
unsigned long ip, unsigned long parent_ip, unsigned long flags,
int pc)
{
struct ftrace_event_call *call = &event_function;
struct ring_buffer *buffer = tr->trace_buffer.buffer;
struct ring_buffer_event *event;
struct ftrace_entry *entry;
/* If we are reading the ring buffer, don't trace */
if (unlikely(__this_cpu_read(ftrace_cpu_disabled)))
return;
event = trace_buffer_lock_reserve(buffer, TRACE_FN, sizeof(*entry),
flags, pc);
if (!event)
return;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->parent_ip = parent_ip;
if (!filter_check_discard(call, entry, buffer, event))
__buffer_unlock_commit(buffer, event);
}
void
ftrace(struct trace_array *tr, struct trace_array_cpu *data,
unsigned long ip, unsigned long parent_ip, unsigned long flags,
int pc)
{
if (likely(!atomic_read(&data->disabled)))
trace_function(tr, ip, parent_ip, flags, pc);
}
#ifdef CONFIG_STACKTRACE
#define FTRACE_STACK_MAX_ENTRIES (PAGE_SIZE / sizeof(unsigned long))
struct ftrace_stack {
unsigned long calls[FTRACE_STACK_MAX_ENTRIES];
};
static DEFINE_PER_CPU(struct ftrace_stack, ftrace_stack);
static DEFINE_PER_CPU(int, ftrace_stack_reserve);
static void __ftrace_trace_stack(struct ring_buffer *buffer,
unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
struct ftrace_event_call *call = &event_kernel_stack;
struct ring_buffer_event *event;
struct stack_entry *entry;
struct stack_trace trace;
int use_stack;
int size = FTRACE_STACK_ENTRIES;
trace.nr_entries = 0;
trace.skip = skip;
/*
* Since events can happen in NMIs there's no safe way to
* use the per cpu ftrace_stacks. We reserve it and if an interrupt
* or NMI comes in, it will just have to use the default
* FTRACE_STACK_SIZE.
*/
preempt_disable_notrace();
use_stack = __this_cpu_inc_return(ftrace_stack_reserve);
/*
* We don't need any atomic variables, just a barrier.
* If an interrupt comes in, we don't care, because it would
* have exited and put the counter back to what we want.
* We just need a barrier to keep gcc from moving things
* around.
*/
barrier();
if (use_stack == 1) {
trace.entries = &__get_cpu_var(ftrace_stack).calls[0];
trace.max_entries = FTRACE_STACK_MAX_ENTRIES;
if (regs)
save_stack_trace_regs(regs, &trace);
else
save_stack_trace(&trace);
if (trace.nr_entries > size)
size = trace.nr_entries;
} else
/* From now on, use_stack is a boolean */
use_stack = 0;
size *= sizeof(unsigned long);
event = trace_buffer_lock_reserve(buffer, TRACE_STACK,
sizeof(*entry) + size, flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
memset(&entry->caller, 0, size);
if (use_stack)
memcpy(&entry->caller, trace.entries,
trace.nr_entries * sizeof(unsigned long));
else {
trace.max_entries = FTRACE_STACK_ENTRIES;
trace.entries = entry->caller;
if (regs)
save_stack_trace_regs(regs, &trace);
else
save_stack_trace(&trace);
}
entry->size = trace.nr_entries;
if (!filter_check_discard(call, entry, buffer, event))
__buffer_unlock_commit(buffer, event);
out:
/* Again, don't let gcc optimize things here */
barrier();
__this_cpu_dec(ftrace_stack_reserve);
preempt_enable_notrace();
}
void ftrace_trace_stack_regs(struct ring_buffer *buffer, unsigned long flags,
int skip, int pc, struct pt_regs *regs)
{
if (!(trace_flags & TRACE_ITER_STACKTRACE))
return;
__ftrace_trace_stack(buffer, flags, skip, pc, regs);
}
void ftrace_trace_stack(struct ring_buffer *buffer, unsigned long flags,
int skip, int pc)
{
if (!(trace_flags & TRACE_ITER_STACKTRACE))
return;
__ftrace_trace_stack(buffer, flags, skip, pc, NULL);
}
void __trace_stack(struct trace_array *tr, unsigned long flags, int skip,
int pc)
{
__ftrace_trace_stack(tr->trace_buffer.buffer, flags, skip, pc, NULL);
}
/**
* trace_dump_stack - record a stack back trace in the trace buffer
* @skip: Number of functions to skip (helper handlers)
*/
void trace_dump_stack(int skip)
{
unsigned long flags;
if (tracing_disabled || tracing_selftest_running)
return;
local_save_flags(flags);
/*
* Skip 3 more, seems to get us at the caller of
* this function.
*/
skip += 3;
__ftrace_trace_stack(global_trace.trace_buffer.buffer,
flags, skip, preempt_count(), NULL);
}
static DEFINE_PER_CPU(int, user_stack_count);
void
ftrace_trace_userstack(struct ring_buffer *buffer, unsigned long flags, int pc)
{
struct ftrace_event_call *call = &event_user_stack;
struct ring_buffer_event *event;
struct userstack_entry *entry;
struct stack_trace trace;
if (!(trace_flags & TRACE_ITER_USERSTACKTRACE))
return;
/*
* NMIs can not handle page faults, even with fix ups.
* The save user stack can (and often does) fault.
*/
if (unlikely(in_nmi()))
return;
/*
* prevent recursion, since the user stack tracing may
* trigger other kernel events.
*/
preempt_disable();
if (__this_cpu_read(user_stack_count))
goto out;
__this_cpu_inc(user_stack_count);
event = trace_buffer_lock_reserve(buffer, TRACE_USER_STACK,
sizeof(*entry), flags, pc);
if (!event)
goto out_drop_count;
entry = ring_buffer_event_data(event);
entry->tgid = current->tgid;
memset(&entry->caller, 0, sizeof(entry->caller));
trace.nr_entries = 0;
trace.max_entries = FTRACE_STACK_ENTRIES;
trace.skip = 0;
trace.entries = entry->caller;
save_stack_trace_user(&trace);
if (!filter_check_discard(call, entry, buffer, event))
__buffer_unlock_commit(buffer, event);
out_drop_count:
__this_cpu_dec(user_stack_count);
out:
preempt_enable();
}
#ifdef UNUSED
static void __trace_userstack(struct trace_array *tr, unsigned long flags)
{
ftrace_trace_userstack(tr, flags, preempt_count());
}
#endif /* UNUSED */
#endif /* CONFIG_STACKTRACE */
/* created for use with alloc_percpu */
struct trace_buffer_struct {
char buffer[TRACE_BUF_SIZE];
};
static struct trace_buffer_struct *trace_percpu_buffer;
static struct trace_buffer_struct *trace_percpu_sirq_buffer;
static struct trace_buffer_struct *trace_percpu_irq_buffer;
static struct trace_buffer_struct *trace_percpu_nmi_buffer;
/*
* The buffer used is dependent on the context. There is a per cpu
* buffer for normal context, softirq contex, hard irq context and
* for NMI context. Thise allows for lockless recording.
*
* Note, if the buffers failed to be allocated, then this returns NULL
*/
static char *get_trace_buf(void)
{
struct trace_buffer_struct *percpu_buffer;
/*
* If we have allocated per cpu buffers, then we do not
* need to do any locking.
*/
if (in_nmi())
percpu_buffer = trace_percpu_nmi_buffer;
else if (in_irq())
percpu_buffer = trace_percpu_irq_buffer;
else if (in_softirq())
percpu_buffer = trace_percpu_sirq_buffer;
else
percpu_buffer = trace_percpu_buffer;
if (!percpu_buffer)
return NULL;
return this_cpu_ptr(&percpu_buffer->buffer[0]);
}
static int alloc_percpu_trace_buffer(void)
{
struct trace_buffer_struct *buffers;
struct trace_buffer_struct *sirq_buffers;
struct trace_buffer_struct *irq_buffers;
struct trace_buffer_struct *nmi_buffers;
buffers = alloc_percpu(struct trace_buffer_struct);
if (!buffers)
goto err_warn;
sirq_buffers = alloc_percpu(struct trace_buffer_struct);
if (!sirq_buffers)
goto err_sirq;
irq_buffers = alloc_percpu(struct trace_buffer_struct);
if (!irq_buffers)
goto err_irq;
nmi_buffers = alloc_percpu(struct trace_buffer_struct);
if (!nmi_buffers)
goto err_nmi;
trace_percpu_buffer = buffers;
trace_percpu_sirq_buffer = sirq_buffers;
trace_percpu_irq_buffer = irq_buffers;
trace_percpu_nmi_buffer = nmi_buffers;
return 0;
err_nmi:
free_percpu(irq_buffers);
err_irq:
free_percpu(sirq_buffers);
err_sirq:
free_percpu(buffers);
err_warn:
WARN(1, "Could not allocate percpu trace_printk buffer");
return -ENOMEM;
}
static int buffers_allocated;
void trace_printk_init_buffers(void)
{
if (buffers_allocated)
return;
if (alloc_percpu_trace_buffer())
return;
pr_info("ftrace: Allocated trace_printk buffers\n");
/* Expand the buffers to set size */
tracing_update_buffers();
buffers_allocated = 1;
/*
* trace_printk_init_buffers() can be called by modules.
* If that happens, then we need to start cmdline recording
* directly here. If the global_trace.buffer is already
* allocated here, then this was called by module code.
*/
if (global_trace.trace_buffer.buffer)
tracing_start_cmdline_record();
}
void trace_printk_start_comm(void)
{
/* Start tracing comms if trace printk is set */
if (!buffers_allocated)
return;
tracing_start_cmdline_record();
}
static void trace_printk_start_stop_comm(int enabled)
{
if (!buffers_allocated)
return;
if (enabled)
tracing_start_cmdline_record();
else
tracing_stop_cmdline_record();
}
/**
* trace_vbprintk - write binary msg to tracing buffer
*
*/
int trace_vbprintk(unsigned long ip, const char *fmt, va_list args)
{
struct ftrace_event_call *call = &event_bprint;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct trace_array *tr = &global_trace;
struct bprint_entry *entry;
unsigned long flags;
char *tbuffer;
int len = 0, size, pc;
if (unlikely(tracing_selftest_running || tracing_disabled))
return 0;
/* Don't pollute graph traces with trace_vprintk internals */
pause_graph_tracing();
pc = preempt_count();
preempt_disable_notrace();
tbuffer = get_trace_buf();
if (!tbuffer) {
len = 0;
goto out;
}
len = vbin_printf((u32 *)tbuffer, TRACE_BUF_SIZE/sizeof(int), fmt, args);
if (len > TRACE_BUF_SIZE/sizeof(int) || len < 0)
goto out;
local_save_flags(flags);
size = sizeof(*entry) + sizeof(u32) * len;
buffer = tr->trace_buffer.buffer;
event = trace_buffer_lock_reserve(buffer, TRACE_BPRINT, size,
flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
entry->ip = ip;
entry->fmt = fmt;
memcpy(entry->buf, tbuffer, sizeof(u32) * len);
if (!filter_check_discard(call, entry, buffer, event)) {
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(buffer, flags, 6, pc);
}
out:
preempt_enable_notrace();
unpause_graph_tracing();
return len;
}
EXPORT_SYMBOL_GPL(trace_vbprintk);
static int
__trace_array_vprintk(struct ring_buffer *buffer,
unsigned long ip, const char *fmt, va_list args)
{
struct ftrace_event_call *call = &event_print;
struct ring_buffer_event *event;
int len = 0, size, pc;
struct print_entry *entry;
unsigned long flags;
char *tbuffer;
if (tracing_disabled || tracing_selftest_running)
return 0;
/* Don't pollute graph traces with trace_vprintk internals */
pause_graph_tracing();
pc = preempt_count();
preempt_disable_notrace();
tbuffer = get_trace_buf();
if (!tbuffer) {
len = 0;
goto out;
}
len = vsnprintf(tbuffer, TRACE_BUF_SIZE, fmt, args);
if (len > TRACE_BUF_SIZE)
goto out;
local_save_flags(flags);
size = sizeof(*entry) + len + 1;
event = trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
flags, pc);
if (!event)
goto out;
entry = ring_buffer_event_data(event);
entry->ip = ip;
memcpy(&entry->buf, tbuffer, len);
entry->buf[len] = '\0';
if (!filter_check_discard(call, entry, buffer, event)) {
stm_log(OST_ENTITY_TRACE_PRINTK, entry->buf, len + 1);
__buffer_unlock_commit(buffer, event);
ftrace_trace_stack(buffer, flags, 6, pc);
}
out:
preempt_enable_notrace();
unpause_graph_tracing();
return len;
}
int trace_array_vprintk(struct trace_array *tr,
unsigned long ip, const char *fmt, va_list args)
{
return __trace_array_vprintk(tr->trace_buffer.buffer, ip, fmt, args);
}
int trace_array_printk(struct trace_array *tr,
unsigned long ip, const char *fmt, ...)
{
int ret;
va_list ap;
if (!(trace_flags & TRACE_ITER_PRINTK))
return 0;
va_start(ap, fmt);
ret = trace_array_vprintk(tr, ip, fmt, ap);
va_end(ap);
return ret;
}
int trace_array_printk_buf(struct ring_buffer *buffer,
unsigned long ip, const char *fmt, ...)
{
int ret;
va_list ap;
if (!(trace_flags & TRACE_ITER_PRINTK))
return 0;
va_start(ap, fmt);
ret = __trace_array_vprintk(buffer, ip, fmt, ap);
va_end(ap);
return ret;
}
int trace_vprintk(unsigned long ip, const char *fmt, va_list args)
{
return trace_array_vprintk(&global_trace, ip, fmt, args);
}
EXPORT_SYMBOL_GPL(trace_vprintk);
static void trace_iterator_increment(struct trace_iterator *iter)
{
struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, iter->cpu);
iter->idx++;
if (buf_iter)
ring_buffer_read(buf_iter, NULL);
}
static struct trace_entry *
peek_next_entry(struct trace_iterator *iter, int cpu, u64 *ts,
unsigned long *lost_events)
{
struct ring_buffer_event *event;
struct ring_buffer_iter *buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter)
event = ring_buffer_iter_peek(buf_iter, ts);
else
event = ring_buffer_peek(iter->trace_buffer->buffer, cpu, ts,
lost_events);
if (event) {
iter->ent_size = ring_buffer_event_length(event);
return ring_buffer_event_data(event);
}
iter->ent_size = 0;
return NULL;
}
static struct trace_entry *
__find_next_entry(struct trace_iterator *iter, int *ent_cpu,
unsigned long *missing_events, u64 *ent_ts)
{
struct ring_buffer *buffer = iter->trace_buffer->buffer;
struct trace_entry *ent, *next = NULL;
unsigned long lost_events = 0, next_lost = 0;
int cpu_file = iter->cpu_file;
u64 next_ts = 0, ts;
int next_cpu = -1;
int next_size = 0;
int cpu;
/*
* If we are in a per_cpu trace file, don't bother by iterating over
* all cpu and peek directly.
*/
if (cpu_file > RING_BUFFER_ALL_CPUS) {
if (ring_buffer_empty_cpu(buffer, cpu_file))
return NULL;
ent = peek_next_entry(iter, cpu_file, ent_ts, missing_events);
if (ent_cpu)
*ent_cpu = cpu_file;
return ent;
}
for_each_tracing_cpu(cpu) {
if (ring_buffer_empty_cpu(buffer, cpu))
continue;
ent = peek_next_entry(iter, cpu, &ts, &lost_events);
/*
* Pick the entry with the smallest timestamp:
*/
if (ent && (!next || ts < next_ts)) {
next = ent;
next_cpu = cpu;
next_ts = ts;
next_lost = lost_events;
next_size = iter->ent_size;
}
}
iter->ent_size = next_size;
if (ent_cpu)
*ent_cpu = next_cpu;
if (ent_ts)
*ent_ts = next_ts;
if (missing_events)
*missing_events = next_lost;
return next;
}
/* Find the next real entry, without updating the iterator itself */
struct trace_entry *trace_find_next_entry(struct trace_iterator *iter,
int *ent_cpu, u64 *ent_ts)
{
return __find_next_entry(iter, ent_cpu, NULL, ent_ts);
}
/* Find the next real entry, and increment the iterator to the next entry */
void *trace_find_next_entry_inc(struct trace_iterator *iter)
{
iter->ent = __find_next_entry(iter, &iter->cpu,
&iter->lost_events, &iter->ts);
if (iter->ent)
trace_iterator_increment(iter);
return iter->ent ? iter : NULL;
}
static void trace_consume(struct trace_iterator *iter)
{
ring_buffer_consume(iter->trace_buffer->buffer, iter->cpu, &iter->ts,
&iter->lost_events);
}
static void *s_next(struct seq_file *m, void *v, loff_t *pos)
{
struct trace_iterator *iter = m->private;
int i = (int)*pos;
void *ent;
WARN_ON_ONCE(iter->leftover);
(*pos)++;
/* can't go backwards */
if (iter->idx > i)
return NULL;
if (iter->idx < 0)
ent = trace_find_next_entry_inc(iter);
else
ent = iter;
while (ent && iter->idx < i)
ent = trace_find_next_entry_inc(iter);
iter->pos = *pos;
return ent;
}
void tracing_iter_reset(struct trace_iterator *iter, int cpu)
{
struct ring_buffer_event *event;
struct ring_buffer_iter *buf_iter;
unsigned long entries = 0;
u64 ts;
per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = 0;
buf_iter = trace_buffer_iter(iter, cpu);
if (!buf_iter)
return;
ring_buffer_iter_reset(buf_iter);
/*
* We could have the case with the max latency tracers
* that a reset never took place on a cpu. This is evident
* by the timestamp being before the start of the buffer.
*/
while ((event = ring_buffer_iter_peek(buf_iter, &ts))) {
if (ts >= iter->trace_buffer->time_start)
break;
entries++;
ring_buffer_read(buf_iter, NULL);
}
per_cpu_ptr(iter->trace_buffer->data, cpu)->skipped_entries = entries;
}
/*
* The current tracer is copied to avoid a global locking
* all around.
*/
static void *s_start(struct seq_file *m, loff_t *pos)
{
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
int cpu_file = iter->cpu_file;
void *p = NULL;
loff_t l = 0;
int cpu;
/*
* copy the tracer to avoid using a global lock all around.
* iter->trace is a copy of current_trace, the pointer to the
* name may be used instead of a strcmp(), as iter->trace->name
* will point to the same string as current_trace->name.
*/
mutex_lock(&trace_types_lock);
if (unlikely(tr->current_trace && iter->trace->name != tr->current_trace->name))
*iter->trace = *tr->current_trace;
mutex_unlock(&trace_types_lock);
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->trace->use_max_tr)
return ERR_PTR(-EBUSY);
#endif
if (!iter->snapshot)
atomic_inc(&trace_record_cmdline_disabled);
if (*pos != iter->pos) {
iter->ent = NULL;
iter->cpu = 0;
iter->idx = -1;
if (cpu_file == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu)
tracing_iter_reset(iter, cpu);
} else
tracing_iter_reset(iter, cpu_file);
iter->leftover = 0;
for (p = iter; p && l < *pos; p = s_next(m, p, &l))
;
} else {
/*
* If we overflowed the seq_file before, then we want
* to just reuse the trace_seq buffer again.
*/
if (iter->leftover)
p = iter;
else {
l = *pos - 1;
p = s_next(m, p, &l);
}
}
trace_event_read_lock();
trace_access_lock(cpu_file);
return p;
}
static void s_stop(struct seq_file *m, void *p)
{
struct trace_iterator *iter = m->private;
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->trace->use_max_tr)
return;
#endif
if (!iter->snapshot)
atomic_dec(&trace_record_cmdline_disabled);
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
}
static void
get_total_entries(struct trace_buffer *buf,
unsigned long *total, unsigned long *entries)
{
unsigned long count;
int cpu;
*total = 0;
*entries = 0;
for_each_tracing_cpu(cpu) {
count = ring_buffer_entries_cpu(buf->buffer, cpu);
/*
* If this buffer has skipped entries, then we hold all
* entries for the trace and we need to ignore the
* ones before the time stamp.
*/
if (per_cpu_ptr(buf->data, cpu)->skipped_entries) {
count -= per_cpu_ptr(buf->data, cpu)->skipped_entries;
/* total is the same as the entries */
*total += count;
} else
*total += count +
ring_buffer_overrun_cpu(buf->buffer, cpu);
*entries += count;
}
}
static void print_lat_help_header(struct seq_file *m)
{
seq_puts(m, "# _------=> CPU# \n");
seq_puts(m, "# / _-----=> irqs-off \n");
seq_puts(m, "# | / _----=> need-resched \n");
seq_puts(m, "# || / _---=> hardirq/softirq \n");
seq_puts(m, "# ||| / _--=> preempt-depth \n");
seq_puts(m, "# |||| / delay \n");
seq_puts(m, "# cmd pid ||||| time | caller \n");
seq_puts(m, "# \\ / ||||| \\ | / \n");
}
static void print_event_info(struct trace_buffer *buf, struct seq_file *m)
{
unsigned long total;
unsigned long entries;
get_total_entries(buf, &total, &entries);
seq_printf(m, "# entries-in-buffer/entries-written: %lu/%lu #P:%d\n",
entries, total, num_online_cpus());
seq_puts(m, "#\n");
}
static void print_func_help_header(struct trace_buffer *buf, struct seq_file *m)
{
print_event_info(buf, m);
seq_puts(m, "# TASK-PID CPU# TIMESTAMP FUNCTION\n");
seq_puts(m, "# | | | | |\n");
}
static void print_func_help_header_tgid(struct trace_buffer *buf, struct seq_file *m)
{
print_event_info(buf, m);
seq_puts(m, "# TASK-PID TGID CPU# TIMESTAMP FUNCTION\n");
seq_puts(m, "# | | | | | |\n");
}
static void print_func_help_header_irq(struct trace_buffer *buf, struct seq_file *m)
{
print_event_info(buf, m);
seq_puts(m, "# _-----=> irqs-off\n");
seq_puts(m, "# / _----=> need-resched\n");
seq_puts(m, "# | / _---=> hardirq/softirq\n");
seq_puts(m, "# || / _--=> preempt-depth\n");
seq_puts(m, "# ||| / delay\n");
seq_puts(m, "# TASK-PID CPU# |||| TIMESTAMP FUNCTION\n");
seq_puts(m, "# | | | |||| | |\n");
}
static void print_func_help_header_irq_tgid(struct trace_buffer *buf, struct seq_file *m)
{
print_event_info(buf, m);
seq_puts(m, "# _-----=> irqs-off\n");
seq_puts(m, "# / _----=> need-resched\n");
seq_puts(m, "# | / _---=> hardirq/softirq\n");
seq_puts(m, "# || / _--=> preempt-depth\n");
seq_puts(m, "# ||| / delay\n");
seq_puts(m, "# TASK-PID TGID CPU# |||| TIMESTAMP FUNCTION\n");
seq_puts(m, "# | | | | |||| | |\n");
}
void
print_trace_header(struct seq_file *m, struct trace_iterator *iter)
{
unsigned long sym_flags = (trace_flags & TRACE_ITER_SYM_MASK);
struct trace_buffer *buf = iter->trace_buffer;
struct trace_array_cpu *data = per_cpu_ptr(buf->data, buf->cpu);
struct tracer *type = iter->trace;
unsigned long entries;
unsigned long total;
const char *name = "preemption";
name = type->name;
get_total_entries(buf, &total, &entries);
seq_printf(m, "# %s latency trace v1.1.5 on %s\n",
name, UTS_RELEASE);
seq_puts(m, "# -----------------------------------"
"---------------------------------\n");
seq_printf(m, "# latency: %lu us, #%lu/%lu, CPU#%d |"
" (M:%s VP:%d, KP:%d, SP:%d HP:%d",
nsecs_to_usecs(data->saved_latency),
entries,
total,
buf->cpu,
#if defined(CONFIG_PREEMPT_NONE)
"server",
#elif defined(CONFIG_PREEMPT_VOLUNTARY)
"desktop",
#elif defined(CONFIG_PREEMPT)
"preempt",
#else
"unknown",
#endif
/* These are reserved for later use */
0, 0, 0, 0);
#ifdef CONFIG_SMP
seq_printf(m, " #P:%d)\n", num_online_cpus());
#else
seq_puts(m, ")\n");
#endif
seq_puts(m, "# -----------------\n");
seq_printf(m, "# | task: %.16s-%d "
"(uid:%d nice:%ld policy:%ld rt_prio:%ld)\n",
data->comm, data->pid,
from_kuid_munged(seq_user_ns(m), data->uid), data->nice,
data->policy, data->rt_priority);
seq_puts(m, "# -----------------\n");
if (data->critical_start) {
seq_puts(m, "# => started at: ");
seq_print_ip_sym(&iter->seq, data->critical_start, sym_flags);
trace_print_seq(m, &iter->seq);
seq_puts(m, "\n# => ended at: ");
seq_print_ip_sym(&iter->seq, data->critical_end, sym_flags);
trace_print_seq(m, &iter->seq);
seq_puts(m, "\n#\n");
}
seq_puts(m, "#\n");
}
static void test_cpu_buff_start(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
if (!(trace_flags & TRACE_ITER_ANNOTATE))
return;
if (!(iter->iter_flags & TRACE_FILE_ANNOTATE))
return;
if (cpumask_test_cpu(iter->cpu, iter->started))
return;
if (per_cpu_ptr(iter->trace_buffer->data, iter->cpu)->skipped_entries)
return;
cpumask_set_cpu(iter->cpu, iter->started);
/* Don't print started cpu buffer for the first entry of the trace */
if (iter->idx > 1)
trace_seq_printf(s, "##### CPU %u buffer started ####\n",
iter->cpu);
}
static enum print_line_t print_trace_fmt(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
unsigned long sym_flags = (trace_flags & TRACE_ITER_SYM_MASK);
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
test_cpu_buff_start(iter);
event = ftrace_find_event(entry->type);
if (trace_flags & TRACE_ITER_CONTEXT_INFO) {
if (iter->iter_flags & TRACE_FILE_LAT_FMT) {
if (!trace_print_lat_context(iter))
goto partial;
} else {
if (!trace_print_context(iter))
goto partial;
}
}
if (event)
return event->funcs->trace(iter, sym_flags, event);
if (!trace_seq_printf(s, "Unknown type %d\n", entry->type))
goto partial;
return TRACE_TYPE_HANDLED;
partial:
return TRACE_TYPE_PARTIAL_LINE;
}
static enum print_line_t print_raw_fmt(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (trace_flags & TRACE_ITER_CONTEXT_INFO) {
if (!trace_seq_printf(s, "%d %d %llu ",
entry->pid, iter->cpu, iter->ts))
goto partial;
}
event = ftrace_find_event(entry->type);
if (event)
return event->funcs->raw(iter, 0, event);
if (!trace_seq_printf(s, "%d ?\n", entry->type))
goto partial;
return TRACE_TYPE_HANDLED;
partial:
return TRACE_TYPE_PARTIAL_LINE;
}
static enum print_line_t print_hex_fmt(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
unsigned char newline = '\n';
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (trace_flags & TRACE_ITER_CONTEXT_INFO) {
SEQ_PUT_HEX_FIELD_RET(s, entry->pid);
SEQ_PUT_HEX_FIELD_RET(s, iter->cpu);
SEQ_PUT_HEX_FIELD_RET(s, iter->ts);
}
event = ftrace_find_event(entry->type);
if (event) {
enum print_line_t ret = event->funcs->hex(iter, 0, event);
if (ret != TRACE_TYPE_HANDLED)
return ret;
}
SEQ_PUT_FIELD_RET(s, newline);
return TRACE_TYPE_HANDLED;
}
static enum print_line_t print_bin_fmt(struct trace_iterator *iter)
{
struct trace_seq *s = &iter->seq;
struct trace_entry *entry;
struct trace_event *event;
entry = iter->ent;
if (trace_flags & TRACE_ITER_CONTEXT_INFO) {
SEQ_PUT_FIELD_RET(s, entry->pid);
SEQ_PUT_FIELD_RET(s, iter->cpu);
SEQ_PUT_FIELD_RET(s, iter->ts);
}
event = ftrace_find_event(entry->type);
return event ? event->funcs->binary(iter, 0, event) :
TRACE_TYPE_HANDLED;
}
int trace_empty(struct trace_iterator *iter)
{
struct ring_buffer_iter *buf_iter;
int cpu;
/* If we are looking at one CPU buffer, only check that one */
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
cpu = iter->cpu_file;
buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter) {
if (!ring_buffer_iter_empty(buf_iter))
return 0;
} else {
if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu))
return 0;
}
return 1;
}
for_each_tracing_cpu(cpu) {
buf_iter = trace_buffer_iter(iter, cpu);
if (buf_iter) {
if (!ring_buffer_iter_empty(buf_iter))
return 0;
} else {
if (!ring_buffer_empty_cpu(iter->trace_buffer->buffer, cpu))
return 0;
}
}
return 1;
}
/* Called with trace_event_read_lock() held. */
enum print_line_t print_trace_line(struct trace_iterator *iter)
{
enum print_line_t ret;
if (iter->lost_events &&
!trace_seq_printf(&iter->seq, "CPU:%d [LOST %lu EVENTS]\n",
iter->cpu, iter->lost_events))
return TRACE_TYPE_PARTIAL_LINE;
if (iter->trace && iter->trace->print_line) {
ret = iter->trace->print_line(iter);
if (ret != TRACE_TYPE_UNHANDLED)
return ret;
}
if (iter->ent->type == TRACE_BPUTS &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_bputs_msg_only(iter);
if (iter->ent->type == TRACE_BPRINT &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_bprintk_msg_only(iter);
if (iter->ent->type == TRACE_PRINT &&
trace_flags & TRACE_ITER_PRINTK &&
trace_flags & TRACE_ITER_PRINTK_MSGONLY)
return trace_print_printk_msg_only(iter);
if (trace_flags & TRACE_ITER_BIN)
return print_bin_fmt(iter);
if (trace_flags & TRACE_ITER_HEX)
return print_hex_fmt(iter);
if (trace_flags & TRACE_ITER_RAW)
return print_raw_fmt(iter);
return print_trace_fmt(iter);
}
void trace_latency_header(struct seq_file *m)
{
struct trace_iterator *iter = m->private;
/* print nothing if the buffers are empty */
if (trace_empty(iter))
return;
if (iter->iter_flags & TRACE_FILE_LAT_FMT)
print_trace_header(m, iter);
if (!(trace_flags & TRACE_ITER_VERBOSE))
print_lat_help_header(m);
}
void trace_default_header(struct seq_file *m)
{
struct trace_iterator *iter = m->private;
if (!(trace_flags & TRACE_ITER_CONTEXT_INFO))
return;
if (iter->iter_flags & TRACE_FILE_LAT_FMT) {
/* print nothing if the buffers are empty */
if (trace_empty(iter))
return;
print_trace_header(m, iter);
if (!(trace_flags & TRACE_ITER_VERBOSE))
print_lat_help_header(m);
} else {
if (!(trace_flags & TRACE_ITER_VERBOSE)) {
if (trace_flags & TRACE_ITER_IRQ_INFO)
if (trace_flags & TRACE_ITER_TGID)
print_func_help_header_irq_tgid(iter->trace_buffer, m);
else
print_func_help_header_irq(iter->trace_buffer, m);
else
if (trace_flags & TRACE_ITER_TGID)
print_func_help_header_tgid(iter->trace_buffer, m);
else
print_func_help_header(iter->trace_buffer, m);
}
}
}
static void test_ftrace_alive(struct seq_file *m)
{
if (!ftrace_is_dead())
return;
seq_printf(m, "# WARNING: FUNCTION TRACING IS CORRUPTED\n");
seq_printf(m, "# MAY BE MISSING FUNCTION EVENTS\n");
}
#ifdef CONFIG_TRACER_MAX_TRACE
static void show_snapshot_main_help(struct seq_file *m)
{
seq_printf(m, "# echo 0 > snapshot : Clears and frees snapshot buffer\n");
seq_printf(m, "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n");
seq_printf(m, "# Takes a snapshot of the main buffer.\n");
seq_printf(m, "# echo 2 > snapshot : Clears snapshot buffer (but does not allocate)\n");
seq_printf(m, "# (Doesn't have to be '2' works with any number that\n");
seq_printf(m, "# is not a '0' or '1')\n");
}
static void show_snapshot_percpu_help(struct seq_file *m)
{
seq_printf(m, "# echo 0 > snapshot : Invalid for per_cpu snapshot file.\n");
#ifdef CONFIG_RING_BUFFER_ALLOW_SWAP
seq_printf(m, "# echo 1 > snapshot : Allocates snapshot buffer, if not already allocated.\n");
seq_printf(m, "# Takes a snapshot of the main buffer for this cpu.\n");
#else
seq_printf(m, "# echo 1 > snapshot : Not supported with this kernel.\n");
seq_printf(m, "# Must use main snapshot file to allocate.\n");
#endif
seq_printf(m, "# echo 2 > snapshot : Clears this cpu's snapshot buffer (but does not allocate)\n");
seq_printf(m, "# (Doesn't have to be '2' works with any number that\n");
seq_printf(m, "# is not a '0' or '1')\n");
}
static void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter)
{
if (iter->tr->allocated_snapshot)
seq_printf(m, "#\n# * Snapshot is allocated *\n#\n");
else
seq_printf(m, "#\n# * Snapshot is freed *\n#\n");
seq_printf(m, "# Snapshot commands:\n");
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
show_snapshot_main_help(m);
else
show_snapshot_percpu_help(m);
}
#else
/* Should never be called */
static inline void print_snapshot_help(struct seq_file *m, struct trace_iterator *iter) { }
#endif
static int s_show(struct seq_file *m, void *v)
{
struct trace_iterator *iter = v;
int ret;
if (iter->ent == NULL) {
if (iter->tr) {
seq_printf(m, "# tracer: %s\n", iter->trace->name);
seq_puts(m, "#\n");
test_ftrace_alive(m);
}
if (iter->snapshot && trace_empty(iter))
print_snapshot_help(m, iter);
else if (iter->trace && iter->trace->print_header)
iter->trace->print_header(m);
else
trace_default_header(m);
} else if (iter->leftover) {
/*
* If we filled the seq_file buffer earlier, we
* want to just show it now.
*/
ret = trace_print_seq(m, &iter->seq);
/* ret should this time be zero, but you never know */
iter->leftover = ret;
} else {
print_trace_line(iter);
ret = trace_print_seq(m, &iter->seq);
/*
* If we overflow the seq_file buffer, then it will
* ask us for this data again at start up.
* Use that instead.
* ret is 0 if seq_file write succeeded.
* -1 otherwise.
*/
iter->leftover = ret;
}
return 0;
}
/*
* Should be used after trace_array_get(), trace_types_lock
* ensures that i_cdev was already initialized.
*/
static inline int tracing_get_cpu(struct inode *inode)
{
if (inode->i_cdev) /* See trace_create_cpu_file() */
return (long)inode->i_cdev - 1;
return RING_BUFFER_ALL_CPUS;
}
static const struct seq_operations tracer_seq_ops = {
.start = s_start,
.next = s_next,
.stop = s_stop,
.show = s_show,
};
static struct trace_iterator *
__tracing_open(struct inode *inode, struct file *file, bool snapshot)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int cpu;
if (tracing_disabled)
return ERR_PTR(-ENODEV);
iter = __seq_open_private(file, &tracer_seq_ops, sizeof(*iter));
if (!iter)
return ERR_PTR(-ENOMEM);
iter->buffer_iter = kzalloc(sizeof(*iter->buffer_iter) * num_possible_cpus(),
GFP_KERNEL);
if (!iter->buffer_iter)
goto release;
/*
* We make a copy of the current tracer to avoid concurrent
* changes on it while we are reading.
*/
mutex_lock(&trace_types_lock);
iter->trace = kzalloc(sizeof(*iter->trace), GFP_KERNEL);
if (!iter->trace)
goto fail;
*iter->trace = *tr->current_trace;
if (!zalloc_cpumask_var(&iter->started, GFP_KERNEL))
goto fail;
iter->tr = tr;
#ifdef CONFIG_TRACER_MAX_TRACE
/* Currently only the top directory has a snapshot */
if (tr->current_trace->print_max || snapshot)
iter->trace_buffer = &tr->max_buffer;
else
#endif
iter->trace_buffer = &tr->trace_buffer;
iter->snapshot = snapshot;
iter->pos = -1;
iter->cpu_file = tracing_get_cpu(inode);
mutex_init(&iter->mutex);
/* Notify the tracer early; before we stop tracing. */
if (iter->trace && iter->trace->open)
iter->trace->open(iter);
/* Annotate start of buffers if we had overruns */
if (ring_buffer_overruns(iter->trace_buffer->buffer))
iter->iter_flags |= TRACE_FILE_ANNOTATE;
/* Output in nanoseconds only if we are using a clock in nanoseconds. */
if (trace_clocks[tr->clock_id].in_ns)
iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
/* stop the trace while dumping if we are not opening "snapshot" */
if (!iter->snapshot)
tracing_stop_tr(tr);
if (iter->cpu_file == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu) {
iter->buffer_iter[cpu] =
ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu);
}
ring_buffer_read_prepare_sync();
for_each_tracing_cpu(cpu) {
ring_buffer_read_start(iter->buffer_iter[cpu]);
tracing_iter_reset(iter, cpu);
}
} else {
cpu = iter->cpu_file;
iter->buffer_iter[cpu] =
ring_buffer_read_prepare(iter->trace_buffer->buffer, cpu);
ring_buffer_read_prepare_sync();
ring_buffer_read_start(iter->buffer_iter[cpu]);
tracing_iter_reset(iter, cpu);
}
mutex_unlock(&trace_types_lock);
return iter;
fail:
mutex_unlock(&trace_types_lock);
kfree(iter->trace);
kfree(iter->buffer_iter);
release:
seq_release_private(inode, file);
return ERR_PTR(-ENOMEM);
}
int tracing_open_generic(struct inode *inode, struct file *filp)
{
if (tracing_disabled)
return -ENODEV;
filp->private_data = inode->i_private;
return 0;
}
/*
* Open and update trace_array ref count.
* Must have the current trace_array passed to it.
*/
int tracing_open_generic_tr(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
filp->private_data = inode->i_private;
return 0;
}
static int tracing_release(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct seq_file *m = file->private_data;
struct trace_iterator *iter;
int cpu;
if (!(file->f_mode & FMODE_READ)) {
trace_array_put(tr);
return 0;
}
/* Writes do not use seq_file */
iter = m->private;
mutex_lock(&trace_types_lock);
for_each_tracing_cpu(cpu) {
if (iter->buffer_iter[cpu])
ring_buffer_read_finish(iter->buffer_iter[cpu]);
}
if (iter->trace && iter->trace->close)
iter->trace->close(iter);
if (!iter->snapshot)
/* reenable tracing if it was previously enabled */
tracing_start_tr(tr);
__trace_array_put(tr);
mutex_unlock(&trace_types_lock);
mutex_destroy(&iter->mutex);
free_cpumask_var(iter->started);
kfree(iter->trace);
kfree(iter->buffer_iter);
seq_release_private(inode, file);
return 0;
}
static int tracing_release_generic_tr(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
trace_array_put(tr);
return 0;
}
static int tracing_single_release_tr(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
trace_array_put(tr);
return single_release(inode, file);
}
static int tracing_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int ret = 0;
if (trace_array_get(tr) < 0)
return -ENODEV;
/* If this file was open for write, then erase contents */
if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) {
int cpu = tracing_get_cpu(inode);
if (cpu == RING_BUFFER_ALL_CPUS)
tracing_reset_online_cpus(&tr->trace_buffer);
else
tracing_reset(&tr->trace_buffer, cpu);
}
if (file->f_mode & FMODE_READ) {
iter = __tracing_open(inode, file, false);
if (IS_ERR(iter))
ret = PTR_ERR(iter);
else if (trace_flags & TRACE_ITER_LATENCY_FMT)
iter->iter_flags |= TRACE_FILE_LAT_FMT;
}
if (ret < 0)
trace_array_put(tr);
return ret;
}
static void *
t_next(struct seq_file *m, void *v, loff_t *pos)
{
struct tracer *t = v;
(*pos)++;
if (t)
t = t->next;
return t;
}
static void *t_start(struct seq_file *m, loff_t *pos)
{
struct tracer *t;
loff_t l = 0;
mutex_lock(&trace_types_lock);
for (t = trace_types; t && l < *pos; t = t_next(m, t, &l))
;
return t;
}
static void t_stop(struct seq_file *m, void *p)
{
mutex_unlock(&trace_types_lock);
}
static int t_show(struct seq_file *m, void *v)
{
struct tracer *t = v;
if (!t)
return 0;
seq_printf(m, "%s", t->name);
if (t->next)
seq_putc(m, ' ');
else
seq_putc(m, '\n');
return 0;
}
static const struct seq_operations show_traces_seq_ops = {
.start = t_start,
.next = t_next,
.stop = t_stop,
.show = t_show,
};
static int show_traces_open(struct inode *inode, struct file *file)
{
if (tracing_disabled)
return -ENODEV;
return seq_open(file, &show_traces_seq_ops);
}
static ssize_t
tracing_write_stub(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
return count;
}
static loff_t tracing_seek(struct file *file, loff_t offset, int origin)
{
if (file->f_mode & FMODE_READ)
return seq_lseek(file, offset, origin);
else
return 0;
}
static const struct file_operations tracing_fops = {
.open = tracing_open,
.read = seq_read,
.write = tracing_write_stub,
.llseek = tracing_seek,
.release = tracing_release,
};
static const struct file_operations show_traces_fops = {
.open = show_traces_open,
.read = seq_read,
.release = seq_release,
.llseek = seq_lseek,
};
/*
* Only trace on a CPU if the bitmask is set:
*/
static cpumask_var_t tracing_cpumask;
/*
* The tracer itself will not take this lock, but still we want
* to provide a consistent cpumask to user-space:
*/
static DEFINE_MUTEX(tracing_cpumask_update_lock);
/*
* Temporary storage for the character representation of the
* CPU bitmask (and one more byte for the newline):
*/
static char mask_str[NR_CPUS + 1];
static ssize_t
tracing_cpumask_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
int len;
mutex_lock(&tracing_cpumask_update_lock);
len = cpumask_scnprintf(mask_str, count, tracing_cpumask);
if (count - len < 2) {
count = -EINVAL;
goto out_err;
}
len += sprintf(mask_str + len, "\n");
count = simple_read_from_buffer(ubuf, count, ppos, mask_str, NR_CPUS+1);
out_err:
mutex_unlock(&tracing_cpumask_update_lock);
return count;
}
static ssize_t
tracing_cpumask_write(struct file *filp, const char __user *ubuf,
size_t count, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
cpumask_var_t tracing_cpumask_new;
int err, cpu;
if (!alloc_cpumask_var(&tracing_cpumask_new, GFP_KERNEL))
return -ENOMEM;
err = cpumask_parse_user(ubuf, count, tracing_cpumask_new);
if (err)
goto err_unlock;
mutex_lock(&tracing_cpumask_update_lock);
local_irq_disable();
arch_spin_lock(&ftrace_max_lock);
for_each_tracing_cpu(cpu) {
/*
* Increase/decrease the disabled counter if we are
* about to flip a bit in the cpumask:
*/
if (cpumask_test_cpu(cpu, tracing_cpumask) &&
!cpumask_test_cpu(cpu, tracing_cpumask_new)) {
atomic_inc(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled);
ring_buffer_record_disable_cpu(tr->trace_buffer.buffer, cpu);
}
if (!cpumask_test_cpu(cpu, tracing_cpumask) &&
cpumask_test_cpu(cpu, tracing_cpumask_new)) {
atomic_dec(&per_cpu_ptr(tr->trace_buffer.data, cpu)->disabled);
ring_buffer_record_enable_cpu(tr->trace_buffer.buffer, cpu);
}
}
arch_spin_unlock(&ftrace_max_lock);
local_irq_enable();
cpumask_copy(tracing_cpumask, tracing_cpumask_new);
mutex_unlock(&tracing_cpumask_update_lock);
free_cpumask_var(tracing_cpumask_new);
return count;
err_unlock:
free_cpumask_var(tracing_cpumask_new);
return err;
}
static const struct file_operations tracing_cpumask_fops = {
.open = tracing_open_generic,
.read = tracing_cpumask_read,
.write = tracing_cpumask_write,
.llseek = generic_file_llseek,
};
static int tracing_trace_options_show(struct seq_file *m, void *v)
{
struct tracer_opt *trace_opts;
struct trace_array *tr = m->private;
u32 tracer_flags;
int i;
mutex_lock(&trace_types_lock);
tracer_flags = tr->current_trace->flags->val;
trace_opts = tr->current_trace->flags->opts;
for (i = 0; trace_options[i]; i++) {
if (trace_flags & (1 << i))
seq_printf(m, "%s\n", trace_options[i]);
else
seq_printf(m, "no%s\n", trace_options[i]);
}
for (i = 0; trace_opts[i].name; i++) {
if (tracer_flags & trace_opts[i].bit)
seq_printf(m, "%s\n", trace_opts[i].name);
else
seq_printf(m, "no%s\n", trace_opts[i].name);
}
mutex_unlock(&trace_types_lock);
return 0;
}
static int __set_tracer_option(struct tracer *trace,
struct tracer_flags *tracer_flags,
struct tracer_opt *opts, int neg)
{
int ret;
ret = trace->set_flag(tracer_flags->val, opts->bit, !neg);
if (ret)
return ret;
if (neg)
tracer_flags->val &= ~opts->bit;
else
tracer_flags->val |= opts->bit;
return 0;
}
/* Try to assign a tracer specific option */
static int set_tracer_option(struct tracer *trace, char *cmp, int neg)
{
struct tracer_flags *tracer_flags = trace->flags;
struct tracer_opt *opts = NULL;
int i;
for (i = 0; tracer_flags->opts[i].name; i++) {
opts = &tracer_flags->opts[i];
if (strcmp(cmp, opts->name) == 0)
return __set_tracer_option(trace, trace->flags,
opts, neg);
}
return -EINVAL;
}
/* Some tracers require overwrite to stay enabled */
int trace_keep_overwrite(struct tracer *tracer, u32 mask, int set)
{
if (tracer->enabled && (mask & TRACE_ITER_OVERWRITE) && !set)
return -1;
return 0;
}
int set_tracer_flag(struct trace_array *tr, unsigned int mask, int enabled)
{
/* do nothing if flag is already set */
if (!!(trace_flags & mask) == !!enabled)
return 0;
/* Give the tracer a chance to approve the change */
if (tr->current_trace->flag_changed)
if (tr->current_trace->flag_changed(tr->current_trace, mask, !!enabled))
return -EINVAL;
if (enabled)
trace_flags |= mask;
else
trace_flags &= ~mask;
if (mask == TRACE_ITER_RECORD_CMD)
trace_event_enable_cmd_record(enabled);
if (mask == TRACE_ITER_OVERWRITE) {
ring_buffer_change_overwrite(tr->trace_buffer.buffer, enabled);
#ifdef CONFIG_TRACER_MAX_TRACE
ring_buffer_change_overwrite(tr->max_buffer.buffer, enabled);
#endif
}
if (mask == TRACE_ITER_PRINTK)
trace_printk_start_stop_comm(enabled);
return 0;
}
static int trace_set_options(struct trace_array *tr, char *option)
{
char *cmp;
int neg = 0;
int ret = -ENODEV;
int i;
cmp = strstrip(option);
if (strncmp(cmp, "no", 2) == 0) {
neg = 1;
cmp += 2;
}
mutex_lock(&trace_types_lock);
for (i = 0; trace_options[i]; i++) {
if (strcmp(cmp, trace_options[i]) == 0) {
ret = set_tracer_flag(tr, 1 << i, !neg);
break;
}
}
/* If no option could be set, test the specific tracer options */
if (!trace_options[i])
ret = set_tracer_option(tr->current_trace, cmp, neg);
mutex_unlock(&trace_types_lock);
return ret;
}
static ssize_t
tracing_trace_options_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct seq_file *m = filp->private_data;
struct trace_array *tr = m->private;
char buf[64];
int ret;
if (cnt >= sizeof(buf))
return -EINVAL;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
ret = trace_set_options(tr, buf);
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static int tracing_trace_options_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
ret = single_open(file, tracing_trace_options_show, inode->i_private);
if (ret < 0)
trace_array_put(tr);
return ret;
}
static const struct file_operations tracing_iter_fops = {
.open = tracing_trace_options_open,
.read = seq_read,
.llseek = seq_lseek,
.release = tracing_single_release_tr,
.write = tracing_trace_options_write,
};
static const char readme_msg[] =
"tracing mini-HOWTO:\n\n"
"# echo 0 > tracing_on : quick way to disable tracing\n"
"# echo 1 > tracing_on : quick way to re-enable tracing\n\n"
" Important files:\n"
" trace\t\t\t- The static contents of the buffer\n"
"\t\t\t To clear the buffer write into this file: echo > trace\n"
" trace_pipe\t\t- A consuming read to see the contents of the buffer\n"
" current_tracer\t- function and latency tracers\n"
" available_tracers\t- list of configured tracers for current_tracer\n"
" buffer_size_kb\t- view and modify size of per cpu buffer\n"
" buffer_total_size_kb - view total size of all cpu buffers\n\n"
" trace_clock\t\t-change the clock used to order events\n"
" local: Per cpu clock but may not be synced across CPUs\n"
" global: Synced across CPUs but slows tracing down.\n"
" counter: Not a clock, but just an increment\n"
" uptime: Jiffy counter from time of boot\n"
" perf: Same clock that perf events use\n"
#ifdef CONFIG_X86_64
" x86-tsc: TSC cycle counter\n"
#endif
"\n trace_marker\t\t- Writes into this file writes into the kernel buffer\n"
" tracing_cpumask\t- Limit which CPUs to trace\n"
" instances\t\t- Make sub-buffers with: mkdir instances/foo\n"
"\t\t\t Remove sub-buffer with rmdir\n"
" trace_options\t\t- Set format or modify how tracing happens\n"
"\t\t\t Disable an option by adding a suffix 'no' to the option name\n"
#ifdef CONFIG_DYNAMIC_FTRACE
"\n available_filter_functions - list of functions that can be filtered on\n"
" set_ftrace_filter\t- echo function name in here to only trace these functions\n"
" accepts: func_full_name, *func_end, func_begin*, *func_middle*\n"
" modules: Can select a group via module\n"
" Format: :mod:<module-name>\n"
" example: echo :mod:ext3 > set_ftrace_filter\n"
" triggers: a command to perform when function is hit\n"
" Format: <function>:<trigger>[:count]\n"
" trigger: traceon, traceoff\n"
" enable_event:<system>:<event>\n"
" disable_event:<system>:<event>\n"
#ifdef CONFIG_STACKTRACE
" stacktrace\n"
#endif
#ifdef CONFIG_TRACER_SNAPSHOT
" snapshot\n"
#endif
" example: echo do_fault:traceoff > set_ftrace_filter\n"
" echo do_trap:traceoff:3 > set_ftrace_filter\n"
" The first one will disable tracing every time do_fault is hit\n"
" The second will disable tracing at most 3 times when do_trap is hit\n"
" The first time do trap is hit and it disables tracing, the counter\n"
" will decrement to 2. If tracing is already disabled, the counter\n"
" will not decrement. It only decrements when the trigger did work\n"
" To remove trigger without count:\n"
" echo '!<function>:<trigger> > set_ftrace_filter\n"
" To remove trigger with a count:\n"
" echo '!<function>:<trigger>:0 > set_ftrace_filter\n"
" set_ftrace_notrace\t- echo function name in here to never trace.\n"
" accepts: func_full_name, *func_end, func_begin*, *func_middle*\n"
" modules: Can select a group via module command :mod:\n"
" Does not accept triggers\n"
#endif /* CONFIG_DYNAMIC_FTRACE */
#ifdef CONFIG_FUNCTION_TRACER
" set_ftrace_pid\t- Write pid(s) to only function trace those pids (function)\n"
#endif
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
" set_graph_function\t- Trace the nested calls of a function (function_graph)\n"
" max_graph_depth\t- Trace a limited depth of nested calls (0 is unlimited)\n"
#endif
#ifdef CONFIG_TRACER_SNAPSHOT
"\n snapshot\t\t- Like 'trace' but shows the content of the static snapshot buffer\n"
"\t\t\t Read the contents for more information\n"
#endif
#ifdef CONFIG_STACKTRACE
" stack_trace\t\t- Shows the max stack trace when active\n"
" stack_max_size\t- Shows current max stack size that was traced\n"
"\t\t\t Write into this file to reset the max size (trigger a new trace)\n"
#ifdef CONFIG_DYNAMIC_FTRACE
" stack_trace_filter\t- Like set_ftrace_filter but limits what stack_trace traces\n"
#endif
#endif /* CONFIG_STACKTRACE */
;
static ssize_t
tracing_readme_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
return simple_read_from_buffer(ubuf, cnt, ppos,
readme_msg, strlen(readme_msg));
}
static const struct file_operations tracing_readme_fops = {
.open = tracing_open_generic,
.read = tracing_readme_read,
.llseek = generic_file_llseek,
};
static ssize_t
tracing_saved_cmdlines_read(struct file *file, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char *buf_comm;
char *file_buf;
char *buf;
int len = 0;
int pid;
int i;
file_buf = kmalloc(SAVED_CMDLINES*(16+TASK_COMM_LEN), GFP_KERNEL);
if (!file_buf)
return -ENOMEM;
buf_comm = kmalloc(TASK_COMM_LEN, GFP_KERNEL);
if (!buf_comm) {
kfree(file_buf);
return -ENOMEM;
}
buf = file_buf;
for (i = 0; i < SAVED_CMDLINES; i++) {
int r;
pid = map_cmdline_to_pid[i];
if (pid == -1 || pid == NO_CMDLINE_MAP)
continue;
trace_find_cmdline(pid, buf_comm);
r = sprintf(buf, "%d %s\n", pid, buf_comm);
buf += r;
len += r;
}
len = simple_read_from_buffer(ubuf, cnt, ppos,
file_buf, len);
kfree(file_buf);
kfree(buf_comm);
return len;
}
static const struct file_operations tracing_saved_cmdlines_fops = {
.open = tracing_open_generic,
.read = tracing_saved_cmdlines_read,
.llseek = generic_file_llseek,
};
static ssize_t
tracing_saved_tgids_read(struct file *file, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char *file_buf;
char *buf;
int len = 0;
int pid;
int i;
file_buf = kmalloc(SAVED_CMDLINES*(16+1+16), GFP_KERNEL);
if (!file_buf)
return -ENOMEM;
buf = file_buf;
for (i = 0; i < SAVED_CMDLINES; i++) {
int tgid;
int r;
pid = map_cmdline_to_pid[i];
if (pid == -1 || pid == NO_CMDLINE_MAP)
continue;
tgid = trace_find_tgid(pid);
r = sprintf(buf, "%d %d\n", pid, tgid);
buf += r;
len += r;
}
len = simple_read_from_buffer(ubuf, cnt, ppos,
file_buf, len);
kfree(file_buf);
return len;
}
static const struct file_operations tracing_saved_tgids_fops = {
.open = tracing_open_generic,
.read = tracing_saved_tgids_read,
.llseek = generic_file_llseek,
};
static ssize_t
tracing_set_trace_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[MAX_TRACER_SIZE+2];
int r;
mutex_lock(&trace_types_lock);
r = sprintf(buf, "%s\n", tr->current_trace->name);
mutex_unlock(&trace_types_lock);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
int tracer_init(struct tracer *t, struct trace_array *tr)
{
tracing_reset_online_cpus(&tr->trace_buffer);
return t->init(tr);
}
static void set_buffer_entries(struct trace_buffer *buf, unsigned long val)
{
int cpu;
for_each_tracing_cpu(cpu)
per_cpu_ptr(buf->data, cpu)->entries = val;
}
#ifdef CONFIG_TRACER_MAX_TRACE
/* resize @tr's buffer to the size of @size_tr's entries */
static int resize_buffer_duplicate_size(struct trace_buffer *trace_buf,
struct trace_buffer *size_buf, int cpu_id)
{
int cpu, ret = 0;
if (cpu_id == RING_BUFFER_ALL_CPUS) {
for_each_tracing_cpu(cpu) {
ret = ring_buffer_resize(trace_buf->buffer,
per_cpu_ptr(size_buf->data, cpu)->entries, cpu);
if (ret < 0)
break;
per_cpu_ptr(trace_buf->data, cpu)->entries =
per_cpu_ptr(size_buf->data, cpu)->entries;
}
} else {
ret = ring_buffer_resize(trace_buf->buffer,
per_cpu_ptr(size_buf->data, cpu_id)->entries, cpu_id);
if (ret == 0)
per_cpu_ptr(trace_buf->data, cpu_id)->entries =
per_cpu_ptr(size_buf->data, cpu_id)->entries;
}
return ret;
}
#endif /* CONFIG_TRACER_MAX_TRACE */
static int __tracing_resize_ring_buffer(struct trace_array *tr,
unsigned long size, int cpu)
{
int ret;
/*
* If kernel or user changes the size of the ring buffer
* we use the size that was given, and we can forget about
* expanding it later.
*/
ring_buffer_expanded = true;
/* May be called before buffers are initialized */
if (!tr->trace_buffer.buffer)
return 0;
ret = ring_buffer_resize(tr->trace_buffer.buffer, size, cpu);
if (ret < 0)
return ret;
#ifdef CONFIG_TRACER_MAX_TRACE
if (!(tr->flags & TRACE_ARRAY_FL_GLOBAL) ||
!tr->current_trace->use_max_tr)
goto out;
ret = ring_buffer_resize(tr->max_buffer.buffer, size, cpu);
if (ret < 0) {
int r = resize_buffer_duplicate_size(&tr->trace_buffer,
&tr->trace_buffer, cpu);
if (r < 0) {
/*
* AARGH! We are left with different
* size max buffer!!!!
* The max buffer is our "snapshot" buffer.
* When a tracer needs a snapshot (one of the
* latency tracers), it swaps the max buffer
* with the saved snap shot. We succeeded to
* update the size of the main buffer, but failed to
* update the size of the max buffer. But when we tried
* to reset the main buffer to the original size, we
* failed there too. This is very unlikely to
* happen, but if it does, warn and kill all
* tracing.
*/
WARN_ON(1);
tracing_disabled = 1;
}
return ret;
}
if (cpu == RING_BUFFER_ALL_CPUS)
set_buffer_entries(&tr->max_buffer, size);
else
per_cpu_ptr(tr->max_buffer.data, cpu)->entries = size;
out:
#endif /* CONFIG_TRACER_MAX_TRACE */
if (cpu == RING_BUFFER_ALL_CPUS)
set_buffer_entries(&tr->trace_buffer, size);
else
per_cpu_ptr(tr->trace_buffer.data, cpu)->entries = size;
return ret;
}
static ssize_t tracing_resize_ring_buffer(struct trace_array *tr,
unsigned long size, int cpu_id)
{
int ret = size;
mutex_lock(&trace_types_lock);
if (cpu_id != RING_BUFFER_ALL_CPUS) {
/* make sure, this cpu is enabled in the mask */
if (!cpumask_test_cpu(cpu_id, tracing_buffer_mask)) {
ret = -EINVAL;
goto out;
}
}
ret = __tracing_resize_ring_buffer(tr, size, cpu_id);
if (ret < 0)
ret = -ENOMEM;
out:
mutex_unlock(&trace_types_lock);
return ret;
}
/**
* tracing_update_buffers - used by tracing facility to expand ring buffers
*
* To save on memory when the tracing is never used on a system with it
* configured in. The ring buffers are set to a minimum size. But once
* a user starts to use the tracing facility, then they need to grow
* to their default size.
*
* This function is to be called when a tracer is about to be used.
*/
int tracing_update_buffers(void)
{
int ret = 0;
mutex_lock(&trace_types_lock);
if (!ring_buffer_expanded)
ret = __tracing_resize_ring_buffer(&global_trace, trace_buf_size,
RING_BUFFER_ALL_CPUS);
mutex_unlock(&trace_types_lock);
return ret;
}
struct trace_option_dentry;
static struct trace_option_dentry *
create_trace_option_files(struct trace_array *tr, struct tracer *tracer);
static void
destroy_trace_option_files(struct trace_option_dentry *topts);
static int tracing_set_tracer(const char *buf)
{
static struct trace_option_dentry *topts;
struct trace_array *tr = &global_trace;
struct tracer *t;
#ifdef CONFIG_TRACER_MAX_TRACE
bool had_max_tr;
#endif
int ret = 0;
mutex_lock(&trace_types_lock);
if (!ring_buffer_expanded) {
ret = __tracing_resize_ring_buffer(tr, trace_buf_size,
RING_BUFFER_ALL_CPUS);
if (ret < 0)
goto out;
ret = 0;
}
for (t = trace_types; t; t = t->next) {
if (strcmp(t->name, buf) == 0)
break;
}
if (!t) {
ret = -EINVAL;
goto out;
}
if (t == tr->current_trace)
goto out;
trace_branch_disable();
tr->current_trace->enabled = false;
if (tr->current_trace->reset)
tr->current_trace->reset(tr);
/* Current trace needs to be nop_trace before synchronize_sched */
tr->current_trace = &nop_trace;
#ifdef CONFIG_TRACER_MAX_TRACE
had_max_tr = tr->allocated_snapshot;
if (had_max_tr && !t->use_max_tr) {
/*
* We need to make sure that the update_max_tr sees that
* current_trace changed to nop_trace to keep it from
* swapping the buffers after we resize it.
* The update_max_tr is called from interrupts disabled
* so a synchronized_sched() is sufficient.
*/
synchronize_sched();
free_snapshot(tr);
}
#endif
destroy_trace_option_files(topts);
topts = create_trace_option_files(tr, t);
#ifdef CONFIG_TRACER_MAX_TRACE
if (t->use_max_tr && !had_max_tr) {
ret = alloc_snapshot(tr);
if (ret < 0)
goto out;
}
#endif
if (t->init) {
ret = tracer_init(t, tr);
if (ret)
goto out;
}
tr->current_trace = t;
tr->current_trace->enabled = true;
trace_branch_enable(tr);
out:
mutex_unlock(&trace_types_lock);
return ret;
}
static ssize_t
tracing_set_trace_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
char buf[MAX_TRACER_SIZE+1];
int i;
size_t ret;
int err;
ret = cnt;
if (cnt > MAX_TRACER_SIZE)
cnt = MAX_TRACER_SIZE;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
/* strip ending whitespace. */
for (i = cnt - 1; i > 0 && isspace(buf[i]); i--)
buf[i] = 0;
err = tracing_set_tracer(buf);
if (err)
return err;
*ppos += ret;
return ret;
}
static ssize_t
tracing_max_lat_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
unsigned long *ptr = filp->private_data;
char buf[64];
int r;
r = snprintf(buf, sizeof(buf), "%ld\n",
*ptr == (unsigned long)-1 ? -1 : nsecs_to_usecs(*ptr));
if (r > sizeof(buf))
r = sizeof(buf);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
tracing_max_lat_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
unsigned long *ptr = filp->private_data;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
*ptr = val * 1000;
return cnt;
}
static int tracing_open_pipe(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
int ret = 0;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
mutex_lock(&trace_types_lock);
/* create a buffer to store the information to pass to userspace */
iter = kzalloc(sizeof(*iter), GFP_KERNEL);
if (!iter) {
ret = -ENOMEM;
__trace_array_put(tr);
goto out;
}
/*
* We make a copy of the current tracer to avoid concurrent
* changes on it while we are reading.
*/
iter->trace = kmalloc(sizeof(*iter->trace), GFP_KERNEL);
if (!iter->trace) {
ret = -ENOMEM;
goto fail;
}
*iter->trace = *tr->current_trace;
if (!alloc_cpumask_var(&iter->started, GFP_KERNEL)) {
ret = -ENOMEM;
goto fail;
}
/* trace pipe does not show start of buffer */
cpumask_setall(iter->started);
if (trace_flags & TRACE_ITER_LATENCY_FMT)
iter->iter_flags |= TRACE_FILE_LAT_FMT;
/* Output in nanoseconds only if we are using a clock in nanoseconds. */
if (trace_clocks[tr->clock_id].in_ns)
iter->iter_flags |= TRACE_FILE_TIME_IN_NS;
iter->tr = tr;
iter->trace_buffer = &tr->trace_buffer;
iter->cpu_file = tracing_get_cpu(inode);
mutex_init(&iter->mutex);
filp->private_data = iter;
if (iter->trace->pipe_open)
iter->trace->pipe_open(iter);
nonseekable_open(inode, filp);
out:
mutex_unlock(&trace_types_lock);
return ret;
fail:
kfree(iter->trace);
kfree(iter);
__trace_array_put(tr);
mutex_unlock(&trace_types_lock);
return ret;
}
static int tracing_release_pipe(struct inode *inode, struct file *file)
{
struct trace_iterator *iter = file->private_data;
struct trace_array *tr = inode->i_private;
mutex_lock(&trace_types_lock);
if (iter->trace->pipe_close)
iter->trace->pipe_close(iter);
mutex_unlock(&trace_types_lock);
free_cpumask_var(iter->started);
mutex_destroy(&iter->mutex);
kfree(iter->trace);
kfree(iter);
trace_array_put(tr);
return 0;
}
static unsigned int
trace_poll(struct trace_iterator *iter, struct file *filp, poll_table *poll_table)
{
/* Iterators are static, they should be filled or empty */
if (trace_buffer_iter(iter, iter->cpu_file))
return POLLIN | POLLRDNORM;
if (trace_flags & TRACE_ITER_BLOCK)
/*
* Always select as readable when in blocking mode
*/
return POLLIN | POLLRDNORM;
else
return ring_buffer_poll_wait(iter->trace_buffer->buffer, iter->cpu_file,
filp, poll_table);
}
static unsigned int
tracing_poll_pipe(struct file *filp, poll_table *poll_table)
{
struct trace_iterator *iter = filp->private_data;
return trace_poll(iter, filp, poll_table);
}
/*
* This is a make-shift waitqueue.
* A tracer might use this callback on some rare cases:
*
* 1) the current tracer might hold the runqueue lock when it wakes up
* a reader, hence a deadlock (sched, function, and function graph tracers)
* 2) the function tracers, trace all functions, we don't want
* the overhead of calling wake_up and friends
* (and tracing them too)
*
* Anyway, this is really very primitive wakeup.
*/
int poll_wait_pipe(struct trace_iterator *iter)
{
set_current_state(TASK_INTERRUPTIBLE);
/* sleep for 100 msecs, and try again. */
schedule_timeout(HZ / 10);
return 0;
}
/* Must be called with trace_types_lock mutex held. */
static int tracing_wait_pipe(struct file *filp)
{
struct trace_iterator *iter = filp->private_data;
int ret;
while (trace_empty(iter)) {
if ((filp->f_flags & O_NONBLOCK)) {
return -EAGAIN;
}
mutex_unlock(&iter->mutex);
ret = iter->trace->wait_pipe(iter);
mutex_lock(&iter->mutex);
if (ret)
return ret;
if (signal_pending(current))
return -EINTR;
/*
* We block until we read something and tracing is disabled.
* We still block if tracing is disabled, but we have never
* read anything. This allows a user to cat this file, and
* then enable tracing. But after we have read something,
* we give an EOF when tracing is again disabled.
*
* iter->pos will be 0 if we haven't read anything.
*/
if (!tracing_is_on() && iter->pos)
break;
}
return 1;
}
/*
* Consumer reader.
*/
static ssize_t
tracing_read_pipe(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_iterator *iter = filp->private_data;
struct trace_array *tr = iter->tr;
ssize_t sret;
/* return any leftover data */
sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
if (sret != -EBUSY)
return sret;
trace_seq_init(&iter->seq);
/* copy the tracer to avoid using a global lock all around */
mutex_lock(&trace_types_lock);
if (unlikely(iter->trace->name != tr->current_trace->name))
*iter->trace = *tr->current_trace;
mutex_unlock(&trace_types_lock);
/*
* Avoid more than one consumer on a single file descriptor
* This is just a matter of traces coherency, the ring buffer itself
* is protected.
*/
mutex_lock(&iter->mutex);
if (iter->trace->read) {
sret = iter->trace->read(iter, filp, ubuf, cnt, ppos);
if (sret)
goto out;
}
waitagain:
sret = tracing_wait_pipe(filp);
if (sret <= 0)
goto out;
/* stop when tracing is finished */
if (trace_empty(iter)) {
sret = 0;
goto out;
}
if (cnt >= PAGE_SIZE)
cnt = PAGE_SIZE - 1;
/* reset all but tr, trace, and overruns */
memset(&iter->seq, 0,
sizeof(struct trace_iterator) -
offsetof(struct trace_iterator, seq));
cpumask_clear(iter->started);
iter->pos = -1;
trace_event_read_lock();
trace_access_lock(iter->cpu_file);
while (trace_find_next_entry_inc(iter) != NULL) {
enum print_line_t ret;
int len = iter->seq.len;
ret = print_trace_line(iter);
if (ret == TRACE_TYPE_PARTIAL_LINE) {
/* don't print partial lines */
iter->seq.len = len;
break;
}
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(iter);
if (iter->seq.len >= cnt)
break;
/*
* Setting the full flag means we reached the trace_seq buffer
* size and we should leave by partial output condition above.
* One of the trace_seq_* functions is not used properly.
*/
WARN_ONCE(iter->seq.full, "full flag set for trace type %d",
iter->ent->type);
}
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
/* Now copy what we have to the user */
sret = trace_seq_to_user(&iter->seq, ubuf, cnt);
if (iter->seq.readpos >= iter->seq.len)
trace_seq_init(&iter->seq);
/*
* If there was nothing to send to user, in spite of consuming trace
* entries, go back to wait for more entries.
*/
if (sret == -EBUSY)
goto waitagain;
out:
mutex_unlock(&iter->mutex);
return sret;
}
static void tracing_pipe_buf_release(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
__free_page(buf->page);
}
static void tracing_spd_release_pipe(struct splice_pipe_desc *spd,
unsigned int idx)
{
__free_page(spd->pages[idx]);
}
static const struct pipe_buf_operations tracing_pipe_buf_ops = {
.can_merge = 0,
.map = generic_pipe_buf_map,
.unmap = generic_pipe_buf_unmap,
.confirm = generic_pipe_buf_confirm,
.release = tracing_pipe_buf_release,
.steal = generic_pipe_buf_steal,
.get = generic_pipe_buf_get,
};
static size_t
tracing_fill_pipe_page(size_t rem, struct trace_iterator *iter)
{
size_t count;
int ret;
/* Seq buffer is page-sized, exactly what we need. */
for (;;) {
count = iter->seq.len;
ret = print_trace_line(iter);
count = iter->seq.len - count;
if (rem < count) {
rem = 0;
iter->seq.len -= count;
break;
}
if (ret == TRACE_TYPE_PARTIAL_LINE) {
iter->seq.len -= count;
break;
}
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(iter);
rem -= count;
if (!trace_find_next_entry_inc(iter)) {
rem = 0;
iter->ent = NULL;
break;
}
}
return rem;
}
static ssize_t tracing_splice_read_pipe(struct file *filp,
loff_t *ppos,
struct pipe_inode_info *pipe,
size_t len,
unsigned int flags)
{
struct page *pages_def[PIPE_DEF_BUFFERS];
struct partial_page partial_def[PIPE_DEF_BUFFERS];
struct trace_iterator *iter = filp->private_data;
struct splice_pipe_desc spd = {
.pages = pages_def,
.partial = partial_def,
.nr_pages = 0, /* This gets updated below. */
.nr_pages_max = PIPE_DEF_BUFFERS,
.flags = flags,
.ops = &tracing_pipe_buf_ops,
.spd_release = tracing_spd_release_pipe,
};
struct trace_array *tr = iter->tr;
ssize_t ret;
size_t rem;
unsigned int i;
if (splice_grow_spd(pipe, &spd))
return -ENOMEM;
/* copy the tracer to avoid using a global lock all around */
mutex_lock(&trace_types_lock);
if (unlikely(iter->trace->name != tr->current_trace->name))
*iter->trace = *tr->current_trace;
mutex_unlock(&trace_types_lock);
mutex_lock(&iter->mutex);
if (iter->trace->splice_read) {
ret = iter->trace->splice_read(iter, filp,
ppos, pipe, len, flags);
if (ret)
goto out_err;
}
ret = tracing_wait_pipe(filp);
if (ret <= 0)
goto out_err;
if (!iter->ent && !trace_find_next_entry_inc(iter)) {
ret = -EFAULT;
goto out_err;
}
trace_event_read_lock();
trace_access_lock(iter->cpu_file);
/* Fill as many pages as possible. */
for (i = 0, rem = len; i < pipe->buffers && rem; i++) {
spd.pages[i] = alloc_page(GFP_KERNEL);
if (!spd.pages[i])
break;
rem = tracing_fill_pipe_page(rem, iter);
/* Copy the data into the page, so we can start over. */
ret = trace_seq_to_buffer(&iter->seq,
page_address(spd.pages[i]),
iter->seq.len);
if (ret < 0) {
__free_page(spd.pages[i]);
break;
}
spd.partial[i].offset = 0;
spd.partial[i].len = iter->seq.len;
trace_seq_init(&iter->seq);
}
trace_access_unlock(iter->cpu_file);
trace_event_read_unlock();
mutex_unlock(&iter->mutex);
spd.nr_pages = i;
ret = splice_to_pipe(pipe, &spd);
out:
splice_shrink_spd(&spd);
return ret;
out_err:
mutex_unlock(&iter->mutex);
goto out;
}
static ssize_t
tracing_entries_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
int cpu = tracing_get_cpu(inode);
char buf[64];
int r = 0;
ssize_t ret;
mutex_lock(&trace_types_lock);
if (cpu == RING_BUFFER_ALL_CPUS) {
int cpu, buf_size_same;
unsigned long size;
size = 0;
buf_size_same = 1;
/* check if all cpu sizes are same */
for_each_tracing_cpu(cpu) {
/* fill in the size from first enabled cpu */
if (size == 0)
size = per_cpu_ptr(tr->trace_buffer.data, cpu)->entries;
if (size != per_cpu_ptr(tr->trace_buffer.data, cpu)->entries) {
buf_size_same = 0;
break;
}
}
if (buf_size_same) {
if (!ring_buffer_expanded)
r = sprintf(buf, "%lu (expanded: %lu)\n",
size >> 10,
trace_buf_size >> 10);
else
r = sprintf(buf, "%lu\n", size >> 10);
} else
r = sprintf(buf, "X\n");
} else
r = sprintf(buf, "%lu\n", per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10);
mutex_unlock(&trace_types_lock);
ret = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
return ret;
}
static ssize_t
tracing_entries_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
/* must have at least 1 entry */
if (!val)
return -EINVAL;
/* value is in KB */
val <<= 10;
ret = tracing_resize_ring_buffer(tr, val, tracing_get_cpu(inode));
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static ssize_t
tracing_total_entries_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[64];
int r, cpu;
unsigned long size = 0, expanded_size = 0;
mutex_lock(&trace_types_lock);
for_each_tracing_cpu(cpu) {
size += per_cpu_ptr(tr->trace_buffer.data, cpu)->entries >> 10;
if (!ring_buffer_expanded)
expanded_size += trace_buf_size >> 10;
}
if (ring_buffer_expanded)
r = sprintf(buf, "%lu\n", size);
else
r = sprintf(buf, "%lu (expanded: %lu)\n", size, expanded_size);
mutex_unlock(&trace_types_lock);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
tracing_free_buffer_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
/*
* There is no need to read what the user has written, this function
* is just to make sure that there is no error when "echo" is used
*/
*ppos += cnt;
return cnt;
}
static int
tracing_free_buffer_release(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
/* disable tracing ? */
if (trace_flags & TRACE_ITER_STOP_ON_FREE)
tracer_tracing_off(tr);
/* resize the ring buffer to 0 */
tracing_resize_ring_buffer(tr, 0, RING_BUFFER_ALL_CPUS);
trace_array_put(tr);
return 0;
}
static ssize_t
tracing_mark_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *fpos)
{
unsigned long addr = (unsigned long)ubuf;
struct trace_array *tr = filp->private_data;
struct ring_buffer_event *event;
struct ring_buffer *buffer;
struct print_entry *entry;
unsigned long irq_flags;
struct page *pages[2];
void *map_page[2];
int nr_pages = 1;
ssize_t written;
int offset;
int size;
int len;
int ret;
int i;
if (tracing_disabled)
return -EINVAL;
if (!(trace_flags & TRACE_ITER_MARKERS))
return -EINVAL;
if (cnt > TRACE_BUF_SIZE)
cnt = TRACE_BUF_SIZE;
/*
* Userspace is injecting traces into the kernel trace buffer.
* We want to be as non intrusive as possible.
* To do so, we do not want to allocate any special buffers
* or take any locks, but instead write the userspace data
* straight into the ring buffer.
*
* First we need to pin the userspace buffer into memory,
* which, most likely it is, because it just referenced it.
* But there's no guarantee that it is. By using get_user_pages_fast()
* and kmap_atomic/kunmap_atomic() we can get access to the
* pages directly. We then write the data directly into the
* ring buffer.
*/
BUILD_BUG_ON(TRACE_BUF_SIZE >= PAGE_SIZE);
/* check if we cross pages */
if ((addr & PAGE_MASK) != ((addr + cnt) & PAGE_MASK))
nr_pages = 2;
offset = addr & (PAGE_SIZE - 1);
addr &= PAGE_MASK;
ret = get_user_pages_fast(addr, nr_pages, 0, pages);
if (ret < nr_pages) {
while (--ret >= 0)
put_page(pages[ret]);
written = -EFAULT;
goto out;
}
for (i = 0; i < nr_pages; i++)
map_page[i] = kmap_atomic(pages[i]);
local_save_flags(irq_flags);
size = sizeof(*entry) + cnt + 2; /* possible \n added */
buffer = tr->trace_buffer.buffer;
event = trace_buffer_lock_reserve(buffer, TRACE_PRINT, size,
irq_flags, preempt_count());
if (!event) {
/* Ring buffer disabled, return as if not open for write */
written = -EBADF;
goto out_unlock;
}
entry = ring_buffer_event_data(event);
entry->ip = _THIS_IP_;
if (nr_pages == 2) {
len = PAGE_SIZE - offset;
memcpy(&entry->buf, map_page[0] + offset, len);
memcpy(&entry->buf[len], map_page[1], cnt - len);
} else
memcpy(&entry->buf, map_page[0] + offset, cnt);
if (entry->buf[cnt - 1] != '\n') {
entry->buf[cnt] = '\n';
entry->buf[cnt + 1] = '\0';
stm_log(OST_ENTITY_TRACE_MARKER, entry->buf, cnt + 2);
} else {
entry->buf[cnt] = '\0';
stm_log(OST_ENTITY_TRACE_MARKER, entry->buf, cnt + 1);
}
__buffer_unlock_commit(buffer, event);
written = cnt;
*fpos += written;
out_unlock:
for (i = nr_pages - 1; i >= 0; i--) {
kunmap_atomic(map_page[i]);
put_page(pages[i]);
}
out:
return written;
}
static int tracing_clock_show(struct seq_file *m, void *v)
{
struct trace_array *tr = m->private;
int i;
for (i = 0; i < ARRAY_SIZE(trace_clocks); i++)
seq_printf(m,
"%s%s%s%s", i ? " " : "",
i == tr->clock_id ? "[" : "", trace_clocks[i].name,
i == tr->clock_id ? "]" : "");
seq_putc(m, '\n');
return 0;
}
static ssize_t tracing_clock_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *fpos)
{
struct seq_file *m = filp->private_data;
struct trace_array *tr = m->private;
char buf[64];
const char *clockstr;
int i;
if (cnt >= sizeof(buf))
return -EINVAL;
if (copy_from_user(&buf, ubuf, cnt))
return -EFAULT;
buf[cnt] = 0;
clockstr = strstrip(buf);
for (i = 0; i < ARRAY_SIZE(trace_clocks); i++) {
if (strcmp(trace_clocks[i].name, clockstr) == 0)
break;
}
if (i == ARRAY_SIZE(trace_clocks))
return -EINVAL;
mutex_lock(&trace_types_lock);
tr->clock_id = i;
ring_buffer_set_clock(tr->trace_buffer.buffer, trace_clocks[i].func);
/*
* New clock may not be consistent with the previous clock.
* Reset the buffer so that it doesn't have incomparable timestamps.
*/
tracing_reset_online_cpus(&tr->trace_buffer);
#ifdef CONFIG_TRACER_MAX_TRACE
if (tr->flags & TRACE_ARRAY_FL_GLOBAL && tr->max_buffer.buffer)
ring_buffer_set_clock(tr->max_buffer.buffer, trace_clocks[i].func);
tracing_reset_online_cpus(&tr->max_buffer);
#endif
mutex_unlock(&trace_types_lock);
*fpos += cnt;
return cnt;
}
static int tracing_clock_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr))
return -ENODEV;
ret = single_open(file, tracing_clock_show, inode->i_private);
if (ret < 0)
trace_array_put(tr);
return ret;
}
struct ftrace_buffer_info {
struct trace_iterator iter;
void *spare;
unsigned int read;
};
#ifdef CONFIG_TRACER_SNAPSHOT
static int tracing_snapshot_open(struct inode *inode, struct file *file)
{
struct trace_array *tr = inode->i_private;
struct trace_iterator *iter;
struct seq_file *m;
int ret = 0;
if (trace_array_get(tr) < 0)
return -ENODEV;
if (file->f_mode & FMODE_READ) {
iter = __tracing_open(inode, file, true);
if (IS_ERR(iter))
ret = PTR_ERR(iter);
} else {
/* Writes still need the seq_file to hold the private data */
ret = -ENOMEM;
m = kzalloc(sizeof(*m), GFP_KERNEL);
if (!m)
goto out;
iter = kzalloc(sizeof(*iter), GFP_KERNEL);
if (!iter) {
kfree(m);
goto out;
}
ret = 0;
iter->tr = tr;
iter->trace_buffer = &tr->max_buffer;
iter->cpu_file = tracing_get_cpu(inode);
m->private = iter;
file->private_data = m;
}
out:
if (ret < 0)
trace_array_put(tr);
return ret;
}
static ssize_t
tracing_snapshot_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct seq_file *m = filp->private_data;
struct trace_iterator *iter = m->private;
struct trace_array *tr = iter->tr;
unsigned long val;
int ret;
ret = tracing_update_buffers();
if (ret < 0)
return ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
mutex_lock(&trace_types_lock);
if (tr->current_trace->use_max_tr) {
ret = -EBUSY;
goto out;
}
switch (val) {
case 0:
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
ret = -EINVAL;
break;
}
if (tr->allocated_snapshot)
free_snapshot(tr);
break;
case 1:
/* Only allow per-cpu swap if the ring buffer supports it */
#ifndef CONFIG_RING_BUFFER_ALLOW_SWAP
if (iter->cpu_file != RING_BUFFER_ALL_CPUS) {
ret = -EINVAL;
break;
}
#endif
if (!tr->allocated_snapshot) {
ret = alloc_snapshot(tr);
if (ret < 0)
break;
}
local_irq_disable();
/* Now, we're going to swap */
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
update_max_tr(tr, current, smp_processor_id());
else
update_max_tr_single(tr, current, iter->cpu_file);
local_irq_enable();
break;
default:
if (tr->allocated_snapshot) {
if (iter->cpu_file == RING_BUFFER_ALL_CPUS)
tracing_reset_online_cpus(&tr->max_buffer);
else
tracing_reset(&tr->max_buffer, iter->cpu_file);
}
break;
}
if (ret >= 0) {
*ppos += cnt;
ret = cnt;
}
out:
mutex_unlock(&trace_types_lock);
return ret;
}
static int tracing_snapshot_release(struct inode *inode, struct file *file)
{
struct seq_file *m = file->private_data;
int ret;
ret = tracing_release(inode, file);
if (file->f_mode & FMODE_READ)
return ret;
/* If write only, the seq_file is just a stub */
if (m)
kfree(m->private);
kfree(m);
return 0;
}
static int tracing_buffers_open(struct inode *inode, struct file *filp);
static ssize_t tracing_buffers_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos);
static int tracing_buffers_release(struct inode *inode, struct file *file);
static ssize_t tracing_buffers_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len, unsigned int flags);
static int snapshot_raw_open(struct inode *inode, struct file *filp)
{
struct ftrace_buffer_info *info;
int ret;
ret = tracing_buffers_open(inode, filp);
if (ret < 0)
return ret;
info = filp->private_data;
if (info->iter.trace->use_max_tr) {
tracing_buffers_release(inode, filp);
return -EBUSY;
}
info->iter.snapshot = true;
info->iter.trace_buffer = &info->iter.tr->max_buffer;
return ret;
}
#endif /* CONFIG_TRACER_SNAPSHOT */
static const struct file_operations tracing_max_lat_fops = {
.open = tracing_open_generic,
.read = tracing_max_lat_read,
.write = tracing_max_lat_write,
.llseek = generic_file_llseek,
};
static const struct file_operations set_tracer_fops = {
.open = tracing_open_generic,
.read = tracing_set_trace_read,
.write = tracing_set_trace_write,
.llseek = generic_file_llseek,
};
static const struct file_operations tracing_pipe_fops = {
.open = tracing_open_pipe,
.poll = tracing_poll_pipe,
.read = tracing_read_pipe,
.splice_read = tracing_splice_read_pipe,
.release = tracing_release_pipe,
.llseek = no_llseek,
};
static const struct file_operations tracing_entries_fops = {
.open = tracing_open_generic_tr,
.read = tracing_entries_read,
.write = tracing_entries_write,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations tracing_total_entries_fops = {
.open = tracing_open_generic_tr,
.read = tracing_total_entries_read,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations tracing_free_buffer_fops = {
.open = tracing_open_generic_tr,
.write = tracing_free_buffer_write,
.release = tracing_free_buffer_release,
};
static const struct file_operations tracing_mark_fops = {
.open = tracing_open_generic_tr,
.write = tracing_mark_write,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
static const struct file_operations trace_clock_fops = {
.open = tracing_clock_open,
.read = seq_read,
.llseek = seq_lseek,
.release = tracing_single_release_tr,
.write = tracing_clock_write,
};
#ifdef CONFIG_TRACER_SNAPSHOT
static const struct file_operations snapshot_fops = {
.open = tracing_snapshot_open,
.read = seq_read,
.write = tracing_snapshot_write,
.llseek = tracing_seek,
.release = tracing_snapshot_release,
};
static const struct file_operations snapshot_raw_fops = {
.open = snapshot_raw_open,
.read = tracing_buffers_read,
.release = tracing_buffers_release,
.splice_read = tracing_buffers_splice_read,
.llseek = no_llseek,
};
#endif /* CONFIG_TRACER_SNAPSHOT */
static int tracing_buffers_open(struct inode *inode, struct file *filp)
{
struct trace_array *tr = inode->i_private;
struct ftrace_buffer_info *info;
int ret;
if (tracing_disabled)
return -ENODEV;
if (trace_array_get(tr) < 0)
return -ENODEV;
info = kzalloc(sizeof(*info), GFP_KERNEL);
if (!info) {
trace_array_put(tr);
return -ENOMEM;
}
mutex_lock(&trace_types_lock);
info->iter.tr = tr;
info->iter.cpu_file = tracing_get_cpu(inode);
info->iter.trace = tr->current_trace;
info->iter.trace_buffer = &tr->trace_buffer;
info->spare = NULL;
/* Force reading ring buffer for first read */
info->read = (unsigned int)-1;
filp->private_data = info;
mutex_unlock(&trace_types_lock);
ret = nonseekable_open(inode, filp);
if (ret < 0)
trace_array_put(tr);
return ret;
}
static unsigned int
tracing_buffers_poll(struct file *filp, poll_table *poll_table)
{
struct ftrace_buffer_info *info = filp->private_data;
struct trace_iterator *iter = &info->iter;
return trace_poll(iter, filp, poll_table);
}
static ssize_t
tracing_buffers_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct ftrace_buffer_info *info = filp->private_data;
struct trace_iterator *iter = &info->iter;
ssize_t ret;
ssize_t size;
if (!count)
return 0;
mutex_lock(&trace_types_lock);
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->tr->current_trace->use_max_tr) {
size = -EBUSY;
goto out_unlock;
}
#endif
if (!info->spare)
info->spare = ring_buffer_alloc_read_page(iter->trace_buffer->buffer,
iter->cpu_file);
size = -ENOMEM;
if (!info->spare)
goto out_unlock;
/* Do we have previous read data to read? */
if (info->read < PAGE_SIZE)
goto read;
again:
trace_access_lock(iter->cpu_file);
ret = ring_buffer_read_page(iter->trace_buffer->buffer,
&info->spare,
count,
iter->cpu_file, 0);
trace_access_unlock(iter->cpu_file);
if (ret < 0) {
if (trace_empty(iter)) {
if ((filp->f_flags & O_NONBLOCK)) {
size = -EAGAIN;
goto out_unlock;
}
mutex_unlock(&trace_types_lock);
ret = iter->trace->wait_pipe(iter);
mutex_lock(&trace_types_lock);
if (ret) {
size = ret;
goto out_unlock;
}
if (signal_pending(current)) {
size = -EINTR;
goto out_unlock;
}
goto again;
}
size = 0;
goto out_unlock;
}
info->read = 0;
read:
size = PAGE_SIZE - info->read;
if (size > count)
size = count;
ret = copy_to_user(ubuf, info->spare + info->read, size);
if (ret == size) {
size = -EFAULT;
goto out_unlock;
}
size -= ret;
*ppos += size;
info->read += size;
out_unlock:
mutex_unlock(&trace_types_lock);
return size;
}
static int tracing_buffers_release(struct inode *inode, struct file *file)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
mutex_lock(&trace_types_lock);
__trace_array_put(iter->tr);
if (info->spare)
ring_buffer_free_read_page(iter->trace_buffer->buffer, info->spare);
kfree(info);
mutex_unlock(&trace_types_lock);
return 0;
}
struct buffer_ref {
struct ring_buffer *buffer;
void *page;
int ref;
};
static void buffer_pipe_buf_release(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
if (--ref->ref)
return;
ring_buffer_free_read_page(ref->buffer, ref->page);
kfree(ref);
buf->private = 0;
}
static void buffer_pipe_buf_get(struct pipe_inode_info *pipe,
struct pipe_buffer *buf)
{
struct buffer_ref *ref = (struct buffer_ref *)buf->private;
ref->ref++;
}
/* Pipe buffer operations for a buffer. */
static const struct pipe_buf_operations buffer_pipe_buf_ops = {
.can_merge = 0,
.map = generic_pipe_buf_map,
.unmap = generic_pipe_buf_unmap,
.confirm = generic_pipe_buf_confirm,
.release = buffer_pipe_buf_release,
.steal = generic_pipe_buf_steal,
.get = buffer_pipe_buf_get,
};
/*
* Callback from splice_to_pipe(), if we need to release some pages
* at the end of the spd in case we error'ed out in filling the pipe.
*/
static void buffer_spd_release(struct splice_pipe_desc *spd, unsigned int i)
{
struct buffer_ref *ref =
(struct buffer_ref *)spd->partial[i].private;
if (--ref->ref)
return;
ring_buffer_free_read_page(ref->buffer, ref->page);
kfree(ref);
spd->partial[i].private = 0;
}
static ssize_t
tracing_buffers_splice_read(struct file *file, loff_t *ppos,
struct pipe_inode_info *pipe, size_t len,
unsigned int flags)
{
struct ftrace_buffer_info *info = file->private_data;
struct trace_iterator *iter = &info->iter;
struct partial_page partial_def[PIPE_DEF_BUFFERS];
struct page *pages_def[PIPE_DEF_BUFFERS];
struct splice_pipe_desc spd = {
.pages = pages_def,
.partial = partial_def,
.nr_pages_max = PIPE_DEF_BUFFERS,
.flags = flags,
.ops = &buffer_pipe_buf_ops,
.spd_release = buffer_spd_release,
};
struct buffer_ref *ref;
int entries, size, i;
ssize_t ret;
mutex_lock(&trace_types_lock);
#ifdef CONFIG_TRACER_MAX_TRACE
if (iter->snapshot && iter->tr->current_trace->use_max_tr) {
ret = -EBUSY;
goto out;
}
#endif
if (splice_grow_spd(pipe, &spd)) {
ret = -ENOMEM;
goto out;
}
if (*ppos & (PAGE_SIZE - 1)) {
ret = -EINVAL;
goto out;
}
if (len & (PAGE_SIZE - 1)) {
if (len < PAGE_SIZE) {
ret = -EINVAL;
goto out;
}
len &= PAGE_MASK;
}
again:
trace_access_lock(iter->cpu_file);
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
for (i = 0; i < pipe->buffers && len && entries; i++, len -= PAGE_SIZE) {
struct page *page;
int r;
ref = kzalloc(sizeof(*ref), GFP_KERNEL);
if (!ref)
break;
ref->ref = 1;
ref->buffer = iter->trace_buffer->buffer;
ref->page = ring_buffer_alloc_read_page(ref->buffer, iter->cpu_file);
if (!ref->page) {
kfree(ref);
break;
}
r = ring_buffer_read_page(ref->buffer, &ref->page,
len, iter->cpu_file, 1);
if (r < 0) {
ring_buffer_free_read_page(ref->buffer, ref->page);
kfree(ref);
break;
}
/*
* zero out any left over data, this is going to
* user land.
*/
size = ring_buffer_page_len(ref->page);
if (size < PAGE_SIZE)
memset(ref->page + size, 0, PAGE_SIZE - size);
page = virt_to_page(ref->page);
spd.pages[i] = page;
spd.partial[i].len = PAGE_SIZE;
spd.partial[i].offset = 0;
spd.partial[i].private = (unsigned long)ref;
spd.nr_pages++;
*ppos += PAGE_SIZE;
entries = ring_buffer_entries_cpu(iter->trace_buffer->buffer, iter->cpu_file);
}
trace_access_unlock(iter->cpu_file);
spd.nr_pages = i;
/* did we read anything? */
if (!spd.nr_pages) {
if ((file->f_flags & O_NONBLOCK) || (flags & SPLICE_F_NONBLOCK)) {
ret = -EAGAIN;
goto out;
}
mutex_unlock(&trace_types_lock);
ret = iter->trace->wait_pipe(iter);
mutex_lock(&trace_types_lock);
if (ret)
goto out;
if (signal_pending(current)) {
ret = -EINTR;
goto out;
}
goto again;
}
ret = splice_to_pipe(pipe, &spd);
splice_shrink_spd(&spd);
out:
mutex_unlock(&trace_types_lock);
return ret;
}
static const struct file_operations tracing_buffers_fops = {
.open = tracing_buffers_open,
.read = tracing_buffers_read,
.poll = tracing_buffers_poll,
.release = tracing_buffers_release,
.splice_read = tracing_buffers_splice_read,
.llseek = no_llseek,
};
static ssize_t
tracing_stats_read(struct file *filp, char __user *ubuf,
size_t count, loff_t *ppos)
{
struct inode *inode = file_inode(filp);
struct trace_array *tr = inode->i_private;
struct trace_buffer *trace_buf = &tr->trace_buffer;
int cpu = tracing_get_cpu(inode);
struct trace_seq *s;
unsigned long cnt;
unsigned long long t;
unsigned long usec_rem;
s = kmalloc(sizeof(*s), GFP_KERNEL);
if (!s)
return -ENOMEM;
trace_seq_init(s);
cnt = ring_buffer_entries_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "entries: %ld\n", cnt);
cnt = ring_buffer_overrun_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "overrun: %ld\n", cnt);
cnt = ring_buffer_commit_overrun_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "commit overrun: %ld\n", cnt);
cnt = ring_buffer_bytes_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "bytes: %ld\n", cnt);
if (trace_clocks[tr->clock_id].in_ns) {
/* local or global for trace_clock */
t = ns2usecs(ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
usec_rem = do_div(t, USEC_PER_SEC);
trace_seq_printf(s, "oldest event ts: %5llu.%06lu\n",
t, usec_rem);
t = ns2usecs(ring_buffer_time_stamp(trace_buf->buffer, cpu));
usec_rem = do_div(t, USEC_PER_SEC);
trace_seq_printf(s, "now ts: %5llu.%06lu\n", t, usec_rem);
} else {
/* counter or tsc mode for trace_clock */
trace_seq_printf(s, "oldest event ts: %llu\n",
ring_buffer_oldest_event_ts(trace_buf->buffer, cpu));
trace_seq_printf(s, "now ts: %llu\n",
ring_buffer_time_stamp(trace_buf->buffer, cpu));
}
cnt = ring_buffer_dropped_events_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "dropped events: %ld\n", cnt);
cnt = ring_buffer_read_events_cpu(trace_buf->buffer, cpu);
trace_seq_printf(s, "read events: %ld\n", cnt);
count = simple_read_from_buffer(ubuf, count, ppos, s->buffer, s->len);
kfree(s);
return count;
}
static const struct file_operations tracing_stats_fops = {
.open = tracing_open_generic_tr,
.read = tracing_stats_read,
.llseek = generic_file_llseek,
.release = tracing_release_generic_tr,
};
#ifdef CONFIG_DYNAMIC_FTRACE
int __weak ftrace_arch_read_dyn_info(char *buf, int size)
{
return 0;
}
static ssize_t
tracing_read_dyn_info(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
static char ftrace_dyn_info_buffer[1024];
static DEFINE_MUTEX(dyn_info_mutex);
unsigned long *p = filp->private_data;
char *buf = ftrace_dyn_info_buffer;
int size = ARRAY_SIZE(ftrace_dyn_info_buffer);
int r;
mutex_lock(&dyn_info_mutex);
r = sprintf(buf, "%ld ", *p);
r += ftrace_arch_read_dyn_info(buf+r, (size-1)-r);
buf[r++] = '\n';
r = simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
mutex_unlock(&dyn_info_mutex);
return r;
}
static const struct file_operations tracing_dyn_info_fops = {
.open = tracing_open_generic,
.read = tracing_read_dyn_info,
.llseek = generic_file_llseek,
};
#endif /* CONFIG_DYNAMIC_FTRACE */
#if defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE)
static void
ftrace_snapshot(unsigned long ip, unsigned long parent_ip, void **data)
{
tracing_snapshot();
}
static void
ftrace_count_snapshot(unsigned long ip, unsigned long parent_ip, void **data)
{
unsigned long *count = (long *)data;
if (!*count)
return;
if (*count != -1)
(*count)--;
tracing_snapshot();
}
static int
ftrace_snapshot_print(struct seq_file *m, unsigned long ip,
struct ftrace_probe_ops *ops, void *data)
{
long count = (long)data;
seq_printf(m, "%ps:", (void *)ip);
seq_printf(m, "snapshot");
if (count == -1)
seq_printf(m, ":unlimited\n");
else
seq_printf(m, ":count=%ld\n", count);
return 0;
}
static struct ftrace_probe_ops snapshot_probe_ops = {
.func = ftrace_snapshot,
.print = ftrace_snapshot_print,
};
static struct ftrace_probe_ops snapshot_count_probe_ops = {
.func = ftrace_count_snapshot,
.print = ftrace_snapshot_print,
};
static int
ftrace_trace_snapshot_callback(struct ftrace_hash *hash,
char *glob, char *cmd, char *param, int enable)
{
struct ftrace_probe_ops *ops;
void *count = (void *)-1;
char *number;
int ret;
/* hash funcs only work with set_ftrace_filter */
if (!enable)
return -EINVAL;
ops = param ? &snapshot_count_probe_ops : &snapshot_probe_ops;
if (glob[0] == '!') {
unregister_ftrace_function_probe_func(glob+1, ops);
return 0;
}
if (!param)
goto out_reg;
number = strsep(¶m, ":");
if (!strlen(number))
goto out_reg;
/*
* We use the callback data field (which is a pointer)
* as our counter.
*/
ret = kstrtoul(number, 0, (unsigned long *)&count);
if (ret)
return ret;
out_reg:
ret = register_ftrace_function_probe(glob, ops, count);
if (ret >= 0)
alloc_snapshot(&global_trace);
return ret < 0 ? ret : 0;
}
static struct ftrace_func_command ftrace_snapshot_cmd = {
.name = "snapshot",
.func = ftrace_trace_snapshot_callback,
};
static int register_snapshot_cmd(void)
{
return register_ftrace_command(&ftrace_snapshot_cmd);
}
#else
static inline int register_snapshot_cmd(void) { return 0; }
#endif /* defined(CONFIG_TRACER_SNAPSHOT) && defined(CONFIG_DYNAMIC_FTRACE) */
struct dentry *tracing_init_dentry_tr(struct trace_array *tr)
{
if (tr->dir)
return tr->dir;
if (!debugfs_initialized())
return NULL;
if (tr->flags & TRACE_ARRAY_FL_GLOBAL)
tr->dir = debugfs_create_dir("tracing", NULL);
if (!tr->dir)
pr_warn_once("Could not create debugfs directory 'tracing'\n");
return tr->dir;
}
struct dentry *tracing_init_dentry(void)
{
return tracing_init_dentry_tr(&global_trace);
}
static struct dentry *tracing_dentry_percpu(struct trace_array *tr, int cpu)
{
struct dentry *d_tracer;
if (tr->percpu_dir)
return tr->percpu_dir;
d_tracer = tracing_init_dentry_tr(tr);
if (!d_tracer)
return NULL;
tr->percpu_dir = debugfs_create_dir("per_cpu", d_tracer);
WARN_ONCE(!tr->percpu_dir,
"Could not create debugfs directory 'per_cpu/%d'\n", cpu);
return tr->percpu_dir;
}
static struct dentry *
trace_create_cpu_file(const char *name, umode_t mode, struct dentry *parent,
void *data, long cpu, const struct file_operations *fops)
{
struct dentry *ret = trace_create_file(name, mode, parent, data, fops);
if (ret) /* See tracing_get_cpu() */
ret->d_inode->i_cdev = (void *)(cpu + 1);
return ret;
}
static void
tracing_init_debugfs_percpu(struct trace_array *tr, long cpu)
{
struct dentry *d_percpu = tracing_dentry_percpu(tr, cpu);
struct dentry *d_cpu;
char cpu_dir[30]; /* 30 characters should be more than enough */
if (!d_percpu)
return;
snprintf(cpu_dir, 30, "cpu%ld", cpu);
d_cpu = debugfs_create_dir(cpu_dir, d_percpu);
if (!d_cpu) {
pr_warning("Could not create debugfs '%s' entry\n", cpu_dir);
return;
}
/* per cpu trace_pipe */
trace_create_cpu_file("trace_pipe", 0444, d_cpu,
tr, cpu, &tracing_pipe_fops);
/* per cpu trace */
trace_create_cpu_file("trace", 0644, d_cpu,
tr, cpu, &tracing_fops);
trace_create_cpu_file("trace_pipe_raw", 0444, d_cpu,
tr, cpu, &tracing_buffers_fops);
trace_create_cpu_file("stats", 0444, d_cpu,
tr, cpu, &tracing_stats_fops);
trace_create_cpu_file("buffer_size_kb", 0444, d_cpu,
tr, cpu, &tracing_entries_fops);
#ifdef CONFIG_TRACER_SNAPSHOT
trace_create_cpu_file("snapshot", 0644, d_cpu,
tr, cpu, &snapshot_fops);
trace_create_cpu_file("snapshot_raw", 0444, d_cpu,
tr, cpu, &snapshot_raw_fops);
#endif
}
#ifdef CONFIG_FTRACE_SELFTEST
/* Let selftest have access to static functions in this file */
#include "trace_selftest.c"
#endif
struct trace_option_dentry {
struct tracer_opt *opt;
struct tracer_flags *flags;
struct trace_array *tr;
struct dentry *entry;
};
static ssize_t
trace_options_read(struct file *filp, char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_option_dentry *topt = filp->private_data;
char *buf;
if (topt->flags->val & topt->opt->bit)
buf = "1\n";
else
buf = "0\n";
return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
}
static ssize_t
trace_options_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_option_dentry *topt = filp->private_data;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (val != 0 && val != 1)
return -EINVAL;
if (!!(topt->flags->val & topt->opt->bit) != val) {
mutex_lock(&trace_types_lock);
ret = __set_tracer_option(topt->tr->current_trace, topt->flags,
topt->opt, !val);
mutex_unlock(&trace_types_lock);
if (ret)
return ret;
}
*ppos += cnt;
return cnt;
}
static const struct file_operations trace_options_fops = {
.open = tracing_open_generic,
.read = trace_options_read,
.write = trace_options_write,
.llseek = generic_file_llseek,
};
static ssize_t
trace_options_core_read(struct file *filp, char __user *ubuf, size_t cnt,
loff_t *ppos)
{
long index = (long)filp->private_data;
char *buf;
if (trace_flags & (1 << index))
buf = "1\n";
else
buf = "0\n";
return simple_read_from_buffer(ubuf, cnt, ppos, buf, 2);
}
static ssize_t
trace_options_core_write(struct file *filp, const char __user *ubuf, size_t cnt,
loff_t *ppos)
{
struct trace_array *tr = &global_trace;
long index = (long)filp->private_data;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (val != 0 && val != 1)
return -EINVAL;
mutex_lock(&trace_types_lock);
ret = set_tracer_flag(tr, 1 << index, val);
mutex_unlock(&trace_types_lock);
if (ret < 0)
return ret;
*ppos += cnt;
return cnt;
}
static const struct file_operations trace_options_core_fops = {
.open = tracing_open_generic,
.read = trace_options_core_read,
.write = trace_options_core_write,
.llseek = generic_file_llseek,
};
struct dentry *trace_create_file(const char *name,
umode_t mode,
struct dentry *parent,
void *data,
const struct file_operations *fops)
{
struct dentry *ret;
ret = debugfs_create_file(name, mode, parent, data, fops);
if (!ret)
pr_warning("Could not create debugfs '%s' entry\n", name);
return ret;
}
static struct dentry *trace_options_init_dentry(struct trace_array *tr)
{
struct dentry *d_tracer;
if (tr->options)
return tr->options;
d_tracer = tracing_init_dentry_tr(tr);
if (!d_tracer)
return NULL;
tr->options = debugfs_create_dir("options", d_tracer);
if (!tr->options) {
pr_warning("Could not create debugfs directory 'options'\n");
return NULL;
}
return tr->options;
}
static void
create_trace_option_file(struct trace_array *tr,
struct trace_option_dentry *topt,
struct tracer_flags *flags,
struct tracer_opt *opt)
{
struct dentry *t_options;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return;
topt->flags = flags;
topt->opt = opt;
topt->tr = tr;
topt->entry = trace_create_file(opt->name, 0644, t_options, topt,
&trace_options_fops);
}
static struct trace_option_dentry *
create_trace_option_files(struct trace_array *tr, struct tracer *tracer)
{
struct trace_option_dentry *topts;
struct tracer_flags *flags;
struct tracer_opt *opts;
int cnt;
if (!tracer)
return NULL;
flags = tracer->flags;
if (!flags || !flags->opts)
return NULL;
opts = flags->opts;
for (cnt = 0; opts[cnt].name; cnt++)
;
topts = kcalloc(cnt + 1, sizeof(*topts), GFP_KERNEL);
if (!topts)
return NULL;
for (cnt = 0; opts[cnt].name; cnt++)
create_trace_option_file(tr, &topts[cnt], flags,
&opts[cnt]);
return topts;
}
static void
destroy_trace_option_files(struct trace_option_dentry *topts)
{
int cnt;
if (!topts)
return;
for (cnt = 0; topts[cnt].opt; cnt++) {
if (topts[cnt].entry)
debugfs_remove(topts[cnt].entry);
}
kfree(topts);
}
static struct dentry *
create_trace_option_core_file(struct trace_array *tr,
const char *option, long index)
{
struct dentry *t_options;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return NULL;
return trace_create_file(option, 0644, t_options, (void *)index,
&trace_options_core_fops);
}
static __init void create_trace_options_dir(struct trace_array *tr)
{
struct dentry *t_options;
int i;
t_options = trace_options_init_dentry(tr);
if (!t_options)
return;
for (i = 0; trace_options[i]; i++)
create_trace_option_core_file(tr, trace_options[i], i);
}
static ssize_t
rb_simple_read(struct file *filp, char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
char buf[64];
int r;
r = tracer_tracing_is_on(tr);
r = sprintf(buf, "%d\n", r);
return simple_read_from_buffer(ubuf, cnt, ppos, buf, r);
}
static ssize_t
rb_simple_write(struct file *filp, const char __user *ubuf,
size_t cnt, loff_t *ppos)
{
struct trace_array *tr = filp->private_data;
struct ring_buffer *buffer = tr->trace_buffer.buffer;
unsigned long val;
int ret;
ret = kstrtoul_from_user(ubuf, cnt, 10, &val);
if (ret)
return ret;
if (buffer) {
mutex_lock(&trace_types_lock);
if (val) {
tracer_tracing_on(tr);
if (tr->current_trace->start)
tr->current_trace->start(tr);
} else {
tracer_tracing_off(tr);
if (tr->current_trace->stop)
tr->current_trace->stop(tr);
}
mutex_unlock(&trace_types_lock);
}
(*ppos)++;
return cnt;
}
static const struct file_operations rb_simple_fops = {
.open = tracing_open_generic_tr,
.read = rb_simple_read,
.write = rb_simple_write,
.release = tracing_release_generic_tr,
.llseek = default_llseek,
};
struct dentry *trace_instance_dir;
static void
init_tracer_debugfs(struct trace_array *tr, struct dentry *d_tracer);
static void init_trace_buffers(struct trace_array *tr, struct trace_buffer *buf)
{
int cpu;
for_each_tracing_cpu(cpu) {
memset(per_cpu_ptr(buf->data, cpu), 0, sizeof(struct trace_array_cpu));
per_cpu_ptr(buf->data, cpu)->trace_cpu.cpu = cpu;
per_cpu_ptr(buf->data, cpu)->trace_cpu.tr = tr;
}
}
static int
allocate_trace_buffer(struct trace_array *tr, struct trace_buffer *buf, int size)
{
enum ring_buffer_flags rb_flags;
rb_flags = trace_flags & TRACE_ITER_OVERWRITE ? RB_FL_OVERWRITE : 0;
buf->tr = tr;
buf->buffer = ring_buffer_alloc(size, rb_flags);
if (!buf->buffer)
return -ENOMEM;
buf->data = alloc_percpu(struct trace_array_cpu);
if (!buf->data) {
ring_buffer_free(buf->buffer);
return -ENOMEM;
}
init_trace_buffers(tr, buf);
/* Allocate the first page for all buffers */
set_buffer_entries(&tr->trace_buffer,
ring_buffer_size(tr->trace_buffer.buffer, 0));
return 0;
}
static int allocate_trace_buffers(struct trace_array *tr, int size)
{
int ret;
ret = allocate_trace_buffer(tr, &tr->trace_buffer, size);
if (ret)
return ret;
#ifdef CONFIG_TRACER_MAX_TRACE
ret = allocate_trace_buffer(tr, &tr->max_buffer,
allocate_snapshot ? size : 1);
if (WARN_ON(ret)) {
ring_buffer_free(tr->trace_buffer.buffer);
free_percpu(tr->trace_buffer.data);
return -ENOMEM;
}
tr->allocated_snapshot = allocate_snapshot;
/*
* Only the top level trace array gets its snapshot allocated
* from the kernel command line.
*/
allocate_snapshot = false;
#endif
return 0;
}
static int new_instance_create(const char *name)
{
struct trace_array *tr;
int ret;
mutex_lock(&trace_types_lock);
ret = -EEXIST;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr->name && strcmp(tr->name, name) == 0)
goto out_unlock;
}
ret = -ENOMEM;
tr = kzalloc(sizeof(*tr), GFP_KERNEL);
if (!tr)
goto out_unlock;
tr->name = kstrdup(name, GFP_KERNEL);
if (!tr->name)
goto out_free_tr;
raw_spin_lock_init(&tr->start_lock);
tr->current_trace = &nop_trace;
INIT_LIST_HEAD(&tr->systems);
INIT_LIST_HEAD(&tr->events);
if (allocate_trace_buffers(tr, trace_buf_size) < 0)
goto out_free_tr;
/* Holder for file callbacks */
tr->trace_cpu.cpu = RING_BUFFER_ALL_CPUS;
tr->trace_cpu.tr = tr;
tr->dir = debugfs_create_dir(name, trace_instance_dir);
if (!tr->dir)
goto out_free_tr;
ret = event_trace_add_tracer(tr->dir, tr);
if (ret) {
debugfs_remove_recursive(tr->dir);
goto out_free_tr;
}
init_tracer_debugfs(tr, tr->dir);
list_add(&tr->list, &ftrace_trace_arrays);
mutex_unlock(&trace_types_lock);
return 0;
out_free_tr:
if (tr->trace_buffer.buffer)
ring_buffer_free(tr->trace_buffer.buffer);
kfree(tr->name);
kfree(tr);
out_unlock:
mutex_unlock(&trace_types_lock);
return ret;
}
static int instance_delete(const char *name)
{
struct trace_array *tr;
int found = 0;
int ret;
mutex_lock(&trace_types_lock);
ret = -ENODEV;
list_for_each_entry(tr, &ftrace_trace_arrays, list) {
if (tr->name && strcmp(tr->name, name) == 0) {
found = 1;
break;
}
}
if (!found)
goto out_unlock;
ret = -EBUSY;
if (tr->ref)
goto out_unlock;
list_del(&tr->list);
event_trace_del_tracer(tr);
debugfs_remove_recursive(tr->dir);
free_percpu(tr->trace_buffer.data);
ring_buffer_free(tr->trace_buffer.buffer);
kfree(tr->name);
kfree(tr);
ret = 0;
out_unlock:
mutex_unlock(&trace_types_lock);
return ret;
}
static int instance_mkdir (struct inode *inode, struct dentry *dentry, umode_t mode)
{
struct dentry *parent;
int ret;
/* Paranoid: Make sure the parent is the "instances" directory */
parent = hlist_entry(inode->i_dentry.first, struct dentry, d_alias);
if (WARN_ON_ONCE(parent != trace_instance_dir))
return -ENOENT;
/*
* The inode mutex is locked, but debugfs_create_dir() will also
* take the mutex. As the instances directory can not be destroyed
* or changed in any other way, it is safe to unlock it, and
* let the dentry try. If two users try to make the same dir at
* the same time, then the new_instance_create() will determine the
* winner.
*/
mutex_unlock(&inode->i_mutex);
ret = new_instance_create(dentry->d_iname);
mutex_lock(&inode->i_mutex);
return ret;
}
static int instance_rmdir(struct inode *inode, struct dentry *dentry)
{
struct dentry *parent;
int ret;
/* Paranoid: Make sure the parent is the "instances" directory */
parent = hlist_entry(inode->i_dentry.first, struct dentry, d_alias);
if (WARN_ON_ONCE(parent != trace_instance_dir))
return -ENOENT;
/* The caller did a dget() on dentry */
mutex_unlock(&dentry->d_inode->i_mutex);
/*
* The inode mutex is locked, but debugfs_create_dir() will also
* take the mutex. As the instances directory can not be destroyed
* or changed in any other way, it is safe to unlock it, and
* let the dentry try. If two users try to make the same dir at
* the same time, then the instance_delete() will determine the
* winner.
*/
mutex_unlock(&inode->i_mutex);
ret = instance_delete(dentry->d_iname);
mutex_lock_nested(&inode->i_mutex, I_MUTEX_PARENT);
mutex_lock(&dentry->d_inode->i_mutex);
return ret;
}
static const struct inode_operations instance_dir_inode_operations = {
.lookup = simple_lookup,
.mkdir = instance_mkdir,
.rmdir = instance_rmdir,
};
static __init void create_trace_instances(struct dentry *d_tracer)
{
trace_instance_dir = debugfs_create_dir("instances", d_tracer);
if (WARN_ON(!trace_instance_dir))
return;
/* Hijack the dir inode operations, to allow mkdir */
trace_instance_dir->d_inode->i_op = &instance_dir_inode_operations;
}
static void
init_tracer_debugfs(struct trace_array *tr, struct dentry *d_tracer)
{
int cpu;
trace_create_file("trace_options", 0644, d_tracer,
tr, &tracing_iter_fops);
trace_create_file("trace", 0644, d_tracer,
tr, &tracing_fops);
trace_create_file("trace_pipe", 0444, d_tracer,
tr, &tracing_pipe_fops);
trace_create_file("buffer_size_kb", 0644, d_tracer,
tr, &tracing_entries_fops);
trace_create_file("buffer_total_size_kb", 0444, d_tracer,
tr, &tracing_total_entries_fops);
trace_create_file("free_buffer", 0644, d_tracer,
tr, &tracing_free_buffer_fops);
trace_create_file("trace_marker", 0220, d_tracer,
tr, &tracing_mark_fops);
trace_create_file("saved_tgids", 0444, d_tracer,
tr, &tracing_saved_tgids_fops);
trace_create_file("trace_clock", 0644, d_tracer, tr,
&trace_clock_fops);
trace_create_file("tracing_on", 0644, d_tracer,
tr, &rb_simple_fops);
#ifdef CONFIG_TRACER_SNAPSHOT
trace_create_file("snapshot", 0644, d_tracer,
tr, &snapshot_fops);
#endif
for_each_tracing_cpu(cpu)
tracing_init_debugfs_percpu(tr, cpu);
}
static __init int tracer_init_debugfs(void)
{
struct dentry *d_tracer;
trace_access_lock_init();
d_tracer = tracing_init_dentry();
if (!d_tracer)
return 0;
init_tracer_debugfs(&global_trace, d_tracer);
trace_create_file("tracing_cpumask", 0644, d_tracer,
&global_trace, &tracing_cpumask_fops);
trace_create_file("available_tracers", 0444, d_tracer,
&global_trace, &show_traces_fops);
trace_create_file("current_tracer", 0644, d_tracer,
&global_trace, &set_tracer_fops);
#ifdef CONFIG_TRACER_MAX_TRACE
trace_create_file("tracing_max_latency", 0644, d_tracer,
&tracing_max_latency, &tracing_max_lat_fops);
#endif
trace_create_file("tracing_thresh", 0644, d_tracer,
&tracing_thresh, &tracing_max_lat_fops);
trace_create_file("README", 0444, d_tracer,
NULL, &tracing_readme_fops);
trace_create_file("saved_cmdlines", 0444, d_tracer,
NULL, &tracing_saved_cmdlines_fops);
#ifdef CONFIG_DYNAMIC_FTRACE
trace_create_file("dyn_ftrace_total_info", 0444, d_tracer,
&ftrace_update_tot_cnt, &tracing_dyn_info_fops);
#endif
create_trace_instances(d_tracer);
create_trace_options_dir(&global_trace);
return 0;
}
static int trace_panic_handler(struct notifier_block *this,
unsigned long event, void *unused)
{
if (ftrace_dump_on_oops)
ftrace_dump(ftrace_dump_on_oops);
return NOTIFY_OK;
}
static struct notifier_block trace_panic_notifier = {
.notifier_call = trace_panic_handler,
.next = NULL,
.priority = 150 /* priority: INT_MAX >= x >= 0 */
};
static int trace_die_handler(struct notifier_block *self,
unsigned long val,
void *data)
{
switch (val) {
case DIE_OOPS:
if (ftrace_dump_on_oops)
ftrace_dump(ftrace_dump_on_oops);
break;
default:
break;
}
return NOTIFY_OK;
}
static struct notifier_block trace_die_notifier = {
.notifier_call = trace_die_handler,
.priority = 200
};
/*
* printk is set to max of 1024, we really don't need it that big.
* Nothing should be printing 1000 characters anyway.
*/
#define TRACE_MAX_PRINT 1000
/*
* Define here KERN_TRACE so that we have one place to modify
* it if we decide to change what log level the ftrace dump
* should be at.
*/
#define KERN_TRACE KERN_EMERG
void
trace_printk_seq(struct trace_seq *s)
{
/* Probably should print a warning here. */
if (s->len >= TRACE_MAX_PRINT)
s->len = TRACE_MAX_PRINT;
/* should be zero ended, but we are paranoid. */
s->buffer[s->len] = 0;
printk(KERN_TRACE "%s", s->buffer);
trace_seq_init(s);
}
void trace_init_global_iter(struct trace_iterator *iter)
{
iter->tr = &global_trace;
iter->trace = iter->tr->current_trace;
iter->cpu_file = RING_BUFFER_ALL_CPUS;
iter->trace_buffer = &global_trace.trace_buffer;
}
void ftrace_dump(enum ftrace_dump_mode oops_dump_mode)
{
/* use static because iter can be a bit big for the stack */
static struct trace_iterator iter;
static atomic_t dump_running;
unsigned int old_userobj;
unsigned long flags;
int cnt = 0, cpu;
/* Only allow one dump user at a time. */
if (atomic_inc_return(&dump_running) != 1) {
atomic_dec(&dump_running);
return;
}
/*
* Always turn off tracing when we dump.
* We don't need to show trace output of what happens
* between multiple crashes.
*
* If the user does a sysrq-z, then they can re-enable
* tracing with echo 1 > tracing_on.
*/
tracing_off();
local_irq_save(flags);
/* Simulate the iterator */
trace_init_global_iter(&iter);
for_each_tracing_cpu(cpu) {
atomic_inc(&per_cpu_ptr(iter.tr->trace_buffer.data, cpu)->disabled);
}
old_userobj = trace_flags & TRACE_ITER_SYM_USEROBJ;
/* don't look at user memory in panic mode */
trace_flags &= ~TRACE_ITER_SYM_USEROBJ;
switch (oops_dump_mode) {
case DUMP_ALL:
iter.cpu_file = RING_BUFFER_ALL_CPUS;
break;
case DUMP_ORIG:
iter.cpu_file = raw_smp_processor_id();
break;
case DUMP_NONE:
goto out_enable;
default:
printk(KERN_TRACE "Bad dumping mode, switching to all CPUs dump\n");
iter.cpu_file = RING_BUFFER_ALL_CPUS;
}
printk(KERN_TRACE "Dumping ftrace buffer:\n");
/* Did function tracer already get disabled? */
if (ftrace_is_dead()) {
printk("# WARNING: FUNCTION TRACING IS CORRUPTED\n");
printk("# MAY BE MISSING FUNCTION EVENTS\n");
}
/*
* We need to stop all tracing on all CPUS to read the
* the next buffer. This is a bit expensive, but is
* not done often. We fill all what we can read,
* and then release the locks again.
*/
while (!trace_empty(&iter)) {
if (!cnt)
printk(KERN_TRACE "---------------------------------\n");
cnt++;
/* reset all but tr, trace, and overruns */
memset(&iter.seq, 0,
sizeof(struct trace_iterator) -
offsetof(struct trace_iterator, seq));
iter.iter_flags |= TRACE_FILE_LAT_FMT;
iter.pos = -1;
if (trace_find_next_entry_inc(&iter) != NULL) {
int ret;
ret = print_trace_line(&iter);
if (ret != TRACE_TYPE_NO_CONSUME)
trace_consume(&iter);
}
touch_nmi_watchdog();
trace_printk_seq(&iter.seq);
}
if (!cnt)
printk(KERN_TRACE " (ftrace buffer empty)\n");
else
printk(KERN_TRACE "---------------------------------\n");
out_enable:
trace_flags |= old_userobj;
for_each_tracing_cpu(cpu) {
atomic_dec(&per_cpu_ptr(iter.trace_buffer->data, cpu)->disabled);
}
atomic_dec(&dump_running);
local_irq_restore(flags);
}
EXPORT_SYMBOL_GPL(ftrace_dump);
__init static int tracer_alloc_buffers(void)
{
int ring_buf_size;
int ret = -ENOMEM;
if (!alloc_cpumask_var(&tracing_buffer_mask, GFP_KERNEL))
goto out;
if (!alloc_cpumask_var(&tracing_cpumask, GFP_KERNEL))
goto out_free_buffer_mask;
/* Only allocate trace_printk buffers if a trace_printk exists */
if (__stop___trace_bprintk_fmt != __start___trace_bprintk_fmt)
/* Must be called before global_trace.buffer is allocated */
trace_printk_init_buffers();
/* To save memory, keep the ring buffer size to its minimum */
if (ring_buffer_expanded)
ring_buf_size = trace_buf_size;
else
ring_buf_size = 1;
cpumask_copy(tracing_buffer_mask, cpu_possible_mask);
cpumask_copy(tracing_cpumask, cpu_all_mask);
raw_spin_lock_init(&global_trace.start_lock);
/* TODO: make the number of buffers hot pluggable with CPUS */
if (allocate_trace_buffers(&global_trace, ring_buf_size) < 0) {
printk(KERN_ERR "tracer: failed to allocate ring buffer!\n");
WARN_ON(1);
goto out_free_cpumask;
}
if (global_trace.buffer_disabled)
tracing_off();
trace_init_cmdlines();
/*
* register_tracer() might reference current_trace, so it
* needs to be set before we register anything. This is
* just a bootstrap of current_trace anyway.
*/
global_trace.current_trace = &nop_trace;
register_tracer(&nop_trace);
/* All seems OK, enable tracing */
tracing_disabled = 0;
atomic_notifier_chain_register(&panic_notifier_list,
&trace_panic_notifier);
register_die_notifier(&trace_die_notifier);
global_trace.flags = TRACE_ARRAY_FL_GLOBAL;
/* Holder for file callbacks */
global_trace.trace_cpu.cpu = RING_BUFFER_ALL_CPUS;
global_trace.trace_cpu.tr = &global_trace;
INIT_LIST_HEAD(&global_trace.systems);
INIT_LIST_HEAD(&global_trace.events);
list_add(&global_trace.list, &ftrace_trace_arrays);
while (trace_boot_options) {
char *option;
option = strsep(&trace_boot_options, ",");
trace_set_options(&global_trace, option);
}
register_snapshot_cmd();
return 0;
out_free_cpumask:
free_percpu(global_trace.trace_buffer.data);
#ifdef CONFIG_TRACER_MAX_TRACE
free_percpu(global_trace.max_buffer.data);
#endif
free_cpumask_var(tracing_cpumask);
out_free_buffer_mask:
free_cpumask_var(tracing_buffer_mask);
out:
return ret;
}
__init static int clear_boot_tracer(void)
{
/*
* The default tracer at boot buffer is an init section.
* This function is called in lateinit. If we did not
* find the boot tracer, then clear it out, to prevent
* later registration from accessing the buffer that is
* about to be freed.
*/
if (!default_bootup_tracer)
return 0;
printk(KERN_INFO "ftrace bootup tracer '%s' not registered.\n",
default_bootup_tracer);
default_bootup_tracer = NULL;
return 0;
}
early_initcall(tracer_alloc_buffers);
fs_initcall(tracer_init_debugfs);
late_initcall(clear_boot_tracer);
| gpl-2.0 |
satriani-vai/ardour | libs/pbd/pbd/demangle.h | 1625 | /*
Copyright (C) 2009 Paul Davis
Author: Sakari Bergen
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __libpbd_demangle_h__
#define __libpbd_demangle_h__
#include <string>
#include <cstdlib>
#include <typeinfo>
#ifdef __GNUC__
#include <cxxabi.h>
#endif
#include "pbd/libpbd_visibility.h"
namespace PBD
{
template<typename T> /*LIBPBD_API*/
std::string demangled_name (T const & obj)
{
#ifdef __GNUC__
int status;
char * res = abi::__cxa_demangle (typeid(obj).name(), 0, 0, &status);
if (status == 0) {
std::string s(res);
free (res);
return s;
}
#endif
/* Note: on win32, you can use UnDecorateSymbolName.
See http://msdn.microsoft.com/en-us/library/ms681400%28VS.85%29.aspx
See also: http://msdn.microsoft.com/en-us/library/ms680344%28VS.85%29.aspx
*/
return typeid(obj).name();
}
} // namespace
#endif // __libpbd_demangle_h__
| gpl-2.0 |
flavioleal/projeto-towb | inc/ruledictionnarynetworkequipmenttypecollection.class.php | 1510 | <?php
/*
* @version $Id: ruledictionnarynetworkequipmenttypecollection.class.php 22656 2014-02-12 16:15:25Z moyo $
-------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique
Copyright (C) 2003-2014 by the INDEPNET Development Team.
http://indepnet.net/ http://glpi-project.org
-------------------------------------------------------------------------
LICENSE
This file is part of GLPI.
GLPI is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
GLPI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with GLPI. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
/** @file
* @brief
*/
class RuleDictionnaryNetworkEquipmentTypeCollection extends RuleDictionnaryDropdownCollection {
public $item_table = "glpi_networkequipmenttypes";
public $menu_option = "type.networking";
/**
* @see RuleCollection::getTitle()
**/
function getTitle() {
return __('Dictionnary of network equipment types');
}
}
?>
| gpl-2.0 |
dmitry-pervushin/android-linux-linaro | arch/arm/mach-omap2/include/mach/omap-secure.h | 2021 | /*
* omap-secure.h: OMAP Secure infrastructure header.
*
* Copyright (C) 2011 Texas Instruments, Inc.
* Santosh Shilimkar <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#ifndef OMAP_ARCH_OMAP_SECURE_H
#define OMAP_ARCH_OMAP_SECURE_H
/* Monitor error code */
#define API_HAL_RET_VALUE_NS2S_CONVERSION_ERROR 0xFFFFFFFE
#define API_HAL_RET_VALUE_SERVICE_UNKNWON 0xFFFFFFFF
/* HAL API error codes */
#define API_HAL_RET_VALUE_OK 0x00
#define API_HAL_RET_VALUE_FAIL 0x01
/* Secure HAL API flags */
#define FLAG_START_CRITICAL 0x4
#define FLAG_IRQFIQ_MASK 0x3
#define FLAG_IRQ_ENABLE 0x2
#define FLAG_FIQ_ENABLE 0x1
#define NO_FLAG 0x0
/* Maximum Secure memory storage size */
#define OMAP_SECURE_RAM_STORAGE (88 * SZ_1K)
/* Secure low power HAL API index */
#define OMAP4_HAL_SAVESECURERAM_INDEX 0x1a
#define OMAP4_HAL_SAVEHW_INDEX 0x1b
#define OMAP4_HAL_SAVEALL_INDEX 0x1c
#define OMAP4_HAL_SAVEGIC_INDEX 0x1d
#define OMAP5_HAL_SAVESECURERAM_INDEX 0x1c
#define OMAP5_HAL_SAVEHW_INDEX 0x1d
#define OMAP5_HAL_SAVEALL_INDEX 0x1e
#define OMAP5_HAL_SAVEGIC_INDEX 0x1f
/* Secure Monitor mode APIs */
#define OMAP4_MON_SCU_PWR_INDEX 0x108
#define OMAP4_MON_L2X0_DBG_CTRL_INDEX 0x100
#define OMAP4_MON_L2X0_CTRL_INDEX 0x102
#define OMAP4_MON_L2X0_AUXCTRL_INDEX 0x109
#define OMAP4_MON_L2X0_PREFETCH_INDEX 0x113
#define OMAP5_MON_CACHES_CLEAN_INDEX 0x103
/* Secure PPA(Primary Protected Application) APIs */
#define OMAP4_PPA_SERVICE_0 0x21
#define OMAP4_PPA_L2_POR_INDEX 0x23
#define OMAP4_PPA_CPU_ACTRL_SMP_INDEX 0x25
#ifndef __ASSEMBLER__
extern u32 omap_secure_dispatcher(u32 idx, u32 flag, u32 nargs,
u32 arg1, u32 arg2, u32 arg3, u32 arg4);
extern u32 omap_smc2(u32 id, u32 falg, u32 pargs);
extern phys_addr_t omap_secure_ram_mempool_base(void);
#endif /* __ASSEMBLER__ */
#endif /* OMAP_ARCH_OMAP_SECURE_H */
| gpl-2.0 |
CyanogenMod/android_external_syslinux | utils/isohybrid.pl | 13971 | #!/usr/bin/perl
## -----------------------------------------------------------------------
##
## Copyright 2002-2008 H. Peter Anvin - All Rights Reserved
## Copyright 2009 Intel Corporation; author: H. Peter Anvin
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, Inc., 53 Temple Place Ste 330,
## Boston MA 02111-1307, USA; either version 2 of the License, or
## (at your option) any later version; incorporated herein by reference.
##
## -----------------------------------------------------------------------
#
# Post-process an ISO 9660 image generated with mkisofs/genisoimage
# to allow "hybrid booting" as a CD-ROM or as a hard disk.
#
use bytes;
use Fcntl;
# User-specifyable options
%opt = (
# Fake geometry (zipdrive-style...)
'h' => 64,
's' => 32,
# Partition number
'entry' => 1,
# Partition offset
'offset' => 0,
# Partition type
'type' => 0x17, # "Windows hidden IFS"
# MBR ID
'id' => undef,
);
%valid_range = (
'h' => [1, 256],
's' => [1, 63],
'entry' => [1, 4],
'offset' => [0, 64],
'type' => [0, 255],
'id' => [0, 0xffffffff],
'hd0' => [0, 2],
'partok' => [0, 1],
);
# Boolean options just set other options
%bool_opt = (
'nohd0' => ['hd0', 0],
'forcehd0' => ['hd0', 1],
'ctrlhd0' => ['hd0', 2],
'nopartok' => ['partok', 0],
'partok' => ['partok', 1],
);
sub usage() {
print STDERR "Usage: $0 [options] filename.iso\n",
"Options:\n",
" -h Number of default geometry heads\n",
" -s Number of default geometry sectors\n",
" -entry Specify partition entry number (1-4)\n",
" -offset Specify partition offset (default 0)\n",
" -type Specify partition type (default 0x17)\n",
" -id Specify MBR ID (default random)\n",
" -forcehd0 Always assume we are loaded as disk ID 0\n",
" -ctrlhd0 Assume disk ID 0 if the Ctrl key is pressed\n",
" -partok Allow booting from within a partition\n";
exit 1;
}
# Parse a C-style integer (decimal/octal/hex)
sub doh($) {
my($n) = @_;
return ($n =~ /^0/) ? oct $n : $n+0;
}
sub get_random() {
# Get a 32-bit random number
my $rfd, $rnd;
my $rid;
if (open($rfd, "< /dev/urandom\0") && read($rfd, $rnd, 4) == 4) {
$rid = unpack("V", $rnd);
}
close($rfd) if (defined($rfd));
return $rid if (defined($rid));
# This sucks but is better than nothing...
return ($$+time()) & 0xffffffff;
}
sub get_hex_data() {
my $mbr = '';
my $line, $byte;
while ( $line = <DATA> ) {
chomp $line;
last if ($line eq '*');
foreach $byte ( split(/\s+/, $line) ) {
$mbr .= chr(hex($byte));
}
}
return $mbr;
}
while ($ARGV[0] =~ /^\-(.*)$/) {
$o = $1;
shift @ARGV;
if (defined($bool_opt{$o})) {
($o, $v) = @{$bool_opt{$o}};
$opt{$o} = $v;
} elsif (exists($opt{$o})) {
$opt{$o} = doh(shift @ARGV);
if (defined($valid_range{$o})) {
($l, $h) = @{$valid_range{$o}};
if ($opt{$o} < $l || $opt{$o} > $h) {
die "$0: valid values for the -$o parameter are $l to $h\n";
}
}
} else {
usage();
}
}
($file) = @ARGV;
if (!defined($file)) {
usage();
}
open(FILE, "+< $file\0") or die "$0: cannot open $file: $!\n";
binmode FILE;
#
# First, actually figure out where mkisofs hid isolinux.bin
#
seek(FILE, 17*2048, SEEK_SET) or die "$0: $file: $!\n";
read(FILE, $boot_record, 2048) == 2048 or die "$0: $file: read error\n";
($br_sign, $br_cat_offset) = unpack("a71V", $boot_record);
if ($br_sign ne ("\0CD001\1EL TORITO SPECIFICATION" . ("\0" x 41))) {
die "$0: $file: no boot record found\n";
}
seek(FILE, $br_cat_offset*2048, SEEK_SET) or die "$0: $file: $!\n";
read(FILE, $boot_cat, 2048) == 2048 or die "$0: $file: read error\n";
# We must have a Validation Entry followed by a Default Entry...
# no fanciness allowed for the Hybrid mode [XXX: might relax this later]
@ve = unpack("v16", $boot_cat);
$cs = 0;
for ($i = 0; $i < 16; $i++) {
$cs += $ve[$i];
}
if ($ve[0] != 0x0001 || $ve[15] != 0xaa55 || $cs & 0xffff) {
die "$0: $file: invalid boot catalog\n";
}
($de_boot, $de_media, $de_seg, $de_sys, $de_mbz1, $de_count,
$de_lba, $de_mbz2) = unpack("CCvCCvVv", substr($boot_cat, 32, 32));
if ($de_boot != 0x88 || $de_media != 0 ||
($de_segment != 0 && $de_segment != 0x7c0) || $de_count != 4) {
die "$0: $file: unexpected boot catalog parameters\n";
}
# Now $de_lba should contain the CD sector number for isolinux.bin
seek(FILE, $de_lba*2048+0x40, SEEK_SET) or die "$0: $file: $!\n";
read(FILE, $ibsig, 4);
if ($ibsig ne "\xfb\xc0\x78\x70") {
die "$0: $file: bootloader does not have a isolinux.bin hybrid signature.".
"Note that isolinux-debug.bin does not support hybrid booting.\n";
}
# Get the total size of the image
(@imgstat = stat(FILE)) or die "$0: $file: $!\n";
$imgsize = $imgstat[7];
if (!$imgsize) {
die "$0: $file: cannot determine length of file\n";
}
# Target image size: round up to a multiple of $h*$s*512
$h = $opt{'h'};
$s = $opt{'s'};
$cylsize = $h*$s*512;
$frac = $imgsize % $cylsize;
$padding = ($frac > 0) ? $cylsize - $frac : 0;
$imgsize += $padding;
$c = int($imgsize/$cylsize);
if ($c > 1024) {
print STDERR "Warning: more than 1024 cylinders ($c).\n";
print STDERR "Not all BIOSes will be able to boot this device.\n";
$cc = 1024;
} else {
$cc = $c;
}
# Preserve id when run again
if (defined($opt{'id'})) {
$id = pack("V", doh($opt{'id'}));
} else {
seek(FILE, 440, SEEK_SET) or die "$0: $file: $!\n";
read(FILE, $id, 4);
if ($id eq "\x00\x00\x00\x00") {
$id = pack("V", get_random());
}
}
# Print the MBR and partition table
seek(FILE, 0, SEEK_SET) or die "$0: $file: $!\n";
for ($i = 0; $i <= $opt{'hd0'}+3*$opt{'partok'}; $i++) {
$mbr = get_hex_data();
}
if ( length($mbr) > 432 ) {
die "$0: Bad MBR code\n";
}
$mbr .= "\0" x (432 - length($mbr));
$mbr .= pack("VV", $de_lba*4, 0); # Offset 432: LBA of isolinux.bin
$mbr .= $id; # Offset 440: MBR ID
$mbr .= "\0\0"; # Offset 446: actual partition table
# Print partition table
$offset = $opt{'offset'};
$psize = $c*$h*$s - $offset;
$bhead = int($offset/$s) % $h;
$bsect = ($offset % $s) + 1;
$bcyl = int($offset/($h*$s));
$bsect += ($bcyl & 0x300) >> 2;
$bcyl &= 0xff;
$ehead = $h-1;
$esect = $s + ((($cc-1) & 0x300) >> 2);
$ecyl = ($cc-1) & 0xff;
$fstype = $opt{'type'}; # Partition type
$pentry = $opt{'entry'}; # Partition slot
for ( $i = 1 ; $i <= 4 ; $i++ ) {
if ( $i == $pentry ) {
$mbr .= pack("CCCCCCCCVV", 0x80, $bhead, $bsect, $bcyl, $fstype,
$ehead, $esect, $ecyl, $offset, $psize);
} else {
$mbr .= "\0" x 16;
}
}
$mbr .= "\x55\xaa";
print FILE $mbr;
# Pad the image to a fake cylinder boundary
seek(FILE, $imgstat[7], SEEK_SET) or die "$0: $file: $!\n";
if ($padding) {
print FILE "\0" x $padding;
}
# Done...
close(FILE);
exit 0;
__END__
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 66 53 66 51 6 57 8e dd 8e c5
52 be 0 7c bf 0 6 b9 0 1 f3 a5 ea 2b 6 0 0 52 b4 41 bb aa 55 31 c9 30 f6 f9
cd 13 72 16 81 fb 55 aa 75 10 83 e1 1 74 b 66 c7 6 d1 6 b4 42 eb 15 eb 0 5a
51 b4 8 cd 13 83 e1 3f 5b 51 f b6 c6 40 50 f7 e1 53 52 50 bb 0 7c b9 4 0 66
a1 b0 7 e8 44 0 f 82 80 0 66 40 80 c7 2 e2 f2 66 81 3e 40 7c fb c0 78 70 75
9 fa bc ec 7b ea 44 7c 0 0 e8 83 0 69 73 6f 6c 69 6e 75 78 2e 62 69 6e 20
6d 69 73 73 69 6e 67 20 6f 72 20 63 6f 72 72 75 70 74 2e d a 66 60 66 31 d2
66 3 6 f8 7b 66 13 16 fc 7b 66 52 66 50 6 53 6a 1 6a 10 89 e6 66 f7 36 e8
7b c0 e4 6 88 e1 88 c5 92 f6 36 ee 7b 88 c6 8 e1 41 b8 1 2 8a 16 f2 7b cd
13 8d 64 10 66 61 c3 e8 1e 0 4f 70 65 72 61 74 69 6e 67 20 73 79 73 74 65
6d 20 6c 6f 61 64 20 65 72 72 6f 72 2e d a 5e ac b4 e 8a 3e 62 4 b3 7 cd 10
3c a 75 f1 cd 18 f4 eb fd 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 66 53 66 51 6 57 8e dd 8e c5
b2 80 52 be 0 7c bf 0 6 b9 0 1 f3 a5 ea 2d 6 0 0 52 b4 41 bb aa 55 31 c9 30
f6 f9 cd 13 72 16 81 fb 55 aa 75 10 83 e1 1 74 b 66 c7 6 d3 6 b4 42 eb 15
eb 0 5a 51 b4 8 cd 13 83 e1 3f 5b 51 f b6 c6 40 50 f7 e1 53 52 50 bb 0 7c
b9 4 0 66 a1 b0 7 e8 44 0 f 82 80 0 66 40 80 c7 2 e2 f2 66 81 3e 40 7c fb
c0 78 70 75 9 fa bc ec 7b ea 44 7c 0 0 e8 83 0 69 73 6f 6c 69 6e 75 78 2e
62 69 6e 20 6d 69 73 73 69 6e 67 20 6f 72 20 63 6f 72 72 75 70 74 2e d a 66
60 66 31 d2 66 3 6 f8 7b 66 13 16 fc 7b 66 52 66 50 6 53 6a 1 6a 10 89 e6
66 f7 36 e8 7b c0 e4 6 88 e1 88 c5 92 f6 36 ee 7b 88 c6 8 e1 41 b8 1 2 8a
16 f2 7b cd 13 8d 64 10 66 61 c3 e8 1e 0 4f 70 65 72 61 74 69 6e 67 20 73
79 73 74 65 6d 20 6c 6f 61 64 20 65 72 72 6f 72 2e d a 5e ac b4 e 8a 3e 62
4 b3 7 cd 10 3c a 75 f1 cd 18 f4 eb fd 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0
*
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 66 53 66 51 6 57 8e dd 8e c5
f6 6 17 4 4 74 2 b2 80 52 be 0 7c bf 0 6 b9 0 1 f3 a5 ea 34 6 0 0 52 b4 41
bb aa 55 31 c9 30 f6 f9 cd 13 72 16 81 fb 55 aa 75 10 83 e1 1 74 b 66 c7 6
da 6 b4 42 eb 15 eb 0 5a 51 b4 8 cd 13 83 e1 3f 5b 51 f b6 c6 40 50 f7 e1
53 52 50 bb 0 7c b9 4 0 66 a1 b0 7 e8 44 0 f 82 80 0 66 40 80 c7 2 e2 f2 66
81 3e 40 7c fb c0 78 70 75 9 fa bc ec 7b ea 44 7c 0 0 e8 83 0 69 73 6f 6c
69 6e 75 78 2e 62 69 6e 20 6d 69 73 73 69 6e 67 20 6f 72 20 63 6f 72 72 75
70 74 2e d a 66 60 66 31 d2 66 3 6 f8 7b 66 13 16 fc 7b 66 52 66 50 6 53 6a
1 6a 10 89 e6 66 f7 36 e8 7b c0 e4 6 88 e1 88 c5 92 f6 36 ee 7b 88 c6 8 e1
41 b8 1 2 8a 16 f2 7b cd 13 8d 64 10 66 61 c3 e8 1e 0 4f 70 65 72 61 74 69
6e 67 20 73 79 73 74 65 6d 20 6c 6f 61 64 20 65 72 72 6f 72 2e d a 5e ac b4
e 8a 3e 62 4 b3 7 cd 10 3c a 75 f1 cd 18 f4 eb fd 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 21 f6 74 26 f6 4 7f 75 21 38
4c 4 74 1c 66 3d 21 47 50 58 75 10 80 7c 4 ed 75 a 66 8b 4c 34 66 8b 5c 38
eb 4 66 8b 4c 8 66 53 66 51 6 57 8e dd 8e c5 52 be 0 7c bf 0 6 b9 0 1 f3 a5
ea 55 6 0 0 52 b4 41 bb aa 55 31 c9 30 f6 f9 cd 13 72 16 81 fb 55 aa 75 10
83 e1 1 74 b 66 c7 6 fb 6 b4 42 eb 15 eb 0 5a 51 b4 8 cd 13 83 e1 3f 5b 51
f b6 c6 40 50 f7 e1 53 52 50 bb 0 7c b9 4 0 66 a1 b0 7 e8 44 0 f 82 80 0 66
40 80 c7 2 e2 f2 66 81 3e 40 7c fb c0 78 70 75 9 fa bc ec 7b ea 44 7c 0 0
e8 83 0 69 73 6f 6c 69 6e 75 78 2e 62 69 6e 20 6d 69 73 73 69 6e 67 20 6f
72 20 63 6f 72 72 75 70 74 2e d a 66 60 66 31 d2 66 3 6 f8 7b 66 13 16 fc
7b 66 52 66 50 6 53 6a 1 6a 10 89 e6 66 f7 36 e8 7b c0 e4 6 88 e1 88 c5 92
f6 36 ee 7b 88 c6 8 e1 41 b8 1 2 8a 16 f2 7b cd 13 8d 64 10 66 61 c3 e8 1e
0 4f 70 65 72 61 74 69 6e 67 20 73 79 73 74 65 6d 20 6c 6f 61 64 20 65 72
72 6f 72 2e d a 5e ac b4 e 8a 3e 62 4 b3 7 cd 10 3c a 75 f1 cd 18 f4 eb fd
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 21 f6 74 26 f6 4 7f 75 21 38
4c 4 74 1c 66 3d 21 47 50 58 75 10 80 7c 4 ed 75 a 66 8b 4c 34 66 8b 5c 38
eb 4 66 8b 4c 8 66 53 66 51 6 57 8e dd 8e c5 b2 80 52 be 0 7c bf 0 6 b9 0
1 f3 a5 ea 57 6 0 0 52 b4 41 bb aa 55 31 c9 30 f6 f9 cd 13 72 16 81 fb 55
aa 75 10 83 e1 1 74 b 66 c7 6 fd 6 b4 42 eb 15 eb 0 5a 51 b4 8 cd 13 83 e1
3f 5b 51 f b6 c6 40 50 f7 e1 53 52 50 bb 0 7c b9 4 0 66 a1 b0 7 e8 44 0 f
82 80 0 66 40 80 c7 2 e2 f2 66 81 3e 40 7c fb c0 78 70 75 9 fa bc ec 7b ea
44 7c 0 0 e8 83 0 69 73 6f 6c 69 6e 75 78 2e 62 69 6e 20 6d 69 73 73 69 6e
67 20 6f 72 20 63 6f 72 72 75 70 74 2e d a 66 60 66 31 d2 66 3 6 f8 7b 66
13 16 fc 7b 66 52 66 50 6 53 6a 1 6a 10 89 e6 66 f7 36 e8 7b c0 e4 6 88 e1
88 c5 92 f6 36 ee 7b 88 c6 8 e1 41 b8 1 2 8a 16 f2 7b cd 13 8d 64 10 66 61
c3 e8 1e 0 4f 70 65 72 61 74 69 6e 67 20 73 79 73 74 65 6d 20 6c 6f 61 64
20 65 72 72 6f 72 2e d a 5e ac b4 e 8a 3e 62 4 b3 7 cd 10 3c a 75 f1 cd 18
f4 eb fd 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*
33 ed fa 8e d5 bc 0 7c fb fc 66 31 db 66 31 c9 21 f6 74 26 f6 4 7f 75 21 38
4c 4 74 1c 66 3d 21 47 50 58 75 10 80 7c 4 ed 75 a 66 8b 4c 34 66 8b 5c 38
eb 4 66 8b 4c 8 66 53 66 51 6 57 8e dd 8e c5 f6 6 17 4 4 74 2 b2 80 52 be
0 7c bf 0 6 b9 0 1 f3 a5 ea 5e 6 0 0 52 b4 41 bb aa 55 31 c9 30 f6 f9 cd 13
72 16 81 fb 55 aa 75 10 83 e1 1 74 b 66 c7 6 4 7 b4 42 eb 15 eb 0 5a 51 b4
8 cd 13 83 e1 3f 5b 51 f b6 c6 40 50 f7 e1 53 52 50 bb 0 7c b9 4 0 66 a1 b0
7 e8 44 0 f 82 80 0 66 40 80 c7 2 e2 f2 66 81 3e 40 7c fb c0 78 70 75 9 fa
bc ec 7b ea 44 7c 0 0 e8 83 0 69 73 6f 6c 69 6e 75 78 2e 62 69 6e 20 6d 69
73 73 69 6e 67 20 6f 72 20 63 6f 72 72 75 70 74 2e d a 66 60 66 31 d2 66 3
6 f8 7b 66 13 16 fc 7b 66 52 66 50 6 53 6a 1 6a 10 89 e6 66 f7 36 e8 7b c0
e4 6 88 e1 88 c5 92 f6 36 ee 7b 88 c6 8 e1 41 b8 1 2 8a 16 f2 7b cd 13 8d
64 10 66 61 c3 e8 1e 0 4f 70 65 72 61 74 69 6e 67 20 73 79 73 74 65 6d 20
6c 6f 61 64 20 65 72 72 6f 72 2e d a 5e ac b4 e 8a 3e 62 4 b3 7 cd 10 3c a
75 f1 cd 18 f4 eb fd 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
*
| gpl-2.0 |
Gurgel100/gcc | libstdc++-v3/testsuite/20_util/underlying_type/requirements/alias_decl.cc | 1091 | // { dg-do compile { target c++14 } }
//
// Copyright (C) 2013-2021 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
//
// NB: This file is for testing type_traits with NO OTHER INCLUDES.
#include <type_traits>
using namespace std;
enum E : long { };
static_assert( is_same<typename underlying_type<E>::type,
underlying_type_t<E>>(),
"underlying_type_t" );
| gpl-2.0 |
sharpmachine/unlikelyheroes.com | wp-content/plugins/ignitiondeck/templates/admin/_deckBuilder.php | 3759 | <div class="wrap">
<div class="postbox-container" style="width:95%; margin-right: 5%">
<div class="metabox-holder">
<div class="meta-box-sortables" style="min-height:0;">
<div class="postbox">
<h3 class="hndle"><span><?php echo $tr_Deck_Builder; ?></span></h3>
<div class="inside">
<p style="width: 50%"><?php echo $tr_Select_Components; ?></p>
<form method="POST" action="" id="idmsg-settings" name="idmsg-settings">
<div class="form-select">
<p>
<label for="deck_select"><?php echo $tr_Create_Select; ?></label><br/>
<select name="deck_select" id="deck_select">
<option><?php echo $tr_New_Deck; ?></option>
</select>
</p>
</div>
<div class="form-input">
<p>
<label for="deck_title"><?php echo $tr_Deck_Title; ?></label><br/>
<input type="text" name="deck_title" id="deck_title" class="deck-attr-text" value="" />
</p>
</div>
<div class="form-check">
<input type="checkbox" name="project_title" id="project_title" class="deck-attr" value="1"/>
<label for="project_title"><?php echo $tr_Project_Title; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_image" id="project_image" class="deck-attr" value="1"/>
<label for="project_image"><?php echo $tr_Product_Image; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_bar" id="project_bar" class="deck-attr" value="1"/>
<label for="project_bar"><?php echo $tr_Percentage_Bar; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_pledged" id="project_pledged" class="deck-attr" value="1"/>
<label for="project_pledged"><?php echo $tr_Total_Raised; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_goal" id="project_goal" class="deck-attr" value="1"/>
<label for="project_goal"><?php echo $tr_Project_Goal; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_pledgers" id="project_pledgers" class="deck-attr" value="1"/>
<label for="project_pledgers"><?php echo $tr_Total_Orders; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="days_left" id="days_left" class="deck-attr" value="1"/>
<label for="days_left"><?php echo $tr_Days_To_Go; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_end" id="project_end" class="deck-attr" value="1"/>
<label for="project_end"><?php echo $tr_End_Date; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_button" id="project_button" class="deck-attr" value="1"/>
<label for="project_button"><?php echo $tr_Buy_Button; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_description" id="project_description" class="deck-attr" value="1"/>
<label for="project_description"><?php echo $tr_meta_project_description; ?></label>
</div>
<div class="form-check">
<input type="checkbox" name="project_levels" id="project_levels" class="deck-attr" value="1"/>
<label for="project_levels"><?php echo $tr_Levels; ?></label>
</div>
<div class="submit">
<input type="submit" name="deck_submit" id="submit" class="button button-primary"/>
<input type="submit" name="deck_delete" id="deck_delete" class="button" value="Delete Deck" style="display: none;"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div> | gpl-2.0 |
RemanenceStudio/intuisens | wp-content/themes/intuisens/js/foundation/jquery.foundation.tabs.js | 1977 | ;(function ($, window, document, undefined) {
'use strict';
var settings = {
callback: $.noop,
deep_linking: true,
init: false
},
methods = {
init : function (options) {
settings = $.extend({}, options, settings);
return this.each(function () {
if (!settings.init) methods.events();
if (settings.deep_linking) methods.from_hash();
});
},
events : function () {
$(document).on('click.fndtn', '.tabs a', function (e) {
methods.set_tab($(this).parent('dd, li'), e);
});
settings.init = true;
},
set_tab : function ($tab, e) {
var $activeTab = $tab.closest('dl, ul').find('.active'),
target = $tab.children('a').attr("href"),
hasHash = /^#/.test(target),
$content = $(target + 'Tab');
if (hasHash && $content.length > 0) {
// Show tab content
if (e && !settings.deep_linking) e.preventDefault();
$content.closest('.tabs-content').children('li').removeClass('active').hide();
$content.css('display', 'block').addClass('active');
}
// Make active tab
$activeTab.removeClass('active');
$tab.addClass('active');
settings.callback();
},
from_hash : function () {
var hash = window.location.hash,
$tab = $('a[href="' + hash + '"]');
$tab.trigger('click.fndtn');
}
}
$.fn.foundationTabs = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.foundationTabs');
}
};
}(jQuery, this, this.document)); | gpl-2.0 |
heqiaoliu/Viral-Dark-Matter | tmp/install_4f209c9de9bf1/plugins/system/jat3/base-themes/default/page/ajax.modules.php | 657 | <?php
/**
* ------------------------------------------------------------------------
* T3V2 Framework
* ------------------------------------------------------------------------
* Copyright (C) 2004-20011 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
* @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
* Author: J.O.O.M Solutions Co., Ltd
* Websites: http://www.joomlart.com - http://www.joomlancers.com
* ------------------------------------------------------------------------
*/
// no direct access
defined('_JEXEC') or die('Restricted access');
?>
<jdoc:include type="modules" name="<?php echo JRequest::getCmd ('name') ?>" /> | gpl-2.0 |
brotalnia/TrinityZero | contrib/extractor/System.cpp | 6690 | #define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <deque>
#include <set>
#ifdef WIN32
#include "direct.h"
#else
#include <sys/stat.h>
#endif
#include "dbcfile.h"
#include "mpq_libmpq.h"
extern unsigned int iRes;
extern ArchiveSet gOpenArchives;
bool ConvertADT(char*,char*);
typedef struct{
char name[64];
unsigned int id;
}map_id;
typedef unsigned char uint8;
typedef unsigned short uint16;
typedef unsigned int uint32;
map_id * map_ids;
uint16 * areas;
char output_path[128]=".";
char input_path[128]=".";
enum Extract
{
EXTRACT_MAP = 1,
EXTRACT_DBC = 2
};
int extract = EXTRACT_MAP | EXTRACT_DBC;
#define ADT_RES 64
void CreateDir( const std::string& Path )
{
#ifdef WIN32
_mkdir( Path.c_str());
#else
mkdir( Path.c_str(), 0777 );
#endif
}
bool FileExists( const char* FileName )
{
if(FILE* fp = fopen( FileName, "rb" ))
{
fclose(fp);
return true;
}
return false;
}
void Usage(char* prg)
{
printf("Usage:\n%s -[var] [value]\n-i set input path\n-o set output path\n-r set resolution\n-e extract only MAP(1)/DBC(2) - standard: both(3)\nExample: %s -r 256 -i \"c:\\games\\game\"",
prg,prg);
exit(1);
}
void HandleArgs(int argc, char * arg[])
{
for(int c=1;c<argc;c++)
{
//i - input path
//o - output path
//r - resolution, array of (r * r) heights will be created
//e - extract only MAP(1)/DBC(2) - standard both(3)
if(arg[c][0] != '-')
Usage(arg[0]);
switch(arg[c][1])
{
case 'i':
if(c+1<argc)//all ok
strcpy(input_path,arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'o':
if(c+1<argc)//all ok
strcpy(output_path,arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'r':
if(c+1<argc)//all ok
iRes=atoi(arg[(c++) +1]);
else
Usage(arg[0]);
break;
case 'e':
if(c+1<argc)//all ok
{
extract=atoi(arg[(c++) +1]);
if(!(extract > 0 && extract < 4))
Usage(arg[0]);
}
else
Usage(arg[0]);
break;
}
}
}
uint32 ReadMapDBC()
{
printf("Read Map.dbc file... ");
DBCFile dbc("DBFilesClient\\Map.dbc");
dbc.open();
uint32 map_count=dbc.getRecordCount();
map_ids=new map_id[map_count];
for(unsigned int x=0;x<map_count;x++)
{
map_ids[x].id=dbc.getRecord(x).getUInt(0);
strcpy(map_ids[x].name,dbc.getRecord(x).getString(1));
}
printf("Done! (%u maps loaded)\n", map_count);
return map_count;
}
void ReadAreaTableDBC()
{
printf("Read AreaTable.dbc file... ");
DBCFile dbc("DBFilesClient\\AreaTable.dbc");
dbc.open();
unsigned int area_count=dbc.getRecordCount();
uint32 maxid = dbc.getMaxId();
areas=new uint16[maxid + 1];
memset(areas, 0xff, sizeof(areas));
for(unsigned int x=0; x<area_count;++x)
areas[dbc.getRecord(x).getUInt(0)] = dbc.getRecord(x).getUInt(3);
printf("Done! (%u areas loaded)\n", area_count);
}
void ExtractMapsFromMpq()
{
char mpq_filename[1024];
char output_filename[1024];
printf("Extracting maps...\n");
uint32 map_count = ReadMapDBC();
ReadAreaTableDBC();
unsigned int total=map_count*ADT_RES*ADT_RES;
unsigned int done=0;
std::string path = output_path;
path += "/maps/";
CreateDir(path);
for(unsigned int x = 0; x < ADT_RES; ++x)
{
for(unsigned int y = 0; y < ADT_RES; ++y)
{
for(unsigned int z = 0; z < map_count; ++z)
{
sprintf(mpq_filename,"World\\Maps\\%s\\%s_%u_%u.adt",map_ids[z].name,map_ids[z].name,x,y);
sprintf(output_filename,"%s/maps/%03u%02u%02u.map",output_path,map_ids[z].id,y,x);
ConvertADT(mpq_filename,output_filename);
done++;
}
//draw progess bar
printf("Processing........................%d%%\r",(100*done)/total);
}
}
delete [] areas;
delete [] map_ids;
}
//bool WMO(char* filename);
void ExtractDBCFiles()
{
printf("Extracting dbc files...\n");
set<string> dbcfiles;
// get DBC file list
for(ArchiveSet::iterator i = gOpenArchives.begin(); i != gOpenArchives.end();++i)
{
vector<string> files;
(*i)->GetFileListTo(files);
for (vector<string>::iterator iter = files.begin(); iter != files.end(); ++iter)
if (iter->rfind(".dbc") == iter->length() - strlen(".dbc"))
dbcfiles.insert(*iter);
}
string path = output_path;
path += "/dbc/";
CreateDir(path);
// extract DBCs
int count = 0;
for (set<string>::iterator iter = dbcfiles.begin(); iter != dbcfiles.end(); ++iter)
{
string filename = path;
filename += (iter->c_str() + strlen("DBFilesClient\\"));
FILE *output=fopen(filename.c_str(), "wb");
if(!output)
{
printf("Can't create the output file '%s'\n", filename.c_str());
continue;
}
MPQFile m(iter->c_str());
if(!m.isEof())
fwrite(m.getPointer(), 1, m.getSize(), output);
fclose(output);
++count;
}
printf("Extracted %u DBC files\n\n", count);
}
void LoadCommonMPQFiles()
{
char filename[512];
sprintf(filename,"%s/Data/terrain.MPQ", input_path);
new MPQArchive(filename);
sprintf(filename,"%s/Data/dbc.MPQ", input_path);
new MPQArchive(filename);
for(int i = 1; i < 5; ++i)
{
char ext[3] = "";
if(i > 1)
sprintf(ext, "-%i", i);
sprintf(filename,"%s/Data/patch%s.MPQ", input_path, ext);
if(FileExists(filename))
new MPQArchive(filename);
}
}
inline void CloseMPQFiles()
{
for(ArchiveSet::iterator j = gOpenArchives.begin(); j != gOpenArchives.end();++j) (*j)->close();
gOpenArchives.clear();
}
int main(int argc, char * arg[])
{
printf("Map & DBC Extractor\n");
printf("===================\n\n");
HandleArgs(argc, arg);
if (extract & EXTRACT_MAP)
{
printf("Loading files.. \n");
// Open MPQs
LoadCommonMPQFiles();
// Extract dbc
ExtractDBCFiles();
// Extract maps
ExtractMapsFromMpq();
// Close MPQs
CloseMPQFiles();
}
return 0;
}
| gpl-2.0 |
spezi77/hellspawn-N4 | arch/arm/mm/dma-mapping.c | 44951 | /*
* linux/arch/arm/mm/dma-mapping.c
*
* Copyright (C) 2000-2004 Russell King
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* DMA uncached mapping support.
*/
#include <linux/module.h>
#include <linux/mm.h>
#include <linux/gfp.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/dma-mapping.h>
#include <linux/dma-contiguous.h>
#include <linux/highmem.h>
#include <linux/memblock.h>
#include <linux/slab.h>
#include <linux/iommu.h>
#include <linux/vmalloc.h>
#include <asm/memory.h>
#include <asm/highmem.h>
#include <asm/cacheflush.h>
#include <asm/tlbflush.h>
#include <asm/sizes.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/system_info.h>
#include <asm/dma-contiguous.h>
#include <asm/dma-iommu.h>
#include "mm.h"
/*
* The DMA API is built upon the notion of "buffer ownership". A buffer
* is either exclusively owned by the CPU (and therefore may be accessed
* by it) or exclusively owned by the DMA device. These helper functions
* represent the transitions between these two ownership states.
*
* Note, however, that on later ARMs, this notion does not work due to
* speculative prefetches. We model our approach on the assumption that
* the CPU does do speculative prefetches, which means we clean caches
* before transfers and delay cache invalidation until transfer completion.
*
*/
static void __dma_page_cpu_to_dev(struct page *, unsigned long,
size_t, enum dma_data_direction);
static void __dma_page_dev_to_cpu(struct page *, unsigned long,
size_t, enum dma_data_direction);
/**
* arm_dma_map_page - map a portion of a page for streaming DMA
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @page: page that buffer resides in
* @offset: offset into page for start of buffer
* @size: size of buffer to map
* @dir: DMA transfer direction
*
* Ensure that any data held in the cache is appropriately discarded
* or written back.
*
* The device owns this memory once this call has completed. The CPU
* can regain ownership by calling dma_unmap_page().
*/
static dma_addr_t arm_dma_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
return pfn_to_dma(dev, page_to_pfn(page)) + offset;
}
/**
* arm_dma_unmap_page - unmap a buffer previously mapped through dma_map_page()
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @handle: DMA address of buffer
* @size: size of buffer (same as passed to dma_map_page)
* @dir: DMA transfer direction (same as passed to dma_map_page)
*
* Unmap a page streaming mode DMA translation. The handle and size
* must match what was provided in the previous dma_map_page() call.
* All other usages are undefined.
*
* After this call, reads by the CPU to the buffer are guaranteed to see
* whatever the device wrote there.
*/
static void arm_dma_unmap_page(struct device *dev, dma_addr_t handle,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
if (!arch_is_coherent())
__dma_page_dev_to_cpu(pfn_to_page(dma_to_pfn(dev, handle)),
handle & ~PAGE_MASK, size, dir);
}
static void arm_dma_sync_single_for_cpu(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
unsigned int offset = handle & (PAGE_SIZE - 1);
struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
}
static void arm_dma_sync_single_for_device(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
unsigned int offset = handle & (PAGE_SIZE - 1);
struct page *page = pfn_to_page(dma_to_pfn(dev, handle-offset));
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
}
static int arm_dma_set_mask(struct device *dev, u64 dma_mask);
struct dma_map_ops arm_dma_ops = {
.alloc = arm_dma_alloc,
.free = arm_dma_free,
.mmap = arm_dma_mmap,
.map_page = arm_dma_map_page,
.unmap_page = arm_dma_unmap_page,
.map_sg = arm_dma_map_sg,
.unmap_sg = arm_dma_unmap_sg,
.sync_single_for_cpu = arm_dma_sync_single_for_cpu,
.sync_single_for_device = arm_dma_sync_single_for_device,
.sync_sg_for_cpu = arm_dma_sync_sg_for_cpu,
.sync_sg_for_device = arm_dma_sync_sg_for_device,
.set_dma_mask = arm_dma_set_mask,
};
EXPORT_SYMBOL(arm_dma_ops);
static u64 get_coherent_dma_mask(struct device *dev)
{
u64 mask = (u64)arm_dma_limit;
if (dev) {
mask = dev->coherent_dma_mask;
/*
* Sanity check the DMA mask - it must be non-zero, and
* must be able to be satisfied by a DMA allocation.
*/
if (mask == 0) {
dev_warn(dev, "coherent DMA mask is unset\n");
return 0;
}
if ((~mask) & (u64)arm_dma_limit) {
dev_warn(dev, "coherent DMA mask %#llx is smaller "
"than system GFP_DMA mask %#llx\n",
mask, (u64)arm_dma_limit);
return 0;
}
}
return mask;
}
static void __dma_clear_buffer(struct page *page, size_t size)
{
void *ptr;
/*
* Ensure that the allocated pages are zeroed, and that any data
* lurking in the kernel direct-mapped region is invalidated.
*/
ptr = page_address(page);
if (ptr) {
memset(ptr, 0, size);
dmac_flush_range(ptr, ptr + size);
outer_flush_range(__pa(ptr), __pa(ptr) + size);
}
}
/*
* Allocate a DMA buffer for 'dev' of size 'size' using the
* specified gfp mask. Note that 'size' must be page aligned.
*/
static struct page *__dma_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
{
unsigned long order = get_order(size);
struct page *page, *p, *e;
page = alloc_pages(gfp, order);
if (!page)
return NULL;
/*
* Now split the huge page and free the excess pages
*/
split_page(page, order);
for (p = page + (size >> PAGE_SHIFT), e = page + (1 << order); p < e; p++)
__free_page(p);
__dma_clear_buffer(page, size);
return page;
}
/*
* Free a DMA buffer. 'size' must be page aligned.
*/
static void __dma_free_buffer(struct page *page, size_t size)
{
struct page *e = page + (size >> PAGE_SHIFT);
while (page < e) {
__free_page(page);
page++;
}
}
#ifdef CONFIG_MMU
#define CONSISTENT_OFFSET(x) (((unsigned long)(x) - consistent_base) >> PAGE_SHIFT)
#define CONSISTENT_PTE_INDEX(x) (((unsigned long)(x) - consistent_base) >> PMD_SHIFT)
/*
* These are the page tables (2MB each) covering uncached, DMA consistent allocations
*/
static pte_t **consistent_pte;
#define DEFAULT_CONSISTENT_DMA_SIZE (7*SZ_2M)
static unsigned long consistent_base = CONSISTENT_END - DEFAULT_CONSISTENT_DMA_SIZE;
void __init init_consistent_dma_size(unsigned long size)
{
unsigned long base = CONSISTENT_END - ALIGN(size, SZ_2M);
BUG_ON(consistent_pte); /* Check we're called before DMA region init */
BUG_ON(base < VMALLOC_END);
/* Grow region to accommodate specified size */
if (base < consistent_base)
consistent_base = base;
}
#include "vmregion.h"
static struct arm_vmregion_head consistent_head = {
.vm_lock = __SPIN_LOCK_UNLOCKED(&consistent_head.vm_lock),
.vm_list = LIST_HEAD_INIT(consistent_head.vm_list),
.vm_end = CONSISTENT_END,
};
#ifdef CONFIG_HUGETLB_PAGE
#error ARM Coherent DMA allocator does not (yet) support huge TLB
#endif
/*
* Initialise the consistent memory allocation.
*/
static int __init consistent_init(void)
{
int ret = 0;
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *pte;
int i = 0;
unsigned long base = consistent_base;
unsigned long num_ptes = (CONSISTENT_END - base) >> PMD_SHIFT;
if (IS_ENABLED(CONFIG_CMA) && !IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU))
return 0;
consistent_pte = kmalloc(num_ptes * sizeof(pte_t), GFP_KERNEL);
if (!consistent_pte) {
pr_err("%s: no memory\n", __func__);
return -ENOMEM;
}
pr_debug("DMA memory: 0x%08lx - 0x%08lx:\n", base, CONSISTENT_END);
consistent_head.vm_start = base;
do {
pgd = pgd_offset(&init_mm, base);
pud = pud_alloc(&init_mm, pgd, base);
if (!pud) {
pr_err("%s: no pud tables\n", __func__);
ret = -ENOMEM;
break;
}
pmd = pmd_alloc(&init_mm, pud, base);
if (!pmd) {
pr_err("%s: no pmd tables\n", __func__);
ret = -ENOMEM;
break;
}
WARN_ON(!pmd_none(*pmd));
pte = pte_alloc_kernel(pmd, base);
if (!pte) {
pr_err("%s: no pte tables\n", __func__);
ret = -ENOMEM;
break;
}
consistent_pte[i++] = pte;
base += PMD_SIZE;
} while (base < CONSISTENT_END);
return ret;
}
core_initcall(consistent_init);
static void *__alloc_from_contiguous(struct device *dev, size_t size,
pgprot_t prot, struct page **ret_page,
bool no_kernel_mapping);
static struct arm_vmregion_head coherent_head = {
.vm_lock = __SPIN_LOCK_UNLOCKED(&coherent_head.vm_lock),
.vm_list = LIST_HEAD_INIT(coherent_head.vm_list),
};
static size_t coherent_pool_size = DEFAULT_CONSISTENT_DMA_SIZE / 8;
static int __init early_coherent_pool(char *p)
{
coherent_pool_size = memparse(p, &p);
return 0;
}
early_param("coherent_pool", early_coherent_pool);
/*
* Initialise the coherent pool for atomic allocations.
*/
static int __init coherent_init(void)
{
pgprot_t prot = pgprot_dmacoherent(pgprot_kernel);
size_t size = coherent_pool_size;
struct page *page;
void *ptr;
if (!IS_ENABLED(CONFIG_CMA))
return 0;
ptr = __alloc_from_contiguous(NULL, size, prot, &page, false);
if (ptr) {
coherent_head.vm_start = (unsigned long) ptr;
coherent_head.vm_end = (unsigned long) ptr + size;
printk(KERN_INFO "DMA: preallocated %u KiB pool for atomic coherent allocations\n",
(unsigned)size / 1024);
return 0;
}
printk(KERN_ERR "DMA: failed to allocate %u KiB pool for atomic coherent allocation\n",
(unsigned)size / 1024);
return -ENOMEM;
}
/*
* CMA is activated by core_initcall, so we must be called after it.
*/
postcore_initcall(coherent_init);
struct dma_contig_early_reserve {
phys_addr_t base;
unsigned long size;
};
static struct dma_contig_early_reserve dma_mmu_remap[MAX_CMA_AREAS] __initdata;
static int dma_mmu_remap_num __initdata;
void __init dma_contiguous_early_fixup(phys_addr_t base, unsigned long size)
{
dma_mmu_remap[dma_mmu_remap_num].base = base;
dma_mmu_remap[dma_mmu_remap_num].size = size;
dma_mmu_remap_num++;
}
void __init dma_contiguous_remap(void)
{
int i;
for (i = 0; i < dma_mmu_remap_num; i++) {
phys_addr_t start = dma_mmu_remap[i].base;
phys_addr_t end = start + dma_mmu_remap[i].size;
struct map_desc map;
unsigned long addr;
if (end > arm_lowmem_limit)
end = arm_lowmem_limit;
if (start >= end)
return;
map.pfn = __phys_to_pfn(start);
map.virtual = __phys_to_virt(start);
map.length = end - start;
map.type = MT_MEMORY_DMA_READY;
/*
* Clear previous low-memory mapping
*/
for (addr = __phys_to_virt(start); addr < __phys_to_virt(end);
addr += PMD_SIZE)
pmd_clear(pmd_off_k(addr));
iotable_init(&map, 1);
}
}
static void *
__dma_alloc_remap(struct page *page, size_t size, gfp_t gfp, pgprot_t prot,
const void *caller)
{
struct arm_vmregion *c;
size_t align;
int bit;
if (!consistent_pte) {
pr_err("%s: not initialised\n", __func__);
dump_stack();
return NULL;
}
/*
* Align the virtual region allocation - maximum alignment is
* a section size, minimum is a page size. This helps reduce
* fragmentation of the DMA space, and also prevents allocations
* smaller than a section from crossing a section boundary.
*/
bit = fls(size - 1);
if (bit > SECTION_SHIFT)
bit = SECTION_SHIFT;
align = 1 << bit;
/*
* Allocate a virtual address in the consistent mapping region.
*/
c = arm_vmregion_alloc(&consistent_head, align, size,
gfp & ~(__GFP_DMA | __GFP_HIGHMEM), caller);
if (c) {
pte_t *pte;
int idx = CONSISTENT_PTE_INDEX(c->vm_start);
u32 off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
pte = consistent_pte[idx] + off;
c->priv = page;
do {
BUG_ON(!pte_none(*pte));
set_pte_ext(pte, mk_pte(page, prot), 0);
page++;
pte++;
off++;
if (off >= PTRS_PER_PTE) {
off = 0;
pte = consistent_pte[++idx];
}
} while (size -= PAGE_SIZE);
dsb();
return (void *)c->vm_start;
}
return NULL;
}
static void __dma_free_remap(void *cpu_addr, size_t size)
{
struct arm_vmregion *c;
unsigned long addr;
pte_t *ptep;
int idx;
u32 off;
c = arm_vmregion_find_remove(&consistent_head, (unsigned long)cpu_addr);
if (!c) {
pr_err("%s: trying to free invalid coherent area: %p\n",
__func__, cpu_addr);
dump_stack();
return;
}
if ((c->vm_end - c->vm_start) != size) {
pr_err("%s: freeing wrong coherent size (%ld != %d)\n",
__func__, c->vm_end - c->vm_start, size);
dump_stack();
size = c->vm_end - c->vm_start;
}
idx = CONSISTENT_PTE_INDEX(c->vm_start);
off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
ptep = consistent_pte[idx] + off;
addr = c->vm_start;
do {
pte_t pte = ptep_get_and_clear(&init_mm, addr, ptep);
ptep++;
addr += PAGE_SIZE;
off++;
if (off >= PTRS_PER_PTE) {
off = 0;
ptep = consistent_pte[++idx];
}
if (pte_none(pte) || !pte_present(pte))
pr_crit("%s: bad page in kernel page table\n",
__func__);
} while (size -= PAGE_SIZE);
flush_tlb_kernel_range(c->vm_start, c->vm_end);
arm_vmregion_free(&consistent_head, c);
}
static int __dma_update_pte(pte_t *pte, pgtable_t token, unsigned long addr,
void *data)
{
struct page *page = virt_to_page(addr);
pgprot_t prot = *(pgprot_t *)data;
set_pte_ext(pte, mk_pte(page, prot), 0);
return 0;
}
static int __dma_clear_pte(pte_t *pte, pgtable_t token, unsigned long addr,
void *data)
{
pte_clear(&init_mm, addr, pte);
return 0;
}
static void __dma_remap(struct page *page, size_t size, pgprot_t prot,
bool no_kernel_map)
{
unsigned long start = (unsigned long) page_address(page);
unsigned end = start + size;
int (*func)(pte_t *pte, pgtable_t token, unsigned long addr,
void *data);
if (no_kernel_map)
func = __dma_clear_pte;
else
func = __dma_update_pte;
apply_to_page_range(&init_mm, start, size, func, &prot);
dsb();
flush_tlb_kernel_range(start, end);
}
static void *__alloc_remap_buffer(struct device *dev, size_t size, gfp_t gfp,
pgprot_t prot, struct page **ret_page,
const void *caller)
{
struct page *page;
void *ptr;
page = __dma_alloc_buffer(dev, size, gfp);
if (!page)
return NULL;
ptr = __dma_alloc_remap(page, size, gfp, prot, caller);
if (!ptr) {
__dma_free_buffer(page, size);
return NULL;
}
*ret_page = page;
return ptr;
}
static void *__alloc_from_pool(struct device *dev, size_t size,
struct page **ret_page, const void *caller)
{
struct arm_vmregion *c;
size_t align;
if (!coherent_head.vm_start) {
printk(KERN_ERR "%s: coherent pool not initialised!\n",
__func__);
dump_stack();
return NULL;
}
/*
* Align the region allocation - allocations from pool are rather
* small, so align them to their order in pages, minimum is a page
* size. This helps reduce fragmentation of the DMA space.
*/
align = PAGE_SIZE << get_order(size);
c = arm_vmregion_alloc(&coherent_head, align, size, 0, caller);
if (c) {
void *ptr = (void *)c->vm_start;
struct page *page = virt_to_page(ptr);
*ret_page = page;
return ptr;
}
return NULL;
}
static int __free_from_pool(void *cpu_addr, size_t size)
{
unsigned long start = (unsigned long)cpu_addr;
unsigned long end = start + size;
struct arm_vmregion *c;
if (start < coherent_head.vm_start || end > coherent_head.vm_end)
return 0;
c = arm_vmregion_find_remove(&coherent_head, (unsigned long)start);
if ((c->vm_end - c->vm_start) != size) {
printk(KERN_ERR "%s: freeing wrong coherent size (%ld != %d)\n",
__func__, c->vm_end - c->vm_start, size);
dump_stack();
size = c->vm_end - c->vm_start;
}
arm_vmregion_free(&coherent_head, c);
return 1;
}
static void *__alloc_from_contiguous(struct device *dev, size_t size,
pgprot_t prot, struct page **ret_page,
bool no_kernel_mapping)
{
unsigned long order = get_order(size);
size_t count = size >> PAGE_SHIFT;
struct page *page;
page = dma_alloc_from_contiguous(dev, count, order);
if (!page)
return NULL;
__dma_clear_buffer(page, size);
__dma_remap(page, size, prot, no_kernel_mapping);
*ret_page = page;
return page_address(page);
}
static void __free_from_contiguous(struct device *dev, struct page *page,
size_t size)
{
__dma_remap(page, size, pgprot_kernel, false);
dma_release_from_contiguous(dev, page, size >> PAGE_SHIFT);
}
static inline pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot)
{
if (dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs))
prot = pgprot_writecombine(prot);
else if (dma_get_attr(DMA_ATTR_STRONGLY_ORDERED, attrs))
prot = pgprot_stronglyordered(prot);
/* if non-consistent just pass back what was given */
else if (!dma_get_attr(DMA_ATTR_NON_CONSISTENT, attrs))
prot = pgprot_dmacoherent(prot);
return prot;
}
#define nommu() 0
#else /* !CONFIG_MMU */
#define nommu() 1
#define __alloc_remap_buffer(dev, size, gfp, prot, ret, c) NULL
#define __alloc_from_pool(dev, size, ret_page, c) NULL
#define __alloc_from_contiguous(dev, size, prot, ret, w) NULL
#define __free_from_pool(cpu_addr, size) 0
#define __free_from_contiguous(dev, page, size) do { } while (0)
#define __dma_free_remap(cpu_addr, size) do { } while (0)
#define __get_dma_pgprot(attrs, prot) __pgprot(0)
#endif /* CONFIG_MMU */
static void *__alloc_simple_buffer(struct device *dev, size_t size, gfp_t gfp,
struct page **ret_page)
{
struct page *page;
page = __dma_alloc_buffer(dev, size, gfp);
if (!page)
return NULL;
*ret_page = page;
return page_address(page);
}
static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, pgprot_t prot, const void *caller,
bool no_kernel_mapping)
{
u64 mask = get_coherent_dma_mask(dev);
struct page *page;
void *addr;
#ifdef CONFIG_DMA_API_DEBUG
u64 limit = (mask + 1) & ~mask;
if (limit && size >= limit) {
dev_warn(dev, "coherent allocation too big (requested %#x mask %#llx)\n",
size, mask);
return NULL;
}
#endif
if (!mask)
return NULL;
if (mask < 0xffffffffULL)
gfp |= GFP_DMA;
/*
* Following is a work-around (a.k.a. hack) to prevent pages
* with __GFP_COMP being passed to split_page() which cannot
* handle them. The real problem is that this flag probably
* should be 0 on ARM as it is not supported on this
* platform; see CONFIG_HUGETLBFS.
*/
gfp &= ~(__GFP_COMP);
*handle = DMA_ERROR_CODE;
size = PAGE_ALIGN(size);
if (arch_is_coherent() || nommu())
addr = __alloc_simple_buffer(dev, size, gfp, &page);
else if (!IS_ENABLED(CONFIG_CMA))
addr = __alloc_remap_buffer(dev, size, gfp, prot, &page, caller);
else if (gfp & GFP_ATOMIC)
addr = __alloc_from_pool(dev, size, &page, caller);
else
addr = __alloc_from_contiguous(dev, size, prot, &page,
no_kernel_mapping);
if (addr)
*handle = pfn_to_dma(dev, page_to_pfn(page));
return addr;
}
/*
* Allocate DMA-coherent memory space and return both the kernel remapped
* virtual and bus address for that space.
*/
void *arm_dma_alloc(struct device *dev, size_t size, dma_addr_t *handle,
gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, PAGE_KERNEL);
void *memory;
bool no_kernel_mapping = dma_get_attr(DMA_ATTR_NO_KERNEL_MAPPING,
attrs);
if (dma_alloc_from_coherent(dev, size, handle, &memory))
return memory;
return __dma_alloc(dev, size, handle, gfp, prot,
__builtin_return_address(0), no_kernel_mapping);
}
/*
* Create userspace mapping for the DMA-coherent memory.
*/
int arm_dma_mmap(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
int ret = -ENXIO;
#ifdef CONFIG_MMU
unsigned long pfn = dma_to_pfn(dev, dma_addr);
vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret))
return ret;
ret = remap_pfn_range(vma, vma->vm_start,
pfn + vma->vm_pgoff,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
#endif /* CONFIG_MMU */
return ret;
}
/*
* Free a buffer as defined by the above mapping.
*/
void arm_dma_free(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t handle, struct dma_attrs *attrs)
{
struct page *page = pfn_to_page(dma_to_pfn(dev, handle));
if (dma_release_from_coherent(dev, get_order(size), cpu_addr))
return;
size = PAGE_ALIGN(size);
if (arch_is_coherent() || nommu()) {
__dma_free_buffer(page, size);
} else if (!IS_ENABLED(CONFIG_CMA)) {
__dma_free_remap(cpu_addr, size);
__dma_free_buffer(page, size);
} else {
if (__free_from_pool(cpu_addr, size))
return;
/*
* Non-atomic allocations cannot be freed with IRQs disabled
*/
WARN_ON(irqs_disabled());
__free_from_contiguous(dev, page, size);
}
}
static void dma_cache_maint_page(struct page *page, unsigned long offset,
size_t size, enum dma_data_direction dir,
void (*op)(const void *, size_t, int))
{
unsigned long pfn;
size_t left = size;
pfn = page_to_pfn(page) + offset / PAGE_SIZE;
offset %= PAGE_SIZE;
/*
* A single sg entry may refer to multiple physically contiguous
* pages. But we still need to process highmem pages individually.
* If highmem is not configured then the bulk of this loop gets
* optimized out.
*/
do {
size_t len = left;
void *vaddr;
page = pfn_to_page(pfn);
if (PageHighMem(page)) {
if (len + offset > PAGE_SIZE)
len = PAGE_SIZE - offset;
vaddr = kmap_high_get(page);
if (vaddr) {
vaddr += offset;
op(vaddr, len, dir);
kunmap_high(page);
} else if (cache_is_vipt()) {
/* unmapped pages might still be cached */
vaddr = kmap_atomic(page);
op(vaddr + offset, len, dir);
kunmap_atomic(vaddr);
}
} else {
vaddr = page_address(page) + offset;
op(vaddr, len, dir);
}
offset = 0;
pfn++;
left -= len;
} while (left);
}
/*
* Make an area consistent for devices.
* Note: Drivers should NOT use this function directly, as it will break
* platforms with CONFIG_DMABOUNCE.
* Use the driver DMA support - see dma-mapping.h (dma_sync_*)
*/
static void __dma_page_cpu_to_dev(struct page *page, unsigned long off,
size_t size, enum dma_data_direction dir)
{
unsigned long paddr;
dma_cache_maint_page(page, off, size, dir, dmac_map_area);
paddr = page_to_phys(page) + off;
if (dir == DMA_FROM_DEVICE) {
outer_inv_range(paddr, paddr + size);
} else {
outer_clean_range(paddr, paddr + size);
}
/* FIXME: non-speculating: flush on bidirectional mappings? */
}
static void __dma_page_dev_to_cpu(struct page *page, unsigned long off,
size_t size, enum dma_data_direction dir)
{
unsigned long paddr = page_to_phys(page) + off;
/* FIXME: non-speculating: not required */
/* don't bother invalidating if DMA to device */
if (dir != DMA_TO_DEVICE)
outer_inv_range(paddr, paddr + size);
dma_cache_maint_page(page, off, size, dir, dmac_unmap_area);
/*
* Mark the D-cache clean for this page to avoid extra flushing.
*/
if (dir != DMA_TO_DEVICE && off == 0 && size >= PAGE_SIZE)
set_bit(PG_dcache_clean, &page->flags);
}
/**
* arm_dma_map_sg - map a set of SG buffers for streaming mode DMA
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map
* @dir: DMA transfer direction
*
* Map a set of buffers described by scatterlist in streaming mode for DMA.
* This is the scatter-gather version of the dma_map_single interface.
* Here the scatter gather list elements are each tagged with the
* appropriate dma address and length. They are obtained via
* sg_dma_{address,length}.
*
* Device ownership issues as mentioned for dma_map_single are the same
* here.
*/
int arm_dma_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i, j;
for_each_sg(sg, s, nents, i) {
#ifdef CONFIG_NEED_SG_DMA_LENGTH
s->dma_length = s->length;
#endif
s->dma_address = ops->map_page(dev, sg_page(s), s->offset,
s->length, dir, attrs);
if (dma_mapping_error(dev, s->dma_address))
goto bad_mapping;
}
return nents;
bad_mapping:
for_each_sg(sg, s, i, j)
ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
return 0;
}
/**
* arm_dma_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to unmap (same as was passed to dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*
* Unmap a set of streaming mode DMA translations. Again, CPU access
* rules concerning calls here are the same as for dma_unmap_single().
*/
void arm_dma_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->unmap_page(dev, sg_dma_address(s), sg_dma_len(s), dir, attrs);
}
/**
* arm_dma_sync_sg_for_cpu
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_dma_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->sync_single_for_cpu(dev, sg_dma_address(s), s->length,
dir);
}
/**
* arm_dma_sync_sg_for_device
* @dev: valid struct device pointer, or NULL for ISA and EISA-like devices
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_dma_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct dma_map_ops *ops = get_dma_ops(dev);
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
ops->sync_single_for_device(dev, sg_dma_address(s), s->length,
dir);
}
/*
* Return whether the given device DMA address mask can be supported
* properly. For example, if your device can only drive the low 24-bits
* during bus mastering, then you would pass 0x00ffffff as the mask
* to this function.
*/
int dma_supported(struct device *dev, u64 mask)
{
if (mask < (u64)arm_dma_limit)
return 0;
return 1;
}
EXPORT_SYMBOL(dma_supported);
static int arm_dma_set_mask(struct device *dev, u64 dma_mask)
{
if (!dev->dma_mask || !dma_supported(dev, dma_mask))
return -EIO;
*dev->dma_mask = dma_mask;
return 0;
}
#define PREALLOC_DMA_DEBUG_ENTRIES 4096
static int __init dma_debug_do_init(void)
{
#ifdef CONFIG_MMU
arm_vmregion_create_proc("dma-mappings", &consistent_head);
#endif
dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES);
return 0;
}
fs_initcall(dma_debug_do_init);
#ifdef CONFIG_ARM_DMA_USE_IOMMU
/* IOMMU */
static inline dma_addr_t __alloc_iova(struct dma_iommu_mapping *mapping,
size_t size)
{
unsigned int order = get_order(size);
unsigned int align = 0;
unsigned int count, start;
unsigned long flags;
count = ((PAGE_ALIGN(size) >> PAGE_SHIFT) +
(1 << mapping->order) - 1) >> mapping->order;
if (order > mapping->order)
align = (1 << (order - mapping->order)) - 1;
spin_lock_irqsave(&mapping->lock, flags);
start = bitmap_find_next_zero_area(mapping->bitmap, mapping->bits, 0,
count, align);
if (start > mapping->bits) {
spin_unlock_irqrestore(&mapping->lock, flags);
return DMA_ERROR_CODE;
}
bitmap_set(mapping->bitmap, start, count);
spin_unlock_irqrestore(&mapping->lock, flags);
return mapping->base + (start << (mapping->order + PAGE_SHIFT));
}
static inline void __free_iova(struct dma_iommu_mapping *mapping,
dma_addr_t addr, size_t size)
{
unsigned int start = (addr - mapping->base) >>
(mapping->order + PAGE_SHIFT);
unsigned int count = ((size >> PAGE_SHIFT) +
(1 << mapping->order) - 1) >> mapping->order;
unsigned long flags;
spin_lock_irqsave(&mapping->lock, flags);
bitmap_clear(mapping->bitmap, start, count);
spin_unlock_irqrestore(&mapping->lock, flags);
}
static struct page **__iommu_alloc_buffer(struct device *dev, size_t size, gfp_t gfp)
{
struct page **pages;
int count = size >> PAGE_SHIFT;
int array_size = count * sizeof(struct page *);
int i = 0;
if (array_size <= PAGE_SIZE)
pages = kzalloc(array_size, gfp);
else
pages = vzalloc(array_size);
if (!pages)
return NULL;
while (count) {
int j, order = __fls(count);
pages[i] = alloc_pages(gfp | __GFP_NOWARN, order);
while (!pages[i] && order)
pages[i] = alloc_pages(gfp | __GFP_NOWARN, --order);
if (!pages[i])
goto error;
if (order)
split_page(pages[i], order);
j = 1 << order;
while (--j)
pages[i + j] = pages[i] + j;
__dma_clear_buffer(pages[i], PAGE_SIZE << order);
i += 1 << order;
count -= 1 << order;
}
return pages;
error:
while (--i)
if (pages[i])
__free_pages(pages[i], 0);
if (array_size < PAGE_SIZE)
kfree(pages);
else
vfree(pages);
return NULL;
}
static int __iommu_free_buffer(struct device *dev, struct page **pages, size_t size)
{
int count = size >> PAGE_SHIFT;
int array_size = count * sizeof(struct page *);
int i;
for (i = 0; i < count; i++)
if (pages[i])
__free_pages(pages[i], 0);
if (array_size < PAGE_SIZE)
kfree(pages);
else
vfree(pages);
return 0;
}
/*
* Create a CPU mapping for a specified pages
*/
static void *
__iommu_alloc_remap(struct page **pages, size_t size, gfp_t gfp, pgprot_t prot)
{
struct arm_vmregion *c;
size_t align;
size_t count = size >> PAGE_SHIFT;
int bit;
if (!consistent_pte[0]) {
pr_err("%s: not initialised\n", __func__);
dump_stack();
return NULL;
}
/*
* Align the virtual region allocation - maximum alignment is
* a section size, minimum is a page size. This helps reduce
* fragmentation of the DMA space, and also prevents allocations
* smaller than a section from crossing a section boundary.
*/
bit = fls(size - 1);
if (bit > SECTION_SHIFT)
bit = SECTION_SHIFT;
align = 1 << bit;
/*
* Allocate a virtual address in the consistent mapping region.
*/
c = arm_vmregion_alloc(&consistent_head, align, size,
gfp & ~(__GFP_DMA | __GFP_HIGHMEM), NULL);
if (c) {
pte_t *pte;
int idx = CONSISTENT_PTE_INDEX(c->vm_start);
int i = 0;
u32 off = CONSISTENT_OFFSET(c->vm_start) & (PTRS_PER_PTE-1);
pte = consistent_pte[idx] + off;
c->priv = pages;
do {
BUG_ON(!pte_none(*pte));
set_pte_ext(pte, mk_pte(pages[i], prot), 0);
pte++;
off++;
i++;
if (off >= PTRS_PER_PTE) {
off = 0;
pte = consistent_pte[++idx];
}
} while (i < count);
dsb();
return (void *)c->vm_start;
}
return NULL;
}
/*
* Create a mapping in device IO address space for specified pages
*/
static dma_addr_t
__iommu_create_mapping(struct device *dev, struct page **pages, size_t size)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
unsigned int count = PAGE_ALIGN(size) >> PAGE_SHIFT;
dma_addr_t dma_addr, iova;
int i, ret = DMA_ERROR_CODE;
dma_addr = __alloc_iova(mapping, size);
if (dma_addr == DMA_ERROR_CODE)
return dma_addr;
iova = dma_addr;
for (i = 0; i < count; ) {
unsigned int next_pfn = page_to_pfn(pages[i]) + 1;
phys_addr_t phys = page_to_phys(pages[i]);
unsigned int len, j;
for (j = i + 1; j < count; j++, next_pfn++)
if (page_to_pfn(pages[j]) != next_pfn)
break;
len = (j - i) << PAGE_SHIFT;
ret = iommu_map(mapping->domain, iova, phys, len, 0);
if (ret < 0)
goto fail;
iova += len;
i = j;
}
return dma_addr;
fail:
iommu_unmap(mapping->domain, dma_addr, iova-dma_addr);
__free_iova(mapping, dma_addr, size);
return DMA_ERROR_CODE;
}
static int __iommu_remove_mapping(struct device *dev, dma_addr_t iova, size_t size)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
/*
* add optional in-page offset from iova to size and align
* result to page size
*/
size = PAGE_ALIGN((iova & ~PAGE_MASK) + size);
iova &= PAGE_MASK;
iommu_unmap(mapping->domain, iova, size);
__free_iova(mapping, iova, size);
return 0;
}
static void *arm_iommu_alloc_attrs(struct device *dev, size_t size,
dma_addr_t *handle, gfp_t gfp, struct dma_attrs *attrs)
{
pgprot_t prot = __get_dma_pgprot(attrs, pgprot_kernel);
struct page **pages;
void *addr = NULL;
*handle = DMA_ERROR_CODE;
size = PAGE_ALIGN(size);
pages = __iommu_alloc_buffer(dev, size, gfp);
if (!pages)
return NULL;
*handle = __iommu_create_mapping(dev, pages, size);
if (*handle == DMA_ERROR_CODE)
goto err_buffer;
addr = __iommu_alloc_remap(pages, size, gfp, prot);
if (!addr)
goto err_mapping;
return addr;
err_mapping:
__iommu_remove_mapping(dev, *handle, size);
err_buffer:
__iommu_free_buffer(dev, pages, size);
return NULL;
}
static int arm_iommu_mmap_attrs(struct device *dev, struct vm_area_struct *vma,
void *cpu_addr, dma_addr_t dma_addr, size_t size,
struct dma_attrs *attrs)
{
struct arm_vmregion *c;
vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot);
c = arm_vmregion_find(&consistent_head, (unsigned long)cpu_addr);
if (c) {
struct page **pages = c->priv;
unsigned long uaddr = vma->vm_start;
unsigned long usize = vma->vm_end - vma->vm_start;
int i = 0;
do {
int ret;
ret = vm_insert_page(vma, uaddr, pages[i++]);
if (ret) {
pr_err("Remapping memory, error: %d\n", ret);
return ret;
}
uaddr += PAGE_SIZE;
usize -= PAGE_SIZE;
} while (usize > 0);
}
return 0;
}
/*
* free a page as defined by the above mapping.
* Must not be called with IRQs disabled.
*/
void arm_iommu_free_attrs(struct device *dev, size_t size, void *cpu_addr,
dma_addr_t handle, struct dma_attrs *attrs)
{
struct arm_vmregion *c;
size = PAGE_ALIGN(size);
c = arm_vmregion_find(&consistent_head, (unsigned long)cpu_addr);
if (c) {
struct page **pages = c->priv;
__dma_free_remap(cpu_addr, size);
__iommu_remove_mapping(dev, handle, size);
__iommu_free_buffer(dev, pages, size);
}
}
/*
* Map a part of the scatter-gather list into contiguous io address space
*/
static int __map_sg_chunk(struct device *dev, struct scatterlist *sg,
size_t size, dma_addr_t *handle,
enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova, iova_base;
int ret = 0;
unsigned int count;
struct scatterlist *s;
size = PAGE_ALIGN(size);
*handle = DMA_ERROR_CODE;
iova_base = iova = __alloc_iova(mapping, size);
if (iova == DMA_ERROR_CODE)
return -ENOMEM;
for (count = 0, s = sg; count < (size >> PAGE_SHIFT); s = sg_next(s)) {
phys_addr_t phys = page_to_phys(sg_page(s));
unsigned int len = PAGE_ALIGN(s->offset + s->length);
if (!arch_is_coherent())
__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
ret = iommu_map(mapping->domain, iova, phys, len, 0);
if (ret < 0)
goto fail;
count += len >> PAGE_SHIFT;
iova += len;
}
*handle = iova_base;
return 0;
fail:
iommu_unmap(mapping->domain, iova_base, count * PAGE_SIZE);
__free_iova(mapping, iova_base, size);
return ret;
}
/**
* arm_iommu_map_sg - map a set of SG buffers for streaming mode DMA
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map
* @dir: DMA transfer direction
*
* Map a set of buffers described by scatterlist in streaming mode for DMA.
* The scatter gather list elements are merged together (if possible) and
* tagged with the appropriate dma address and length. They are obtained via
* sg_dma_{address,length}.
*/
int arm_iommu_map_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s = sg, *dma = sg, *start = sg;
int i, count = 0;
unsigned int offset = s->offset;
unsigned int size = s->offset + s->length;
unsigned int max = dma_get_max_seg_size(dev);
for (i = 1; i < nents; i++) {
s = sg_next(s);
s->dma_address = DMA_ERROR_CODE;
s->dma_length = 0;
if (s->offset || (size & ~PAGE_MASK) || size + s->length > max) {
if (__map_sg_chunk(dev, start, size, &dma->dma_address,
dir) < 0)
goto bad_mapping;
dma->dma_address += offset;
dma->dma_length = size - offset;
size = offset = s->offset;
start = s;
dma = sg_next(dma);
count += 1;
}
size += s->length;
}
if (__map_sg_chunk(dev, start, size, &dma->dma_address, dir) < 0)
goto bad_mapping;
dma->dma_address += offset;
dma->dma_length = size - offset;
return count+1;
bad_mapping:
for_each_sg(sg, s, count, i)
__iommu_remove_mapping(dev, sg_dma_address(s), sg_dma_len(s));
return 0;
}
/**
* arm_iommu_unmap_sg - unmap a set of SG buffers mapped by dma_map_sg
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to unmap (same as was passed to dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*
* Unmap a set of streaming mode DMA translations. Again, CPU access
* rules concerning calls here are the same as for dma_unmap_single().
*/
void arm_iommu_unmap_sg(struct device *dev, struct scatterlist *sg, int nents,
enum dma_data_direction dir, struct dma_attrs *attrs)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i) {
if (sg_dma_len(s))
__iommu_remove_mapping(dev, sg_dma_address(s),
sg_dma_len(s));
if (!arch_is_coherent())
__dma_page_dev_to_cpu(sg_page(s), s->offset,
s->length, dir);
}
}
/**
* arm_iommu_sync_sg_for_cpu
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_iommu_sync_sg_for_cpu(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
if (!arch_is_coherent())
__dma_page_dev_to_cpu(sg_page(s), s->offset, s->length, dir);
}
/**
* arm_iommu_sync_sg_for_device
* @dev: valid struct device pointer
* @sg: list of buffers
* @nents: number of buffers to map (returned from dma_map_sg)
* @dir: DMA transfer direction (same as was passed to dma_map_sg)
*/
void arm_iommu_sync_sg_for_device(struct device *dev, struct scatterlist *sg,
int nents, enum dma_data_direction dir)
{
struct scatterlist *s;
int i;
for_each_sg(sg, s, nents, i)
if (!arch_is_coherent())
__dma_page_cpu_to_dev(sg_page(s), s->offset, s->length, dir);
}
/**
* arm_iommu_map_page
* @dev: valid struct device pointer
* @page: page that buffer resides in
* @offset: offset into page for start of buffer
* @size: size of buffer to map
* @dir: DMA transfer direction
*
* IOMMU aware version of arm_dma_map_page()
*/
static dma_addr_t arm_iommu_map_page(struct device *dev, struct page *page,
unsigned long offset, size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t dma_addr;
int ret, len = PAGE_ALIGN(size + offset);
if (!arch_is_coherent())
__dma_page_cpu_to_dev(page, offset, size, dir);
dma_addr = __alloc_iova(mapping, len);
if (dma_addr == DMA_ERROR_CODE)
return dma_addr;
ret = iommu_map(mapping->domain, dma_addr, page_to_phys(page), len, 0);
if (ret < 0)
goto fail;
return dma_addr + offset;
fail:
__free_iova(mapping, dma_addr, len);
return DMA_ERROR_CODE;
}
/**
* arm_iommu_unmap_page
* @dev: valid struct device pointer
* @handle: DMA address of buffer
* @size: size of buffer (same as passed to dma_map_page)
* @dir: DMA transfer direction (same as passed to dma_map_page)
*
* IOMMU aware version of arm_dma_unmap_page()
*/
static void arm_iommu_unmap_page(struct device *dev, dma_addr_t handle,
size_t size, enum dma_data_direction dir,
struct dma_attrs *attrs)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
int offset = handle & ~PAGE_MASK;
int len = PAGE_ALIGN(size + offset);
if (!iova)
return;
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
iommu_unmap(mapping->domain, iova, len);
__free_iova(mapping, iova, len);
}
static void arm_iommu_sync_single_for_cpu(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
unsigned int offset = handle & ~PAGE_MASK;
if (!iova)
return;
if (!arch_is_coherent())
__dma_page_dev_to_cpu(page, offset, size, dir);
}
static void arm_iommu_sync_single_for_device(struct device *dev,
dma_addr_t handle, size_t size, enum dma_data_direction dir)
{
struct dma_iommu_mapping *mapping = dev->archdata.mapping;
dma_addr_t iova = handle & PAGE_MASK;
struct page *page = phys_to_page(iommu_iova_to_phys(mapping->domain, iova));
unsigned int offset = handle & ~PAGE_MASK;
if (!iova)
return;
__dma_page_cpu_to_dev(page, offset, size, dir);
}
struct dma_map_ops iommu_ops = {
.alloc = arm_iommu_alloc_attrs,
.free = arm_iommu_free_attrs,
.mmap = arm_iommu_mmap_attrs,
.map_page = arm_iommu_map_page,
.unmap_page = arm_iommu_unmap_page,
.sync_single_for_cpu = arm_iommu_sync_single_for_cpu,
.sync_single_for_device = arm_iommu_sync_single_for_device,
.map_sg = arm_iommu_map_sg,
.unmap_sg = arm_iommu_unmap_sg,
.sync_sg_for_cpu = arm_iommu_sync_sg_for_cpu,
.sync_sg_for_device = arm_iommu_sync_sg_for_device,
};
/**
* arm_iommu_create_mapping
* @bus: pointer to the bus holding the client device (for IOMMU calls)
* @base: start address of the valid IO address space
* @size: size of the valid IO address space
* @order: accuracy of the IO addresses allocations
*
* Creates a mapping structure which holds information about used/unused
* IO address ranges, which is required to perform memory allocation and
* mapping with IOMMU aware functions.
*
* The client device need to be attached to the mapping with
* arm_iommu_attach_device function.
*/
struct dma_iommu_mapping *
arm_iommu_create_mapping(struct bus_type *bus, dma_addr_t base, size_t size,
int order)
{
unsigned int count = size >> (PAGE_SHIFT + order);
unsigned int bitmap_size = BITS_TO_LONGS(count) * sizeof(long);
struct dma_iommu_mapping *mapping;
int err = -ENOMEM;
if (!count)
return ERR_PTR(-EINVAL);
mapping = kzalloc(sizeof(struct dma_iommu_mapping), GFP_KERNEL);
if (!mapping)
goto err;
mapping->bitmap = kzalloc(bitmap_size, GFP_KERNEL);
if (!mapping->bitmap)
goto err2;
mapping->base = base;
mapping->bits = BITS_PER_BYTE * bitmap_size;
mapping->order = order;
spin_lock_init(&mapping->lock);
mapping->domain = iommu_domain_alloc(bus);
if (!mapping->domain)
goto err3;
kref_init(&mapping->kref);
return mapping;
err3:
kfree(mapping->bitmap);
err2:
kfree(mapping);
err:
return ERR_PTR(err);
}
static void release_iommu_mapping(struct kref *kref)
{
struct dma_iommu_mapping *mapping =
container_of(kref, struct dma_iommu_mapping, kref);
iommu_domain_free(mapping->domain);
kfree(mapping->bitmap);
kfree(mapping);
}
void arm_iommu_release_mapping(struct dma_iommu_mapping *mapping)
{
if (mapping)
kref_put(&mapping->kref, release_iommu_mapping);
}
/**
* arm_iommu_attach_device
* @dev: valid struct device pointer
* @mapping: io address space mapping structure (returned from
* arm_iommu_create_mapping)
*
* Attaches specified io address space mapping to the provided device,
* this replaces the dma operations (dma_map_ops pointer) with the
* IOMMU aware version. More than one client might be attached to
* the same io address space mapping.
*/
int arm_iommu_attach_device(struct device *dev,
struct dma_iommu_mapping *mapping)
{
int err;
err = iommu_attach_device(mapping->domain, dev);
if (err)
return err;
kref_get(&mapping->kref);
dev->archdata.mapping = mapping;
set_dma_ops(dev, &iommu_ops);
pr_info("Attached IOMMU controller to %s device.\n", dev_name(dev));
return 0;
}
#endif
| gpl-2.0 |
MSusik/invenio | scripts/pep8.py | 29318 | #!/usr/bin/python
# pep8.py - Check Python source code formatting, according to PEP 8
# Copyright (C) 2006 Johann C. Rocholl <[email protected]>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import print_function
"""
Check Python source code formatting, according to PEP 8:
http://www.python.org/dev/peps/pep-0008/
For usage and a list of options, try this:
$ python pep8.py -h
This program and its regression test suite live here:
http://svn.browsershots.org/trunk/devtools/pep8/
http://trac.browsershots.org/browser/trunk/devtools/pep8/
Groups of errors and warnings:
E errors
W warnings
100 indentation
200 whitespace
300 blank lines
400 imports
500 line length
600 deprecation
700 statements
You can add checks to this program by writing plugins. Each plugin is
a simple function that is called for each line of source code, either
physical or logical.
Physical line:
- Raw line of text from the input file.
Logical line:
- Multi-line statements converted to a single line.
- Stripped left and right.
- Contents of strings replaced with 'xxx' of same length.
- Comments removed.
The check function requests physical or logical lines by the name of
the first argument:
def maximum_line_length(physical_line)
def extraneous_whitespace(logical_line)
def blank_lines(logical_line, blank_lines, indent_level, line_number)
The last example above demonstrates how check plugins can request
additional information with extra arguments. All attributes of the
Checker object are available. Some examples:
lines: a list of the raw lines from the input file
tokens: the tokens that contribute to this logical line
line_number: line number in the input file
blank_lines: blank lines before this one
indent_char: first indentation character in this file (' ' or '\t')
indent_level: indentation (with tabs expanded to multiples of 8)
previous_indent_level: indentation on previous line
previous_logical: previous logical line
The docstring of each check function shall be the relevant part of
text from PEP 8. It is printed if the user enables --show-pep8.
"""
import os
import sys
import re
import time
import inspect
import tokenize
from optparse import OptionParser
from keyword import iskeyword
from fnmatch import fnmatch
from six import iteritems
__version__ = '0.2.0'
__revision__ = '$Rev$'
default_exclude = '.svn,CVS,*.pyc,*.pyo'
indent_match = re.compile(r'([ \t]*)').match
raise_comma_match = re.compile(r'raise\s+\w+\s*(,)').match
operators = """
+ - * / % ^ & | = < > >> <<
+= -= *= /= %= ^= &= |= == <= >= >>= <<=
!= <> :
in is or not and
""".split()
options = None
args = None
##############################################################################
# Plugins (check functions) for physical lines
##############################################################################
def tabs_or_spaces(physical_line, indent_char):
"""
Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
"""
indent = indent_match(physical_line).group(1)
for offset, char in enumerate(indent):
if char != indent_char:
return offset, "E101 indentation contains mixed spaces and tabs"
def tabs_obsolete(physical_line):
"""
For new projects, spaces-only are strongly recommended over tabs. Most
editors have features that make this easy to do.
"""
indent = indent_match(physical_line).group(1)
if indent.count('\t'):
return indent.index('\t'), "W191 indentation contains tabs"
def trailing_whitespace(physical_line):
"""
JCR: Trailing whitespace is superfluous.
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
stripped = physical_line.rstrip()
if physical_line != stripped:
return len(stripped), "W291 trailing whitespace"
def trailing_blank_lines(physical_line, lines, line_number):
"""
JCR: Trailing blank lines are superfluous.
"""
if physical_line.strip() == '' and line_number == len(lines):
return 0, "W391 blank line at end of file"
def missing_newline(physical_line):
"""
JCR: The last line should have a newline.
"""
if physical_line.rstrip() == physical_line:
return len(physical_line), "W292 no newline at end of file"
def maximum_line_length(physical_line):
"""
Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to have
several windows side-by-side. The default wrapping on such devices looks
ugly. Therefore, please limit all lines to a maximum of 79 characters.
For flowing long blocks of text (docstrings or comments), limiting the
length to 72 characters is recommended.
"""
length = len(physical_line.rstrip())
if length > 79:
return 79, "E501 line too long (%d characters)" % length
##############################################################################
# Plugins (check functions) for logical lines
##############################################################################
def blank_lines(logical_line, blank_lines, indent_level, line_number,
previous_logical):
"""
Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
"""
if line_number == 1:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
return # Don't expect blank lines after function decorator
if (logical_line.startswith('def ') or
logical_line.startswith('class ') or
logical_line.startswith('@')):
if indent_level > 0 and blank_lines != 1:
return 0, "E301 expected 1 blank line, found %d" % blank_lines
if indent_level == 0 and blank_lines != 2:
return 0, "E302 expected 2 blank lines, found %d" % blank_lines
if blank_lines > 2:
return 0, "E303 too many blank lines (%d)" % blank_lines
def extraneous_whitespace(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- Immediately inside parentheses, brackets or braces.
- Immediately before a comma, semicolon, or colon.
"""
line = logical_line
for char in '([{':
found = line.find(char + ' ')
if found > -1:
return found + 1, "E201 whitespace after '%s'" % char
for char in '}])':
found = line.find(' ' + char)
if found > -1 and line[found - 1] != ',':
return found, "E202 whitespace before '%s'" % char
for char in ',;:':
found = line.find(' ' + char)
if found > -1:
return found, "E203 whitespace before '%s'" % char
def missing_whitespace(logical_line):
"""
JCR: Each comma, semicolon or colon should be followed by whitespace.
"""
line = logical_line
for index in range(len(line) - 1):
char = line[index]
if char in ',;:' and line[index + 1] != ' ':
before = line[:index]
if char == ':' and before.count('[') > before.count(']'):
continue # Slice syntax, no space required
return index, "E231 missing whitespace after '%s'" % char
def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level):
"""
Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
"""
if indent_char == ' ' and indent_level % 4:
return 0, "E111 indentation is not a multiple of four"
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
return 0, "E112 expected an indented block"
if indent_level > previous_indent_level and not indent_expect:
return 0, "E113 unexpected indentation"
def whitespace_before_parameters(logical_line, tokens):
"""
Avoid extraneous whitespace in the following situations:
- Immediately before the open parenthesis that starts the argument
list of a function call.
- Immediately before the open parenthesis that starts an indexing or
slicing.
"""
prev_type = tokens[0][0]
prev_text = tokens[0][1]
prev_end = tokens[0][3]
for index in range(1, len(tokens)):
token_type, text, start, end, line = tokens[index]
if (token_type == tokenize.OP and
text in '([' and
start != prev_end and
prev_type == tokenize.NAME and
(index < 2 or tokens[index - 2][1] != 'class') and
(not iskeyword(prev_text))):
return prev_end, "E211 whitespace before '%s'" % text
prev_type = token_type
prev_text = text
prev_end = end
def whitespace_around_operator(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- More than one space around an assignment (or other) operator to
align it with another.
"""
line = logical_line
for operator in operators:
found = line.find(' ' + operator)
if found > -1:
return found, "E221 multiple spaces before operator"
found = line.find(operator + ' ')
if found > -1:
return found, "E222 multiple spaces after operator"
found = line.find('\t' + operator)
if found > -1:
return found, "E223 tab before operator"
found = line.find(operator + '\t')
if found > -1:
return found, "E224 tab after operator"
def whitespace_around_comma(logical_line):
"""
Avoid extraneous whitespace in the following situations:
- More than one space around an assignment (or other) operator to
align it with another.
JCR: This should also be applied around comma etc.
"""
line = logical_line
for separator in ',;:':
found = line.find(separator + ' ')
if found > -1:
return found + 1, "E241 multiple spaces after '%s'" % separator
found = line.find(separator + '\t')
if found > -1:
return found + 1, "E242 tab after '%s'" % separator
def imports_on_separate_lines(logical_line):
"""
Imports should usually be on separate lines.
"""
line = logical_line
if line.startswith('import '):
found = line.find(',')
if found > -1:
return found, "E401 multiple imports on one line"
def compound_statements(logical_line):
"""
Compound statements (multiple statements on the same line) are
generally discouraged.
"""
line = logical_line
found = line.find(':')
if -1 < found < len(line) - 1:
before = line[:found]
if (before.count('{') <= before.count('}') and # {'a': 1} (dict)
before.count('[') <= before.count(']') and # [1:2] (slice)
not re.search(r'\blambda\b', before)): # lambda x: x
return found, "E701 multiple statements on one line (colon)"
found = line.find(';')
if -1 < found:
return found, "E702 multiple statements on one line (semicolon)"
def python_3000_has_key(logical_line):
"""
The {}.has_key() method will be removed in the future version of
Python. Use the 'in' operation instead, like:
d = {"a": 1, "b": 2}
if "b" in d:
print d["b"]
"""
pos = logical_line.find('.has_key(')
if pos > -1:
return pos, "W601 .has_key() is deprecated, use 'in'"
def python_3000_raise_comma(logical_line):
"""
When raising an exception, use "raise ValueError('message')"
instead of the older form "raise ValueError, 'message'".
The paren-using form is preferred because when the exception arguments
are long or include string formatting, you don't need to use line
continuation characters thanks to the containing parentheses. The older
form will be removed in Python 3000.
"""
match = raise_comma_match(logical_line)
if match:
return match.start(1), "W602 deprecated form of raising exception"
##############################################################################
# Helper functions
##############################################################################
def expand_indent(line):
"""
Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
8
>>> expand_indent(' \\t')
16
"""
result = 0
for char in line:
if char == '\t':
result = result / 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result
##############################################################################
# Framework to run all checks
##############################################################################
def message(text):
"""Print a message."""
# print >> sys.stderr, options.prog + ': ' + text
# print >> sys.stderr, text
print(text)
def find_checks(argument_name):
"""
Find all globally visible functions where the first argument name
starts with argument_name.
"""
checks = []
function_type = type(find_checks)
for name, function in iteritems(globals()):
if type(function) is function_type:
args = inspect.getargspec(function)[0]
if len(args) >= 1 and args[0].startswith(argument_name):
checks.append((name, function, args))
checks.sort()
return checks
def mute_string(text):
"""
Replace contents with 'xxx' to prevent syntax matching.
>>> mute_string('"abc"')
'"xxx"'
>>> mute_string("'''abc'''")
"'''xxx'''"
>>> mute_string("r'abc'")
"r'xxx'"
"""
start = 1
end = len(text) - 1
# String modifiers (e.g. u or r)
if text.endswith('"'):
start += text.index('"')
elif text.endswith("'"):
start += text.index("'")
# Triple quotes
if text.endswith('"""') or text.endswith("'''"):
start += 2
end -= 2
return text[:start] + 'x' * (end - start) + text[end:]
class Checker:
"""
Load a Python source file, tokenize it, check coding style.
"""
def __init__(self, filename):
self.filename = filename
self.lines = file(filename).readlines()
self.physical_checks = find_checks('physical_line')
self.logical_checks = find_checks('logical_line')
options.counters['physical lines'] = \
options.counters.get('physical lines', 0) + len(self.lines)
def readline(self):
"""
Get the next line from the input buffer.
"""
self.line_number += 1
if self.line_number > len(self.lines):
return ''
return self.lines[self.line_number - 1]
def readline_check_physical(self):
"""
Check and return the next physical line. This method can be
used to feed tokenize.generate_tokens.
"""
line = self.readline()
if line:
self.check_physical(line)
return line
def run_check(self, check, argument_names):
"""
Run a check plugin.
"""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments)
def check_physical(self, line):
"""
Run all physical checks on a raw input line.
"""
self.physical_line = line
if self.indent_char is None and len(line) and line[0] in ' \t':
self.indent_char = line[0]
for name, check, argument_names in self.physical_checks:
result = self.run_check(check, argument_names)
if result is not None:
offset, text = result
self.report_error(self.line_number, offset, text, check)
def build_tokens_line(self):
"""
Build a logical line from tokens.
"""
self.mapping = []
logical = []
length = 0
previous = None
for token in self.tokens:
token_type, text = token[0:2]
if token_type in (tokenize.COMMENT, tokenize.NL,
tokenize.INDENT, tokenize.DEDENT,
tokenize.NEWLINE):
continue
if token_type == tokenize.STRING:
text = mute_string(text)
if previous:
end_line, end = previous[3]
start_line, start = token[2]
if end_line != start_line: # different row
if self.lines[end_line - 1][end - 1] not in '{[(':
logical.append(' ')
length += 1
elif end != start: # different column
fill = self.lines[end_line - 1][end:start]
logical.append(fill)
length += len(fill)
self.mapping.append((length, token))
logical.append(text)
length += len(text)
previous = token
self.logical_line = ''.join(logical)
assert self.logical_line.lstrip() == self.logical_line
assert self.logical_line.rstrip() == self.logical_line
def check_logical(self):
"""
Build a line from tokens and run all logical checks on it.
"""
options.counters['logical lines'] = \
options.counters.get('logical lines', 0) + 1
self.build_tokens_line()
first_line = self.lines[self.mapping[0][1][2][0] - 1]
indent = first_line[:self.mapping[0][1][2][1]]
self.previous_indent_level = self.indent_level
self.indent_level = expand_indent(indent)
if options.verbose >= 2:
print(self.logical_line[:80].rstrip())
for name, check, argument_names in self.logical_checks:
if options.verbose >= 3:
print(' ', name)
result = self.run_check(check, argument_names)
if result is not None:
offset, text = result
if type(offset) is tuple:
original_number, original_offset = offset
else:
for token_offset, token in self.mapping:
if offset >= token_offset:
original_number = token[2][0]
original_offset = (token[2][1]
+ offset - token_offset)
self.report_error(original_number, original_offset,
text, check)
self.previous_logical = self.logical_line
def check_all(self):
"""
Run all checks on the input file.
"""
self.file_errors = 0
self.line_number = 0
self.indent_char = None
self.indent_level = 0
self.previous_logical = ''
self.blank_lines = 0
self.tokens = []
parens = 0
for token in tokenize.generate_tokens(self.readline_check_physical):
# print tokenize.tok_name[token[0]], repr(token)
self.tokens.append(token)
token_type, text = token[0:2]
if token_type == tokenize.OP and text in '([{':
parens += 1
if token_type == tokenize.OP and text in '}])':
parens -= 1
if token_type == tokenize.NEWLINE and not parens:
self.check_logical()
self.blank_lines = 0
self.tokens = []
if token_type == tokenize.NL and not parens:
self.blank_lines += 1
self.tokens = []
if token_type == tokenize.COMMENT:
source_line = token[4]
token_start = token[2][1]
if source_line[:token_start].strip() == '':
self.blank_lines = 0
return self.file_errors
def report_error(self, line_number, offset, text, check):
"""
Report an error, according to options.
"""
if options.quiet == 1 and not self.file_errors:
message(self.filename)
self.file_errors += 1
code = text[:4]
options.counters[code] = options.counters.get(code, 0) + 1
options.messages[code] = text[5:]
if options.quiet:
return
if options.testsuite:
base = os.path.basename(self.filename)[:4]
if base == code:
return
if base[0] == 'E' and code[0] == 'W':
return
if ignore_code(code):
return
if options.counters[code] == 1 or options.repeat:
message("%s:%s:%d: %s" %
(self.filename, line_number, offset + 1, text))
if options.show_source:
line = self.lines[line_number - 1]
message(line.rstrip())
message(' ' * offset + '^')
if options.show_pep8:
message(check.__doc__.lstrip('\n').rstrip())
def input_file(filename):
"""
Run all checks on a Python source file.
"""
if excluded(filename) or not filename_match(filename):
return {}
if options.verbose:
message('checking ' + filename)
options.counters['files'] = options.counters.get('files', 0) + 1
errors = Checker(filename).check_all()
if options.testsuite and not errors:
message("%s: %s" % (filename, "no errors found"))
def input_dir(dirname):
"""
Check all Python source files in this directory and all subdirectories.
"""
dirname = dirname.rstrip('/')
if excluded(dirname):
return
for root, dirs, files in os.walk(dirname):
if options.verbose:
message('directory ' + root)
options.counters['directories'] = \
options.counters.get('directories', 0) + 1
dirs.sort()
for subdir in dirs:
if excluded(subdir):
dirs.remove(subdir)
files.sort()
for filename in files:
input_file(os.path.join(root, filename))
def excluded(filename):
"""
Check if options.exclude contains a pattern that matches filename.
"""
basename = os.path.basename(filename)
for pattern in options.exclude:
if fnmatch(basename, pattern):
# print basename, 'excluded because it matches', pattern
return True
def filename_match(filename):
"""
Check if options.filename contains a pattern that matches filename.
If options.filename is unspecified, this always returns True.
"""
if not options.filename:
return True
for pattern in options.filename:
if fnmatch(filename, pattern):
return True
def ignore_code(code):
"""
Check if options.ignore contains a prefix of the error code.
"""
for ignore in options.ignore:
if code.startswith(ignore):
return True
def get_error_statistics():
"""Get error statistics."""
return get_statistics("E")
def get_warning_statistics():
"""Get warning statistics."""
return get_statistics("W")
def get_statistics(prefix=''):
"""
Get statistics for message codes that start with the prefix.
prefix='' matches all errors and warnings
prefix='E' matches all errors
prefix='W' matches all warnings
prefix='E4' matches all errors that have to do with imports
"""
stats = []
keys = options.messages.keys()
keys.sort()
for key in keys:
if key.startswith(prefix):
stats.append('%-7s %s %s' %
(options.counters[key], key, options.messages[key]))
return stats
def print_statistics(prefix=''):
"""Print overall statistics (number of errors and warnings)."""
for line in get_statistics(prefix):
print(line)
def print_benchmark(elapsed):
"""
Print benchmark numbers.
"""
print('%-7.2f %s' % (elapsed, 'seconds elapsed'))
keys = ['directories', 'files',
'logical lines', 'physical lines']
for key in keys:
if key in options.counters:
print('%-7d %s per second (%d total)' % (
options.counters[key] / elapsed, key,
options.counters[key]))
def process_options(arglist=None):
"""
Process options passed either via arglist or via command line args.
"""
global options, args
usage = "%prog [options] input ..."
parser = OptionParser(usage)
parser.add_option('-v', '--verbose', default=0, action='count',
help="print status messages, or debug with -vv")
parser.add_option('-q', '--quiet', default=0, action='count',
help="report only file names, or nothing with -qq")
parser.add_option('--exclude', metavar='patterns', default=default_exclude,
help="skip matches (default %s)" % default_exclude)
parser.add_option('--filename', metavar='patterns',
help="only check matching files (e.g. *.py)")
parser.add_option('--ignore', metavar='errors', default='',
help="skip errors and warnings (e.g. E4,W)")
parser.add_option('--repeat', action='store_true',
help="show all occurrences of the same error")
parser.add_option('--show-source', action='store_true',
help="show source code for each error")
parser.add_option('--show-pep8', action='store_true',
help="show text of PEP 8 for each error")
parser.add_option('--statistics', action='store_true',
help="count errors and warnings")
parser.add_option('--benchmark', action='store_true',
help="measure processing speed")
parser.add_option('--testsuite', metavar='dir',
help="run regression tests from dir")
parser.add_option('--doctest', action='store_true',
help="run doctest on myself")
options, args = parser.parse_args(arglist)
if options.testsuite:
args.append(options.testsuite)
if len(args) == 0:
parser.error('input not specified')
options.prog = os.path.basename(sys.argv[0])
options.exclude = options.exclude.split(',')
for index in range(len(options.exclude)):
options.exclude[index] = options.exclude[index].rstrip('/')
if options.filename:
options.filename = options.filename.split(',')
if options.ignore:
options.ignore = options.ignore.split(',')
else:
options.ignore = []
options.counters = {}
options.messages = {}
return options, args
def _main():
"""
Parse options and run checks on Python source.
"""
options, args = process_options()
if options.doctest:
import doctest
return doctest.testmod()
start_time = time.time()
for path in args:
if os.path.isdir(path):
input_dir(path)
else:
input_file(path)
elapsed = time.time() - start_time
if options.statistics:
print_statistics()
if options.benchmark:
print_benchmark(elapsed)
if __name__ == '__main__':
_main()
| gpl-2.0 |
jfzazo/wireshark-hwgen | src/epan/dissectors/packet-enip.h | 3557 | /* packet-enip.h
* Routines for EtherNet/IP (Industrial Protocol) dissection
* EtherNet/IP Home: www.odva.org
*
* Conversation data support for CIP
* Jan Bartels, Siempelkamp Maschinen- und Anlagenbau GmbH & Co. KG
* Copyright 2007
*
* Wireshark - Network traffic analyzer
* By Gerald Combs <[email protected]>
* Copyright 1998 Gerald Combs
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef PACKET_ENIP_H
#define PACKET_ENIP_H
/* Offsets of fields within the DLR Common Frame Header */
#define DLR_CFH_SUB_TYPE 0
#define DLR_CFH_PROTO_VERSION 1
/* Offsets (from beginning of the packet) of fields within the DLR Message
* Payload Fields
*/
#define DLR_MPF_FRAME_TYPE 2
#define DLR_MPF_SOURCE_PORT 3
#define DLR_MPF_SOURCE_IP 4
#define DLR_MPF_SEQUENCE_ID 8
/* Offset for Beacon frames */
#define DLR_BE_RING_STATE 12
#define DLR_BE_SUPERVISOR_PRECEDENCE 13
#define DLR_BE_BEACON_INTERVAL 14
#define DLR_BE_BEACON_TIMEOUT 18
#define DLR_BE_RESERVED 22
/* Offset for Neighbor_Check_Request frames */
#define DLR_NREQ_RESERVED 12
/* Offset for Neighbor_Check_Response frames */
#define DLR_NRES_SOURCE_PORT 12
#define DLR_NRES_RESERVED 13
/* Offset for Link_Status/Neighbor_Status frames */
#define DLR_LNS_SOURCE_PORT 12
#define DLR_LNS_RESERVED 13
/* Offset for Locate_Fault frames */
#define DLR_LF_RESERVED 12
/* Offset for Announce frames */
#define DLR_AN_RING_STATE 12
#define DLR_AN_RESERVED 13
/* Offset for Sign_On frames */
#define DLR_SO_NUM_NODES 12
#define DLR_SO_NODE_1_MAC 14
/* Offset for Advertise frames */
#define DLR_ADV_GATEWAY_STATE 12
#define DLR_ADV_GATEWAY_PRECEDENCE 13
#define DLR_ADV_ADVERTISE_INTERVAL 14
#define DLR_ADV_ADVERTISE_TIMEOUT 18
#define DLR_ADV_LEARNING_UPDATE_ENABLE 22
#define DLR_ADV_RESERVED 23
/* Offset for Advertise frames */
#define DLR_FLUSH_LEARNING_UPDATE_ENABLE 12
#define DLR_FLUSH_RESERVED 13
/* Offset for Advertise frames */
#define DLR_LEARN_RESERVED 12
/* DLR commmands */
#define DLR_FT_BEACON 1
#define DLR_FT_NEIGHBOR_REQ 2
#define DLR_FT_NEIGHBOR_RES 3
#define DLR_FT_LINK_STAT 4
#define DLR_FT_LOCATE_FLT 5
#define DLR_FT_ANNOUNCE 6
#define DLR_FT_SIGN_ON 7
#define DLR_FT_ADVERTISE 8
#define DLR_FT_FLUSH_TABLES 9
#define DLR_FT_LEARNING_UPDATE 10
typedef struct {
guint32 req_num, rep_num;
nstime_t req_time;
cip_req_info_t* cip_info;
} enip_request_info_t;
enum enip_connid_type {ECIDT_UNKNOWN, ECIDT_O2T, ECIDT_T2O};
void enip_close_cip_connection( packet_info *pinfo, guint16 ConnSerialNumber, guint16 VendorID, guint32 DeviceSerialNumber );
extern attribute_info_t enip_attribute_vals[45];
#endif /* PACKET_ENIP_H */
| gpl-2.0 |
abyssinia/Lacuna-Server-Open | bin/saben/warning2.pl | 2222 | use 5.010;
use strict;
use lib '/data/Lacuna-Server/lib';
use Lacuna::DB;
use Lacuna;
use Lacuna::Util qw(randint format_date);
use Getopt::Long;
use List::MoreUtils qw(uniq);
use utf8;
$|=1;
our $quiet;
GetOptions(
'quiet' => \$quiet,
);
out('Started');
my $start = time;
out('Loading DB');
our $db = Lacuna->db;
my $empires = Lacuna->db->resultset('Lacuna::DB::Result::Empire');
out('getting empires...');
my $saben = $empires->find(-1);
my $lec = $empires->find(1);
out('Sending warning...');
my $message = q{Our recon teams have spotted a fleet of over 50 colony ships leaving the Sābēn staging colony in fringe space. It looks like they should reach the center of the Expanse in about a week, two at the most. We have no idea if there will be more, or if more have already left before we discovered that the Sābēn were back. This is far worse than we thought it would be.
We still are unsure what their plan of attack is, but we do know that it is more bold than anything we expected. We thought they'd start a single point of attack and push forward. However, the colony ships seem to be spreading out. Their current trajectory indicates that they will cover many zones at once. Maybe as much as -2|-1 to 2|3.
This tactic means that we won't be able to defend you. We simply do not have the ships or the ship building capabilitiy to cover so much area. You and your allies will have to defend each other. I wish I had better news, however, we'll still be happy to supply you with resources for all your ship building needs. You do still have that Subspace Transporter I gave you, right?
Your Trading Partner,
Tou Re Ell
Lacuna Expanse Corp};
$empires = $empires->search({tutorial_stage => 'turing'});
while (my $empire = $empires->next) {
$empire->send_message(
tag => 'Correspondence',
subject => 'Ships Spotted',
from => $lec,
body => $message,
);
}
my $finish = time;
out('Finished');
out((($finish - $start)/60)." minutes have elapsed");
###############
## SUBROUTINES
###############
sub out {
my $message = shift;
unless ($quiet) {
say format_date(DateTime->now), " ", $message;
}
}
| gpl-2.0 |
CyanogenMod/hardkernel-kernel-4412 | drivers/usb/host/xhci-pci.c | 9776 | /*
* xHCI host controller driver PCI Bus Glue.
*
* Copyright (C) 2008 Intel Corp.
*
* Author: Sarah Sharp
* Some code borrowed from the Linux EHCI driver.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/pci.h>
#include <linux/slab.h>
#include "xhci.h"
/* Device for a quirk */
#define PCI_VENDOR_ID_FRESCO_LOGIC 0x1b73
#define PCI_DEVICE_ID_FRESCO_LOGIC_PDK 0x1000
#define PCI_VENDOR_ID_ETRON 0x1b6f
#define PCI_DEVICE_ID_ASROCK_P67 0x7023
static const char hcd_name[] = "xhci_hcd";
/* called after powerup, by probe or system-pm "wakeup" */
static int xhci_pci_reinit(struct xhci_hcd *xhci, struct pci_dev *pdev)
{
/*
* TODO: Implement finding debug ports later.
* TODO: see if there are any quirks that need to be added to handle
* new extended capabilities.
*/
/* PCI Memory-Write-Invalidate cycle support is optional (uncommon) */
if (!pci_set_mwi(pdev))
xhci_dbg(xhci, "MWI active\n");
xhci_dbg(xhci, "Finished xhci_pci_reinit\n");
return 0;
}
static void xhci_pci_quirks(struct device *dev, struct xhci_hcd *xhci)
{
struct pci_dev *pdev = to_pci_dev(dev);
/* Look for vendor-specific quirks */
if (pdev->vendor == PCI_VENDOR_ID_FRESCO_LOGIC &&
pdev->device == PCI_DEVICE_ID_FRESCO_LOGIC_PDK) {
if (pdev->revision == 0x0) {
xhci->quirks |= XHCI_RESET_EP_QUIRK;
xhci_dbg(xhci, "QUIRK: Fresco Logic xHC needs configure"
" endpoint cmd after reset endpoint\n");
}
/* Fresco Logic confirms: all revisions of this chip do not
* support MSI, even though some of them claim to in their PCI
* capabilities.
*/
xhci->quirks |= XHCI_BROKEN_MSI;
xhci_dbg(xhci, "QUIRK: Fresco Logic revision %u "
"has broken MSI implementation\n",
pdev->revision);
xhci->quirks |= XHCI_TRUST_TX_LENGTH;
}
if (pdev->vendor == PCI_VENDOR_ID_NEC)
xhci->quirks |= XHCI_NEC_HOST;
if (pdev->vendor == PCI_VENDOR_ID_AMD && xhci->hci_version == 0x96)
xhci->quirks |= XHCI_AMD_0x96_HOST;
/* AMD PLL quirk */
if (pdev->vendor == PCI_VENDOR_ID_AMD && usb_amd_find_chipset_info())
xhci->quirks |= XHCI_AMD_PLL_FIX;
if (pdev->vendor == PCI_VENDOR_ID_INTEL &&
pdev->device == PCI_DEVICE_ID_INTEL_PANTHERPOINT_XHCI) {
xhci->quirks |= XHCI_SPURIOUS_SUCCESS;
xhci->quirks |= XHCI_EP_LIMIT_QUIRK;
xhci->limit_active_eps = 64;
/*
* PPT desktop boards DH77EB and DH77DF will power back on after
* a few seconds of being shutdown. The fix for this is to
* switch the ports from xHCI to EHCI on shutdown. We can't use
* DMI information to find those particular boards (since each
* vendor will change the board name), so we have to key off all
* PPT chipsets.
*/
xhci->quirks |= XHCI_SPURIOUS_REBOOT;
xhci->quirks |= XHCI_AVOID_BEI;
}
if (pdev->vendor == PCI_VENDOR_ID_ETRON &&
pdev->device == PCI_DEVICE_ID_ASROCK_P67) {
xhci->quirks |= XHCI_RESET_ON_RESUME;
xhci_dbg(xhci, "QUIRK: Resetting on resume\n");
xhci->quirks |= XHCI_TRUST_TX_LENGTH;
}
}
/* called during probe() after chip reset completes */
static int xhci_pci_setup(struct usb_hcd *hcd)
{
struct xhci_hcd *xhci;
struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
int retval;
retval = xhci_gen_setup(hcd, xhci_pci_quirks);
if (retval)
return retval;
xhci = hcd_to_xhci(hcd);
if (!usb_hcd_is_primary_hcd(hcd))
return 0;
pci_read_config_byte(pdev, XHCI_SBRN_OFFSET, &xhci->sbrn);
xhci_dbg(xhci, "Got SBRN %u\n", (unsigned int) xhci->sbrn);
/* Find any debug ports */
retval = xhci_pci_reinit(xhci, pdev);
if (!retval)
return retval;
kfree(xhci);
return retval;
}
/*
* We need to register our own PCI probe function (instead of the USB core's
* function) in order to create a second roothub under xHCI.
*/
static int xhci_pci_probe(struct pci_dev *dev, const struct pci_device_id *id)
{
int retval;
struct xhci_hcd *xhci;
struct hc_driver *driver;
struct usb_hcd *hcd;
driver = (struct hc_driver *)id->driver_data;
/* Register the USB 2.0 roothub.
* FIXME: USB core must know to register the USB 2.0 roothub first.
* This is sort of silly, because we could just set the HCD driver flags
* to say USB 2.0, but I'm not sure what the implications would be in
* the other parts of the HCD code.
*/
retval = usb_hcd_pci_probe(dev, id);
if (retval)
return retval;
/* USB 2.0 roothub is stored in the PCI device now. */
hcd = dev_get_drvdata(&dev->dev);
xhci = hcd_to_xhci(hcd);
xhci->shared_hcd = usb_create_shared_hcd(driver, &dev->dev,
pci_name(dev), hcd);
if (!xhci->shared_hcd) {
retval = -ENOMEM;
goto dealloc_usb2_hcd;
}
if (pdev->vendor == PCI_VENDOR_ID_VIA)
xhci->quirks |= XHCI_RESET_ON_RESUME;
/* Set the xHCI pointer before xhci_pci_setup() (aka hcd_driver.reset)
* is called by usb_add_hcd().
*/
*((struct xhci_hcd **) xhci->shared_hcd->hcd_priv) = xhci;
retval = usb_add_hcd(xhci->shared_hcd, dev->irq,
IRQF_DISABLED | IRQF_SHARED);
if (retval)
goto put_usb3_hcd;
/* Roothub already marked as USB 3.0 speed */
return 0;
put_usb3_hcd:
usb_put_hcd(xhci->shared_hcd);
dealloc_usb2_hcd:
usb_hcd_pci_remove(dev);
return retval;
}
static void xhci_pci_remove(struct pci_dev *dev)
{
struct xhci_hcd *xhci;
xhci = hcd_to_xhci(pci_get_drvdata(dev));
if (xhci->shared_hcd) {
usb_remove_hcd(xhci->shared_hcd);
usb_put_hcd(xhci->shared_hcd);
}
usb_hcd_pci_remove(dev);
kfree(xhci);
}
#ifdef CONFIG_PM
static int xhci_pci_suspend(struct usb_hcd *hcd, bool do_wakeup)
{
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
int retval = 0;
if (hcd->state != HC_STATE_SUSPENDED ||
xhci->shared_hcd->state != HC_STATE_SUSPENDED)
return -EINVAL;
retval = xhci_suspend(xhci);
return retval;
}
static int xhci_pci_resume(struct usb_hcd *hcd, bool hibernated)
{
struct xhci_hcd *xhci = hcd_to_xhci(hcd);
struct pci_dev *pdev = to_pci_dev(hcd->self.controller);
int retval = 0;
/* The BIOS on systems with the Intel Panther Point chipset may or may
* not support xHCI natively. That means that during system resume, it
* may switch the ports back to EHCI so that users can use their
* keyboard to select a kernel from GRUB after resume from hibernate.
*
* The BIOS is supposed to remember whether the OS had xHCI ports
* enabled before resume, and switch the ports back to xHCI when the
* BIOS/OS semaphore is written, but we all know we can't trust BIOS
* writers.
*
* Unconditionally switch the ports back to xHCI after a system resume.
* We can't tell whether the EHCI or xHCI controller will be resumed
* first, so we have to do the port switchover in both drivers. Writing
* a '1' to the port switchover registers should have no effect if the
* port was already switched over.
*/
if (usb_is_intel_switchable_xhci(pdev))
usb_enable_xhci_ports(pdev);
retval = xhci_resume(xhci, hibernated);
return retval;
}
#endif /* CONFIG_PM */
static const struct hc_driver xhci_pci_hc_driver = {
.description = hcd_name,
.product_desc = "xHCI Host Controller",
.hcd_priv_size = sizeof(struct xhci_hcd *),
/*
* generic hardware linkage
*/
.irq = xhci_irq,
.flags = HCD_MEMORY | HCD_USB3 | HCD_SHARED,
/*
* basic lifecycle operations
*/
.reset = xhci_pci_setup,
.start = xhci_run,
#ifdef CONFIG_PM
.pci_suspend = xhci_pci_suspend,
.pci_resume = xhci_pci_resume,
#endif
.stop = xhci_stop,
.shutdown = xhci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = xhci_urb_enqueue,
.urb_dequeue = xhci_urb_dequeue,
.alloc_dev = xhci_alloc_dev,
.free_dev = xhci_free_dev,
.alloc_streams = xhci_alloc_streams,
.free_streams = xhci_free_streams,
.add_endpoint = xhci_add_endpoint,
.drop_endpoint = xhci_drop_endpoint,
.endpoint_reset = xhci_endpoint_reset,
.check_bandwidth = xhci_check_bandwidth,
.reset_bandwidth = xhci_reset_bandwidth,
.address_device = xhci_address_device,
.update_hub_device = xhci_update_hub_device,
.reset_device = xhci_discover_or_reset_device,
/*
* scheduling support
*/
.get_frame_number = xhci_get_frame,
/* Root hub support */
.hub_control = xhci_hub_control,
.hub_status_data = xhci_hub_status_data,
.bus_suspend = xhci_bus_suspend,
.bus_resume = xhci_bus_resume,
};
/*-------------------------------------------------------------------------*/
/* PCI driver selection metadata; PCI hotplugging uses this */
static const struct pci_device_id pci_ids[] = { {
/* handle any USB 3.0 xHCI controller */
PCI_DEVICE_CLASS(PCI_CLASS_SERIAL_USB_XHCI, ~0),
.driver_data = (unsigned long) &xhci_pci_hc_driver,
},
{ /* end: all zeroes */ }
};
MODULE_DEVICE_TABLE(pci, pci_ids);
/* pci driver glue; this is a "new style" PCI driver module */
static struct pci_driver xhci_pci_driver = {
.name = (char *) hcd_name,
.id_table = pci_ids,
.probe = xhci_pci_probe,
.remove = xhci_pci_remove,
/* suspend and resume implemented later */
.shutdown = usb_hcd_pci_shutdown,
#ifdef CONFIG_PM_SLEEP
.driver = {
.pm = &usb_hcd_pci_pm_ops
},
#endif
};
int __init xhci_register_pci(void)
{
return pci_register_driver(&xhci_pci_driver);
}
void __exit xhci_unregister_pci(void)
{
pci_unregister_driver(&xhci_pci_driver);
}
| gpl-2.0 |
aldencolerain/mc2kernel | drivers/crypto/mvebu_cesa/Makefile | 728 | #
# Makefile for the Marvell CESA driver
#
CPU_ARCH = ARM
ifeq ($(CONFIG_CPU_BIG_ENDIAN),y)
ENDIAN = BE
else
ENDIAN = LE
endif
MV_DEFINE = -DMV_LINUX -DMV_CPU_$(ENDIAN) -DMV_$(CPU_ARCH)
CESA_DIR := drivers/crypto/mvebu_cesa
obj-y += cesa_if.o cesa_ocf_drv.o cesa_test.o
obj-$(CONFIG_MV_CESA_TOOL) += cesa_dev.o
obj-y += hal/mvCesa.o hal/mvCesaDebug.o hal/mvSHA256.o \
hal/mvMD5.o hal/mvSHA1.o hal/AES/mvAesAlg.o \
hal/AES/mvAesApi.o
EXTRA_INCLUDE = -I$(CESA_DIR)
EXTRA_INCLUDE += -I$(srctree)/arch/arm/mach-mvebu/include/mach
EXTRA_INCLUDE += -I$(srctree)/arch/arm/mach-mvebu/linux_oss
EXTRA_INCLUDE += -I$(CESA_DIR)/hal
EXTRA_INCLUDE += -I$(srctree)/crypto/ocf
ccflags-y += $(EXTRA_INCLUDE) $(MV_DEFINE)
| gpl-2.0 |
DZB-Team/kernel_torino_cm11 | drivers/regulator/max8986-regulator.c | 29852 | /*******************************************************************************
* Copyright 2010 Broadcom Corporation. All rights reserved.
*
* @file drivers/regulator/max8986-regulator.c
*
* Unless you and Broadcom execute a separate written software license agreement
* governing use of this software, this software is licensed to you under the
* terms of the GNU General Public License version 2, available at
* http://www.gnu.org/copyleft/gpl.html (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*******************************************************************************/
/**
*
* @file max8986-regulator.c
*
* @brief Regulator Driver for Broadcom MAX8986 PMU
*
****************************************************************************/
#include <linux/kernel.h>
#include <linux/version.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/ioport.h>
#include <linux/delay.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/platform_device.h>
#include <linux/ioctl.h>
#include <linux/uaccess.h>
#include <linux/mfd/max8986/max8986.h>
#include <asm/io.h>
#include <linux/regulator/machine.h>
#include <linux/regulator/driver.h>
#define MICRO_VOLT(x) ((x)*1000L*1000L)
#define _DEFINE_REGL_VOLT(vol, regVal) { MICRO_VOLT(vol), regVal }
#define MAX8986_DEFINE_REGL(_name, _pm_reg, _ctrl_reg, _vol_list)\
[MAX8986_REGL_##_name] =\
{\
.desc = {\
.name = "MAX8986_REGL_"#_name,\
.ops = &max8986_regulator_ops,\
.type = REGULATOR_VOLTAGE,\
.id = MAX8986_REGL_##_name,\
.owner = THIS_MODULE,\
},\
.ctrl_reg = _ctrl_reg,\
.pm_reg = _pm_reg,\
.num_vol = ARRAY_SIZE(_vol_list),\
.vol_list = _vol_list,\
}
enum {
PC2PC1_00 = 0,
PC2PC1_01 = 2,
PC2PC1_10 = 4,
PC2PC1_11 = 6
};
struct max8986_regl {
struct regulator_desc desc;
u32 ctrl_reg;
u32 pm_reg;
u8 num_vol;
u8 dsm_opmode;
int const (*vol_list)[2];
};
struct max8986_regl_priv {
struct max8986 *max8986;
int num_regl;
struct regulator_dev *regl[];
};
static const int aldo1_vol[][2] = {
_DEFINE_REGL_VOLT(3.0, 7), /*111: 3.0V */
};
static const int aldo2_vol[][2] = {
_DEFINE_REGL_VOLT(2.5, 0), /*000: 2.5V */
_DEFINE_REGL_VOLT(2.6, 1), /*001: 2.6V */
_DEFINE_REGL_VOLT(2.7, 2), /*010: 2.7V */
_DEFINE_REGL_VOLT(2.8, 3), /*011: 2.8V */
};
static const int aldo3_vol[][2] = {
_DEFINE_REGL_VOLT(3.3, 7), /*111: 3.3V */
};
static const int aldo4_vol[][2] = {
_DEFINE_REGL_VOLT(2.8, 0x10), /*10 000: 2.8V */
};
static const int aldo5_vol[][2] = {
_DEFINE_REGL_VOLT(2.8, 0x1F), /*11 111: 2.8V */
};
static const int aldo6_vol[][2] = {
_DEFINE_REGL_VOLT(1.2, 0), /*0000: 1.2V */
_DEFINE_REGL_VOLT(1.4, 7), /*0111: 1.4V */
_DEFINE_REGL_VOLT(1.5, 8), /*1001: 1.5V */
_DEFINE_REGL_VOLT(1.8, 9), /*1001: 1.8V */
_DEFINE_REGL_VOLT(2.7, 0xA), /*1010: 2.7V */
_DEFINE_REGL_VOLT(2.8, 0xB), /*1011: 2.8V */
_DEFINE_REGL_VOLT(2.9, 0xC), /*1100: 2.9V */
_DEFINE_REGL_VOLT(3.0, 0xD), /*1101: 3.0V */
_DEFINE_REGL_VOLT(3.3, 0xE), /*1110: 3.3V */
_DEFINE_REGL_VOLT(1.3, 0xF), /*1111: 1.3V */
};
/* aldo9, dldo3, dldo4 and auxldo1 are having same values like aldo7_vol
* Becareful while changing aldo7_vol values
*/
static const int aldo7_vol[][2] = {
_DEFINE_REGL_VOLT(1.2, 0), /*00000: 1.2V */
_DEFINE_REGL_VOLT(1.3, 1), /*00001: 1.3V */
_DEFINE_REGL_VOLT(1.4, 2), /*00010: 1.4V */
_DEFINE_REGL_VOLT(1.5, 3), /*00011: 1.5V */
_DEFINE_REGL_VOLT(1.6, 4), /*00100: 1.6V */
_DEFINE_REGL_VOLT(1.7, 5), /*00101: 1.7V */
_DEFINE_REGL_VOLT(1.8, 6), /*00110: 1.8V */
_DEFINE_REGL_VOLT(1.9, 7), /*00111: 1.9V */
_DEFINE_REGL_VOLT(2.0, 8), /*01000: 2.0V */
_DEFINE_REGL_VOLT(2.1, 9), /*01001: 2.1V */
_DEFINE_REGL_VOLT(2.2, 0xA), /*01010: 2.2V */
_DEFINE_REGL_VOLT(2.3, 0xB), /*01011: 2.3V */
_DEFINE_REGL_VOLT(2.4, 0xC), /*01100: 2.4V */
_DEFINE_REGL_VOLT(2.5, 0xD), /*01101: 2.5V */
_DEFINE_REGL_VOLT(2.6, 0xE), /*01110: 2.6V */
_DEFINE_REGL_VOLT(2.7, 0xF), /*01111: 2.7V */
_DEFINE_REGL_VOLT(2.8, 0x10), /*10000: 2.8V */
_DEFINE_REGL_VOLT(2.9, 0x11), /*10001: 2.9V */
_DEFINE_REGL_VOLT(3.0, 0x12), /*10010: 3.0V */
_DEFINE_REGL_VOLT(3.1, 0x13), /*10011: 3.1V */
_DEFINE_REGL_VOLT(3.2, 0x14), /*10100: 3.2V */
_DEFINE_REGL_VOLT(3.3, 0x15), /*10101: 3.3V */
};
static const int aldo8_vol[][2] = {
_DEFINE_REGL_VOLT(2.5, 0), /*0000: 2.5V */
_DEFINE_REGL_VOLT(2.6, 1), /*0001: 2.6V */
_DEFINE_REGL_VOLT(2.8, 2), /*0010: 2.8V */
_DEFINE_REGL_VOLT(2.9, 3), /*0011: 2.9V */
_DEFINE_REGL_VOLT(3.0, 4), /*0100: 3.0V */
_DEFINE_REGL_VOLT(1.8, 5), /*0101: 1.8V */
_DEFINE_REGL_VOLT(3.3, 6), /*0110: 3.3V */
_DEFINE_REGL_VOLT(2.7, 7), /*0111: 2.7V */
};
/* aldo9 & aldo7 have same voltage values */
#define aldo9_vol aldo7_vol
/* hcldo1_vol and hcldo2_vol are having same values like dldo1_vol
* Becareful while changing dldo1_vol values
*/
static const int dldo1_vol[][2] = {
_DEFINE_REGL_VOLT(2.5, 0), /*00000: 2.5V */
_DEFINE_REGL_VOLT(2.6, 1), /*00001: 2.6V */
_DEFINE_REGL_VOLT(2.7, 2), /*00010: 2.7V */
_DEFINE_REGL_VOLT(2.8, 3), /*00011: 2.8V */
_DEFINE_REGL_VOLT(2.9, 4), /*00100: 2.9V */
_DEFINE_REGL_VOLT(3.3, 5), /*00101: 3.3V */
_DEFINE_REGL_VOLT(3.1, 6), /*00110: 3.1V */
_DEFINE_REGL_VOLT(3.0, 7), /*00111: 3.0V */
};
static const int dldo2_vol[][2] = {
_DEFINE_REGL_VOLT(1.8, 6), /*00110: 1.8V */
};
/* dldo3 & aldo7 have same voltage values */
#define dldo3_vol aldo7_vol
/* dldo4 & aldo7 have same voltage values */
#define dldo4_vol aldo7_vol
/* hcldo1 & dldo1 have same voltage values */
#define hcldo1_vol dldo1_vol
/* hcldo2 & dldo1 have same voltage values */
#define hcldo2_vol dldo1_vol
static const int lvldo_vol[][2] = {
_DEFINE_REGL_VOLT(1.2, 0), /*00000: 1.2V */
};
static const int simldo_vol[][2] = {
_DEFINE_REGL_VOLT(3.0, 0), /*00: 3.0V */
_DEFINE_REGL_VOLT(2.5, 1), /*01: 2.5V */
_DEFINE_REGL_VOLT(3.1, 2), /*10: 3.1V */
_DEFINE_REGL_VOLT(1.8, 3), /*11: 1.8V */
};
/* auxldo1 & aldo7 have same voltage values */
#define auxldo1_vol aldo7_vol
static const int tsrldo_vol[][2] = {
_DEFINE_REGL_VOLT(0.7, 0), /*00000: 0.7V */
_DEFINE_REGL_VOLT(0.8, 1), /*00001: 0.8V */
_DEFINE_REGL_VOLT(0.9, 2), /*00010: 0.9V */
_DEFINE_REGL_VOLT(1.0, 3), /*00011: 1.0V */
_DEFINE_REGL_VOLT(1.1, 4), /*00100: 1.1V */
_DEFINE_REGL_VOLT(1.2, 5), /*00101: 1.2V */
_DEFINE_REGL_VOLT(1.3, 6), /*00110: 1.3V */
_DEFINE_REGL_VOLT(1.4, 7), /*00111: 1.4V */
_DEFINE_REGL_VOLT(1.5, 8), /*01000: 1.5V */
_DEFINE_REGL_VOLT(1.6, 9), /*01001: 1.6V */
_DEFINE_REGL_VOLT(1.7, 0xA), /*01010: 1.7V */
_DEFINE_REGL_VOLT(1.8, 0xB), /*01011: 1.8V */
_DEFINE_REGL_VOLT(1.9, 0xC), /*01100: 1.9V */
_DEFINE_REGL_VOLT(2.0, 0xD), /*01101: 2.0V */
_DEFINE_REGL_VOLT(2.1, 0xE), /*01110: 2.1V */
_DEFINE_REGL_VOLT(2.2, 0xF), /*01111: 2.2V */
_DEFINE_REGL_VOLT(2.3, 0x10), /*10000: 2.3V */
_DEFINE_REGL_VOLT(2.4, 0x11), /*10001: 2.4V */
_DEFINE_REGL_VOLT(2.5, 0x12), /*10010: 2.5V */
_DEFINE_REGL_VOLT(2.6, 0x13), /*10011: 2.6V */
_DEFINE_REGL_VOLT(2.7, 0x14), /*10100: 2.7V */
_DEFINE_REGL_VOLT(2.8, 0x15), /*10101: 2.8V */
_DEFINE_REGL_VOLT(2.9, 0x16), /*10110: 2.9V */
};
#ifdef CONFIG_MFD_MAX8999_REV0
static const int csr_dvs_vol[][2] = {
_DEFINE_REGL_VOLT(0.84, 0),
_DEFINE_REGL_VOLT(0.86, 1),
_DEFINE_REGL_VOLT(1.46, 2),
_DEFINE_REGL_VOLT(1.44, 3),
_DEFINE_REGL_VOLT(1.42, 4),
_DEFINE_REGL_VOLT(1.40, 5),
_DEFINE_REGL_VOLT(1.38, 6),
_DEFINE_REGL_VOLT(1.36, 7),
_DEFINE_REGL_VOLT(1.34, 8),
_DEFINE_REGL_VOLT(1.32, 9),
_DEFINE_REGL_VOLT(1.30, 0xA),
_DEFINE_REGL_VOLT(1.28, 0xB),
_DEFINE_REGL_VOLT(1.26, 0xC),
_DEFINE_REGL_VOLT(1.24, 0xD),
_DEFINE_REGL_VOLT(1.22, 0xE),
_DEFINE_REGL_VOLT(1.20, 0xF),
_DEFINE_REGL_VOLT(1.18, 0x10),
_DEFINE_REGL_VOLT(1.16, 0x11),
_DEFINE_REGL_VOLT(1.14, 0x12),
_DEFINE_REGL_VOLT(1.12, 0x13),
_DEFINE_REGL_VOLT(1.10, 0x14),
_DEFINE_REGL_VOLT(1.08, 0x15),
_DEFINE_REGL_VOLT(1.06, 0x16),
_DEFINE_REGL_VOLT(1.04, 0x17),
_DEFINE_REGL_VOLT(1.02, 0x18),
_DEFINE_REGL_VOLT(1.00, 0x19),
_DEFINE_REGL_VOLT(0.98, 0x1A),
_DEFINE_REGL_VOLT(0.96, 0x1B),
_DEFINE_REGL_VOLT(0.94, 0x1C),
_DEFINE_REGL_VOLT(0.92, 0x1D),
_DEFINE_REGL_VOLT(0.90, 0x1E),
_DEFINE_REGL_VOLT(0.88, 0x1F)
};
static const int iosr_vol[][2] = {
_DEFINE_REGL_VOLT(1.70, 0),
_DEFINE_REGL_VOLT(1.75, 1),
_DEFINE_REGL_VOLT(1.80, 2),
_DEFINE_REGL_VOLT(1.85, 3),
_DEFINE_REGL_VOLT(1.90, 4),
_DEFINE_REGL_VOLT(1.95, 5),
_DEFINE_REGL_VOLT(2.00, 6),
_DEFINE_REGL_VOLT(2.05, 7),
};
#else /* !CONFIG_MFD_MAX8999_REV0 */
static const int csr_dvs_vol[][2] = {
_DEFINE_REGL_VOLT(0.76, 0),
_DEFINE_REGL_VOLT(0.78, 1),
_DEFINE_REGL_VOLT(0.80, 2),
_DEFINE_REGL_VOLT(0.82, 3),
_DEFINE_REGL_VOLT(0.84, 4),
_DEFINE_REGL_VOLT(0.86, 5),
_DEFINE_REGL_VOLT(1.38, 6),
_DEFINE_REGL_VOLT(1.36, 7),
_DEFINE_REGL_VOLT(1.34, 8),
_DEFINE_REGL_VOLT(1.32, 9),
_DEFINE_REGL_VOLT(1.30, 0xA),
_DEFINE_REGL_VOLT(1.28, 0xB),
_DEFINE_REGL_VOLT(1.26, 0xC),
_DEFINE_REGL_VOLT(1.24, 0xD),
_DEFINE_REGL_VOLT(1.22, 0xE),
_DEFINE_REGL_VOLT(1.20, 0xF),
_DEFINE_REGL_VOLT(1.18, 0x10),
_DEFINE_REGL_VOLT(1.16, 0x11),
_DEFINE_REGL_VOLT(1.14, 0x12),
_DEFINE_REGL_VOLT(1.12, 0x13),
_DEFINE_REGL_VOLT(1.10, 0x14),
_DEFINE_REGL_VOLT(1.08, 0x15),
_DEFINE_REGL_VOLT(1.06, 0x16),
_DEFINE_REGL_VOLT(1.04, 0x17),
_DEFINE_REGL_VOLT(1.02, 0x18),
_DEFINE_REGL_VOLT(1.00, 0x19),
_DEFINE_REGL_VOLT(0.98, 0x1A),
_DEFINE_REGL_VOLT(0.96, 0x1B),
_DEFINE_REGL_VOLT(0.94, 0x1C),
_DEFINE_REGL_VOLT(0.92, 0x1D),
_DEFINE_REGL_VOLT(0.90, 0x1E),
_DEFINE_REGL_VOLT(0.88, 0x1F)
};
static const int iosr_vol[][2] = {
_DEFINE_REGL_VOLT(1.8, 7), /*00111: 1.8V */
};
#endif /* #ifdef CONFIG_MFD_MAX8999_REV0 */
static struct regulator_ops max8986_regulator_ops;
static struct max8986_regl max8986_regls[] = {
MAX8986_DEFINE_REGL(ALDO1, MAX8986_PM_REG_A1OPMODCTRL,
MAX8986_PM_REG_A1_D1_LDOCTRL, aldo1_vol),
MAX8986_DEFINE_REGL(ALDO2, MAX8986_PM_REG_A2OPMODCTRL,
MAX8986_PM_REG_A8_A2_LDOCTRL, aldo2_vol),
MAX8986_DEFINE_REGL(ALDO3, MAX8986_PM_REG_A3OPMODCTRL,
MAX8986_PM_REG_A5_A3_LDOCTRL, aldo3_vol),
MAX8986_DEFINE_REGL(ALDO4, MAX8986_PM_REG_A4OPMODCTRL,
MAX8986_PM_REG_A4_SIM_LDOCTRL, aldo4_vol),
MAX8986_DEFINE_REGL(ALDO5, MAX8986_PM_REG_A5OPMODCTRL,
MAX8986_PM_REG_A5_A3_LDOCTRL, aldo5_vol),
MAX8986_DEFINE_REGL(ALDO6, MAX8986_PM_REG_A6OPMODCTRL,
MAX8986_PM_REG_LV_A6_LDOCTRL, aldo6_vol),
MAX8986_DEFINE_REGL(ALDO7, MAX8986_PM_REG_A7OPMODCTRL,
MAX8986_PM_REG_A7LDOCTRL, aldo7_vol),
MAX8986_DEFINE_REGL(ALDO8, MAX8986_PM_REG_A8OPMODCTRL,
MAX8986_PM_REG_A8_A2_LDOCTRL, aldo8_vol),
MAX8986_DEFINE_REGL(ALDO9, MAX8986_PM_REG_A9OPMODCTRL,
MAX8986_PM_REG_A9LDOCTRL, aldo9_vol),
MAX8986_DEFINE_REGL(DLDO1, MAX8986_PM_REG_D1OPMODCTRL,
MAX8986_PM_REG_A1_D1_LDOCTRL, dldo1_vol),
MAX8986_DEFINE_REGL(DLDO2, MAX8986_PM_REG_D2OPMODCTRL,
MAX8986_PM_REG_D2LDOCTRL, dldo2_vol),
MAX8986_DEFINE_REGL(DLDO3, MAX8986_PM_REG_D3OPMODCTRL,
MAX8986_PM_REG_D3LDOCTRL, dldo3_vol),
MAX8986_DEFINE_REGL(DLDO4, MAX8986_PM_REG_D4OPMODCTRL,
MAX8986_PM_REG_D4LDOCTRL, dldo4_vol),
MAX8986_DEFINE_REGL(HCLDO1, MAX8986_PM_REG_H1OPMODCTRL,
MAX8986_PM_REG_HCLDOCTRL, hcldo1_vol),
MAX8986_DEFINE_REGL(HCLDO2, MAX8986_PM_REG_H2OPMODCTRL,
MAX8986_PM_REG_HCLDOCTRL, hcldo2_vol),
MAX8986_DEFINE_REGL(LVLDO, MAX8986_PM_REG_LVOPMODCTRL,
MAX8986_PM_REG_LV_A6_LDOCTRL, lvldo_vol),
MAX8986_DEFINE_REGL(SIMLDO, MAX8986_PM_REG_SIMOPMODCTRL,
MAX8986_PM_REG_A4_SIM_LDOCTRL, simldo_vol),
MAX8986_DEFINE_REGL(AUXLDO1, MAX8986_PM_REG_AX1OPMODCTRL,
MAX8986_PM_REG_AX1LDOCTRL, auxldo1_vol),
MAX8986_DEFINE_REGL(TSRLDO, MAX8986_PM_REG_TSROPMODCTRL,
MAX8986_PM_REG_TSRCTRL, tsrldo_vol),
/*CSR is registered as 3 regulators to control LPM, NM1 & NM2 voltages */
MAX8986_DEFINE_REGL(CSR_NM1, MAX8986_PM_REG_CSROPMODCTRL,
MAX8986_PM_REG_CSRCTRL10, csr_dvs_vol),
MAX8986_DEFINE_REGL(CSR_NM2, MAX8986_PM_REG_CSROPMODCTRL,
MAX8986_PM_REG_CSRCTRL3, csr_dvs_vol),
MAX8986_DEFINE_REGL(CSR_LPM, MAX8986_PM_REG_CSROPMODCTRL,
MAX8986_PM_REG_CSRCTRL1, csr_dvs_vol),
MAX8986_DEFINE_REGL(IOSR, MAX8986_PM_REG_IOSROPMODCTRL,
MAX8986_PM_REG_IOSRCTRL2, iosr_vol),
};
int max8986_csr_reg2volt(int reg)
{
int volt = -EINVAL;
int i;
for (i = 0; i < ARRAY_SIZE(csr_dvs_vol); i++) {
if (csr_dvs_vol[i][1] == reg) {
volt = csr_dvs_vol[i][0];
break;
}
}
return volt;
}
EXPORT_SYMBOL(max8986_csr_reg2volt);
static u8 max8986_regulator_ctrl_reg_mask(int regl_id, int *bitPos)
{
u8 mask = 0;
switch (regl_id) {
case MAX8986_REGL_ALDO1:
case MAX8986_REGL_ALDO8:
case MAX8986_REGL_HCLDO1:
*bitPos = 0;
mask = 0x7;
break;
case MAX8986_REGL_DLDO1:
case MAX8986_REGL_ALDO2:
case MAX8986_REGL_HCLDO2:
*bitPos = 4;
mask = 0x7;
break;
case MAX8986_REGL_AUXLDO1:
case MAX8986_REGL_ALDO4:
case MAX8986_REGL_DLDO2:
case MAX8986_REGL_ALDO5:
case MAX8986_REGL_ALDO7:
case MAX8986_REGL_DLDO3:
case MAX8986_REGL_DLDO4:
case MAX8986_REGL_ALDO9:
case MAX8986_REGL_TSRLDO:
*bitPos = 0;
mask = 0x1F;
break;
case MAX8986_REGL_ALDO3:
*bitPos = 5;
mask = 0x7;
break;
case MAX8986_REGL_SIMLDO:
*bitPos = 6;
mask = 0x3;
break;
case MAX8986_REGL_LVLDO:
*bitPos = 0;
mask = 0xF;
break;
case MAX8986_REGL_ALDO6:
*bitPos = 4;
mask = 0xF;
break;
case MAX8986_REGL_CSR_LPM:
case MAX8986_REGL_CSR_NM2:
case MAX8986_REGL_CSR_NM1:
mask = 0x1F;
*bitPos = 0;
break;
case MAX8986_REGL_IOSR:
*bitPos = 2;
mask = 0x1F;
break;
default:
return 0;
}
mask <<= *bitPos;
return mask;
}
static int _max8986_regulator_enable(struct max8986_regl_priv *regl_priv,
int id)
{
struct max8986 *max8986 = regl_priv->max8986;
int ret;
u8 regVal;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
ret = max8986->read_dev(max8986, max8986_regls[id].pm_reg, ®Val);
/*00: ON (normal) 01: Low power mode 10: OFF */
/*Normal mode : PC1 = 1*/
regVal &= ~((PMU_REGL_MASK << PC2PC1_01) |
(PMU_REGL_MASK << PC2PC1_11));
switch (max8986_regls[id].dsm_opmode) {
case MAX8986_REGL_OFF_IN_DSM:
/* clear LPM bits */
regVal &= ~((PMU_REGL_MASK << PC2PC1_00) |
(PMU_REGL_MASK << PC2PC1_10));
/* set to off in DSM */
regVal |= ((PMU_REGL_OFF << PC2PC1_00) |
(PMU_REGL_OFF << PC2PC1_10));
break;
case MAX8986_REGL_LPM_IN_DSM:
regVal &= ~((PMU_REGL_MASK << PC2PC1_00) |
(PMU_REGL_MASK << PC2PC1_10));
regVal |= ((PMU_REGL_ECO << PC2PC1_00) |
(PMU_REGL_ECO << PC2PC1_10));
break;
case MAX8986_REGL_ON_IN_DSM:
/* clear LPM bits - on in DSM */
regVal &= ~((PMU_REGL_MASK << PC2PC1_00) |
(PMU_REGL_MASK << PC2PC1_10));
break;
}
ret |= max8986->write_dev(max8986, max8986_regls[id].pm_reg, regVal);
return ret;
}
static int max8986_regulator_enable(struct regulator_dev *rdev)
{
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
return _max8986_regulator_enable(regl_priv, id);
}
static int _max8986_regulator_disable(struct max8986_regl_priv *regl_priv,
int id)
{
struct max8986 *max8986 = regl_priv->max8986;
int ret;
u8 regVal = 0;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
/*00: ON (normal) 01: Low power mode 10: OFF*/
/*Normal mode : PC1 = 1*/
regVal = ((PMU_REGL_OFF << PC2PC1_00) |
(PMU_REGL_OFF << PC2PC1_10) |
(PMU_REGL_OFF << PC2PC1_01) |
(PMU_REGL_OFF << PC2PC1_11));
/* set to off in all modes */
ret = max8986->write_dev(max8986, max8986_regls[id].pm_reg, regVal);
return ret;
}
static int max8986_regulator_disable(struct regulator_dev *rdev)
{
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
return _max8986_regulator_disable(regl_priv, id);
}
static int _max8986_regulator_is_enabled(struct max8986_regl_priv *regl_priv,
int id)
{
struct max8986 *max8986 = regl_priv->max8986;
int ret;
u8 regVal;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return 0;
ret = max8986->read_dev(max8986, max8986_regls[id].pm_reg, ®Val);
if (ret < 0)
return 0;
/*00: ON (normal) 01: Low power mode 10: OFF*/
return ((regVal & (PMU_REGL_MASK << PC2PC1_01)) == 0);
}
static int max8986_regulator_is_enabled(struct regulator_dev *rdev)
{
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
return _max8986_regulator_is_enabled(regl_priv, id);
}
static int max8986_get_best_voltage_inx(int reg_id, int min_uV, int max_uV)
{
/*int reg_id = rdev_get_id(rdev); */
int i;
int bestmatch;
int bestindex;
/*
* Locate the minimum voltage fitting the criteria on
* this regulator. The switchable voltages are not
* in strict falling order so we need to check them
* all for the best match.
*/
if ((reg_id < 0) || (reg_id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
bestmatch = INT_MAX;
bestindex = -1;
for (i = 0; i < max8986_regls[reg_id].num_vol; i++) {
if (max8986_regls[reg_id].vol_list[i][0] >= min_uV &&
max8986_regls[reg_id].vol_list[i][0] < bestmatch) {
bestmatch = max8986_regls[reg_id].vol_list[i][0];
bestindex = i;
}
}
if (bestindex < 0 || bestmatch > max_uV) {
pr_info("%s: no possible values for min_uV = %d & max_uV = %d\n"
, __func__, min_uV, max_uV);
return -EINVAL;
}
return bestindex;
}
static int _max8986_regulator_set_voltage(struct max8986_regl_priv *pri_dev,
int id, int volt)
{
struct max8986_regl_priv *regl_priv = pri_dev;
struct max8986 *max8986 = regl_priv->max8986;
int bitPos, ret;
u8 mask, regVal;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
mask = max8986_regulator_ctrl_reg_mask(id, &bitPos);
if (!mask)
return -EINVAL;
ret = max8986->read_dev(max8986, max8986_regls[id].ctrl_reg, ®Val);
regVal &= ~(mask);
volt <<= bitPos;
regVal |= (volt & mask);
ret |= max8986->write_dev(max8986, max8986_regls[id].ctrl_reg, regVal);
/*Dummy read to account for regualtor voltage ramp up/down delay*/
max8986->read_dev(max8986, max8986_regls[id].ctrl_reg, ®Val);
return ret;
}
static int max8986_regulator_set_voltage(struct regulator_dev *rdev,
int min_uV, int max_uV)
{
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
int inx;
u8 value;
/* Find the best index */
inx = max8986_get_best_voltage_inx(id, min_uV, max_uV);
if (inx < 0 || inx >= max8986_regls[id].num_vol)
return inx;
value = max8986_regls[id].vol_list[inx][1];
return _max8986_regulator_set_voltage(regl_priv, id, value);
}
static int _max8986_regulator_get_voltage(struct max8986_regl_priv *pri_dev,
int id)
{
int ret, val;
u8 mask, regVal;
int bitPos, i;
struct max8986_regl_priv *regl_priv = pri_dev;
struct max8986 *max8986 = regl_priv->max8986;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
ret = max8986->read_dev(max8986, max8986_regls[id].ctrl_reg, ®Val);
if (ret)
return ret;
mask = max8986_regulator_ctrl_reg_mask(id, &bitPos);
val = (regVal & mask) >> bitPos;
for (i = 0; i < max8986_regls[id].num_vol; i++) {
if (val == max8986_regls[id].vol_list[i][1]) {
pr_info("%s id: %d val: %d\n", __func__, id, val);
return max8986_regls[id].vol_list[i][0];
}
}
return -EINVAL;
}
static int max8986_regulator_get_voltage(struct regulator_dev *rdev)
{
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
return _max8986_regulator_get_voltage(regl_priv, id);
}
static int _max8986_regulator_set_mode(struct max8986_regl_priv *pri_dev,
int id, pmu_regl_state mode)
{
struct max8986_regl_priv *regl_priv = pri_dev;
struct max8986 *max8986 = regl_priv->max8986;
u8 regVal;
int ret;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
if (mode < 0 || mode >= PMU_REGL_MASK)
return -EINVAL;
ret = max8986->read_dev(max8986, max8986_regls[id].pm_reg, ®Val);
if (ret)
return ret;
/*Clear it off and then set the passed mode. */
regVal &= ~((PMU_REGL_MASK << PC2PC1_00) |
(PMU_REGL_MASK << PC2PC1_10));
regVal |= ((mode << PC2PC1_00) | (mode << PC2PC1_10));
printk(KERN_INFO "%s: rgVal = %x\n",__func__,regVal);
ret = max8986->write_dev(max8986, max8986_regls[id].pm_reg, regVal);
return ret;
}
static int max8986_regulator_set_mode(struct regulator_dev *rdev,
unsigned int mode)
{
u8 opmode;
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
printk(KERN_INFO "%s:mode = %d\n",__func__,mode);
switch(mode)
{
case REGULATOR_MODE_FAST:
opmode = PMU_REGL_TURBO;
break;
case REGULATOR_MODE_NORMAL:
opmode = PMU_REGL_ON;
break;
case REGULATOR_MODE_IDLE:
opmode = PMU_REGL_ECO;
break;
case REGULATOR_MODE_STANDBY:
opmode = PMU_REGL_OFF;
break;
default:
return -EINVAL;
}
return _max8986_regulator_set_mode(regl_priv, id, opmode);
}
static int _max8986_regulator_get_mode(struct max8986_regl_priv *pri_dev,
int id)
{
struct max8986_regl_priv *regl_priv = pri_dev;
struct max8986 *max8986 = regl_priv->max8986;
u8 regVal = 0;
int ret;
if ((id < 0) || (id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
ret = max8986->read_dev(max8986, max8986_regls[id].pm_reg, ®Val);
pr_info("%s : regVal = 0x%x\n", __func__, regVal);
if (ret)
return ret;
regVal &= (PMU_REGL_MASK << PC2PC1_00);
regVal >>= PC2PC1_00;
return regVal;
}
static unsigned int max8986_regulator_get_mode(struct regulator_dev *rdev)
{
u8 mode;
struct max8986_regl_priv *regl_priv = rdev_get_drvdata(rdev);
int id = rdev_get_id(rdev);
mode = _max8986_regulator_get_mode(regl_priv, id);
printk(KERN_INFO "%s:opmode = %d\n",__func__,mode);
switch(mode)
{
case PMU_REGL_ON:
return REGULATOR_MODE_NORMAL;
case PMU_REGL_ECO:
return REGULATOR_MODE_IDLE;
case PMU_REGL_OFF:
return REGULATOR_MODE_STANDBY;
case PMU_REGL_TURBO:
return REGULATOR_MODE_FAST;
}
return 0;
}
static struct regulator_ops max8986_regulator_ops = {
.enable = max8986_regulator_enable,
.disable = max8986_regulator_disable,
.is_enabled = max8986_regulator_is_enabled,
.set_voltage = max8986_regulator_set_voltage,
.get_voltage = max8986_regulator_get_voltage,
.set_mode = max8986_regulator_set_mode,
.get_mode = max8986_regulator_get_mode,
};
static int max8986_regulator_ioctl_handler(u32 cmd, u32 arg, void *pri_data)
{
struct max8986_regl_priv *regl_priv =
(struct max8986_regl_priv *) pri_data;
int ret = -EINVAL;
pr_debug("Inside %s, IOCTL command is %d\n", __func__, cmd);
switch (cmd) {
case BCM_PMU_IOCTL_SET_VOLTAGE:
{
pmu_regl_volt regulator;
int inx;
u8 value;
if (copy_from_user(®ulator,
(pmu_regl_volt *)arg,
sizeof(pmu_regl_volt)) != 0) {
return -EFAULT;
}
if ((regulator.regl_id < 0) ||
(regulator.regl_id >= MAX8986_REGL_NUM_REGULATOR))
return -EINVAL;
/* Validate the input voltage */
inx = max8986_get_best_voltage_inx(
regulator.regl_id,
regulator.voltage,
regulator.voltage);
if (inx < 0 || inx >= max8986_regls[regulator.regl_id].num_vol)
return -EINVAL;
value =
(u8)max8986_regls[regulator.regl_id].vol_list[inx][1];
ret = _max8986_regulator_set_voltage(regl_priv,
regulator.regl_id,
value);
break;
}
case BCM_PMU_IOCTL_GET_VOLTAGE:
{
pmu_regl_volt regulator;
int volt;
if (copy_from_user(®ulator,
(pmu_regl_volt *)arg,
sizeof(pmu_regl_volt)) != 0) {
return -EFAULT;
}
volt = _max8986_regulator_get_voltage(
regl_priv,
regulator.regl_id);
if (volt > 0) {
regulator.voltage = volt;
ret = copy_to_user((pmu_regl_volt *)arg,
®ulator,
sizeof(regulator));
} else
ret = volt;
break;
}
case BCM_PMU_IOCTL_GET_REGULATOR_STATE:
{
pmu_regl rmode;
if (copy_from_user(&rmode, (pmu_regl *)arg,
sizeof(pmu_regl)) != 0) {
return -EFAULT;
}
rmode.state = _max8986_regulator_get_mode(
regl_priv,
rmode.regl_id);
if (rmode.state > 0)
ret = copy_to_user((pmu_regl *)arg,
&rmode,
sizeof(rmode));
else
ret = rmode.state;
break;
}
case BCM_PMU_IOCTL_SET_REGULATOR_STATE:
{
pmu_regl rmode;
if (copy_from_user(&rmode, (pmu_regl *)arg,
sizeof(pmu_regl)) != 0)
return -EFAULT;
ret = _max8986_regulator_set_mode(regl_priv,
rmode.regl_id,
rmode.state);
break;
}
case BCM_PMU_IOCTL_ACTIVATESIM:
{
/* Unused IOCTL */
break;
}
case BCM_PMU_IOCTL_DEACTIVATESIM:
{
/* Unused IOCTL */
break;
}
} /*end of switch*/
return ret;
}
static int __devinit max8986_regulator_probe(struct platform_device *pdev)
{
struct max8986_regl_priv *regl_priv;
struct max8986 *max8986 = dev_get_drvdata(pdev->dev.parent);
struct max8986_regl_pdata *regulators;
int i, ret;
pr_info("%s\n", __func__);
if (unlikely(!max8986->pdata || !max8986->pdata->regulators)) {
pr_err("%s: invalid platform data !!!\n", __func__);
return -EINVAL;
}
regulators = max8986->pdata->regulators;
regl_priv = kzalloc((sizeof(struct max8986_regl_priv) +
regulators->num_regulators*sizeof(
struct regulator_dev *)),
GFP_KERNEL);
if (unlikely(!regl_priv))
return -ENOMEM;
regl_priv->max8986 = max8986;
for (i = 0; i < regulators->num_regulators; i++) {
/* copy flag */
max8986_regls[regulators->regl_init[i].regl_id].dsm_opmode =
regulators->regl_init[i].dsm_opmode;
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 30))
pdev->dev.platform_data = regulators->regl_init[i].init_data;
regl_priv->regl[i] = regulator_register(
&max8986_regls[regulators->regl_init[i].regl_id].desc,
&pdev->dev, regl_priv);
#else
regl_priv->regl[i] = regulator_register(
&max8986_regls[regulators->regl_init[i].regl_id].desc,
&pdev->dev, regulators->regl_init[i].init_data,
regl_priv);
#endif
if (IS_ERR(regl_priv->regl[i])) {
pr_err("%s: regulator_register Error !!!\n", __func__);
ret = PTR_ERR(regl_priv->regl[i]);
goto err;
}
}
regl_priv->num_regl = regulators->num_regulators;
/* Set default Regualtor PM mode values */
max8986->write_dev(max8986, MAX8986_PM_REG_A1OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO1]);
max8986->write_dev(max8986, MAX8986_PM_REG_A2OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO2]);
max8986->write_dev(max8986, MAX8986_PM_REG_A3OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO3]);
max8986->write_dev(max8986, MAX8986_PM_REG_A4OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO4]);
max8986->write_dev(max8986, MAX8986_PM_REG_A5OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO5]);
max8986->write_dev(max8986, MAX8986_PM_REG_A6OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO6]);
max8986->write_dev(max8986, MAX8986_PM_REG_A7OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO7]);
max8986->write_dev(max8986, MAX8986_PM_REG_A8OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO8]);
max8986->write_dev(max8986, MAX8986_PM_REG_A9OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_ALDO9]);
max8986->write_dev(max8986, MAX8986_PM_REG_D1OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_DLDO1]);
max8986->write_dev(max8986, MAX8986_PM_REG_D2OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_DLDO2]);
max8986->write_dev(max8986, MAX8986_PM_REG_D3OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_DLDO3]);
max8986->write_dev(max8986, MAX8986_PM_REG_D4OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_DLDO4]);
max8986->write_dev(max8986, MAX8986_PM_REG_H1OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_HCLDO1]);
max8986->write_dev(max8986, MAX8986_PM_REG_H2OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_HCLDO2]);
max8986->write_dev(max8986, MAX8986_PM_REG_LVOPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_LVLDO]);
max8986->write_dev(max8986, MAX8986_PM_REG_AX1OPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_AUXLDO1]);
max8986->write_dev(max8986, MAX8986_PM_REG_TSROPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_TSRLDO]);
max8986->write_dev(max8986, MAX8986_PM_REG_CSROPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_CSR_LPM]);
max8986->write_dev(max8986, MAX8986_PM_REG_IOSROPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_IOSR]);
max8986->write_dev(max8986, MAX8986_PM_REG_SIMOPMODCTRL,
regulators->regl_default_pmmode[MAX8986_REGL_SIMLDO]);
platform_set_drvdata(pdev, regl_priv);
max8986_register_ioctl_handler(max8986, MAX8986_SUBDEV_REGULATOR,
max8986_regulator_ioctl_handler,
regl_priv);
pr_info("%s: success\n", __func__);
return 0;
err:
while (--i >= 0)
regulator_unregister(regl_priv->regl[i]);
kfree(regl_priv);
return ret;
}
static int __devexit max8986_regulator_remove(struct platform_device *pdev)
{
struct max8986_regl_priv *regl_priv = platform_get_drvdata(pdev);
int i;
for (i = 0; i < regl_priv->num_regl; i++)
regulator_unregister(regl_priv->regl[i]);
return 0;
}
static struct platform_driver max8986_regulator_driver = {
.driver = {
.name = "max8986-regulator",
.owner = THIS_MODULE,
},
.remove = __devexit_p(max8986_regulator_remove),
.probe = max8986_regulator_probe,
};
static int __init max8986_regulator_init(void)
{
return platform_driver_register(&max8986_regulator_driver);
}
subsys_initcall(max8986_regulator_init);
static void __exit max8986_regulator_exit(void)
{
platform_driver_unregister(&max8986_regulator_driver);
}
module_exit(max8986_regulator_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Regulator Driver for MAX8986 PMU");
MODULE_ALIAS("platform:max8986-regulator");
| gpl-2.0 |
Xilinx/eglibc | nptl/tst-mutex8.c | 8388 | /* Copyright (C) 2003-2013 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Ulrich Drepper <[email protected]>, 2003.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This test checks behavior not required by POSIX. */
#include <errno.h>
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
static pthread_mutex_t *m;
static pthread_barrier_t b;
static pthread_cond_t c;
static bool done;
static void
cl (void *arg)
{
if (pthread_mutex_unlock (m) != 0)
{
puts ("cl: mutex_unlocked failed");
exit (1);
}
}
static void *
tf (void *arg)
{
if (pthread_mutex_lock (m) != 0)
{
puts ("tf: mutex_lock failed");
return (void *) 1l;
}
int e = pthread_barrier_wait (&b);
if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
{
puts ("barrier_wait failed");
return (void *) 1l;
}
if (arg == NULL)
do
if (pthread_cond_wait (&c, m) != 0)
{
puts ("tf: cond_wait failed");
return (void *) 1l;
}
while (! done);
else
do
{
pthread_cleanup_push (cl, NULL);
if (pthread_cond_wait (&c, m) != 0)
{
puts ("tf: cond_wait failed");
return (void *) 1l;
}
pthread_cleanup_pop (0);
}
while (! done);
if (pthread_mutex_unlock (m) != 0)
{
puts ("tf: mutex_unlock failed");
return (void *) 1l;
}
return NULL;
}
static int
check_type (const char *mas, pthread_mutexattr_t *ma)
{
int e __attribute__((unused));
if (pthread_mutex_init (m, ma) != 0)
{
printf ("1st mutex_init failed for %s\n", mas);
return 1;
}
if (pthread_mutex_destroy (m) != 0)
{
printf ("immediate mutex_destroy failed for %s\n", mas);
return 1;
}
if (pthread_mutex_init (m, ma) != 0)
{
printf ("2nd mutex_init failed for %s\n", mas);
return 1;
}
if (pthread_mutex_lock (m) != 0)
{
printf ("1st mutex_lock failed for %s\n", mas);
return 1;
}
/* Elided mutexes don't fail destroy. If elision is not explicitly disabled
we don't know, so can also not check this. */
#ifndef ENABLE_LOCK_ELISION
e = pthread_mutex_destroy (m);
if (e == 0)
{
printf ("mutex_destroy of self-locked mutex succeeded for %s\n", mas);
return 1;
}
if (e != EBUSY)
{
printf ("mutex_destroy of self-locked mutex did not return EBUSY %s\n",
mas);
return 1;
}
#endif
if (pthread_mutex_unlock (m) != 0)
{
printf ("1st mutex_unlock failed for %s\n", mas);
return 1;
}
if (pthread_mutex_trylock (m) != 0)
{
printf ("mutex_trylock failed for %s\n", mas);
return 1;
}
/* Elided mutexes don't fail destroy. */
#ifndef ENABLE_LOCK_ELISION
e = pthread_mutex_destroy (m);
if (e == 0)
{
printf ("mutex_destroy of self-trylocked mutex succeeded for %s\n", mas);
return 1;
}
if (e != EBUSY)
{
printf ("\
mutex_destroy of self-trylocked mutex did not return EBUSY %s\n",
mas);
return 1;
}
#endif
if (pthread_mutex_unlock (m) != 0)
{
printf ("2nd mutex_unlock failed for %s\n", mas);
return 1;
}
pthread_t th;
if (pthread_create (&th, NULL, tf, NULL) != 0)
{
puts ("1st create failed");
return 1;
}
done = false;
e = pthread_barrier_wait (&b);
if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
{
puts ("1st barrier_wait failed");
return 1;
}
if (pthread_mutex_lock (m) != 0)
{
printf ("2nd mutex_lock failed for %s\n", mas);
return 1;
}
if (pthread_mutex_unlock (m) != 0)
{
printf ("3rd mutex_unlock failed for %s\n", mas);
return 1;
}
/* Elided mutexes don't fail destroy. */
#ifndef ENABLE_LOCK_ELISION
e = pthread_mutex_destroy (m);
if (e == 0)
{
printf ("mutex_destroy of condvar-used mutex succeeded for %s\n", mas);
return 1;
}
if (e != EBUSY)
{
printf ("\
mutex_destroy of condvar-used mutex did not return EBUSY for %s\n", mas);
return 1;
}
#endif
done = true;
if (pthread_cond_signal (&c) != 0)
{
puts ("cond_signal failed");
return 1;
}
void *r;
if (pthread_join (th, &r) != 0)
{
puts ("join failed");
return 1;
}
if (r != NULL)
{
puts ("thread didn't return NULL");
return 1;
}
if (pthread_mutex_destroy (m) != 0)
{
printf ("mutex_destroy after condvar-use failed for %s\n", mas);
return 1;
}
if (pthread_mutex_init (m, ma) != 0)
{
printf ("3rd mutex_init failed for %s\n", mas);
return 1;
}
if (pthread_create (&th, NULL, tf, (void *) 1) != 0)
{
puts ("2nd create failed");
return 1;
}
done = false;
e = pthread_barrier_wait (&b);
if (e != 0 && e != PTHREAD_BARRIER_SERIAL_THREAD)
{
puts ("2nd barrier_wait failed");
return 1;
}
if (pthread_mutex_lock (m) != 0)
{
printf ("3rd mutex_lock failed for %s\n", mas);
return 1;
}
if (pthread_mutex_unlock (m) != 0)
{
printf ("4th mutex_unlock failed for %s\n", mas);
return 1;
}
/* Elided mutexes don't fail destroy. */
#ifndef ENABLE_LOCK_ELISION
e = pthread_mutex_destroy (m);
if (e == 0)
{
printf ("2nd mutex_destroy of condvar-used mutex succeeded for %s\n",
mas);
return 1;
}
if (e != EBUSY)
{
printf ("\
2nd mutex_destroy of condvar-used mutex did not return EBUSY for %s\n",
mas);
return 1;
}
#endif
if (pthread_cancel (th) != 0)
{
puts ("cond_cancel failed");
return 1;
}
if (pthread_join (th, &r) != 0)
{
puts ("join failed");
return 1;
}
if (r != PTHREAD_CANCELED)
{
puts ("thread not canceled");
return 1;
}
if (pthread_mutex_destroy (m) != 0)
{
printf ("mutex_destroy after condvar-canceled failed for %s\n", mas);
return 1;
}
return 0;
}
static int
do_test (void)
{
pthread_mutex_t mm;
m = &mm;
if (pthread_barrier_init (&b, NULL, 2) != 0)
{
puts ("barrier_init failed");
return 1;
}
if (pthread_cond_init (&c, NULL) != 0)
{
puts ("cond_init failed");
return 1;
}
puts ("check normal mutex");
int res = check_type ("normal", NULL);
pthread_mutexattr_t ma;
if (pthread_mutexattr_init (&ma) != 0)
{
puts ("1st mutexattr_init failed");
return 1;
}
if (pthread_mutexattr_settype (&ma, PTHREAD_MUTEX_RECURSIVE) != 0)
{
puts ("1st mutexattr_settype failed");
return 1;
}
#ifdef ENABLE_PI
if (pthread_mutexattr_setprotocol (&ma, PTHREAD_PRIO_INHERIT))
{
puts ("1st pthread_mutexattr_setprotocol failed");
return 1;
}
#endif
puts ("check recursive mutex");
res |= check_type ("recursive", &ma);
if (pthread_mutexattr_destroy (&ma) != 0)
{
puts ("1st mutexattr_destroy failed");
return 1;
}
if (pthread_mutexattr_init (&ma) != 0)
{
puts ("2nd mutexattr_init failed");
return 1;
}
if (pthread_mutexattr_settype (&ma, PTHREAD_MUTEX_ERRORCHECK) != 0)
{
puts ("2nd mutexattr_settype failed");
return 1;
}
#ifdef ENABLE_PI
if (pthread_mutexattr_setprotocol (&ma, PTHREAD_PRIO_INHERIT))
{
puts ("2nd pthread_mutexattr_setprotocol failed");
return 1;
}
#endif
puts ("check error-checking mutex");
res |= check_type ("error-checking", &ma);
if (pthread_mutexattr_destroy (&ma) != 0)
{
puts ("2nd mutexattr_destroy failed");
return 1;
}
return res;
}
#define TEST_FUNCTION do_test ()
#include "../test-skeleton.c"
| gpl-2.0 |
pazos/android_kernel_samsung_goyawifi | drivers/marvell/graphics/galcore_src/arch/unified_reg/hal/kernel/gc_hal_kernel_hardware.h | 3645 | /****************************************************************************
*
* Copyright (c) 2005 - 2012 by Vivante Corp.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the license, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
*****************************************************************************/
#ifndef __gc_hal_kernel_hardware_h_
#define __gc_hal_kernel_hardware_h_
#if gcdENABLE_VG
#include "gc_hal_kernel_hardware_vg.h"
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* gckHARDWARE object. */
struct _gckHARDWARE
{
/* Object. */
gcsOBJECT object;
/* Pointer to gctKERNEL object. */
gckKERNEL kernel;
/* Pointer to gctOS object. */
gckOS os;
/* Core */
gceCORE core;
/* Chip characteristics. */
gcsHAL_QUERY_CHIP_IDENTITY identity;
gctBOOL allowFastClear;
gctBOOL allowCompression;
gctUINT32 powerBaseAddress;
gctBOOL extraEventStates;
/* Big endian */
gctBOOL bigEndian;
/* Chip status */
gctPOINTER powerMutex;
gctUINT32 powerProcess;
gctUINT32 powerThread;
gceCHIPPOWERSTATE chipPowerState;
gctUINT32 lastWaitLink;
gctBOOL clockState;
gctBOOL powerState;
gctPOINTER globalSemaphore;
gckRecursiveMutex recMutexPower;
gctBOOL clk2D3D_Enable;
gctUINT32 refExtClock;
gctUINT32 refExtPower;
/* flag for auto_pulse_eater(dvfs) */
gceDVFS dvfs;
gctISRMANAGERFUNC startIsr;
gctISRMANAGERFUNC stopIsr;
gctPOINTER isrContext;
gctUINT32 mmuVersion;
/* Type */
gceHARDWARE_TYPE type;
#if gcdPOWEROFF_TIMEOUT
gctUINT32 powerOffTime;
gctUINT32 powerOffTimeout;
gctPOINTER powerOffTimer;
#endif
#if gcdENABLE_FSCALE_VAL_ADJUST
gctUINT32 powerOnFscaleVal;
#endif
gctPOINTER pageTableDirty;
#if MRVL_CONFIG_ENABLE_GPUFREQ
struct gcsDEVOBJECT devObj;
#endif
#if gcdLINK_QUEUE_SIZE
struct _gckLINKQUEUE linkQueue;
#endif
gctUINT32 outstandingRequest;
gctUINT32 outstandingLimitation;
};
gceSTATUS
gckHARDWARE_GetBaseAddress(
IN gckHARDWARE Hardware,
OUT gctUINT32_PTR BaseAddress
);
gceSTATUS
gckHARDWARE_NeedBaseAddress(
IN gckHARDWARE Hardware,
IN gctUINT32 State,
OUT gctBOOL_PTR NeedBase
);
gceSTATUS
gckHARDWARE_GetFrameInfo(
IN gckHARDWARE Hardware,
OUT gcsHAL_FRAME_INFO * FrameInfo
);
#ifdef __cplusplus
}
#endif
#endif /* __gc_hal_kernel_hardware_h_ */
| gpl-2.0 |
effortlesssites/template | components/com_roksprocket/lib/RokSprocket/Provider/EasyBlog/ItemPrivacyPopulator.php | 616 | <?php
/**
* @version $Id: ItemPrivacyPopulator.php 10887 2013-05-30 06:31:57Z btowles $
* @author RocketTheme http://www.rockettheme.com
* @copyright Copyright (C) 2007 - 2013 RocketTheme, LLC
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only
*/
class RokSprocket_Provider_EasyBlog_ItemPrivacyPopulator implements RokCommon_Filter_IPicklistPopulator
{
/**
*
* @return array;
*/
public function getPicklistOptions()
{
$options = array();
$options['private'] = "Private";
$options['public'] = "Public";
return $options;
}
}
| gpl-2.0 |
scriptum/ohcount | ruby/gestalt/rules/csproj_rule.rb | 739 | require 'rexml/document'
module Ohcount
module Gestalt
class CsprojRule < FileRule
attr_accessor :import
def initialize(*args)
@import = args.shift || /.*/
@import = /^#{Regexp.escape(@import.to_s)}$/ unless @import.is_a? Regexp
super(args)
end
def process_source_file(source_file)
if source_file.filename =~ /\.csproj$/ && source_file.language_breakdown('xml')
callback = lambda do |import|
@count += 1 if import =~ @import
end
begin
REXML::Document.parse_stream(source_file.language_breakdown('xml').code, CsprojListener.new(callback))
rescue REXML::ParseException
# Malformed XML! -- ignore and move on
end
end
end
end
end
end
| gpl-2.0 |
rbazaud/pcmanfm-qt | pcmanfm/translations/pcmanfm-qt_cs_CZ.ts | 53147 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="cs_CZ">
<context>
<name>AboutDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="134"/>
<source>About</source>
<translation type="unfinished">O</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="135"/>
<source><html><head/><body><p><span style=" font-size:16pt; font-weight:600;">PCManFM</span></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="137"/>
<source>Lightweight file manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="143"/>
<source>PCMan File Manager
Copyright (C) 2009 - 2014 洪任諭 (Hong Jen Yee)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="139"/>
<source>Programming:
* Hong Jen Yee (PCMan) <[email protected]>
</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="138"/>
<source><html><head/><body><p><a href="http://lxqt.org/"><span style=" text-decoration: underline; color:#0000ff;">http://lxqt.org/</span></a></p></body></html></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="142"/>
<source>Authors</source>
<translation type="unfinished">Autoři</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_about.h" line="160"/>
<source>License</source>
<translation type="unfinished">Licence</translation>
</message>
</context>
<context>
<name>AutoRunDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="110"/>
<source>Removable medium is inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="112"/>
<source><b>Removable medium is inserted</b></source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="113"/>
<source>Type of medium:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="114"/>
<source>Detecting...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_autorun.h" line="115"/>
<source>Please select the action you want to perform:</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DesktopFolder</name>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="75"/>
<source>Form</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="76"/>
<source>Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="77"/>
<source>Desktop folder:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="79"/>
<source>Image file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="84"/>
<source>Folder path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-folder.h" line="85"/>
<source>&Browse</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>DesktopPreferencesDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="254"/>
<source>Desktop Preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="255"/>
<source>Background</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="256"/>
<source>Wallpaper mode:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="257"/>
<source>Wallpaper image file:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="259"/>
<source>Select background color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="261"/>
<source>Image file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="266"/>
<source>Image file path</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="267"/>
<source>&Browse</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="268"/>
<source>Label Text</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="271"/>
<source>Select text color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="272"/>
<source>Select shadow color:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="273"/>
<source>Select font:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="275"/>
<source>General</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="276"/>
<source>Window Manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="277"/>
<source>Show menus provided by window managers when desktop is clicked</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_desktop-preferences.h" line="278"/>
<source>Advanced</source>
<translation type="unfinished">Pokročilé</translation>
</message>
</context>
<context>
<name>MainWindow</name>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="557"/>
<source>File Manager</source>
<translation type="unfinished">Správce souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="560"/>
<source>Go Up</source>
<translation type="unfinished">Nahoru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="562"/>
<source>Alt+Up</source>
<translation type="unfinished">Alt+Nahoru</translation>
</message>
<message>
<source>Home</source>
<translation type="obsolete">Domů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="564"/>
<source>Alt+Home</source>
<translation type="unfinished">Alt+Home</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="583"/>
<source>Reload</source>
<translation type="unfinished">Obnovit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="566"/>
<source>F5</source>
<translation type="unfinished">F5</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="563"/>
<source>&Home</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="565"/>
<source>&Reload</source>
<translation type="unfinished">&Obnovit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="567"/>
<source>Go</source>
<translation type="unfinished">Jdi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="568"/>
<source>Quit</source>
<translation type="unfinished">ukončit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="569"/>
<source>&About</source>
<translation type="unfinished">&O programu</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="572"/>
<source>New Window</source>
<translation type="unfinished">Nové okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="574"/>
<source>Ctrl+N</source>
<translation type="unfinished">Ctrl+N</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="575"/>
<source>Show &Hidden</source>
<translation type="unfinished">Zobrazit &skryté</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="576"/>
<source>Ctrl+H</source>
<translation type="unfinished">Ctrl+H</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="577"/>
<source>&Computer</source>
<translation type="unfinished">Počítač</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="578"/>
<source>&Trash</source>
<translation type="unfinished">&Koš</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="579"/>
<source>&Network</source>
<translation type="unfinished">Síť</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="580"/>
<source>&Desktop</source>
<translation type="unfinished">Plocha</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="581"/>
<source>&Add to Bookmarks</source>
<translation type="unfinished">Přidat k záložkám</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="582"/>
<source>&Applications</source>
<translation type="unfinished">Programy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="589"/>
<source>Ctrl+X</source>
<translation type="unfinished">Ctrl+X</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="590"/>
<source>&Copy</source>
<translation type="unfinished">Kopírovat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="591"/>
<source>Ctrl+C</source>
<translation type="unfinished">Ctrl+C</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="592"/>
<source>&Paste</source>
<translation type="unfinished">Vložit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="593"/>
<source>Ctrl+V</source>
<translation type="unfinished">Ctrl+V</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="594"/>
<source>Select &All</source>
<translation type="unfinished">Vybrat všechno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="596"/>
<source>Pr&eferences</source>
<translation type="unfinished">&Nastavení</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="597"/>
<source>&Ascending</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="598"/>
<source>&Descending</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="599"/>
<source>&By File Name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="600"/>
<source>By &Modification Time</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="601"/>
<source>By File &Type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="602"/>
<source>By &Owner</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="603"/>
<source>&Folder First</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="619"/>
<source>&Invert Selection</source>
<translation type="unfinished">Invertovat výběr</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="620"/>
<source>&Delete</source>
<translation type="unfinished">Smazat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="622"/>
<source>&Rename</source>
<translation type="unfinished">Přejmenovat</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="629"/>
<source>&Case Sensitive</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="630"/>
<source>By File &Size</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="631"/>
<source>&Close Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="595"/>
<source>Ctrl+A</source>
<translation type="unfinished">Ctrl+A</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="558"/>
<source>Go &Up</source>
<translation type="unfinished">Nahoru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="570"/>
<source>&New Window</source>
<translation type="unfinished">Nové &okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="584"/>
<source>&Icon View</source>
<translation type="unfinished">Pohled s ikonami</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="585"/>
<source>&Compact View</source>
<translation type="unfinished">Kompaktní pohled</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="586"/>
<source>&Detailed List</source>
<translation type="unfinished">Seznam s podrobnostmi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="587"/>
<source>&Thumbnail View</source>
<translation type="unfinished">Pohled s náhledy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="588"/>
<source>Cu&t</source>
<translation type="unfinished">Vyjmout</translation>
</message>
<message>
<source>Ascending</source>
<translation type="obsolete">Vzestupně</translation>
</message>
<message>
<source>Descending</source>
<translation type="obsolete">Sestupně</translation>
</message>
<message>
<source>By File Name</source>
<translation type="obsolete">Podle jména</translation>
</message>
<message>
<source>By Modification Time</source>
<translation type="obsolete">Podle času</translation>
</message>
<message>
<source>By File Type</source>
<translation type="obsolete">Podle typu</translation>
</message>
<message>
<source>By Owner</source>
<translation type="obsolete">Podle vlastníka</translation>
</message>
<message>
<source>Folder First</source>
<translation type="obsolete">Složky jako první</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="604"/>
<source>New &Tab</source>
<translation type="unfinished">Nový &panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="606"/>
<source>New Tab</source>
<translation type="unfinished">Nový panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="608"/>
<source>Ctrl+T</source>
<translation type="unfinished">Ctrl+T</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="609"/>
<source>Go &Back</source>
<translation type="unfinished">Zpět</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="611"/>
<source>Go Back</source>
<translation type="unfinished">Zpět</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="613"/>
<source>Alt+Left</source>
<translation type="unfinished">Alt+Vlevo</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="614"/>
<source>Go &Forward</source>
<translation type="unfinished">&Vpřed</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="616"/>
<source>Go Forward</source>
<translation type="unfinished">Vpřed</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="618"/>
<source>Alt+Right</source>
<translation type="unfinished">Alt+Vpravo</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="621"/>
<source>Del</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="623"/>
<source>F2</source>
<translation type="unfinished">F2</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="624"/>
<source>C&lose Tab</source>
<translation type="unfinished">Zavřít panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="626"/>
<source>File &Properties</source>
<translation type="unfinished">Vlastnosti souboru</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="628"/>
<source>&Folder Properties</source>
<translation type="unfinished">Vlastnosti složky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="638"/>
<source>Ctrl+Shift+N</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="640"/>
<source>Ctrl+Alt+N</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="643"/>
<source>Filter</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="646"/>
<source>C&reate New</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="649"/>
<source>&Sorting</source>
<translation type="unfinished">Řadit</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="654"/>
<source>Main Toolbar</source>
<translation type="unfinished">Hlavní panel</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="625"/>
<source>Ctrl+W</source>
<translation type="unfinished">Ctrl+W</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="627"/>
<source>Alt+Return</source>
<translation type="unfinished">Alt+Return</translation>
</message>
<message>
<source>Case Sensitive</source>
<translation type="obsolete">Rozlišovat velikost písmen</translation>
</message>
<message>
<source>By File Size</source>
<translation type="obsolete">Podle velikosti</translation>
</message>
<message>
<source>Close Window</source>
<translation type="obsolete">Zavřít okno</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="632"/>
<source>Edit Bookmarks</source>
<translation type="unfinished">Upravit záložky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="633"/>
<source>Open &Terminal</source>
<translation type="unfinished">Otevřít &terminál</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="634"/>
<source>F4</source>
<translation type="unfinished">F4</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="635"/>
<source>Open as &Root</source>
<translation type="unfinished">Otevřít jako &Root</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="636"/>
<source>&Edit Bookmarks</source>
<translation type="unfinished">Upravit záložky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="637"/>
<source>&Folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="639"/>
<source>&Blank File</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="641"/>
<source>&Find Files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="642"/>
<source>F3</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="644"/>
<source>Filter by string...</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="645"/>
<source>&File</source>
<translation type="unfinished">&Soubor</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="647"/>
<source>&Help</source>
<translation type="unfinished">&Nápověda</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="648"/>
<source>&View</source>
<translation type="unfinished">&Zobrazení</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="650"/>
<source>&Edit</source>
<translation type="unfinished">Úpr&avy</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="651"/>
<source>&Bookmarks</source>
<translation type="unfinished">Zál&ožky</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="652"/>
<source>&Go</source>
<translation type="unfinished">&Jdi</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_main-win.h" line="653"/>
<source>&Tool</source>
<translation type="unfinished">Nás&troje</translation>
</message>
</context>
<context>
<name>PCManFM::Application</name>
<message>
<location filename="../application.cpp" line="162"/>
<source>Name of configuration profile</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="162"/>
<source>PROFILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="165"/>
<source>Run PCManFM as a daemon</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="168"/>
<source>Quit PCManFM</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="171"/>
<source>Launch desktop manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="174"/>
<source>Turn off desktop manager if it's running</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="177"/>
<source>Open desktop preference dialog on the page with the specified name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="177"/>
<location filename="../application.cpp" line="193"/>
<source>NAME</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="180"/>
<source>Open new window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="183"/>
<source>Open Find Files utility</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="186"/>
<source>Set desktop wallpaper from image FILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="186"/>
<source>FILE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="190"/>
<source>Set mode of desktop wallpaper. MODE=(color|stretch|fit|center|tile)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="190"/>
<source>MODE</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="193"/>
<source>Open Preferences dialog on the page with the specified name</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="196"/>
<source>Files or directories to open</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="196"/>
<source>[FILE1, FILE2,...]</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="500"/>
<location filename="../application.cpp" line="507"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../application.cpp" line="507"/>
<source>Terminal emulator is not set.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::AutoRunDialog</name>
<message>
<location filename="../autorundialog.cpp" line="43"/>
<source>Open in file manager</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../autorundialog.cpp" line="133"/>
<source>Removable Disk</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::DesktopPreferencesDialog</name>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="50"/>
<source>Fill with background color only</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="51"/>
<source>Stretch to fill the entire screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="52"/>
<source>Stretch to fit the screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="53"/>
<source>Center on the screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="54"/>
<source>Tile the image to fill the entire screen</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktoppreferencesdialog.cpp" line="157"/>
<source>Image Files</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::DesktopWindow</name>
<message>
<location filename="../desktopwindow.cpp" line="366"/>
<source>Stic&k to Current Position</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../desktopwindow.cpp" line="388"/>
<source>Desktop Preferences</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::MainWindow</name>
<message>
<location filename="../mainwindow.cpp" line="190"/>
<source>Clear text (Ctrl+K)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="455"/>
<source>Version: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="907"/>
<source>&Move to Trash</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="907"/>
<source>&Delete</source>
<translation type="unfinished">Smazat</translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="969"/>
<location filename="../mainwindow.cpp" line="980"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../mainwindow.cpp" line="980"/>
<source>Switch user command is not set.</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::PreferencesDialog</name>
<message>
<location filename="../preferencesdialog.cpp" line="190"/>
<source>Icon View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="191"/>
<source>Compact Icon View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="192"/>
<source>Thumbnail View</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../preferencesdialog.cpp" line="193"/>
<source>Detailed List View</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::TabPage</name>
<message>
<location filename="../tabpage.cpp" line="248"/>
<source>Error</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../tabpage.cpp" line="261"/>
<source>Free space: %1 (Total: %2)</source>
<translation type="unfinished"></translation>
</message>
<message numerus="yes">
<location filename="../tabpage.cpp" line="276"/>
<source>%n item(s)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message numerus="yes">
<location filename="../tabpage.cpp" line="278"/>
<source> (%n hidden)</source>
<translation type="unfinished">
<numerusform></numerusform>
<numerusform></numerusform>
<numerusform></numerusform>
</translation>
</message>
<message>
<location filename="../tabpage.cpp" line="426"/>
<source>%1 item(s) selected</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PCManFM::View</name>
<message>
<location filename="../view.cpp" line="103"/>
<source>Open in New T&ab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../view.cpp" line="107"/>
<source>Open in New Win&dow</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../view.cpp" line="114"/>
<source>Open in Termina&l</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>PreferencesDialog</name>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="706"/>
<source>Preferences</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="715"/>
<source>User Interface</source>
<translation type="unfinished">Uživatelské rozhraní</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="711"/>
<source>Behavior</source>
<translation type="unfinished">Chování</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="717"/>
<location filename="../../build/pcmanfm/ui_preferences.h" line="779"/>
<source>Thumbnail</source>
<translation type="unfinished">Náhled</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="719"/>
<source>Volume</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="721"/>
<source>Advanced</source>
<translation type="unfinished">Pokročilé</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="742"/>
<source>Icons</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="744"/>
<source>Size of big icons:</source>
<translation type="unfinished">Velikost velkých ikon:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="745"/>
<source>Size of small icons:</source>
<translation type="unfinished">Velikost malých ikon:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="746"/>
<source>Size of thumbnails:</source>
<translation type="unfinished">Velikost náhledů:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="747"/>
<source>Size of side pane icons:</source>
<translation type="unfinished">Velikost ikon v postranním panelu:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="743"/>
<source>Icon theme:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="753"/>
<source>Window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="757"/>
<source>Default width of new windows:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="758"/>
<source>Default height of new windows:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="754"/>
<source>Always show the tab bar</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="755"/>
<source>Show 'Close' buttons on tabs </source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="756"/>
<source>Remember the size of the last closed window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="724"/>
<source>Browsing</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="725"/>
<source>Open files with single click</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="726"/>
<source>Delay of auto-selection in single click mode (0 to disable)</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="727"/>
<source>Default view mode:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="728"/>
<source> sec</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="736"/>
<source>File Operations</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="737"/>
<source>Confirm before deleting files</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="738"/>
<source>Move deleted files to "trash bin" instead of erasing from disk.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="783"/>
<source>Show thumbnails of files</source>
<translation type="unfinished">Zobrazovat náhledy souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="782"/>
<source>Only show thumbnails for local files</source>
<translation type="unfinished">Zobrazovat náhlet jen u lokálních souborů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="713"/>
<source>Display</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="729"/>
<source>Bookmarks:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="732"/>
<source>Open in current tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="733"/>
<source>Open in new tab</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="734"/>
<source>Open in new window</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="739"/>
<source>Erase files on removable media instead of "trash can" creation</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="740"/>
<source>Confirm before moving files into "trash can"</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="741"/>
<source>Don't ask options on launch executable file</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="748"/>
<source>User interface</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="750"/>
<source>Treat backup files as hidden</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="751"/>
<source>Always show full file names</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="752"/>
<source>Show icons of hidden files shadowed</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="759"/>
<source>Show in places</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="764"/>
<source>Home</source>
<translation type="unfinished">Domů</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="766"/>
<source>Desktop</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="768"/>
<source>Trash can</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="770"/>
<source>Computer</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="772"/>
<source>Applications</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="774"/>
<source>Devices</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="776"/>
<source>Network</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="780"/>
<source>Do not generate thumbnails for image files exceeding this size:</source>
<translation type="unfinished">Negenerovat náhledy obrázků přesahujících tuto velikost:</translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="781"/>
<source> KB</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="784"/>
<source>Auto Mount</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="785"/>
<source>Mount mountable volumes automatically on program startup</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="786"/>
<source>Mount removable media automatically when they are inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="787"/>
<source>Show available options for removable media when they are inserted</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="788"/>
<source>When removable medium unmounted:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="789"/>
<source>Close &tab containing removable medium</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="790"/>
<source>Chan&ge folder in the tab to home folder</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="793"/>
<source>Switch &user command:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="796"/>
<source>Archiver in&tegration:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="797"/>
<source>Templates</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="798"/>
<source>Show only user defined templates in menu</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="799"/>
<source>Show only one template for each MIME type</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="800"/>
<source>Run default application after creation from template</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="791"/>
<source>Programs</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="792"/>
<source>Terminal emulator:</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="794"/>
<source>Examples: "xterm -e %s" for terminal or "gksu %s" for switching user.
%s = the command line you want to execute with terminal or su.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../build/pcmanfm/ui_preferences.h" line="749"/>
<source>Use SI decimal prefixes instead of IEC binary prefixes</source>
<translation type="unfinished"></translation>
</message>
</context>
</TS>
| gpl-2.0 |
hawpaw/KreyosFirmware-hwp- | Watch/core/net/psock.h | 12948 | /*
* Copyright (c) 2004, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*
* Author: Adam Dunkels <[email protected]>
*
* $Id: psock.h,v 1.8 2010/06/15 14:19:22 nifi Exp $
*/
/**
* \addtogroup uip
* @{
*/
/**
* \defgroup psock Protosockets library
* @{
*
* The protosocket library provides an interface to the uIP stack that is
* similar to the traditional BSD socket interface. Unlike programs
* written for the ordinary uIP event-driven interface, programs
* written with the protosocket library are executed in a sequential
* fashion and does not have to be implemented as explicit state
* machines.
*
* Protosockets only work with TCP connections.
*
* The protosocket library uses \ref pt protothreads to provide
* sequential control flow. This makes the protosockets lightweight in
* terms of memory, but also means that protosockets inherits the
* functional limitations of protothreads. Each protosocket lives only
* within a single function block. Automatic variables (stack
* variables) are not necessarily retained across a protosocket
* library function call.
*
* \note Because the protosocket library uses protothreads, local variables
* will not always be saved across a call to a protosocket library
* function. It is therefore advised that local variables are used
* with extreme care.
*
* The protosocket library provides functions for sending data without
* having to deal with retransmissions and acknowledgements, as well
* as functions for reading data without having to deal with data
* being split across more than one TCP segment.
*
* Because each protosocket runs as a protothread, the protosocket has to be
* started with a call to PSOCK_BEGIN() at the start of the function
* in which the protosocket is used. Similarly, the protosocket protothread can
* be terminated by a call to PSOCK_EXIT().
*
*/
/**
* \file
* Protosocket library header file
* \author
* Adam Dunkels <[email protected]>
*
*/
#ifndef __PSOCK_H__
#define __PSOCK_H__
#include "contiki.h"
#include "contiki-lib.h"
#include "contiki-net.h"
/*
* The structure that holds the state of a buffer.
*
* This structure holds the state of a uIP buffer. The structure has
* no user-visible elements, but is used through the functions
* provided by the library.
*
*/
struct psock_buf {
uint8_t *ptr;
unsigned short left;
};
/**
* The representation of a protosocket.
*
* The protosocket structrure is an opaque structure with no user-visible
* elements.
*/
struct psock {
struct pt pt, psockpt; /* Protothreads - one that's using the psock
functions, and one that runs inside the
psock functions. */
const uint8_t *sendptr; /* Pointer to the next data to be sent. */
uint8_t *readptr; /* Pointer to the next data to be read. */
uint8_t *bufptr; /* Pointer to the buffer used for buffering
incoming data. */
uint16_t sendlen; /* The number of bytes left to be sent. */
uint16_t readlen; /* The number of bytes left to be read. */
struct psock_buf buf; /* The structure holding the state of the
input buffer. */
unsigned int bufsize; /* The size of the input buffer. */
unsigned char state; /* The state of the protosocket. */
};
void psock_init(struct psock *psock, uint8_t *buffer, unsigned int buffersize);
/**
* Initialize a protosocket.
*
* This macro initializes a protosocket and must be called before the
* protosocket is used. The initialization also specifies the input buffer
* for the protosocket.
*
* \param psock (struct psock *) A pointer to the protosocket to be
* initialized
*
* \param buffer (uint8_t *) A pointer to the input buffer for the
* protosocket.
*
* \param buffersize (unsigned int) The size of the input buffer.
*
* \hideinitializer
*/
#define PSOCK_INIT(psock, buffer, buffersize) \
psock_init(psock, buffer, buffersize)
/**
* Start the protosocket protothread in a function.
*
* This macro starts the protothread associated with the protosocket and
* must come before other protosocket calls in the function it is used.
*
* \param psock (struct psock *) A pointer to the protosocket to be
* started.
*
* \hideinitializer
*/
#define PSOCK_BEGIN(psock) PT_BEGIN(&((psock)->pt))
PT_THREAD(psock_send(struct psock *psock, const uint8_t *buf, unsigned int len));
/**
* Send data.
*
* This macro sends data over a protosocket. The protosocket protothread blocks
* until all data has been sent and is known to have been received by
* the remote end of the TCP connection.
*
* \param psock (struct psock *) A pointer to the protosocket over which
* data is to be sent.
*
* \param data (uint8_t *) A pointer to the data that is to be sent.
*
* \param datalen (unsigned int) The length of the data that is to be
* sent.
*
* \hideinitializer
*/
#define PSOCK_SEND(psock, data, datalen) \
PT_WAIT_THREAD(&((psock)->pt), psock_send(psock, data, datalen))
/**
* \brief Send a null-terminated string.
* \param psock Pointer to the protosocket.
* \param str The string to be sent.
*
* This function sends a null-terminated string over the
* protosocket.
*
* \hideinitializer
*/
#define PSOCK_SEND_STR(psock, str) \
PT_WAIT_THREAD(&((psock)->pt), psock_send(psock, (uint8_t *)str, strlen(str)))
PT_THREAD(psock_generator_send(struct psock *psock,
unsigned short (*f)(void *), void *arg));
/**
* \brief Generate data with a function and send it
* \param psock Pointer to the protosocket.
* \param generator Pointer to the generator function
* \param arg Argument to the generator function
*
* This function generates data and sends it over the
* protosocket. This can be used to dynamically generate
* data for a transmission, instead of generating the data
* in a buffer beforehand. This function reduces the need for
* buffer memory. The generator function is implemented by
* the application, and a pointer to the function is given
* as an argument with the call to PSOCK_GENERATOR_SEND().
*
* The generator function should place the generated data
* directly in the uip_appdata buffer, and return the
* length of the generated data. The generator function is
* called by the protosocket layer when the data first is
* sent, and once for every retransmission that is needed.
*
* \hideinitializer
*/
#define PSOCK_GENERATOR_SEND(psock, generator, arg) \
PT_WAIT_THREAD(&((psock)->pt), \
psock_generator_send(psock, generator, arg))
/**
* Close a protosocket.
*
* This macro closes a protosocket and can only be called from within the
* protothread in which the protosocket lives.
*
* \param psock (struct psock *) A pointer to the protosocket that is to
* be closed.
*
* \hideinitializer
*/
#define PSOCK_CLOSE(psock) uip_close()
PT_THREAD(psock_readbuf_len(struct psock *psock, uint16_t len));
/**
* Read data until the buffer is full.
*
* This macro will block waiting for data and read the data into the
* input buffer specified with the call to PSOCK_INIT(). Data is read
* until the buffer is full..
*
* \param psock (struct psock *) A pointer to the protosocket from which
* data should be read.
*
* \hideinitializer
*/
#define PSOCK_READBUF(psock) \
PT_WAIT_THREAD(&((psock)->pt), psock_readbuf_len(psock, 1))
/**
* Read data until at least len bytes have been read.
*
* This macro will block waiting for data and read the data into the
* input buffer specified with the call to PSOCK_INIT(). Data is read
* until the buffer is full or len bytes have been read.
*
* \param psock (struct psock *) A pointer to the protosocket from which
* data should be read.
* \param len (uint16_t) The minimum number of bytes to read.
*
* \hideinitializer
*/
#define PSOCK_READBUF_LEN(psock, len) \
PT_WAIT_THREAD(&((psock)->pt), psock_readbuf_len(psock, len))
PT_THREAD(psock_readto(struct psock *psock, unsigned char c));
/**
* Read data up to a specified character.
*
* This macro will block waiting for data and read the data into the
* input buffer specified with the call to PSOCK_INIT(). Data is only
* read until the specified character appears in the data stream.
*
* \param psock (struct psock *) A pointer to the protosocket from which
* data should be read.
*
* \param c (char) The character at which to stop reading.
*
* \hideinitializer
*/
#define PSOCK_READTO(psock, c) \
PT_WAIT_THREAD(&((psock)->pt), psock_readto(psock, c))
/**
* The length of the data that was previously read.
*
* This macro returns the length of the data that was previously read
* using PSOCK_READTO() or PSOCK_READ().
*
* \param psock (struct psock *) A pointer to the protosocket holding the data.
*
* \hideinitializer
*/
#define PSOCK_DATALEN(psock) psock_datalen(psock)
uint16_t psock_datalen(struct psock *psock);
/**
* Exit the protosocket's protothread.
*
* This macro terminates the protothread of the protosocket and should
* almost always be used in conjunction with PSOCK_CLOSE().
*
* \sa PSOCK_CLOSE_EXIT()
*
* \param psock (struct psock *) A pointer to the protosocket.
*
* \hideinitializer
*/
#define PSOCK_EXIT(psock) PT_EXIT(&((psock)->pt))
/**
* Close a protosocket and exit the protosocket's protothread.
*
* This macro closes a protosocket and exits the protosocket's protothread.
*
* \param psock (struct psock *) A pointer to the protosocket.
*
* \hideinitializer
*/
#define PSOCK_CLOSE_EXIT(psock) \
do { \
PSOCK_CLOSE(psock); \
PSOCK_EXIT(psock); \
} while(0)
/**
* Declare the end of a protosocket's protothread.
*
* This macro is used for declaring that the protosocket's protothread
* ends. It must always be used together with a matching PSOCK_BEGIN()
* macro.
*
* \param psock (struct psock *) A pointer to the protosocket.
*
* \hideinitializer
*/
#define PSOCK_END(psock) PT_END(&((psock)->pt))
char psock_newdata(struct psock *s);
/**
* Check if new data has arrived on a protosocket.
*
* This macro is used in conjunction with the PSOCK_WAIT_UNTIL()
* macro to check if data has arrived on a protosocket.
*
* \param psock (struct psock *) A pointer to the protosocket.
*
* \hideinitializer
*/
#define PSOCK_NEWDATA(psock) psock_newdata(psock)
/**
* Wait until a condition is true.
*
* This macro blocks the protothread until the specified condition is
* true. The macro PSOCK_NEWDATA() can be used to check if new data
* arrives when the protosocket is waiting.
*
* Typically, this macro is used as follows:
*
\code
PT_THREAD(thread(struct psock *s, struct timer *t))
{
PSOCK_BEGIN(s);
PSOCK_WAIT_UNTIL(s, PSOCK_NEWDATA(s) || timer_expired(t));
if(PSOCK_NEWDATA(s)) {
PSOCK_READTO(s, '\n');
} else {
handle_timed_out(s);
}
PSOCK_END(s);
}
\endcode
*
* \param psock (struct psock *) A pointer to the protosocket.
* \param condition The condition to wait for.
*
* \hideinitializer
*/
#define PSOCK_WAIT_UNTIL(psock, condition) \
PT_WAIT_UNTIL(&((psock)->pt), (condition));
#define PSOCK_WAIT_THREAD(psock, condition) \
PT_WAIT_THREAD(&((psock)->pt), (condition))
#endif /* __PSOCK_H__ */
/** @} */
/** @} */
| gpl-2.0 |
assusdan/android_kernel_hs_zerasrs | drivers/misc/mediatek/lcm/otm9605a_dsi_vdo_dijing/otm9605a_dsi_vdo_dijing.c | 15047 | #ifdef BUILD_LK
#else
#include <linux/string.h>
#ifndef BUILD_UBOOT
#include <linux/kernel.h>
#endif
#endif
#include "lcm_drv.h"
// ---------------------------------------------------------------------------
// Local Constants
// ---------------------------------------------------------------------------
#define FRAME_WIDTH (540)
#define FRAME_HEIGHT (960)
#define LCM_ID_OTM9605A 0x9605
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
static unsigned int lcm_esd_test = 0; ///only for ESD test
// ---------------------------------------------------------------------------
// Local Variables
// ---------------------------------------------------------------------------
static LCM_UTIL_FUNCS lcm_util = {0};
#define SET_RESET_PIN(v) (lcm_util.set_reset_pin((v)))
#define UDELAY(n) (lcm_util.udelay(n))
#define MDELAY(n) (lcm_util.mdelay(n))
#define REGFLAG_DELAY 0XFE
#define REGFLAG_END_OF_TABLE 0x1FF // END OF REGISTERS MARKER
extern int IMM_GetOneChannelValue(int dwChannel, int data[4], int *rawdata);
extern void CKT_SET_HS_READ(void);
extern void CKT_RESTORE_HS_READ(void);
// ---------------------------------------------------------------------------
// Local Functions
// ---------------------------------------------------------------------------
#define dsi_set_cmdq_V2(cmd, count, ppara, force_update) lcm_util.dsi_set_cmdq_V2(cmd, count, ppara, force_update)
#define dsi_set_cmdq(pdata, queue_size, force_update) lcm_util.dsi_set_cmdq(pdata, queue_size, force_update)
#define wrtie_cmd(cmd) lcm_util.dsi_write_cmd(cmd)
#define write_regs(addr, pdata, byte_nums) lcm_util.dsi_write_regs(addr, pdata, byte_nums)
//#define read_reg lcm_util.dsi_read_reg()
#define read_reg_v2(cmd, buffer, buffer_size) lcm_util.dsi_dcs_read_lcm_reg_v2(cmd, buffer, buffer_size)
#define LCM_DSI_CMD_MODE 0
struct LCM_setting_table {
unsigned cmd;
unsigned char count;
unsigned char para_list[64];
};
static struct LCM_setting_table lcm_initialization_setting[] = {
/*
Note :
Data ID will depends on the following rule.
count of parameters > 1 => Data ID = 0x39
count of parameters = 1 => Data ID = 0x15
count of parameters = 0 => Data ID = 0x05
Structure Format :
{DCS command, count of parameters, {parameter list}}
{REGFLAG_DELAY, milliseconds of time, {}},
...
Setting ending by predefined flag
{REGFLAG_END_OF_TABLE, 0x00, {}}
*/
{0x00, 1, {0x00}},
{0xff, 3, {0x96,0x05,0x01}},
{0x00, 1, {0x80}},
{0xff, 2, {0x96,0x05}},
{0x00, 1, {0x92}},
{0xff, 2, {0x10,0x02}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0x00, 1, {0x00}},
{0xA0, 1, {0x00}},
{0x00, 1, {0xA0}},
{0xC1, 1, {0x00}},
{0x00, 1, {0x80}},
{0xC1, 2, {0x36,0x66}},
{0x00, 1, {0x89}},
{0xC0, 1, {0x01}},
{0x00, 1, {0xB1}},
{0xC5, 1, {0x28}},
{0x00, 1, {0xC0}},
{0xC5, 1, {0x00}},
{0x00, 1, {0x80}},
{0xC4, 1, {0x9C}},
{0x00, 1, {0x90}},
{0xC0, 6, {0x00,0x44,0x00,0x00,0x00,0x03}},
{0x00, 1, {0xB4}},
{0xC0, 1, {0x10}},
{0x00, 1, {0xA6}},
{0xC1, 3, {0x00,0x00,0x00}},
{0x00, 1, {0x91}},
{0xC5, 1, {0x76}},
{0x00, 1, {0x93}},
{0xC5, 1, {0x76}},
{0x00, 1, {0xB2}},
{0xF5, 4, {0x15,0x00,0x15,0x00}},
{0x00, 1, {0x80}},
{0xCB, 10, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0x90}},
{0xCB, 15, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xA0}},
{0xCB, 15, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xB0}},
{0xCB, 10, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xC0}},
{0xCB, 15, {0x00,0x00,0x00,0x04,0x00,0x00,0x04,0x04,0x00,0x00,0x04,0x04,0x04,0x00,0x00}},
{0x00, 1, {0xD0}},
{0xCB, 15, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x04,0x04,0x00,0x00,0x04,0x04}},
{0x00, 1, {0xE0}},
{0xCB, 10, {0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xF0}},
{0xCB, 10, {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}},
{0x00, 1, {0x80}},
{0xCC, 10, {0x00,0x00,0x00,0x02,0x00,0x00,0x0A,0x0E,0x00,0x00}},
{0x00, 1, {0x90}},
{0xCC, 15, {0x0C,0x10,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x09}},
{0x00, 1, {0xA0}},
{0xCC, 15, {0x0D,0x00,0x00,0x0B,0x0F,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xB0}},
{0xCC, 10, {0x00,0x00,0x00,0x02,0x00,0x00,0x0A,0x0E,0x00,0x00}},
{0x00, 1, {0xC0}},
{0xCC, 15, {0x0C,0x10,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x09}},
{0x00, 1, {0xD0}},
{0xCC, 15, {0x0D,0x00,0x00,0x0B,0x0F,0x00,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x00,0x00}},
{0x00, 1, {0x80}},
{0xCE, 12, {0x85,0x03,0x18,0x84,0x03,0x18,0x00,0x0F,0x00,0x00,0x0F,0x00}},
{0x00, 1, {0x90}},
{0xCE, 14, {0x33,0xC5,0x18,0x33,0xC6,0x18,0xF0,0x00,0x00,0xF0,0x00,0x00,0x00,0x00}},
{0x00, 1, {0xA0}},
{0xCE, 14, {0x38,0x03,0x03,0xBF,0x00,0x18,0x00,0x38,0x02,0x03,0xC0,0x00,0x18,0x00}},
{0x00, 1, {0xB0}},
{0xCE, 14, {0x38,0x01,0x03,0xC1,0x00,0x18,0x00,0x38,0x00,0x03,0xC2,0x00,0x18,0x00}},
{0x00, 1, {0xC0}},
{0xCE, 14, {0x30,0x00,0x03,0xC3,0x00,0x18,0x00,0x30,0x01,0x03,0xC4,0x00,0x18,0x00}},
{0x00, 1, {0xD0}},
{0xCE, 14, {0x30,0x02,0x03,0xC5,0x00,0x18,0x00,0x30,0x03,0x03,0xC6,0x00,0x18,0x00}},
{0x00, 1, {0x80}},
{0xCF, 14, {0xF0,0x00,0x00,0x10,0x00,0x00,0x00,0xF0,0x00,0x00,0x10,0x00,0x00,0x00}},
{0x00, 1, {0x90}},
{0xCF, 14, {0xF0,0x00,0x00,0x10,0x00,0x00,0x00,0xF0,0x00,0x00,0x10,0x00,0x00,0x00}},
{0x00, 1, {0xA0}},
{0xCF, 14, {0xF0,0x00,0x00,0x10,0x00,0x00,0x00,0xF0,0x00,0x00,0x10,0x00,0x00,0x00}},
{0x00, 1, {0xB0}},
{0xCF, 14, {0xF0,0x00,0x00,0x10,0x00,0x00,0x00,0xF0,0x00,0x00,0x10,0x00,0x00,0x00}},
{0x00, 1, {0xC0}},
{0xCF, 10, {0x01,0x01,0x20,0x20,0x00,0x00,0x02,0x00,0x00,0x00}},
//{0x00, 1, {0x00}},
//{0xD1, 2, {0x00,0x00}},
{0x00, 1, {0x00}},
{0xD8, 2, {0x67,0x67}},
{0x00, 1, {0x00}},
{0xD9, 1, {0x62}},
{0x00, 1, {0x00}},
{0xE1, 16, {0x02,0x06,0x0A,0x0C,0x05,0x0C,0x0A,0x08,0x05,0x08,0x0F,0x09,0x10,0x18,0x12,0x08}},
{0x00, 1, {0x00}},
{0xE2, 16, {0x02,0x07,0x0A,0x0C,0x05,0x0B,0x0A,0x08,0x05,0x08,0x0F,0x09,0x10,0x18,0x12,0x08}},
{0x00, 1, {0xB1}},
{0xC5, 1, {0x28}},
{0x00, 1, {0x80}},
{0xC4, 1, {0x9C}},
{0x00, 1, {0xC0}},
{0xC5, 1, {0x00}},
{0x00, 1, {0xB2}},
{0xF5, 4, {0x15,0x00,0x15,0x00}},
{0x00, 1, {0x93}},
{0xC5, 3, {0x03,0X55,0X55}},
{0x00, 1, {0x80}},
{0xC1, 2, {0x36,0x66}},
{0x00, 1, {0x89}},
{0xC0, 1, {0x01}},
{0x00, 1, {0xA0}},
{0xC1, 1, {0x02}},//00
{0x00, 1, {0xC5}},
{0xB0, 1, {0x03}},
{0x00, 1, {0x00}},
{0xFF, 3, {0xFF,0xFF,0xFF}},
{0x11, 1, {0x00}},
{REGFLAG_DELAY, 120, {}},
{0x29, 1, {0x00}},
// Note
// Strongly recommend not to set Sleep out / Display On here. That will cause messed frame to be shown as later the backlight is on.
// Setting ending by predefined flag
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_sleep_out_setting[] = {
// Sleep Out
{0x11, 1, {0x00}},
{REGFLAG_DELAY,120, {}},
// Display ON
{0x29, 1, {0x00}},
{REGFLAG_DELAY, 120, {}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_sleep_mode_in_setting[] = {
// Display off sequence
{0x28, 1, {0x00}},
{REGFLAG_DELAY, 120, {}},
// Sleep Mode On
{0x10, 1, {0x00}},
{REGFLAG_DELAY, 120, {}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static struct LCM_setting_table lcm_compare_id_setting[] = {
// Display off sequence
{0xF0, 5, {0x55, 0xaa, 0x52,0x08,0x00}},
{REGFLAG_DELAY, 10, {}},
{REGFLAG_END_OF_TABLE, 0x00, {}}
};
static void push_table(struct LCM_setting_table *table, unsigned int count, unsigned char force_update)
{
unsigned int i;
for(i = 0; i < count; i++)
{
unsigned cmd;
cmd = table[i].cmd;
switch (cmd)
{
case REGFLAG_DELAY :
MDELAY(table[i].count);
break;
case REGFLAG_END_OF_TABLE :
break;
default:
dsi_set_cmdq_V2(cmd, table[i].count, table[i].para_list, force_update);
MDELAY(2);
}
}
}
static void init_lcm_registers(void)
{
unsigned int data_array[16];
}
// ---------------------------------------------------------------------------
// LCM Driver Implementations
// ---------------------------------------------------------------------------
static void lcm_set_util_funcs(const LCM_UTIL_FUNCS *util)
{
memcpy(&lcm_util, util, sizeof(LCM_UTIL_FUNCS));
}
static void lcm_get_params(LCM_PARAMS *params)
{
memset(params, 0, sizeof(LCM_PARAMS));
params->type = LCM_TYPE_DSI;
params->width = FRAME_WIDTH;
params->height = FRAME_HEIGHT;
#if (LCM_DSI_CMD_MODE)
params->dsi.mode = CMD_MODE;
#else
params->dsi.mode = SYNC_PULSE_VDO_MODE;
#endif
// DSI
/* Command mode setting */
params->dsi.LANE_NUM = LCM_TWO_LANE;
//The following defined the fomat for data coming from LCD engine.
params->dsi.data_format.format = LCM_DSI_FORMAT_RGB888;
params->dbi.io_driving_current = LCM_DRIVING_CURRENT_4MA;
// Video mode setting
params->dsi.PS=LCM_PACKED_PS_24BIT_RGB888;
params->dsi.vertical_sync_active = 1;// 3 2
params->dsi.vertical_backporch = 16;// 20 1
params->dsi.vertical_frontporch = 15; // 1 12
params->dsi.vertical_active_line = FRAME_HEIGHT;
params->dsi.horizontal_sync_active = 4;// 50 2
params->dsi.horizontal_backporch = 32;
params->dsi.horizontal_frontporch = 32;
params->dsi.horizontal_active_pixel = FRAME_WIDTH;
// Bit rate calculation
params->dsi.PLL_CLOCK=210;
params->dsi.pll_div1=0; // div1=0,1,2,3;div1_real=1,2,4,4 ----0: 546Mbps 1:273Mbps
params->dsi.pll_div2=0; // div2=0,1,2,3;div1_real=1,2,4,4
#if (LCM_DSI_CMD_MODE)
params->dsi.fbk_div =9;
#else
params->dsi.fbk_div =9; // fref=26MHz, fvco=fref*(fbk_div+1)*2/(div1_real*div2_real)
#endif
//params->dsi.compatibility_for_nvk = 1; // this parameter would be set to 1 if DriverIC is NTK's and when force match DSI clock for NTK's
}
static unsigned int lcm_compare_id(void)
{
return 1;
}
static void lcm_init(void)
{
SET_RESET_PIN(0);
MDELAY(200);
SET_RESET_PIN(1);
MDELAY(200);
//lcm_compare_id();
push_table(lcm_initialization_setting, sizeof(lcm_initialization_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_suspend(void)
{
unsigned int data_array[16];
data_array[0] = 0x00280500;
dsi_set_cmdq(data_array, 1, 1);
MDELAY(10);
data_array[0] = 0x00100500;
dsi_set_cmdq(data_array, 1, 1);
MDELAY(120);
}
static void lcm_resume(void)
{
//lcm_init();
#ifdef BUILD_LK
printf("zhibin uboot %s\n", __func__);
#else
printk("zhibin kernel %s\n", __func__);
#endif
push_table(lcm_sleep_out_setting, sizeof(lcm_sleep_out_setting) / sizeof(struct LCM_setting_table), 1);
}
static void lcm_update(unsigned int x, unsigned int y,
unsigned int width, unsigned int height)
{
unsigned int x0 = x;
unsigned int y0 = y;
unsigned int x1 = x0 + width - 1;
unsigned int y1 = y0 + height - 1;
unsigned char x0_MSB = ((x0>>8)&0xFF);
unsigned char x0_LSB = (x0&0xFF);
unsigned char x1_MSB = ((x1>>8)&0xFF);
unsigned char x1_LSB = (x1&0xFF);
unsigned char y0_MSB = ((y0>>8)&0xFF);
unsigned char y0_LSB = (y0&0xFF);
unsigned char y1_MSB = ((y1>>8)&0xFF);
unsigned char y1_LSB = (y1&0xFF);
unsigned int data_array[16];
#ifdef BUILD_LK
printf("zhibin uboot %s\n", __func__);
#else
printk("zhibin kernel %s\n", __func__);
#endif
data_array[0]= 0x00053902;
data_array[1]= (x1_MSB<<24)|(x0_LSB<<16)|(x0_MSB<<8)|0x2a;
data_array[2]= (x1_LSB);
data_array[3]= 0x00053902;
data_array[4]= (y1_MSB<<24)|(y0_LSB<<16)|(y0_MSB<<8)|0x2b;
data_array[5]= (y1_LSB);
data_array[6]= 0x002c3909;
dsi_set_cmdq(&data_array, 7, 0);
}
//#define ESD_DEBUG
static unsigned int lcm_esd_check(void)
{
#ifndef BUILD_LK
static int count = 0;
static int err_count = 0;
static int uncount = 0;
int i;
unsigned char fResult;
unsigned char buffer[12];
unsigned int array[16];
#ifdef ESD_DEBUG
printk("lcm_esd_check <<<\n");
#endif
for (i = 0; i < 12; i++)
buffer[i] = 0x00;
//---------------------------------
// Set Maximum Return Size
//---------------------------------
//CKT_SET_HS_READ();
array[0] = 0x00013708;
dsi_set_cmdq(array, 1, 1);
//---------------------------------
// Read [9Ch, 00h, ECC] + Error Report(4 Bytes)
//---------------------------------
read_reg_v2(0x0A, buffer, 1);
//CKT_RESTORE_HS_READ();
#ifdef ESD_DEBUG
printk("lcm_esd_check : read(0x0A) : [0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x, 0x%x]\n", buffer[0],buffer[1],buffer[2],buffer[3],buffer[4],buffer[5],buffer[6]);
#endif
//---------------------------------
// Judge Readout & Error Report
//---------------------------------
if (buffer[3] == 0x02) // Check data identifier of error report
{
if (buffer[4] & 0x02) // Check SOT sync error
err_count ++;
else
err_count = 0;
}
else
{
err_count = 0;
}
#ifdef ESD_DEBUG
printk("lcm_esd_check err_count = %d\n", err_count);
#endif
if ((buffer[0] != 0x9C) || (err_count >= 2))
{
err_count = 0;
uncount++;
#ifndef BUILD_LK
printk("lcm_esd_check failed, err_count = %d\n", err_count);
for (i = 0; i < 7; i++)
printk("buffer[%d] : 0x%x \n", i, buffer[i]);
#endif
#ifdef ESD_DEBUG
printk("lcm_esd_check unnormal uncount = %d\n", uncount);
printk("lcm_esd_check >>>\n");
#endif
fResult = 1;
}
else
{
count ++;
#ifdef ESD_DEBUG
printk("lcm_esd_check normal count = %d\n", count);
printk("lcm_esd_check >>>\n");
#endif
fResult = 0;
}
#if 0
printk("lcm_esd_check lcm_esd_test:%d\n",lcm_esd_test);
if(lcm_esd_test==20)
{
lcm_esd_test = 0;
return TRUE;
}
lcm_esd_test++;
return FALSE;
#endif
if (fResult)
return TRUE;
else
return FALSE;
#endif
}
static unsigned int lcm_esd_recover(void)
{
#ifndef BUILD_LK
static int recount = 0;
#ifdef ESD_DEBUG
printk("lcm_esd_recover\n");
#endif
lcm_init();
recount ++;
//printk("lcm_esd_recover recover recount = %d\n", recount);
return TRUE;
#endif
}
LCM_DRIVER otm9605a_dsi_vdo_dijing_lcm_drv =
{
.name = "otm9605a_dsi_vdo_dijing",
.set_util_funcs = lcm_set_util_funcs,
.compare_id = lcm_compare_id,
.get_params = lcm_get_params,
.init = lcm_init,
.suspend = lcm_suspend,
.resume = lcm_resume,
.esd_check = lcm_esd_check,
.esd_recover = lcm_esd_recover,
#if (LCM_DSI_CMD_MODE)
.update = lcm_update,
#endif
};
| gpl-2.0 |
leprechau/freeradius-server | scripts/jenkins/README.md | 1872 | ### Jenkins scripted build pipeline for FreeRADIUS
#### Summary
The Jenkinsfile in this directory is used to build packages for
different Linux distributions. They are mostly here for the
FreeRADIUS development team, and they create the packages available at
[packages.networkradius.com](https://packages.networkradius.com).
The Jenkinsfile is meant to be run with [Jenkins](https://jenkins.io/)
and uses [Docker](https://www.docker.com/) and the files in
`scripts/docker/` directory to build packages for multiple
distributions on one server.
#### Usage
To build these packages, you need the following software:
* [Docker](https://www.docker.com/)
* [Jenkins](https://jenkins.io/) with the following plugins:
* [Pipeline](https://plugins.jenkins.io/workflow-aggregator)
* [Docker Pipeline](https://plugins.jenkins.io/docker-workflow)
Once the software is installed, you should create a new Pipeline Item
in Jenkins and [configure the job to run the
Jenkinsfile](https://jenkins.io/pipeline/getting-started-pipelines/#loading-pipeline-scripts-from-scm)
The Jenkinsfile currently builds packages for the following platforms:
* Ubuntu 14.04 (Trusty Tahir)
* Ubuntu 16.04 (Xenial Xerus)
* Ubuntu 18.04 (Bionic Beaver)
* Debian 8 (Jessie)
* Debian 9 (Stretch)
* Debian 10 (Buster)
* CentOS 7
* CentOS 8
Once complete, the packages are available as artifacts and accessible
from the job page by clicking the "Build Artifacts" link or by
accessing the url:
* https://\<jenkins\_uri\>/job/\<job\_name\>/\<build\_number\>/artifact
The packages can also be access from the last successful build on the
project page, by clicking the "Last Successful Artifacts" link, or by
going to the URL:
* https://\<jenkins\_uri\>/job/\<job\_name\>/lastSuccessfulBuild/artifact/
That page contains directories, which in turn contain packages for
each of the Linux distributions.
| gpl-2.0 |
damirkusar/jvoicebridge | softphone/src/com/sun/mc/softphone/media/coreaudio/CoreAudioAudioServiceProvider.java | 4493 | /*
* Copyright 2007 Sun Microsystems, Inc.
*
* This file is part of jVoiceBridge.
*
* jVoiceBridge is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation and distributed hereunder
* to you.
*
* jVoiceBridge is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Sun designates this particular file as subject to the "Classpath"
* exception as provided by Sun in the License file that accompanied this
* code.
*/
package com.sun.mc.softphone.media.coreaudio;
import com.sun.mc.softphone.media.NativeLibUtil;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.prefs.Preferences;
import java.util.ArrayList;
import com.sun.voip.Logger;
import com.sun.mc.softphone.media.AudioServiceProvider;
import com.sun.mc.softphone.media.Microphone;
import com.sun.mc.softphone.media.Speaker;
public class CoreAudioAudioServiceProvider implements AudioServiceProvider {
private static final String CORE_AUDIO_NAME = "libMediaFramework.jnilib";
private static AudioDriver audioDriver;
private Microphone microphone;
private Speaker speaker;
public CoreAudioAudioServiceProvider() throws IOException {
Logger.println("Loading CoreAudio provider");
// load the libarary
String arch = System.getProperty("os.arch");
String nativeLibraryName = CORE_AUDIO_NAME;
Logger.println("Loading native library: " + nativeLibraryName);
NativeLibUtil.loadLibrary(getClass(), nativeLibraryName);
return;
}
public void initialize(int sampleRate, int channels,
int microphoneSampleRate, int microphoneChannels,
int microphoneBufferSize, int speakerBufferSize)
throws IOException {
shutdown(); // stop old driver if running
audioDriver = new AudioDriverMac();
audioDriver.initialize(microphoneBufferSize, speakerBufferSize);
Logger.println("Initializing audio driver to " + sampleRate
+ "/" + channels + " microphoneBufferSize " + microphoneBufferSize
+ " speakerBufferSize " + speakerBufferSize);
/*
* The speaker is always set to 2 channels.
* Resampling is done if necessary.
*
* When set to 1 channel, sound only comes
* out of 1 channel instead of 2.
*/
audioDriver.start(
sampleRate, // speaker sample rate
2, // speaker channels
2*2, // speaker bytes per packet
1, // speaker frames per packet
2*2, // speaker frame size
16, // speaker bits per channel
microphoneSampleRate,// microphone sample rate
microphoneChannels, // microphone channels,
2*microphoneChannels,// microphone bytes per packet
1, // microphone frames per packet
2*microphoneChannels,// microphone bytes per frame
16); // microphone bits per channel
initializeMicrophone(microphoneSampleRate, microphoneChannels,
microphoneBufferSize);
initializeSpeaker(sampleRate, channels, speakerBufferSize);
}
public void shutdown() {
if (audioDriver != null) {
audioDriver.stop();
audioDriver = null;
}
}
public Microphone getMicrophone() {
return microphone;
}
public String[] getMicrophoneList() {
return new String[0];
}
private void initializeMicrophone(int sampleRate, int channels,
int microphoneBufferSize) throws IOException {
microphone = new MicrophoneCoreAudioImpl(sampleRate, channels,
microphoneBufferSize, audioDriver);
}
public Speaker getSpeaker() {
return speaker;
}
public String[] getSpeakerList() {
return new String[0];
}
private void initializeSpeaker(int sampleRate, int channels,
int speakerBufferSize) throws IOException {
speaker = new SpeakerCoreAudioImpl(sampleRate, channels,
speakerBufferSize, audioDriver);
}
}
| gpl-2.0 |
tongrhj/racing-clicker | app/views/tabs.html | 4020 | <ul ng-if="!isOffline" class="nav nav-tabs" role="tablist">
<li ng-repeat="tab in tabs.list | filter:filterVisible" class="tab-resource tab-{{name}}" ng-class="{active: cur.name === tab.name}">
<a ng-href="#{{tab.url()}}" role="tab">
<div class="tab-icon-resource tab-icon-{{tab.name}} icon-{{tab.name}}"></div>
<!-- TODO why isnt' pluralize working? -->
{{tab.leadunit.count()|bignum:0}}
<span class="tab-label label-{{tab.leadunit.name}}">
<span class="label-label">{{tab.leadunit.unittype.plural}}</span>
<span class="label-suffix"></span>
</span>
<span ng-if="tab.leadunit.capValue()">({{tab.leadunit.capPercent()|percent:{floor:true,places:0} }})</span>
<!--br>{{tab.unit.velocity()|bignum:0}}/sec-->
<!--TODO: ewww, a special case-->
<span ng-if="tab.name=='mutagen'">(+{{game.unit('premutagen').count()|bignum:0}})</span>
<span ng-if="tab.isNewlyUpgradable()" title="New upgrade available" class="animif glyphicon glyphicon-circle-arrow-up"></span>
</a>
</li>
<li role="tab" class="dropdown" ng-class="{active: !cur}">
<a class="dropdown-toggle" data-toggle="dropdown" href="javascript:">
More...
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li role="presentation" ng-class="{disabled:game.availableAutobuyUpgrades() <= 0}"><a role="menuitem" tabindex="-1" href="javascript:" ng-click="buyUpgrades(game.availableAutobuyUpgrades())">
<span class="glyphicon glyphicon-circle-arrow-up"></span> Buy all {{game.availableAutobuyUpgrades().length | number}} upgrades
</a></li>
<li role="presentation" ng-class="{disabled:game.availableAutobuyUpgrades(0.25) <= 0}"><a role="menuitem" tabindex="-1" href="javascript:" ng-click="buyUpgrades(game.availableAutobuyUpgrades(0.25), 0.25)">
<span class="glyphicon glyphicon-upload"></span> Buy cheapest {{game.availableAutobuyUpgrades(0.25).length | number}} upgrades
</a></li>
<li role="presentation" class="divider"></li>
<li ng-class="{disabled:!isUndoable()}" role="presentation">
<a role="menuitem" tabindex="-1" href="javascript:" ng-click="undo()">
<span class="glyphicon glyphicon-share-alt mirror"></span>
Undo
<span ng-if="isUndoable()">({{undoLimitSeconds - secondsSinceLastAction() | number:0}} sec)</span>
</a>
</li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/options">
<span class="glyphicon glyphicon-cog"></span> Options
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/achievements">
<span class="glyphicon glyphicon-ok"></span> Achievements
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/statistics">
<span class="glyphicon glyphicon-stats"></span> Statistics
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/changelog">
<span class="glyphicon glyphicon-book"></span> Patch Notes
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="http://reddit.com/r/swarmsim" target="_blank">
<span class="glyphicon glyphicon-user"></span> Community
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/contact">
<span class="fa fa-comment"></span> Send Feedback
</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/contact?error">
<span class="fa fa-bug"></span> Report Problem
</a></li>
<!--li role="presentation"><a role="menuitem" tabindex="-1" href="javascript:" ng-click="hotkeys.toggleCheatSheet()" target="_blank">
<span class="glyphicon glyphicon-share-alt"></span> Keyboard Shortcuts
</a></li-->
<li role="presentation"><a role="menuitem" tabindex="-1" href="#/tab/all">
<span class="glyphicon glyphicon-list-alt"></span> Show all units
</a></li>
</ul>
</li>
</ul>
| gpl-2.0 |
liutianpingyanxiaoyu/cpe | package_bak/goahead/src/management.c | 139330 | #include "uemf.h"
#include "wsIntrn.h"
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <stdlib.h>
#ifdef WEBS_SSL_SUPPORT
#include "websSSL.h"
#endif
#ifdef USER_MANAGEMENT_SUPPORT
#include "um.h"
void formDefineUserMgmt(void);
#endif
#include "management.h"
#include "webs.h"
#include "internet.h"
#include "nvram.h"
#include "nvram_rule.h"
#include <utils.h>
//#include <shutils.h>
#include <syslog.h>
#include <sys/sysinfo.h>
#include "ethread.h"
#include "mid_detail.h"
//#include "ezpcom-lib.h"
//#include "shared.h"
//#include "nvram.h"
//#include "utils.h"
//#include "internet.h"
//#include "wireless.h"
//#include "wps.h"
//#define REFRESH_TIMEOUT "40000" /* 40000 = 40 secs*/
//extern void WPSRestart(void);
//extern void formDefineWPS(void);
#define BUF_256 256
#define TMP_LEN 256 //aron patch for giga, from httpd common.h
#define LONG_BUF_LEN 8192 //aron patch for giga, from httpd common.h
#define SHORT_BUF_LEN 32
#define COMMAND_MAX 1024
static char system_command[COMMAND_MAX];
/*---------Added by Andy in 2013/11/15: WLAN Statistics--------*/
#define Radio2G 0
#define Radio5G 1
#define RadioEX 1
#define RadioNoEX 0
#define SSIDNum 8
static int getStatisticsRadioStatus(int radio);
/*--------------------------------------------------------*/
#if 1//Arthur Chow 2009-03-02: For getWebMessage
extern int setWebMessage(int flag, char *str);
#endif
#if 1//Arthur Chow 2008-12-16: For login.asp/login_fail.asp
/*
* goform/web_login
*/
extern int g_Admin_inactivity_timer_stamp;
extern int g_Force_login_inactivity_timer_stamp;
extern int g_Force_login_current_username;
static void web_login(webs_t wp, char_t *path, char_t *query)
{
char * brand;
char admpass[BUF_256];
char_t *uname;
printf("web_login\n");
#if 1 //Steve179
char_t *loginpass;
char_t *cur_ip=websGetRequestIpaddr(wp);
char_t accessable_ip[33];
FILE *fp = NULL;
int len=0;
char *sz_set_flag;
int set_flag=0;
char *tz;
char *city;
char *degree;
struct sysinfo info;
//Steve
char_t TempBuf[32];
char mgmt_value[32];
char cmd[1024];
ezplib_get_attr_val("log_rule", 0, "web_mgmt", mgmt_value, 32, EZPLIB_USE_CLI);
sz_set_flag = websGetVar(wp, T("set_flag"), T(""));
if (strlen(sz_set_flag)) {
set_flag=atoi(sz_set_flag);
}
//happiness add for checking selected ip
// char_t *cur_ip=websGetRequestIpaddr(wp);
if(checkSelectedIp(cur_ip))
{
system("echo warning2>/dev/console");
websRedirect(wp, "index_warning2.asp");
return;
}
if (set_flag==0)//Login
{
if (NULL == (fp = fopen("/web/accessip", "r")))
{
error(E_L, E_LOG, T("GetAccessableIpaddr: open /web/accessip error"));
websHeader(wp);
websWrite(wp, T("<script>location.href='/index.asp';</script>\n"));
websFooter(wp);
websDone(wp, 200);
return;
}
len = fscanf(fp, "%s", accessable_ip);
fclose(fp);
if (len)
{
uname = websGetVar(wp, T("Loginusername"), T(""));
if(!strcmp(uname,"admin"))
{
ezplib_get_attr_val("http_rule", 0, "admpasswd", admpass,
BUF_256, EZPLIB_USE_CLI);
}
else if(!strcmp(uname, "guest"))
{
ezplib_get_attr_val("http_rule", 0, "passwd", admpass,
BUF_256, EZPLIB_USE_CLI);
}
else
{
//setWebMessage(1, "User Name error!");
//Chged by Andy Yu in 2013/08/07 : User Name input Error
websRedirect(wp, "index_warning3.asp");
return;
}
loginpass = websGetVar(wp, T("LoginPassword"), T(""));
#if 0//Arthur Chow 2009-01-06: secret password
if (!strcmp(loginpass, "admin"))
{
int admin_inactivity_timer = 0;
//int admin_inactivity_timer = atoi(nvram_bufget(RT2860_NVRAM, "AdminInactivityTimer"));
//char_t *first_config=nvram_get(RT2860_NVRAM, "FirstConfig");
ezplib_get_attr_val("http_rule", 0, "adm_timeout", TempBuf, 32, EZPLIB_USE_CLI);
admin_inactivity_timer = atoi(TempBuf);
//printf("\n\n Steve debug admin_inactivity_timer=%d\n\n", admin_inactivity_timer);
if (admin_inactivity_timer>0)
{
sysinfo(&info);
g_Admin_inactivity_timer_stamp=(int) info.uptime;
}
/* modify /web/accessip to new accessable ip */
if (!strcmp(mgmt_value, "1")){
//syslog(LOG_INFO, "Web management login by secret password success for user 'admin' from %s.\n", cur_ip);
snprintf(cmd, 1024, "logger EZP_USR %s %s\n", "Login by secret password success for user 'admin' from",cur_ip);
system(cmd);
}
doSystem("echo '%s' > /web/accessip", cur_ip);
ezplib_replace_attr("http_rule", 0, "curusername", uname);
{
if (!strcmp(admpass, "admin") && !strcmp(uname, "admin") && !strcmp(nvram_safe_get("FirstConfig"), "1"))
{
nvram_set("FirstConfig", "0");
nvram_commit();
websRedirect(wp, "local/passWarning.asp");
}
else
{
//websRedirect(wp, "local/networkmap.asp");
websRedirect(wp, "local/advance/dashboard.asp");
}
}
return;
}
#endif
/*-------------------------Chged By Andy Yu in 2013/10/17: Force Login-------------------------------*/
if (!strcmp(admpass, loginpass)) {
if ((!strcmp(accessable_ip, "0.0.0.0"))||(!strcmp(accessable_ip, cur_ip))) {
//int admin_inactivity_timer = atoi(nvram_bufget(RT2860_NVRAM, "AdminInactivityTimer"));
//char_t *first_config=nvram_get(RT2860_NVRAM, "FirstConfig");
int admin_inactivity_timer = 0;
ezplib_get_attr_val("http_rule", 0, "adm_timeout", TempBuf, 32, EZPLIB_USE_CLI);
admin_inactivity_timer = atoi(TempBuf);
//printf("\n\n Steve debug admin_inactivity_timer=%d\n\n", admin_inactivity_timer);
//char_t *first_config=nvram_safe_get("FirstConfig");
if (admin_inactivity_timer>0)
{
sysinfo(&info);
g_Admin_inactivity_timer_stamp=(int) info.uptime;
}
/* modify /etc_ro/web/accessip to new accessable ip */
//Steve modified 2009/10/19
//syslog(LOG_INFO, "Web management login password success for user 'admin' from %s.\n", cur_ip);
//int web_port = atoi(nvram_bufget(RT2860_NVRAM, "RemoteManagementPort"));
int web_port = 80;
if (!strcmp(mgmt_value, "1")){
//syslog(LOG_INFO, "Web management login password success for user 'admin' from %s port:%d.\n", cur_ip, web_port);
snprintf(cmd, 1024, "logger EZP_USR %s %s:%d\n", "Login password success for user admin from",cur_ip,web_port);
system(cmd);
}
doSystem("echo '%s' > /web/accessip", cur_ip);
ezplib_replace_attr("http_rule", 0, "curusername", uname);
/*if (!strcmp(first_config, "1"))
websRedirect(wp, "local/genie.asp");
else*/
{
if (!strcmp(admpass, "admin") && !strcmp(uname, "admin") && !strcmp(nvram_safe_get("FirstConfig"), "1"))
{
nvram_set("FirstConfig", "0");
nvram_commit();
websRedirect(wp, "local/passWarning.asp");
}
else
{
//websRedirect(wp, "local/networkmap.asp");
websRedirect(wp, "local/advance/dashboard.asp");
}
}
}else {
sysinfo(&info);
g_Force_login_inactivity_timer_stamp=(int) info.uptime;
doSystem("echo '%s' > /web/faccessip", cur_ip);
if (!strcmp(uname,"admin")) {
g_Force_login_current_username = 0;
} else if (!strcmp(uname, "guest")) {
g_Force_login_current_username = 1;
}
websRedirect(wp, "index_flogin.asp");
}
return;
}
else {
if (!strcmp(mgmt_value, "1")){
//syslog(LOG_INFO, "Web management login password fail for user 'admin'.\n");
snprintf(cmd, 1024, "logger EZP_USR %s %s\n", "Login password fail for user admin ipaddres:",cur_ip);
system(cmd);
}
websRedirect(wp, "index_warning1.asp");
return;
}
#if 0
if ((!strcmp(accessable_ip, "0.0.0.0"))||(!strcmp(accessable_ip, cur_ip)))
{
if (!strcmp(admpass, loginpass))
{
//int admin_inactivity_timer = atoi(nvram_bufget(RT2860_NVRAM, "AdminInactivityTimer"));
//char_t *first_config=nvram_get(RT2860_NVRAM, "FirstConfig");
int admin_inactivity_timer = 0;
ezplib_get_attr_val("http_rule", 0, "adm_timeout", TempBuf, 32, EZPLIB_USE_CLI);
admin_inactivity_timer = atoi(TempBuf);
//printf("\n\n Steve debug admin_inactivity_timer=%d\n\n", admin_inactivity_timer);
//char_t *first_config=nvram_safe_get("FirstConfig");
if (admin_inactivity_timer>0)
{
sysinfo(&info);
g_Admin_inactivity_timer_stamp=(int) info.uptime;
}
/* modify /etc_ro/web/accessip to new accessable ip */
//Steve modified 2009/10/19
//syslog(LOG_INFO, "Web management login password success for user 'admin' from %s.\n", cur_ip);
//int web_port = atoi(nvram_bufget(RT2860_NVRAM, "RemoteManagementPort"));
int web_port = 80;
if (!strcmp(mgmt_value, "1")){
//syslog(LOG_INFO, "Web management login password success for user 'admin' from %s port:%d.\n", cur_ip, web_port);
snprintf(cmd, 1024, "logger EZP_USR %s %s:%d\n", "Login password success for user admin from",cur_ip,web_port);
system(cmd);
}
doSystem("echo '%s' > /web/accessip", cur_ip);
ezplib_replace_attr("http_rule", 0, "curusername", uname);
/*if (!strcmp(first_config, "1"))
websRedirect(wp, "local/genie.asp");
else*/
{
if (!strcmp(admpass, "admin") && !strcmp(uname, "admin") && !strcmp(nvram_safe_get("FirstConfig"), "1"))
{
nvram_set("FirstConfig", "0");
nvram_commit();
websRedirect(wp, "local/passWarning.asp");
}
else
{
//websRedirect(wp, "local/networkmap.asp");
websRedirect(wp, "local/advance/dashboard.asp");
}
}
}
else
{
if (!strcmp(mgmt_value, "1")){
//syslog(LOG_INFO, "Web management login password fail for user 'admin'.\n");
snprintf(cmd, 1024, "logger EZP_USR %s %s\n", "Login password fail for user admin ipaddres:",cur_ip);
system(cmd);
}
websRedirect(wp, "index_warning1.asp");
}
return;
}
else
{
websRedirect(wp, "index.asp");
return;
}
#endif
}
websHeader(wp);
websWrite(wp, T("<script>location.href='/index.asp';</script>\n"));
websFooter(wp);
websDone(wp, 200);
}
if (set_flag==1)//Set Weather
{
printf("\nSet Weather\n");
city = websGetVar(wp, T("city_select"), T(""));
ezplib_replace_attr("weather_rule", 0, "city", city);
degree = websGetVar(wp, T("degree_select"), T(""));
ezplib_replace_attr("weather_rule", 0, "degree", degree);
printf("nvram_commit\n");
nvram_commit();
websRedirect(wp, "/index.asp");
}
if (set_flag==2)//Set Time Zone
{
printf("NUM=0 TYPE=wan /etc/rc.common /etc/init.d/ntpclient stop \n");
system("NUM=0 TYPE=wan /etc/rc.common /etc/init.d/ntpclient stop");
tz = websGetVar(wp, T("time_zone"), T(""));
ezplib_replace_attr("ntp_rule", 0, "zone", tz);
printf("NUM=0 TYPE=wan /etc/rc.common /etc/init.d/ntpclient start \n");
system("NUM=0 TYPE=wan /etc/rc.common /etc/init.d/ntpclient start");
printf("nvram_commit\n");
nvram_commit();
websRedirect(wp, "/index.asp");
}
#endif //Steve179
}
#endif
#if 1//Arthur Chow 2009-03-02: For getWebMessage
int gWebMessageFlag=0;//0:normal message 1:error message
char gWebMessage[65]="Ready";
int setWebMessage(int flag, char *str);
int getWebMessage(int eid, webs_t wp, int argc, char_t **argv)
{
websWrite(wp, T("%s"), gWebMessage);
strcpy(gWebMessage, "Ready");
gWebMessageFlag=0;
}
int getWebMessageFlag(int eid, webs_t wp, int argc, char_t **argv)
{
websWrite(wp, T("%d"), gWebMessageFlag);
}
int setWebMessage(int flag, char *str)
{
if (flag==0)
{
gWebMessageFlag=flag;
strcpy(gWebMessage, "Configuration updated successfully.");
}
else
{
gWebMessageFlag=flag;
strcpy(gWebMessage, str);
}
}
#endif
//============================================================================
//Steve
#if 1 //Steve220
#if 1//Arthur Chow 2008-12-20: For Set Password
/*
* goform/setSysPass
*/
static void setSysPass(webs_t wp, char_t *path, char_t *query)
{
char_t *admpass_old, *admpass_new, *uname;
char nv_admpass[TMP_LEN];
char cmd[1024];
uname = websGetVar(wp, T("User_Select"), T(""));
admpass_old = websGetVar(wp, T("admpass_old"), T(""));
admpass_new = websGetVar(wp, T("admpass"), T(""));
if(!strcmp(uname, "admin"))
{
ezplib_get_attr_val("http_rule", 0, "admpasswd", nv_admpass, TMP_LEN, EZPLIB_USE_CLI);
if (!strcmp(admpass_old, nv_admpass))
{
ezplib_replace_attr("http_rule", 0, "admpasswd", admpass_new);
printf("nvram_commit()\n");
nvram_commit();
snprintf(cmd, 1024, "logger EZP_USR %s\n","modify password successful");
system(cmd);
}
else
{
char temp_str[65];
strcpy(temp_str, "Old Password not match.");
setWebMessage(1, (char *)&temp_str);
}
}
else if(!strcmp(uname, "guest"))
{
ezplib_replace_attr("http_rule", 0, "passwd", admpass_new);
printf("nvram_commit()\n");
nvram_commit();
}
else
{
setWebMessage(1, "User name error!");
}
setWebMessage(0, NULL);
websRedirect(wp, "local/advance/password.asp");
#if 0//Alvin comments
if (!strcmp(admpass_old, nv_admpass))
{
#if 1//Arthur Chow 2009-03-06
setWebMessage(0, NULL);
#endif
if(!strcmp(uname, "admin"))
{
ezplib_replace_attr("http_rule", 0, "admpasswd", admpass_new);
}
else
{
ezplib_replace_attr("http_rule", 0, "passwd", admpass_new);
}
printf("nvram_commit()\n");
nvram_commit();
websRedirect(wp, "local/advance/password.asp");
}
else
{
#if 1//Arthur Chow 2009-03-06
char temp_str[65];
strcpy(temp_str, "Old Password not match.");
setWebMessage(1, (char *)&temp_str);
websRedirect(wp, "local/advance/password.asp");
#else
websHeader(wp);
websWrite(wp, T("<h2>Error: Old Password not match</h2><br>\n"));
websFooter(wp);
websDone(wp, 200);
#endif
}
#endif
}
#endif
#if 1//Arthur Chow 2009-01-14: For Easy mode Set Password
/*
* goform/setSysPassEasy
*/
static void setSysPassEasy(webs_t wp, char_t *path, char_t *query)
{
char_t *admpass_old, *admpass_new, *admpass;
char TempBuf[32];
//char_t *operation_mode = nvram_bufget(RT2860_NVRAM, "OP_Mode");
//ezplib_get_attr_val("wl_mode_rule", 0, "mode", TempBuf, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("system_mode", 0, "name", TempBuf, 32, EZPLIB_USE_CLI);
admpass_new = websGetVar(wp, T("admpass"), T(""));
ezplib_replace_attr("http_rule", 0, "passwd", admpass_new);
nvram_set("FirstConfig", "0");
printf("nvram_commit\n");
nvram_commit();
if (!strcmp(TempBuf, "wisp0"))
websRedirect(wp, "/local/genie5.html");
else
websRedirect(wp, "/local/genie4.asp");
}
#endif
#if 1//Arthur Chow 2009-01-17: For Set Password after Login
/*
* goform/setSysPassLogin
*/
static void setSysPassLogin(webs_t wp, char_t *path, char_t *query)
{
char_t *admpass_new;
admpass_new = websGetVar(wp, T("admpass"), T(""));
ezplib_replace_attr("http_rule", 0, "admpasswd", admpass_new);
printf("nvram_commit()\n");
nvram_commit();
//websRedirect(wp, "/local/networkmap.asp");
websRedirect(wp, "local/advance/dashboard.asp");
}
#endif
#if 1//Arthur Chow 2008-12-30: For maintenance.asp
/*
* goform/maintenance_general
*/
static void maintenance_general(webs_t wp, char_t *path, char_t *query)
{
char_t *sys_name, *domain_name, *admin_inactivity_timer ;
struct sysinfo info;
char buf[2],*value=buf;
sys_name = websGetVar(wp, T("system_name"), T(""));
nvram_set("hostname", sys_name);
doSystem("/etc/rc.common /etc/init.d/dnsmasq stop");
domain_name = websGetVar(wp, T("domain_name"), T(""));
ezplib_replace_attr("lan_dhcps_rule", 0, "domain", domain_name);
doSystem("/etc/rc.common /etc/init.d/dnsmasq start");
admin_inactivity_timer = websGetVar(wp, T("admin_inactivity_timer"), T(""));
ezplib_replace_attr("http_rule", 0, "adm_timeout", admin_inactivity_timer);
//update hostname of system by kevin, 20130826
doSystem("echo %s > /proc/sys/kernel/hostname",sys_name);
ezplib_get_attr_val("log_rule", 0, "enable", buf, 2, EZPLIB_USE_CLI);
if(atoi(value)==1)
{
printf("syslog is on");
system("/etc/init.d/syslog-ng restart");
}
printf("nvram_commit\n");
nvram_commit();
#if 1
#else
if (atoi(admin_inactivity_timer)>0)
{
sysinfo(&info);
g_Admin_inactivity_timer_stamp=(int) info.uptime;
}
//aron add 2009.07.02
system("echo 1 > /var/keep_udhcpd");
doSystem("lan.sh");
doSystem("ralink_init make_wireless_config rt2860");
management_init();
system("rm -f /var/keep_udhcpd");
#endif
#if 1//Arthur Chow 2009-03-06
setWebMessage(0, NULL);
#endif
/* websRedirect(wp, "/local/advance/maintenance.asp");*/
websHeader(wp);
websWrite(wp, T("<script>\n"));
websWrite(wp, T("function waitingpage(){\n"));
websWrite(wp, T("top.location.href = '/local/advance/loading.asp?2';\n"));
websWrite(wp, T("}\n"));
websWrite(wp, T("waitingpage();\n"));
websWrite(wp, T("</script>\n"));
websFooter(wp);
websDone(wp, 200);
}
#endif
#if 1//Arthur Chow 2009-02-04: For detecting/checking wan type
int detectEthernetWanType(int eid, webs_t wp, int argc, char_t **argv)
{
nvram_set("FirstConfig", "0");
nvram_commit();
//doSystem("pppoe -I eth2.2 -d -t 1 > /tmp/statusEthernetWanPPPoE &");
doSystem("pppoe-discovery -I vlan2 > /tmp/statusEthernetWanPPPoE &");
websWrite(wp, T("start detect"));
return 0;
}
int checkEthernetWanType(int eid, webs_t wp, int argc, char_t **argv)
{
char buf[1024];
FILE *fp = NULL;
int len=0;
printf("\n ==> Steve checkEthernetWanType\n");
#if 0
websWrite(wp, T("0"));
return 1;
#else
if (NULL == (fp = fopen("/tmp/statusEthernetWanPPPoE", "r")))
{
websWrite(wp, T("0"));
return 1;
}
len = fscanf(fp, "%s", buf);
fclose(fp);
if (len==1)
{
printf("PPPoE => get %s\n", buf);
websWrite(wp, T("1"));//PPPoE
return 1;
}
websWrite(wp, T("0"));//Not PPPoE
return 1;
#endif
}
#endif
#if 1//Arthur Chow 2009-02-09: For get Yahoo Weather
int checkWeather(int eid, webs_t wp, int argc, char_t **argv)
{
char code[33], temp[33];
FILE *fp = NULL;
int len=0;
char *city;
char *degree;
char city_str[33];
char degree_str[33];
char TempBuf[32];
printf("\ncheckWeather\n");
ezplib_get_attr_val("weather_rule", 0, "city", TempBuf, 32, EZPLIB_USE_CLI);
city = TempBuf;
if(strlen(city))
{
if (!strcmp(city, "AUXX0025"))
strcpy(city_str, "c1");
else
if (!strcmp(city, "CHXX0008"))
strcpy(city_str, "c2");
else
if (!strcmp(city, "CSXX0009"))
strcpy(city_str, "c3");
else
if (!strcmp(city, "EZXX0012"))
strcpy(city_str, "c4");
else
if (!strcmp(city, "DAXX0009"))
strcpy(city_str, "c5");
else
if (!strcmp(city, "FIXX0002"))
strcpy(city_str, "c6");
else
if (!strcmp(city, "FRXX0076"))
strcpy(city_str, "c7");
else
if (!strcmp(city, "GMXX0007"))
strcpy(city_str, "c8");
else
if (!strcmp(city, "GRXX0004"))
strcpy(city_str, "c9");
else
if (!strcmp(city, "INXX0096"))
strcpy(city_str, "c10");
else
if (!strcmp(city, "IDXX0022"))
strcpy(city_str, "c11");
else
if (!strcmp(city, "ITXX0067"))
strcpy(city_str, "c12");
else
if (!strcmp(city, "JAXX0085"))
strcpy(city_str, "c13");
else
if (!strcmp(city, "MYXX0008"))
strcpy(city_str, "c14");
else
if (!strcmp(city, "NLXX0002"))
strcpy(city_str, "c15");
else
if (!strcmp(city, "NOXX0029"))
strcpy(city_str, "c16");
else
if (!strcmp(city, "RSXX0063"))
strcpy(city_str, "c17");
else
if (!strcmp(city, "SNXX0006"))
strcpy(city_str, "c18");
else
if (!strcmp(city, "SPXX0050"))
strcpy(city_str, "c19");
else
if (!strcmp(city, "SWXX0031"))
strcpy(city_str, "c20");
else
if (!strcmp(city, "SZXX0006"))
strcpy(city_str, "c21");
else
if (!strcmp(city, "TWXX0021"))
strcpy(city_str, "c22");
else
if (!strcmp(city, "THXX0002"))
strcpy(city_str, "c23");
else
if (!strcmp(city, "TUXX0002"))
strcpy(city_str, "c24");
else
if (!strcmp(city, "UKXX0085"))
strcpy(city_str, "c25");
else
if (!strcmp(city, "UKXX1428"))
strcpy(city_str, "c26");
else
if (!strcmp(city, "USNY0996"))
strcpy(city_str, "c27");
else
if (!strcmp(city, "USDC0001"))
strcpy(city_str, "c28");
else
if (!strcmp(city, "USCA0638"))
strcpy(city_str, "c29");
else
if (!strcmp(city, "VMXX0006"))
strcpy(city_str, "c30");
else
strcpy(city_str, "c26");
}
else
strcpy(city_str, "c26");
ezplib_get_attr_val("weather_rule", 0, "degree", TempBuf, 32, EZPLIB_USE_CLI);
degree = TempBuf;
if(strlen(degree))
{
if (!strcmp(degree, "f"))
strcpy(degree_str, "F");
else
strcpy(degree_str, "C");
}
else
strcpy(degree_str, "C");
doSystem("killall wget");
doSystem("cat /tmp/weather | grep 'condition' | sed 's/^.*code=\"//g' | sed 's/\".*$//g' > /tmp/weather_code");
doSystem("cat /tmp/weather | grep 'condition' | sed 's/^.*temp=\"//g' | sed 's/\".*$//g' > /tmp/weather_temp");
if (NULL == (fp = fopen("/tmp/weather_code", "r")))
{
websWrite(wp, T("parent.show_div(true, 'nointernet_msg');\n"));
websWrite(wp, T("parent.show_div(false, 'nointernet_check');\n"));
return 1;
}
len = fscanf(fp, "%s", code);
fclose(fp);
if (len!=1)
{
websWrite(wp, T("parent.show_div(true, 'nointernet_msg');\n"));
websWrite(wp, T("parent.show_div(false, 'nointernet_check');\n"));
return 1;
}
if (NULL == (fp = fopen("/tmp/weather_temp", "r")))
{
websWrite(wp, T("parent.show_div(true, 'nointernet_msg');\n"));
websWrite(wp, T("parent.show_div(false, 'nointernet_check');\n"));
return 1;
}
len = fscanf(fp, "%s", temp);
fclose(fp);
if (len!=1)
{
websWrite(wp, T("parent.show_div(true, 'nointernet_msg');\n"));
websWrite(wp, T("parent.show_div(false, 'nointernet_check');\n"));
return 1;
}
switch(atoi(code))
{
case 19:
case 20:
case 21:
case 22:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
case 33:
case 44:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/cloudy.jpg)';\n"));
break;
case 32:
case 36:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/fine.jpg)';\n"));
break;
case 23:
case 24:
case 25:
case 34:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/fine_cloudy.jpg)';\n"));
break;
case 1:
case 8:
case 9:
case 10:
case 11:
case 12:
case 35:
case 40:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/rain.jpg)';\n"));
break;
case 5:
case 6:
case 7:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 41:
case 42:
case 43:
case 46:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/snowy.jpg)';\n"));
break;
case 0:
case 2:
case 3:
case 4:
case 37:
case 38:
case 39:
case 45:
case 47:
websWrite(wp, T("parent.document.getElementById('jpg_display').style.backgroundImage='url(/thunder_shower.jpg)';\n"));
break;
}
websWrite(wp, T("parent.showcity('%s');\n"), city_str);
websWrite(wp, T("parent.document.getElementById('temp_display').innerHTML='%s°%s';\n"), temp, degree_str);
websWrite(wp, T("parent.show_div(false, 'nointernet_msg');\n"));
websWrite(wp, T("parent.show_div(false, 'nointernet_check');\n"));
return 1;
}
int detectWeather(int eid, webs_t wp, int argc, char_t **argv)
{
char *city;
char *degree;
char city_str[33];
char degree_str[33];
char TempBuf[32];
printf("\detectWeather\n");
ezplib_get_attr_val("weather_rule", 0, "city", TempBuf, 32, EZPLIB_USE_CLI);
city = TempBuf;
if(strlen(city))
strcpy(city_str, city);
else
strcpy(city_str, "UKXX1428");
ezplib_get_attr_val("weather_rule", 0, "degree", TempBuf, 32, EZPLIB_USE_CLI);
degree = TempBuf;
if(strlen(degree))
strcpy(degree_str, degree);
else
strcpy(degree_str, "c");
doSystem("rm /tmp/weather");
doSystem("wget 'http://weather.yahooapis.com/forecastrss?p=%s&u=%s' -O /tmp/weather &", city_str, degree_str);
return 1;
}
int set_language(int eid, webs_t wp, int argc, char_t **argv)
{
char *lang;
lang=wp->url+18;
printf("\n\nLanguage =%s\n\n", lang);
//Chged by Andy Yu in 2013/07/11: Synchronize(nvram)
//doSystem("nvram set lang=%s", lang);
nvram_set("lang", lang);
nvram_commit();
return 1;
}
#endif
/*
* goform/setSysAdm
*/
static void setSysAdm(webs_t wp, char_t *path, char_t *query)
{
char_t *admuser, *admpass;
char *old_user;
//old_user = nvram_bufget(RT2860_NVRAM, "Login");
admuser = websGetVar(wp, T("admuser"), T(""));
admpass = websGetVar(wp, T("admpass"), T(""));
if (!strlen(admuser)) {
error(E_L, E_LOG, T("setSysAdm: account empty, leave it unchanged"));
return;
}
if (!strlen(admpass)) {
error(E_L, E_LOG, T("setSysAdm: password empty, leave it unchanged"));
return;
}
//nvram_bufset(RT2860_NVRAM, "Login", admuser);
//nvram_bufset(RT2860_NVRAM, "Password", admpass);
//nvram_commit(RT2860_NVRAM);
/* modify /etc/passwd to new user name and passwd */
doSystem("sed -e 's/^%s:/%s:/' /etc/passwd > /etc/newpw", old_user, admuser);
doSystem("cp /etc/newpw /etc/passwd");
doSystem("rm -f /etc/newpw");
doSystem("chpasswd.sh %s %s", admuser, admpass);
// Tommy, Wireless Scheduler: change /var/spool/cron/crontabs/Orig_file to new username file
char *scheduling_enable;
//scheduling_enable = nvram_bufget(RT2860_NVRAM, "WiFiScheduleEnable");
char *Radio_OFF;
//Radio_OFF = nvram_bufget(RT2860_NVRAM, "RadioOff");
#if 0
if (!strcmp(Radio_OFF, "0")){
if (!strcmp(scheduling_enable, "1")){
doSystem("killall crond");
doSystem("cat /var/spool/cron/crontabs/%s > /var/spool/cron/crontabs/%s",old_user, admuser);
doSystem("rm -f /var/spool/cron/crontabs/%s",old_user);
doSystem("crond");
}
}
#else
doSystem("cat /var/spool/cron/crontabs/%s > /var/spool/cron/crontabs/%s",old_user, admuser);
doSystem("rm -f /var/spool/cron/crontabs/%s",old_user);
if ( (!strcmp(Radio_OFF, "0")) && (!strcmp(scheduling_enable, "1")) ){
// Execute "cron" daemon
doSystem("crond");
}else{
doSystem("killall crond");
}
#endif
#ifdef USER_MANAGEMENT_SUPPORT
if (umGroupExists(T("adm")) == FALSE)
umAddGroup(T("adm"), 0x07, AM_DIGEST, FALSE, FALSE);
if (old_user != NULL && umUserExists(old_user))
umDeleteUser(old_user);
if (umUserExists(admuser))
umDeleteUser(admuser);
umAddUser(admuser, admpass, T("adm"), FALSE, FALSE);
#endif
websHeader(wp);
websWrite(wp, T("<h2>Adminstrator Settings</h2><br>\n"));
websWrite(wp, T("adm user: %s<br>\n"), admuser);
websWrite(wp, T("adm pass: %s<br>\n"), admpass);
websFooter(wp);
websDone(wp, 200);
}
/*
* goform/setSysLang
*/
static void setSysLang(webs_t wp, char_t *path, char_t *query)
{
char_t *lang;
lang = websGetVar(wp, T("langSelection"), T(""));
//nvram_bufset(RT2860_NVRAM, "Language", lang);
//nvram_commit(RT2860_NVRAM);
websHeader(wp);
websWrite(wp, T("<h2>Language Selection</h2><br>\n"));
websWrite(wp, T("language: %s<br>\n"), lang);
websFooter(wp);
websDone(wp, 200);
}
// Aaron 2009/8/13 move to here!
// Tommy, check scheduling status and do action, 2009/3/12 01:59
void check_do_scheduling(void)
{
int currtime, scheduler_starttime, scheduler_endtime, do_action;
char currweek[4], scheduler_week[4];
FILE *currtime_file,*scheduler_file;
int match_week=0;
char tmpValue[64];
doSystem("date \"+%%a %%H%%M\" > /var/spool/cron/crontabs/currtime");
currtime_file = fopen("/var/spool/cron/crontabs/currtime", "r");
if (!currtime_file){
printf("indicate error: Cannot open /var/spool/cron/crontabs/currtime !!!\n");
return;
}else{
fscanf(currtime_file,"%s %d",currweek,&currtime);
//printf("############### Get Current Time file = %s %d\n",currweek,currtime);
fclose(currtime_file);
}
scheduler_file = fopen("/var/spool/cron/crontabs/scheduler", "r");
if (!scheduler_file){
printf("indicate error: Cannot open /var/spool/cron/crontabs/scheduler !!!\n");
return;
}else{
while ( (fscanf(scheduler_file,"%s %d %d %d",scheduler_week,&scheduler_starttime,
&scheduler_endtime,&do_action)) != EOF){
//printf("############### Get scheduler file = %s %d %d %d\n",scheduler_week,scheduler_starttime,scheduler_endtime,do_action);
if ((!strcmp(scheduler_week,"Eve")) || (!strcmp(scheduler_week ,currweek))){
match_week++;
if ((currtime >= scheduler_starttime) && (currtime <= scheduler_endtime)){
//doSystem("iwpriv rai0 set RadioOn=%d",do_action);
snprintf(tmpValue,sizeof(tmpValue),"/sbin/ezp-wps-set 0 0 11 %d",do_action);
system(tmpValue);
doSystem("nvram_set SchedulerRadioOn %d",do_action);
//printf("############### Set do_action = %d\n",do_action);
}else{
//doSystem("iwpriv rai0 set RadioOn=%d",(do_action)? 0:1);
snprintf(tmpValue,sizeof(tmpValue),"/sbin/ezp-wps-set 0 0 11 %d",(do_action)? 0:1);
system(tmpValue);
doSystem("nvram_set SchedulerRadioOn %d",(do_action)? 0:1);
//printf("############### Set action !do_action = %d\n",(do_action)? 0:1);
}
}
}
fclose(scheduler_file);
}
if (!match_week){
// schedule is not in rule table(admin or scheduler), set Radio ON
//doSystem("iwpriv rai0 set RadioOn=1");
system("/sbin/ezp-wps-set 0 0 11 1");
doSystem("nvram_set SchedulerRadioOn 1");
}
// Tommy, restart crond, 2009/4/7 09:35
doSystem("killall crond");
doSystem("rm -f /var/spool/cron/crontabs/currtime");
doSystem("crond");
}
// Tommy, check scheduling status and do action, 2009/3/12 01:59
void check_scheduler(void)
{
//char_t *Radio_OFF = nvram_bufget(RT2860_NVRAM, "RadioOff");
//char_t *operation_mode = nvram_bufget(RT2860_NVRAM, "OP_Mode");
//char_t *scheduling_enable = nvram_bufget(RT2860_NVRAM, "WiFiScheduleEnable");
//if ( (!strcmp(operation_mode, "6")) || (!strcmp(Radio_OFF, "1")) || (!strcmp(scheduling_enable, "0")) ){
// printf("@@@@@@@@@@@@@@@ DON'T do Scheduling action!!!!\n");
//}else{
// printf("@@@@@@@@@@@@@@@ do Scheduling action !!!!\n");
// check_do_scheduling();
//}
}
//goform/showlog
static void showlog(webs_t wp, char_t *path, char_t *query)
{
char *index, *all, *asd, *dns, upnp;
index=0;
index=websGetVar(wp, T("log_index"), T(""));
//printf("aaa==[%s]\n",index);
if(!(strcmp(index,"show_all")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "show_all");
nvram_set("log_index", "show_all");
}
if(!(strcmp(index,"System_Maintenance")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "System_Maintenance");
nvram_set("log_index", "System_Maintenance");
}
if(!(strcmp(index,"dns")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "dns");
nvram_set("log_index", "dns");
}
if(!(strcmp(index,"PPP")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "PPP");
nvram_set("log_index", "PPP");
}
if(!(strcmp(index,"UPnP")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "UPnP");
nvram_set("log_index", "UPnP");
}
if(!(strcmp(index,"WLAN")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "WLAN");
nvram_set("log_index", "WLAN");
}
if(!(strcmp(index,"NTPClient")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "NTPClient");
nvram_set("log_index", "NTPClient");
}
if(!(strcmp(index,"SYSwarning")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "SYSwarning");
nvram_set("log_index", "SYSwarning");
}
//-------- aron add 2009.10.23
if(!(strcmp(index,"dhcpServer")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "dhcpServer");
nvram_set("log_index", "dhcpServer");
}
if(!(strcmp(index,"dhcpClient")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "dhcpClient");
nvram_set("log_index", "dhcpClient");
}
if(!(strcmp(index,"ddns")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "ddns");
nvram_set("log_index", "ddns");
}
if(!(strcmp(index,"vpn")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "vpn");
nvram_set("log_index", "vpn");
}
//--------- steve add 2009.10.27
if(!(strcmp(index,"Firewall")))
{
//nvram_bufset(RT2860_NVRAM, "log_index", "Firewall");
nvram_set("log_index", "Firewall");
}
//------------------------------
nvram_commit();
websRedirect(wp, "/local/advance/syslog_gordon.asp");
}
//goform/logsetting
static void logsetting(webs_t wp, char_t *path, char_t *query)
{
char *SystemMaintenance, *logdns, *PPP, *UPnP, *WLAN, *NTPClient, *SYSwarning, *select_num;
char *dhcpServer, *dhcpClient, *ddns; //aron add 2009.10.23
char *Firewall; //Steve add 2009/10/22
char *vpn,*enable,*ipaddr,*port;
char *value,buf[32]={0};
enable = websGetVar(wp, T("enable"), T("1"));
ezplib_replace_attr("log_rule", 0, "enable", enable);
if(atoi(enable) == 1)
{
value = buf;
strcpy(value,nvram_get("log_index"));
system("killall syslog-ng");
SystemMaintenance=websGetVar(wp, T("System_Maintenance"), T("0"));
ezplib_replace_attr("log_rule", 0, "web_mgmt", SystemMaintenance);
if(!strcmp(SystemMaintenance,"0")){
if(!strcmp(value,"System_Maintenance"))
nvram_set("log_index", "show_all");
}
logdns=websGetVar(wp, T("dns"), T("0"));
ezplib_replace_attr("log_rule", 0, "dns", logdns);
if(!strcmp(logdns,"0")){
if(!strcmp(value,"dns"))
nvram_set("log_index", "show_all");
}
PPP=websGetVar(wp, T("PPP"), T("0"));
ezplib_replace_attr("log_rule", 0, "ppp", PPP);
if(!strcmp(PPP,"0")){
if(!strcmp(value,"PPP"))
nvram_set("log_index", "show_all");
}
UPnP=websGetVar(wp, T("UPnP"), T("0"));
ezplib_replace_attr("log_rule", 0, "upnp", UPnP);
if(!strcmp(UPnP,"0")){
if(!strcmp(value,"UPnP"))
nvram_set("log_index", "show_all");
}
WLAN=websGetVar(wp, T("WLAN"), T("0"));
ezplib_replace_attr("log_rule", 0, "wireless", WLAN);
if(!strcmp(WLAN,"0")){
if(!strcmp(value,"WLAN"))
nvram_set("log_index", "show_all");
}
NTPClient=websGetVar(wp, T("NTPClient"), T("0"));
ezplib_replace_attr("log_rule", 0, "ntp", NTPClient);
if(!strcmp(NTPClient,"0")){
if(!strcmp(value,"NTPClient"))
nvram_set("log_index", "show_all");
}
SYSwarning=websGetVar(wp, T("SYSwarning"), T("0"));
ezplib_replace_attr("log_rule", 0, "sys_warning", SYSwarning);
if(!strcmp(SYSwarning,"0")){
if(!strcmp(value,"SYSwarning"))
nvram_set("log_index", "show_all");
}
select_num=websGetVar(wp, T("select_num"), T(""));
nvram_set("log_selected_num", select_num);
//----- aron add 2009.10.23
dhcpServer=websGetVar(wp, T("DhcpServer"), T("0"));
ezplib_replace_attr("log_rule", 0, "dhcp_serv", dhcpServer);
if(!strcmp(dhcpServer,"0")){
if(!strcmp(value,"dhcpServer"))
nvram_set("log_index", "show_all");
}
dhcpClient=websGetVar(wp, T("DhcpClient"), T("0"));
ezplib_replace_attr("log_rule", 0, "dhcp_cli", dhcpClient);
if(!strcmp(dhcpClient,"0")){
if(!strcmp(value,"dhcpClient"))
nvram_set("log_index", "show_all");
}
ddns=websGetVar(wp, T("DDNS"), T("0"));
ezplib_replace_attr("log_rule", 0, "ddns", ddns);
if(!strcmp(ddns,"0")){
if(!strcmp(value,"ddns"))
nvram_set("log_index", "show_all");
}
//add by bingley start
vpn=websGetVar(wp, T("vpn"), T("0"));
ezplib_replace_attr("log_rule", 0, "vpn", vpn);
if(!strcmp(vpn,"0")){
if(!strcmp(value,"vpn"))
nvram_set("log_index", "show_all");
}// add by bingley end
//--------------------------------------
ipaddr = websGetVar(wp, T("ipaddr"), T(""));
ezplib_replace_attr("log_rule", 0, "ipaddr", ipaddr);
port = websGetVar(wp, T("port"), T(""));
if(port_conflict_judge(port, SYSLOG_PORT) == -1)
{
websRedirect(wp, "local/advance/LogSettings.asp");
setWebMessage(1, "Port has been occupied");
return ;
}
int p=atoi(port);
if(p>0&&p<=65535)
{
ezplib_replace_attr("log_rule", 0, "port", port);
}
else
{
fprintf(stderr,"the port number is out of range\r\n");
}
//-------steve add 2009.10.22
Firewall=websGetVar(wp, T("Firewall"), T(""));
ezplib_replace_attr("log_rule", 0, "firewall", Firewall);
if(!strcmp(Firewall,"0")){
if(!strcmp(value,"Firewall"))
nvram_set("log_index", "show_all");
}
nvram_commit();
system("/etc/init.d/syslog-ng start");
//-------------------------------------------
}
else
{
nvram_commit();
system("killall syslog-ng");
}
//snprintf(tmp, TMP_LEN, "/sbin/syslog-ng-init start");
setWebMessage(0, NULL);
websRedirect(wp, "/local/advance/LogSettings.asp");
}
/*
*goform/turnToIndex
*/
static void turnToIndex(webs_t wp, char_t *path, char_t *query)
{
websRedirect(wp, "/index.asp");
}
/*
* goform/NTP
*/
static void NTP(webs_t wp, char_t *path, char_t *query)
{
char tmp[TMP_LEN], tmp1[TMP_LEN];
char *enable, *type, *ipaddr, *zone, *manual, *daylight;
char *hour, *min, *sec, *year, *mon, *date;
char *startMon, *startDay, *startClock, *endMon, *endDay, *endClock;
char *rule_set = "ntp_rule";
int len, manual_type, daylightEnb, change = 0;
//preaction
snprintf(tmp1, TMP_LEN, "/etc/init.d/ntpclientweb stop");
system(tmp1);
//system("/etc/rc.common /etc/init.d/ntpclient stop");
//AboCom always make it "enabled"
enable = "1";
/* Time setting type */
snprintf(tmp, sizeof(tmp), "mten_ServiceType");
manual = websGetVar(wp, tmp, "");
manual_type = atoi(manual);
if(manual_type ==0) //Abocom treat "manual time" as "0"
manual = "1"; //AXIM treat "manual time" as "1"
else if(manual_type ==1)
manual = "0";
if (!strcmp(manual, "1")) //setting time manually
{
/* hour */
snprintf(tmp, sizeof(tmp), "current_hour");
hour = websGetVar(wp, tmp, "");
/* minute */
snprintf(tmp, sizeof(tmp), "current_Min");
min = websGetVar(wp, tmp, "");
/* second */
snprintf(tmp, sizeof(tmp), "current_Sec");
sec = websGetVar(wp, tmp, "");
/* year */
snprintf(tmp, sizeof(tmp), "current_Year");
year = websGetVar(wp, tmp, "");
/* month */
snprintf(tmp, sizeof(tmp), "current_Mon");
mon = websGetVar(wp, tmp, "");
/* date */
snprintf(tmp, sizeof(tmp), "current_Day");
date = websGetVar(wp, tmp, "");
ezplib_replace_attr(rule_set, 0, "hour", hour);
ezplib_replace_attr(rule_set, 0, "min", min);
ezplib_replace_attr(rule_set, 0, "sec", sec);
ezplib_replace_attr(rule_set, 0, "year", year);
ezplib_replace_attr(rule_set, 0, "mon", mon);
ezplib_replace_attr(rule_set, 0, "date", date);
}
else if (!strcmp(manual, "0")) //get from time server
{
#if 0
/* Time Server type */
snprintf(tmp, sizeof(tmp), "time_ServerType");
type = websGetVar(wp, tmp, "");
if (!strcmp(type, "0"))
type = "pool";
else if (!strcmp(type, "1"))
type = "ipaddr";
if (!strcmp(type, "pool"))
{
//AboCom don't have server area to be chosen on UI
}
else
{
/* IP Address */
snprintf(tmp, sizeof(tmp), "NTPServerIP");
ipaddr = websGetVar(wp, tmp, "");
ezplib_replace_attr(rule_set, 0, "ipaddr", ipaddr);
}
ezplib_replace_attr(rule_set, 0, "type", type);
#else
/* Time Server type */
snprintf(tmp, sizeof(tmp), "time_ServerType");
type = websGetVar(wp, tmp, "");
if (!strcmp(type, "0"))
{
//AboCom don't have server area to be chosen on UI
ezplib_replace_attr(rule_set, 0, "type", "pool");
}
else
{
/* IP Address */
snprintf(tmp, sizeof(tmp), "NTPServerIP");
ipaddr = websGetVar(wp, tmp, "");
ezplib_replace_attr(rule_set, 0, "type", "ipaddr");
ezplib_replace_attr(rule_set, 0, "serv_ipaddr", ipaddr);
}
ezplib_replace_attr(rule_set, 0, "custom_server", type);
#endif
}
ezplib_replace_attr(rule_set, 0, "custom_time", manual);
/* Zone */
snprintf(tmp, sizeof(tmp), "time_zone");
zone = websGetVar(wp, tmp, "");
ezplib_replace_attr(rule_set, 0, "zone", zone);
/* daylight saving */
snprintf(tmp, sizeof(tmp), "enabledaylight");
daylight = websGetVar(wp, tmp, "");
daylightEnb = atoi(daylight);
if(daylightEnb ==0)
daylight = "0";
else if(daylightEnb ==1)
daylight = "1";
if (!strcmp(daylight, "1")) //enabled
{
/* start Month */
snprintf(tmp, sizeof(tmp), "dst_startMon");
startMon = websGetVar(wp, tmp, "");
/* start Day */
snprintf(tmp, sizeof(tmp), "dst_startDay");
startDay = websGetVar(wp, tmp, "");
/* start clock */
snprintf(tmp, sizeof(tmp), "dst_startclock");
startClock = websGetVar(wp, tmp, "");
/* end Month */
snprintf(tmp, sizeof(tmp), "dst_endMon");
endMon = websGetVar(wp, tmp, "");
/* end Day */
snprintf(tmp, sizeof(tmp), "dst_endDay");
endDay = websGetVar(wp, tmp, "");
/* end Clock */
snprintf(tmp, sizeof(tmp), "dst_endclock");
endClock = websGetVar(wp, tmp, "");
ezplib_replace_attr(rule_set, 0, "ds_start_mon", startMon);
ezplib_replace_attr(rule_set, 0, "ds_start_day", startDay);
ezplib_replace_attr(rule_set, 0, "ds_start_hour", startClock);
ezplib_replace_attr(rule_set, 0, "ds_end_mon", endMon);
ezplib_replace_attr(rule_set, 0, "ds_end_day", endDay);
ezplib_replace_attr(rule_set, 0, "ds_end_hour", endClock);
}
ezplib_replace_attr(rule_set, 0, "daylight_saving", daylight);
//postaction
snprintf(tmp1, TMP_LEN, "/etc/init.d/ntpclientweb start");
system(tmp1);
//system("/etc/rc.common /etc/init.d/ntpclient start");
nvram_commit();
setWebMessage(0, NULL);
websRedirect(wp, "/local/advance/management_gordon.asp");
}
/*
* goform/NTPSyncWithHost
*/
static void NTPSyncWithHost(webs_t wp, char_t *path, char_t *query)
{
if(!query || (!strlen(query)))
return;
if(strchr(query, ';'))
return;
doSystem("date -s %s", query);
websWrite(wp, T("HTTP/1.1 200 OK\nContent-type: text/plain\nPragma: no-cache\nCache-Control: no-cache\n\n"));
websWrite(wp, T("n/a"));
websDone(wp, 200);
}
/*
* goform/DDNS
*/
static void DDNS(webs_t wp, char_t *path, char_t *query)
{
char *rule_num = nvram_safe_get("wan_num"); // Corresponding to wan_num
char buf[LONG_BUF_LEN], tmp[TMP_LEN];
char *rule_set = "wan_ddns_rule";
char *enable, *type, *username, *passwd, *hostname;
int num, i, len, change = 0;
int ddnsEnb;
char *server;
if (!*rule_num)
num = 1;
else
num = atoi(rule_num);
for (i = 0; i < num; i++) {
if(i==0) //Normally, the nth for "0"
{
/* Enable */
snprintf(tmp, sizeof(tmp), "ddnsenabled");
enable = websGetVar(wp, tmp, "");
}
else //increased nth for "1", "2",...etc.
{
/* Enable */
snprintf(tmp, sizeof(tmp), "ddnsenabled_%d", i);
enable = websGetVar(wp, tmp, "");
}
//preaction
snprintf(tmp, TMP_LEN, "NUM=%d TYPE=wan /etc/rc.common /etc/rc.d/T60ddns stop", i);
system(tmp);
//system("/etc/rc.common /etc/init.d/ddns stop");
ddnsEnb=atoi(enable);
if (ddnsEnb == 0) //disabled
{
ezplib_replace_attr(rule_set, i, "enable", "0");
change = 1;
}
else //enabled
{
if(i==0) //Normally, the nth for "0"
{
/* Type */
snprintf(tmp, sizeof(tmp), "DDNSProvider");
type = websGetVar(wp, tmp, "");
/* User Name */
snprintf(tmp, sizeof(tmp), "Account");
username = websGetVar(wp, tmp, "");
/* Passwd */
snprintf(tmp, sizeof(tmp), "Password");
passwd = websGetVar(wp, tmp, "");
/* Host Name */
snprintf(tmp, sizeof(tmp), "DDNS");
hostname = websGetVar(wp, tmp, "");
/*Custom Server*/
snprintf(tmp, sizeof(tmp), "CustomServer");
server= websGetVar(wp, tmp, "");
}
else //increased nth for "1", "2",...etc.
{
/* Type */
snprintf(tmp, sizeof(tmp), "DDNSProvider_%d", i);
type = websGetVar(wp, tmp, "");
/* User Name */
snprintf(tmp, sizeof(tmp), "Account_%d", i);
username = websGetVar(wp, tmp, "");
/* Passwd */
snprintf(tmp, sizeof(tmp), "Password_%d", i);
passwd = websGetVar(wp, tmp, "");
/* Host Name */
snprintf(tmp, sizeof(tmp), "DDNS_%d", i);
hostname = websGetVar(wp, tmp, "");
}
//Translate AboCom's dns provider to AXIM's nvram format
if(!strcmp(type, "dyndns.org"))
type = "dyndns";
else if(!strcmp(type, "no-ip.com"))
type = "noip";
else if(!strcmp(type, "eurodyndns"))
type = "eurodyndns";
else if(!strcmp(type, "regfish"))
type = "regfish";
len =
snprintf(buf, TMP_LEN, "WAN%d_DDNS^%s^%s^%s^%s^%s^%s",
i+1, enable, type, "", "", hostname, "");
if (len >= TMP_LEN)
{
return 0;
}
ezplib_replace_rule(rule_set, i, buf);
ezplib_replace_attr(rule_set, i, "username", username);
ezplib_replace_attr(rule_set, i, "passwd", passwd);
ezplib_replace_attr(rule_set, i, "server", server);
change = 1;
//postaction
snprintf(tmp, TMP_LEN, "NUM=%d TYPE=wan /etc/rc.common /etc/rc.d/T60ddns start", i);
system(tmp);
//system("/etc/rc.common /etc/init.d/ddns start");
}
}
nvram_commit();
//return change;
setWebMessage(0, NULL);
char_t *submitUrl;
submitUrl = websGetVar(wp, T("ddns_url"), T("")); // aron add for hidden page
websRedirect(wp, submitUrl);
}
static void SystemCommand(webs_t wp, char_t *path, char_t *query)
{
char *command;
command = websGetVar(wp, T("command"), T(""));
if(!command)
return;
if(!strlen(command)){
doSystem("cat /dev/null > %s", SYSTEM_COMMAND_LOG);
}else if(strchr(command, '>') || strchr(command, '<')){
doSystem("cat /dev/null > %s", SYSTEM_COMMAND_LOG);
snprintf(system_command, COMMAND_MAX, "%s", command);
}else{
snprintf(system_command, COMMAND_MAX, "%s 1>%s 2>&1", command, SYSTEM_COMMAND_LOG);
}
if(strlen(system_command))
doSystem(system_command);
// FIXME/TODO, YYHuang 07/04/11
// the path here should be obtained by goahead internal function.
// (is it existed?)
websRedirect(wp, "adm/system_command.asp");
return;
}
int showSystemCommandASP(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
char buf[1024];
fp = fopen(SYSTEM_COMMAND_LOG, "r");
if(!fp){
websWrite(wp, T(""));
return 0;
}
while(fgets(buf, 1024, fp)){
websWrite(wp, T("%s"), buf);
}
fclose(fp);
return 0;
}
static inline char *strip_space(char *str)
{
while( *str == ' ')
str++;
return str;
}
char* getField(char *a_line, char *delim, int count)
{
int i=0;
char *tok;
tok = strtok(a_line, delim);
while(tok){
if(i == count)
break;
i++;
tok = strtok(NULL, delim);
}
if(tok)
return tok;
return NULL;
}
/*
* C version. (ASP version is below)
*/
static long long getIfStatistic(char *interface, int type)
{
int found_flag = 0;
int skip_line = 2;
char buf[1024], *field, *semiColon = NULL;
FILE *fp = fopen(PROC_IF_STATISTIC, "r");
if(!fp){
printf("no proc?\n");
return -1;
}
while(fgets(buf, 1024, fp)){
char *ifname;
if(skip_line != 0){
skip_line--;
continue;
}
if(! (semiColon = strchr(buf, ':')) )
continue;
*semiColon = '\0';
ifname = buf;
ifname = strip_space(ifname);
if(!strcmp(ifname, interface)){
found_flag = 1;
break;
}
}
fclose(fp);
//Added by Andy Yu in 2013/07/16: No Device-Return 0
if (found_flag == 0) {
printf("%s:Device not found\n", interface);
return 0;
}
semiColon++;
switch(type){
case TXBYTE:
if( (field = getField(semiColon, " ", 8)) ){
return strtoll(field, NULL, 10);
}
break;
case TXPACKET:
if( (field = getField(semiColon, " ", 9)) ){
return strtoll(field, NULL, 10);
}
break;
case RXBYTE:
if( (field = getField(semiColon, " ", 0)) ){
return strtoll(field, NULL, 10);
}
break;
case RXPACKET:
if( (field = getField(semiColon, " ", 1)) ){
return strtoll(field, NULL, 10);
}
break;
// Tommy, Add Collisions field, 2009/2/4 09:18
#if 1
case COLLS:
if( (field = getField(semiColon, " ", 13)) ){
return strtoll(field, NULL, 10);
}
break;
#endif
}
return -1;
}
/*
* getIfStatistic() ASP version
*/
int getIfStatisticASP(int eid, webs_t wp, int argc, char_t **argv)
{
int found_flag = 0;
int skip_line = 2;
char *interface, *type, *field, *semiColon = NULL;
char buf[1024], result[32];
FILE *fp = fopen(PROC_IF_STATISTIC, "r");
if(!fp){
websWrite(wp, T("no proc?\n"));
return -1;
}
if(ejArgs(argc, argv, T("%s %s"), &interface, &type) != 2){
websWrite(wp, T("Wrong argument.\n"));
return -1;
}
while(fgets(buf, 1024, fp)){
char *ifname;
if(skip_line != 0){
skip_line--;
continue;
}
if(! (semiColon = strchr(buf, ':')) )
continue;
*semiColon = '\0';
ifname = buf;
ifname = strip_space(ifname);
if(!strcmp(ifname, interface)){
found_flag = 1;
break;
}
}
fclose(fp);
semiColon++;
if(!strcmp(type, T("TXBYTE") )){
if( (field = getField(semiColon, " ", 8)) ){
snprintf(result, 32,"%lld", strtoll(field, NULL, 10));
ejSetResult(eid, result);
}
}else if(!strcmp(type, T("TXPACKET") )){
if( (field = getField(semiColon, " ", 9)) ){
snprintf(result, 32,"%lld", strtoll(field, NULL, 10));
ejSetResult(eid, result);
}
}else if(!strcmp(type, T("RXBYTE") )){
if( (field = getField(semiColon, " ", 0)) ){
snprintf(result, 32,"%lld", strtoll(field, NULL, 10));
ejSetResult(eid, result);
}
}else if(!strcmp(type, T("RXPACKET") )){
if( (field = getField(semiColon, " ", 1)) ){
snprintf(result, 32,"%lld", strtoll(field, NULL, 10));
ejSetResult(eid, result);
}
}else{
websWrite(wp, T("unknown type.") );
return -1;
}
return -1;
}
void GetIfConfigCounter(char *interface, char *whichCounter, long long *reVal)
{
FILE *fp;
unsigned long tmp;
if (!strcmp(whichCounter, "TX packets")){
doSystem("ifconfig %s | grep 'TX packets:' | cut -d ':' -f2 | cut -d ' ' -f1 > /tmp/IfCounter", interface);
}else if (!strcmp(whichCounter, "RX packets")){
doSystem("ifconfig %s | grep 'RX packets:' | cut -d ':' -f2 | cut -d ' ' -f1 > /tmp/IfCounter", interface);
}else if (!strcmp(whichCounter, "collisions")){
doSystem("ifconfig %s | grep 'collisions:' | cut -d ':' -f2 | cut -d ' ' -f1 > /tmp/IfCounter", interface);
}else if (!strcmp(whichCounter, "TX bytes")){
doSystem("ifconfig %s | grep 'TX bytes:' | cut -d ':' -f3 | cut -d ' ' -f1 > /tmp/IfCounter", interface);
}else if (!strcmp(whichCounter, "RX bytes")){
doSystem("ifconfig %s | grep 'RX bytes:' | cut -d ':' -f2 | cut -d ' ' -f1 > /tmp/IfCounter", interface);
}else{
system("ehco 0 > /tmp/IfCounter");
}
fp = fopen("/tmp/IfCounter", "r");
fscanf(fp,"%lu",&tmp);
fclose(fp);
*reVal = tmp;
system("rm -f /tmp/IfCounter");
}
/*----Added by Andy Yu in 2013/11/13: Port Statistics----*/
static long long PortRXBytesPerSec[5];
static long long PortTXBytesPerSec[5];
int GetPortIfBytesPerSecASP(int eid, webs_t wp, int argc, char_t **argv)
{
int i = 0;
int portNum = 0;
char port_device[32] = {0};
long long PortTXBytes0s[5] = {0};
long long PortRXBytes0s[5] = {0};
long long PortTXBytes1s[5] = {0};
long long PortRXBytes1s[5] = {0};
portNum = ezplib_get_rule_num("port_device_rule");
for (i=0; i<portNum; i++) {
ezplib_get_attr_val("port_device_rule", i, "port_device", port_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
PortRXBytes0s[i] = getIfStatistic( port_device, RXBYTE);
PortTXBytes0s[i] = getIfStatistic( port_device, TXBYTE);
}
//Delay 1 second
system("sleep 1");
for (i=0; i<portNum; i++) {
ezplib_get_attr_val("port_device_rule", i, "port_device", port_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
PortRXBytes1s[i] = getIfStatistic( port_device, RXBYTE);
PortTXBytes1s[i] = getIfStatistic( port_device, TXBYTE);
}
for (i=0; i<portNum; i++) {
PortRXBytesPerSec[i] = PortRXBytes1s[i] - PortRXBytes0s[i];
PortTXBytesPerSec[i] = PortTXBytes1s[i] - PortTXBytes0s[i];
}
websWrite(wp, T("OK"));
return 0;
}
static int getStatisticsPortsLinkStatus(char *portid, char *portLink)
{
struct eth_port_status ethport;
memset(ðport, 0, sizeof(struct eth_port_status));
ethport.port = atoi(portid);
if (ethread(ðport) < 0) {
printf("ethread error\n");
strcpy(portLink, "Down");
return 0;
}
if (ethport.link) {
if (ethport.speed == 0) {
strcpy(portLink, "10M");
} else if (ethport.speed == 1) {
strcpy(portLink, "100M");
} else if (ethport.speed == 2) {
strcpy(portLink, "1000M");
}
} else {
strcpy(portLink, "Down");
}
return 0;
}
int getPortsStatistics(int eid, webs_t wp, int argc, char_t **argv)
{
int i = 0;
int portNum = 0;
long long txdata = 0;
long long rxdata = 0;
long long codata = 0;
char portid[32] = {0};
char portdevice[32] = {0};
char portLink[32] = {0};
char portV[128] = {0};
char result[1024] = {0};
portNum = ezplib_get_rule_num("port_device_rule");
for (i = 0; i < portNum; i++) {
memset(portV, 0, sizeof(portV));
memset(portLink, 0, sizeof(portLink));
ezplib_get_attr_val("port_device_rule", i, "portid", portid, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ezplib_get_attr_val("port_device_rule", i, "port_device", portdevice, SHORT_BUF_LEN, EZPLIB_USE_CLI);
getStatisticsPortsLinkStatus(portid, portLink);
if (!strcmp(portLink,"Down")) {
sprintf(portV, "%s;%s;%s;%s;%s;%s", portLink, "--", "--", "--", "--", "--");
gstrncat(result, portV, 1024);
} else {
txdata = getIfStatistic( portdevice, TXPACKET);
rxdata = getIfStatistic( portdevice, RXPACKET);
codata = getIfStatistic( portdevice, COLLS);
sprintf(portV, "%s;%lld;%lld;%lld;%lld;%lld", portLink, txdata, rxdata, codata, PortTXBytesPerSec[i], PortRXBytesPerSec[i]);
gstrncat(result, portV, 1024);
}
if (i != (portNum-1)) {
gstrncat(result, "$", 1024);
}
}
websWrite(wp, T("%s"), result);
return 0;
}
/*-------------------------------------------------*/
/*----Added by Andy Yu in 2013/11/13: WLAN Statistics----*/
static long long WLAN2GRXBytesPerSec[8];
static long long WLAN2GTXBytesPerSec[8];
static long long WLAN2GRXBytesPerSecSta;
static long long WLAN2GTXBytesPerSecSta;
static long long WLAN5GRXBytesPerSec[8];
static long long WLAN5GTXBytesPerSec[8];
static long long WLAN5GRXBytesPerSecSta;
static long long WLAN5GTXBytesPerSecSta;
static int getStatisticsRadioStatus(int radio)
{
int ret2 = 0;
int ret5 = 0;
int radio2_status = 0;
int radio5_status = 0;
char APStr0[32] = {0};
char StaStr0[32] = {0};
char APStr1[32] = {0};
char StaStr1[32] = {0};
if (radio == Radio2G) {
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid0_device", APStr0, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", StaStr0, 32, EZPLIB_USE_CLI);
ret2 = get_radio_status(radio, &radio2_status);
if (ret2 == -1) {
printf("ERROR:Get Radio Staus Failure!\n");
return RadioNoEX;
}
if (strcmp(APStr0,"") && strcmp(StaStr0,"") && (radio2_status == 1)) {
return RadioEX;
} else {
return RadioNoEX;
}
} else if (radio == Radio5G) {
ezplib_get_attr_val("wl_ap_device_rule", 1, "ssid0_device", APStr1, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_sta_device_rule", 1, "sta_device", StaStr1, 32, EZPLIB_USE_CLI);
ret5 = get_radio_status(radio, &radio5_status);
if (ret5 == -1) {
printf("ERROR:Get Radio Staus Failure!\n");
return RadioNoEX;
}
if (strcmp(APStr1,"") && strcmp(StaStr1,"") && (radio5_status == 1)) {
return RadioEX;
} else {
return RadioNoEX;
}
}
return RadioNoEX;
}
int GetWLANIfBytesPerSecASP(int eid, webs_t wp, int argc, char_t **argv)
{
int i = 0;
int ret0 = 0;
int ret1 = 0;
char ModeTmpBuf0[32] = {0};
char ModeTmpBuf1[32] = {0};
char SSID_attr[32] = {0};
char SSID_device[32] = {0};
long long WLAN2TXBytes0s[8] = {0};
long long WLAN2RXBytes0s[8] = {0};
long long WLAN2TXBytes1s[8] = {0};
long long WLAN2RXBytes1s[8] = {0};
long long WLAN2TXBytesSta0s = 0;
long long WLAN2RXBytesSta0s = 0;
long long WLAN2TXBytesSta1s = 0;
long long WLAN2RXBytesSta1s = 0;
long long WLAN5TXBytes0s[8] = {0};
long long WLAN5RXBytes0s[8] = {0};
long long WLAN5TXBytes1s[8] = {0};
long long WLAN5RXBytes1s[8] = {0};
long long WLAN5TXBytesSta0s = 0;
long long WLAN5RXBytesSta0s = 0;
long long WLAN5TXBytesSta1s = 0;
long long WLAN5RXBytesSta1s = 0;
ezplib_get_attr_val("wl_mode_rule", 0, "mode", ModeTmpBuf0, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl1_mode_rule", 0, "mode", ModeTmpBuf1, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ret0 = getStatisticsRadioStatus(Radio2G);
ret1 = getStatisticsRadioStatus(Radio5G);
//2.4G: 0s
if (ret0 == RadioEX) {
if (!strcmp(ModeTmpBuf0,"ap")) {
for (i=0; i<SSIDNum; i++) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 0, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN2RXBytes0s[i] = getIfStatistic( SSID_device, RXBYTE);
WLAN2TXBytes0s[i] = getIfStatistic( SSID_device, TXBYTE);
}
} else if (!strcmp(ModeTmpBuf0,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN2RXBytesSta0s = getIfStatistic( SSID_device, RXBYTE);
WLAN2TXBytesSta0s = getIfStatistic( SSID_device, TXBYTE);
}
}
//5G: 0s
if (ret1 == RadioEX) {
if (!strcmp(ModeTmpBuf1,"ap")) {
for (i=0; i<SSIDNum; i++) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 1, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN5RXBytes0s[i] = getIfStatistic( SSID_device, RXBYTE);
WLAN5TXBytes0s[i] = getIfStatistic( SSID_device, TXBYTE);
}
} else if (!strcmp(ModeTmpBuf1,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 1, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN5RXBytesSta0s = getIfStatistic( SSID_device, RXBYTE);
WLAN5TXBytesSta0s = getIfStatistic( SSID_device, TXBYTE);
}
}
//Delay 1 second
system("sleep 1");
//2.4G: 1s
if (ret0 == RadioEX) {
if (!strcmp(ModeTmpBuf0,"ap")) {
for (i=0; i<SSIDNum; i++) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 0, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN2RXBytes1s[i] = getIfStatistic( SSID_device, RXBYTE);
WLAN2TXBytes1s[i] = getIfStatistic( SSID_device, TXBYTE);
}
} else if (!strcmp(ModeTmpBuf0,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN2RXBytesSta1s = getIfStatistic( SSID_device, RXBYTE);
WLAN2TXBytesSta1s = getIfStatistic( SSID_device, TXBYTE);
}
}
//5G: 1s
if (ret1 == RadioEX) {
if (!strcmp(ModeTmpBuf1,"ap")) {
for (i=0; i<SSIDNum; i++) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 1, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN5RXBytes1s[i] = getIfStatistic( SSID_device, RXBYTE);
WLAN5TXBytes1s[i] = getIfStatistic( SSID_device, TXBYTE);
}
} else if (!strcmp(ModeTmpBuf1,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 1, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
WLAN5RXBytesSta1s = getIfStatistic( SSID_device, RXBYTE);
WLAN5TXBytesSta1s = getIfStatistic( SSID_device, TXBYTE);
}
}
//2.4G: Bytes = 1s - 0s
if (ret0 == RadioEX) {
if (!strcmp(ModeTmpBuf0,"ap")) {
for (i=0; i<SSIDNum; i++) {
WLAN2GRXBytesPerSec[i] = WLAN2RXBytes1s[i] - WLAN2RXBytes0s[i];
WLAN2GTXBytesPerSec[i] = WLAN2TXBytes1s[i] - WLAN2TXBytes0s[i];
}
} else if (!strcmp(ModeTmpBuf0,"client")) {
WLAN2GRXBytesPerSecSta = WLAN2RXBytesSta1s - WLAN2RXBytesSta0s;
WLAN2GTXBytesPerSecSta = WLAN2TXBytesSta1s - WLAN2TXBytesSta0s;
}
}
//5G: Bytes = 1s - 0s
if (ret1 == RadioEX) {
if (!strcmp(ModeTmpBuf1,"ap")) {
for (i=0; i<SSIDNum; i++) {
WLAN5GRXBytesPerSec[i] = WLAN5RXBytes1s[i] - WLAN5RXBytes0s[i];
WLAN5GTXBytesPerSec[i] = WLAN5TXBytes1s[i] - WLAN5TXBytes0s[i];
}
} else if (!strcmp(ModeTmpBuf1,"client")) {
WLAN5GRXBytesPerSecSta = WLAN5RXBytesSta1s - WLAN5RXBytesSta0s;
WLAN5GTXBytesPerSecSta = WLAN5TXBytesSta1s - WLAN5TXBytesSta0s;
}
}
websWrite(wp, T("OK"));
return 0;
}
int getWLANStatistics(int eid, webs_t wp, int argc, char_t **argv)
{
int i = 0;
int ret0 = 0;
int ret1 = 0;
long long txdata = 0;
long long rxdata = 0;
long long codata = 0;
char txStr[32] = {0};
char rxStr[32] = {0};
char coStr[32] = {0};
char txBStr[32] = {0};
char rxBStr[32] = {0};
char ModeTmpBuf0[32] = {0};
char ModeTmpBuf1[32] = {0};
char SSID_attr[32] = {0};
char SSID_device[32] = {0};
char buf[TMP_LEN] = {0};
char reValue[TMP_LEN] = {0};
ezplib_get_attr_val("wl_mode_rule", 0, "mode", ModeTmpBuf0, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl1_mode_rule", 0, "mode", ModeTmpBuf1, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ret0 = getStatisticsRadioStatus(Radio2G);
ret1 = getStatisticsRadioStatus(Radio5G);
if (ret0 == RadioEX) {
if (!strcmp(ModeTmpBuf0,"ap")) {
for (i = 0; i < SSIDNum; i++) {
ezplib_get_attr_val("wl0_ssid_rule", i, "ssid", buf, 33, EZPLIB_USE_CLI);
strcpy(reValue, buf);
char *str;
str=sub_replace(reValue, "&", "&");
strcpy(reValue,str);
free(str);
str=sub_replace(reValue, "\"", """);
strcpy(reValue,str);
free(str);
str=sub_replace(reValue, " ", " ");
strcpy(reValue,str);
free(str);
websWrite(wp, T("<tr ><td width='10%'><center><span class='table_left'>%s</span></center></td>"), reValue);
ezplib_get_attr_val("wl0_basic_rule", i, "enable", buf, 32, EZPLIB_USE_CLI);
if (!strcmp(buf,"1")) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 0, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
txdata = getIfStatistic( SSID_device, TXPACKET);
rxdata = getIfStatistic( SSID_device, RXPACKET);
codata = getIfStatistic( SSID_device, COLLS);
sprintf(txStr, "%lld", txdata);
sprintf(rxStr, "%lld", rxdata);
sprintf(coStr, "%lld", codata);
sprintf(txBStr, "%lld", WLAN2GTXBytesPerSec[i]);
sprintf(rxBStr, "%lld", WLAN2GRXBytesPerSec[i]);
} else {
sprintf(txStr, "%s", "--");
sprintf(rxStr, "%s", "--");
sprintf(coStr, "%s", "--");
sprintf(txBStr, "%s", "--");
sprintf(rxBStr, "%s", "--");
}
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), rxStr);
websWrite(wp, T("<td width='14%'><center><span class='table_font'>%s</span></center></td>"), coStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txBStr);
websWrite(wp, T("<td width='19%'><center><span class='table_right'>%s</span></center></td></tr>"), rxBStr);
}
}else if (!strcmp(ModeTmpBuf0,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
txdata = getIfStatistic( SSID_device, TXPACKET);
rxdata = getIfStatistic( SSID_device, RXPACKET);
codata = getIfStatistic( SSID_device, COLLS);
sprintf(txStr, "%lld", txdata);
sprintf(rxStr, "%lld", rxdata);
sprintf(coStr, "%lld", codata);
sprintf(txBStr, "%lld", WLAN2GTXBytesPerSecSta);
sprintf(rxBStr, "%lld", WLAN2GRXBytesPerSecSta);
websWrite(wp, T("<tr ><td width='10%'><center><span class='table_left'>%s</span></center></td>"), "WLAN2.4G");
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), rxStr);
websWrite(wp, T("<td width='14%'><center><span class='table_font'>%s</span></center></td>"), coStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txBStr);
websWrite(wp, T("<td width='19%'><center><span class='table_right'>%s</span></center></td></tr>"), rxBStr);
}
}
if (ret1 == RadioEX) {
if (!strcmp(ModeTmpBuf1,"ap")) {
for (i = 0; i < SSIDNum; i++) {
ezplib_get_attr_val("wl1_ssid_rule", i, "ssid", buf, 33, EZPLIB_USE_CLI);
strcpy(reValue, buf);
char *str;
str=sub_replace(reValue, "&", "&");
strcpy(reValue,str);
free(str);
str=sub_replace(reValue, "\"", """);
strcpy(reValue,str);
free(str);
str=sub_replace(reValue, " ", " ");
strcpy(reValue,str);
free(str);
websWrite(wp, T("<tr ><td width='10%'><center><span class='table_left'>%s</span></center></td>"), reValue);
ezplib_get_attr_val("wl1_basic_rule", i, "enable", buf, 32, EZPLIB_USE_CLI);
if (!strcmp(buf,"1")) {
sprintf(SSID_attr, "ssid%d_device", i);
ezplib_get_attr_val("wl_ap_device_rule", 1, SSID_attr, SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
txdata = getIfStatistic( SSID_device, TXPACKET);
rxdata = getIfStatistic( SSID_device, RXPACKET);
codata = getIfStatistic( SSID_device, COLLS);
sprintf(txStr, "%lld", txdata);
sprintf(rxStr, "%lld", rxdata);
sprintf(coStr, "%lld", codata);
sprintf(txBStr, "%lld", WLAN5GTXBytesPerSec[i]);
sprintf(rxBStr, "%lld", WLAN5GRXBytesPerSec[i]);
} else {
sprintf(txStr, "%s", "--");
sprintf(rxStr, "%s", "--");
sprintf(coStr, "%s", "--");
sprintf(txBStr, "%s", "--");
sprintf(rxBStr, "%s", "--");
}
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), rxStr);
websWrite(wp, T("<td width='14%'><center><span class='table_font'>%s</span></center></td>"), coStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txBStr);
websWrite(wp, T("<td width='19%'><center><span class='table_right'>%s</span></center></td></tr>"), rxBStr);
}
}else if (!strcmp(ModeTmpBuf1,"client")) {
ezplib_get_attr_val("wl_sta_device_rule", 1, "sta_device", SSID_device, SHORT_BUF_LEN, EZPLIB_USE_CLI);
txdata = getIfStatistic( SSID_device, TXPACKET);
rxdata = getIfStatistic( SSID_device, RXPACKET);
codata = getIfStatistic( SSID_device, COLLS);
sprintf(txStr, "%lld", txdata);
sprintf(rxStr, "%lld", rxdata);
sprintf(coStr, "%lld", codata);
sprintf(txBStr, "%lld", WLAN5GTXBytesPerSecSta);
sprintf(rxBStr, "%lld", WLAN5GRXBytesPerSecSta);
websWrite(wp, T("<tr ><td width='10%'><center><span class='table_left'>%s</span></center></td>"), "WLAN5G");
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), rxStr);
websWrite(wp, T("<td width='14%'><center><span class='table_font'>%s</span></center></td>"), coStr);
websWrite(wp, T("<td width='19%'><center><span class='table_font'>%s</span></center></td>"), txBStr);
websWrite(wp, T("<td width='19%'><center><span class='table_right'>%s</span></center></td></tr>"), rxBStr);
}
}
return 0;
}
/*---------------------------------------------------*/
// Tommy , Add WLAN Statistics , 2009/2/4 09:38
/*----Chged by Andy Yu in 2013/11/15: WLAN Statistics----*/
#if 0
int getWLANRxByteASP(int eid, webs_t wp, int argc, char_t **argv)
{
#if 1
char_t buf[256];
snprintf(buf, 256, "%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld", WLANRXBytesPerSec, WLAN2RXBytesPerSec,
WLAN3RXBytesPerSec, WLAN4RXBytesPerSec, WLAN5RXBytesPerSec, WLAN6RXBytesPerSec, WLAN7RXBytesPerSec, WLAN8RXBytesPerSec, APCLITXBytesPerSec);
websWrite(wp, T("%s"), buf);
return 0;
#else
FILE *fwlanlink;
int updays, uphours, upminutes, upseconds;
unsigned long wlanuptime, disptime;
//struct sysinfo info;
char TempBuf[32];
unsigned long wlancurrtime;
ezplib_get_attr_val("wlan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
wlanuptime = atol(TempBuf);
system("sed 's/\\..*$//g' /proc/uptime > /tmp/wlancurrtime");
fwlanlink = fopen("/tmp/wlancurrtime", "r");
fscanf(fwlanlink,"%lu",&wlancurrtime);
fclose(fwlanlink);
system("rm -f /tmp/wlancurrtime");
disptime = wlancurrtime - wlanuptime;
char_t buf[32];
long long data = getIfStatistic( "ra0", RXBYTE);
snprintf(buf, 32, "%lld", data/disptime);
websWrite(wp, T("%s"), buf);
return 0;
#endif
}
int getWLAN1RxByteASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
snprintf(buf, 32, "%lld", WLAN1RXBytesPerSec);
websWrite(wp, T("%s"), buf);
return 0;
}
int getWLANRxPacketASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[256];
char_t ssid0[32];
char_t ssid1[32];
char_t ssid2[32];
char_t ssid3[32];
char_t ssid4[32];
char_t ssid5[32];
char_t ssid6[32];
char_t ssid7[32];
char_t station[32];
//AP Mode: SSID_device
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid0_device", ssid0, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid1_device", ssid1, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid2_device", ssid2, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid3_device", ssid3, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid4_device", ssid4, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid5_device", ssid5, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid6_device", ssid6, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid7_device", ssid7, 32, EZPLIB_USE_CLI);
//Station Mode: sta_device
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", station, 32, EZPLIB_USE_CLI);
long long data = getIfStatistic( ssid0, RXPACKET);
long long data1 = getIfStatistic( ssid1, RXPACKET);
long long data2 = getIfStatistic( ssid2, RXPACKET);
long long data3 = getIfStatistic( ssid3, RXPACKET);
long long data4 = getIfStatistic( ssid4, RXPACKET);
long long data5 = getIfStatistic( ssid5, RXPACKET);
long long data6 = getIfStatistic( ssid6, RXPACKET);
long long data7 = getIfStatistic( ssid7, RXPACKET);
long long apcli_data = getIfStatistic( station, RXPACKET);
snprintf(buf, 256, "%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld", data, data1, data2, data3, data4, data5, data6, data7, apcli_data);
websWrite(wp, T("%s"), buf);
return 0;
}
int getWLAN1RxPacketASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
long long data = getIfStatistic( "ra0", RXPACKET);
snprintf(buf, 32, "%lld", data);
websWrite(wp, T("%s"), buf);
return 0;
}
int getWLANTxByteASP(int eid, webs_t wp, int argc, char_t **argv)
{
#if 1
char_t buf[256];
snprintf(buf, 256, "%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld", WLANTXBytesPerSec, WLAN2TXBytesPerSec,
WLAN3TXBytesPerSec, WLAN4TXBytesPerSec, WLAN5TXBytesPerSec, WLAN6TXBytesPerSec, WLAN7TXBytesPerSec, WLAN8TXBytesPerSec, APCLITXBytesPerSec);
websWrite(wp, T("%s"), buf);
return 0;
#else
FILE *fwlanlink;
int updays, uphours, upminutes, upseconds;
unsigned long wlanuptime, disptime;
//struct sysinfo info;
char TempBuf[32];
unsigned long wlancurrtime;
ezplib_get_attr_val("wlan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
wlanuptime = atol(TempBuf);
system("sed 's/\\..*$//g' /proc/uptime > /tmp/wlancurrtime");
fwlanlink = fopen("/tmp/wlancurrtime", "r");
fscanf(fwlanlink,"%lu",&wlancurrtime);
fclose(fwlanlink);
system("rm -f /tmp/wlancurrtime");
disptime = wlancurrtime - wlanuptime;
char_t buf[32];
long long data = getIfStatistic( "ra0", TXBYTE);
snprintf(buf, 32, "%lld", data/disptime);
websWrite(wp, T("%s"), buf);
return 0;
#endif
}
int getWLAN1TxByteASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
snprintf(buf, 32, "%lld", WLAN1TXBytesPerSec);
websWrite(wp, T("%s"), buf);
return 0;
}
int getWLANTxPacketASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[256];
char_t ssid0[32];
char_t ssid1[32];
char_t ssid2[32];
char_t ssid3[32];
char_t ssid4[32];
char_t ssid5[32];
char_t ssid6[32];
char_t ssid7[32];
char_t station[32];
//AP Mode: SSID_device
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid0_device", ssid0, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid1_device", ssid1, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid2_device", ssid2, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid3_device", ssid3, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid4_device", ssid4, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid5_device", ssid5, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid6_device", ssid6, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid7_device", ssid7, 32, EZPLIB_USE_CLI);
//Station Mode: sta_device
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", station, 32, EZPLIB_USE_CLI);
long long data = getIfStatistic( ssid0, TXPACKET);
long long data1 = getIfStatistic( ssid1, TXPACKET);
long long data2 = getIfStatistic( ssid2, TXPACKET);
long long data3 = getIfStatistic( ssid3, TXPACKET);
long long data4 = getIfStatistic( ssid4, TXPACKET);
long long data5 = getIfStatistic( ssid5, TXPACKET);
long long data6 = getIfStatistic( ssid6, TXPACKET);
long long data7 = getIfStatistic( ssid7, TXPACKET);
long long apcli_data = getIfStatistic( station, TXPACKET);
snprintf(buf, 256, "%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld", data, data1, data2, data3, data4, data5, data6, data7, apcli_data);
websWrite(wp, T("%s"),buf);
return 0;
}
int getWLAN1TxPacketASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
long long data = getIfStatistic( "ra0", TXPACKET);
snprintf(buf, 32, "%lld", data);
websWrite(wp, T("%s"),buf);
return 0;
}
int getWLANSSID(int eid, webs_t wp, int argc, char_t **argv)
{
int ssid_num, i;
char buf[64], tmp[64];
char ssid_name[512];
memset(tmp,0,sizeof(tmp));
memset(buf,0,sizeof(buf));
memset(ssid_name,0,sizeof(ssid_name));
ssid_num = ezplib_get_rule_num("wl0_ssid_rule");
if (ssid_num == 0) {
printf("Error: No SSID\n");
websWrite(wp, T(""));
return -1;
}
for (i = 0; i < ssid_num; i++) {
ezplib_get_attr_val("wl0_ssid_rule", i, "ssid", buf, 33, EZPLIB_USE_CLI);
printf("buf = %s\n", buf);
if (i==0) {
strcat(ssid_name, buf);
} else {
sprintf(tmp,";%s", buf);
strcat(ssid_name, tmp);
}
printf("buf = %s==ssid_name = %s\n", buf, ssid_name);
}
//sprintf(tmp,";%s", "Total");
//strcat(ssid_name, tmp);
//printf("ssid_name = %s\n", ssid_name);
websWrite(wp, T("%s"),ssid_name);
return 0;
}
//Added by Andy Yu in 2013/09/30: Wireless Statistics
int getWLANSSIDEnable(int eid, webs_t wp, int argc, char_t **argv)
{
int ssid_num, i;
char buf[64], tmp[64];
char ssid_enable[512];
memset(tmp,0,sizeof(tmp));
memset(buf,0,sizeof(buf));
memset(ssid_enable,0,sizeof(ssid_enable));
ssid_num = ezplib_get_rule_num("wl0_ssid_rule");
if (ssid_num == 0) {
printf("Error: No SSID\n");
websWrite(wp, T(""));
return -1;
}
for (i = 0; i < ssid_num; i++) {
ezplib_get_attr_val("wl0_basic_rule", i, "enable", buf, 32, EZPLIB_USE_CLI);
if (i==0) {
strcat(ssid_enable, buf);
} else {
sprintf(tmp,";%s", buf);
strcat(ssid_enable, tmp);
}
}
ezplib_get_attr_val("wl0_apcli_rule", 0, "enable", buf, 32, EZPLIB_USE_CLI);
sprintf(tmp,";%s", buf);
strcat(ssid_enable, tmp);
websWrite(wp, T("%s"),ssid_enable);
return 0;
}
#endif
#if 0
int getWANCollsASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
char value[32];
ezplib_get_attr_val("port_device_rule", 0, "port_device", value, 32, EZPLIB_USE_CLI);
long long data = getIfStatistic( value, COLLS);
snprintf(buf, 32, "%lld", data);
websWrite(wp, T("%s"),buf);
return 0;
}
int getLANCollsASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32] = {0};
char TempBuf[32] = {0};
ezplib_get_attr_val("board_model_rule", 0, "bd_model", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "WP838") != 0) {
ezplib_get_attr_val("port_device_rule", 1, "port_device", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
} else {
ezplib_get_attr_val("port_device_rule", 0, "port_device", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
}
long long data = getIfStatistic(TempBuf, COLLS);
snprintf(buf, 32, "%lld", data);
websWrite(wp, T("%s"),buf);
return 0;
}
int getWLANCollsASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[256];
char_t ssid0[32];
char_t ssid1[32];
char_t ssid2[32];
char_t ssid3[32];
char_t ssid4[32];
char_t ssid5[32];
char_t ssid6[32];
char_t ssid7[32];
char_t station[32];
//AP Mode: SSID_device
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid0_device", ssid0, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid1_device", ssid1, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid2_device", ssid2, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid3_device", ssid3, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid4_device", ssid4, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid5_device", ssid5, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid6_device", ssid6, 32, EZPLIB_USE_CLI);
ezplib_get_attr_val("wl_ap_device_rule", 0, "ssid7_device", ssid7, 32, EZPLIB_USE_CLI);
//Station Mode: sta_device
ezplib_get_attr_val("wl_sta_device_rule", 0, "sta_device", station, 32, EZPLIB_USE_CLI);
long long data = getIfStatistic( ssid0, COLLS);
long long data1 = getIfStatistic( ssid1, COLLS);
long long data2 = getIfStatistic( ssid2, COLLS);
long long data3 = getIfStatistic( ssid3, COLLS);
long long data4 = getIfStatistic( ssid4, COLLS);
long long data5 = getIfStatistic( ssid5, COLLS);
long long data6 = getIfStatistic( ssid6, COLLS);
long long data7 = getIfStatistic( ssid7, COLLS);
long long apcli_data = getIfStatistic( station, COLLS);
snprintf(buf, 256, "%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld;%lld", data, data1, data2, data3, data4, data5, data6, data7, apcli_data);
websWrite(wp, T("%s"),buf);
return 0;
}
int getWLAN1CollsASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
long long data = getIfStatistic( "ra0", COLLS);
snprintf(buf, 32, "%lld", data);
websWrite(wp, T("%s"),buf);
return 0;
}
#endif
int getPortLinkStatus(port_num)
{
int port, rc;
FILE *fp;
char buf[1024];
port = port_num;
char *pos;
int link = 0;
FILE *proc_file = fopen("/proc/rt2880/gmac", "w");
if (!proc_file){
printf("indicate error: Cannot open /proc/rt2880/gmac file !!!\n");
}
fprintf(proc_file, "%d", port);
fclose(proc_file);
if ((fp = popen("ethtool eth2", "r")) == NULL){
printf("indicate error: Cannot do <ethtool eth2>!!!\n");
}
rc = fread(buf, 1, 1024, fp);
pclose(fp);
if(rc == -1){
printf("indicate error: Cannot read the result of <ethtool eth2> !!!\n");
}else{
// get Link status
if((pos = strstr(buf, "Link detected: ")) != NULL){
pos += strlen("Link detected: ");
if(*pos == 'y')
link = 1;
}
if (link == 1){
// get speed
if((pos = strstr(buf, "Speed: ")) != NULL){
pos += strlen("Speed: ");
if(*pos == '1' && *(pos+1) == '0' && *(pos+2) == 'M')
link = 10;
#if 0
if(*pos == '1' && *(pos+1) == '0' && *(pos+2) == '0' && *(pos+3) == '0' && *(pos+4) == 'M')
#else
if(*pos == '1' && *(pos+1) == '0' && *(pos+2) == '0' && *(pos+3) == 'M')
#endif
link = 100;
}
}
}
return link;
}
int getWANPortLinkStatus(void)
{
// Need to get 2 times, because the first time always fail to get port status
getPortLinkStatus(4); // Don't take away.
return getPortLinkStatus(4); // WAN port = port 4
}
int getLANLinkStatus(int eid, webs_t wp, int argc, char_t **argv)
{
/*-----Chged by Andy Yu in 2013/11/05: Get LAN Ports Info WP688 and WP838-----*/
char TempBuf[32] = {0};
char lan0_port[32] = {0};
struct eth_port_status ethport;
memset(ðport, 0, sizeof(struct eth_port_status));
ezplib_get_attr_val("board_model_rule", 0, "bd_model", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "WP838") != 0) {
ezplib_get_attr_val("port_device_rule", 1, "portid", lan0_port, SHORT_BUF_LEN, EZPLIB_USE_CLI);
} else {
ezplib_get_attr_val("port_device_rule", 0, "portid", lan0_port, SHORT_BUF_LEN, EZPLIB_USE_CLI);
}
ethport.port = atoi(lan0_port);
if (ethread(ðport) < 0) {
printf("read error\n");
websWrite(wp, T("Down"));
return 0;
}
if (ethport.link) {
if (ethport.speed == 0) {
websWrite(wp, T("10M"));
return 0;
} else if (ethport.speed == 1) {
websWrite(wp, T("100M"));
return 0;
} else if (ethport.speed == 2) {
websWrite(wp, T("1000M"));
return 0;
}
} else {
websWrite(wp, T("Down"));
return 0;
}
return 0;
}
int getWANLinkStatus(int eid, webs_t wp, int argc, char_t **argv)
{
/*----Chged by Andy Yu in 2013/11/05: Get WAN Ports Info WP688 and WP838----*/
char wan0_port[32] = {0};
struct eth_port_status ethport;
memset(ðport, 0, sizeof(struct eth_port_status));
ezplib_get_attr_val("port_device_rule", 0, "portid", wan0_port, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ethport.port = atoi(wan0_port);
if (ethread(ðport) < 0) {
printf("read error\n");
websWrite(wp, T("Down"));
return 0;
}
if (ethport.link) {
if (ethport.speed == 0) {
websWrite(wp, T("10M"));
return 0;
} else if (ethport.speed == 1) {
websWrite(wp, T("100M"));
return 0;
} else if (ethport.speed == 2) {
websWrite(wp, T("1000M"));
return 0;
}
} else {
websWrite(wp, T("Down"));
return 0;
}
return 0;
}
/* Added by Andy Yu in 2013/07/11: WLAN Tx/Rx Rate --> Rate*/
int getWLANLinkRate(int eid, webs_t wp, int argc, char_t **argv)
{
int ret = 0;
int rate = 0;
ret = get_wlan_rate(RADIO_2G, &rate);
if (ret == T_FAILURE) {
printf("ERROR: Get 802.11 Mode failure\n");
websWrite(wp, T(""));
return -1;
}
if (rate == 0) {
websWrite(wp, T(""));
} else {
websWrite(wp, T("%dM"), rate);
}
return 0;
}
int getWLANLinkStatus(int eid, webs_t wp, int argc, char_t **argv)
{
#if 0
char TempBuf[32];
char ModeTmpBuf[32];
/*ezplib_get_attr_val("wl_mode_rule", 0, "mode", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "wisp")){
websWrite(wp, T("300M"));
return 0;
}*/
ezplib_get_attr_val("wl_mode_rule", 0, "mode", ModeTmpBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(ModeTmpBuf, "ap")){
ezplib_get_attr_val("wl_ap_basic_rule", 0, "enable", TempBuf, 32, EZPLIB_USE_CLI);
} else {
ezplib_get_attr_val("wl_basic_rule", 0, "enable", TempBuf, 32, EZPLIB_USE_CLI);
}
if (!strcmp(TempBuf, "1")){
websWrite(wp, T("300M"));
}else{
websWrite(wp, T("Down"));
}
return 0;
#endif
int ret = 0;
int radio_status = 0;
ret = get_radio_status(RADIO_2G, &radio_status);
if (ret == -1) {
printf("ERROR:Get Radio Staus Failure!\n");
websWrite(wp, T("OFF"));
return 0;
}
if (radio_status == 1) {
websWrite(wp, T("ON"));
} else {
websWrite(wp, T("OFF"));
}
return 0;
}
//Added by Andy Yu in 2013/07/17: Main_SSID
int getWLANMainSSID(int eid, webs_t wp, int argc, char_t **argv)
{
int ret;
char ssid[256];
char *essid;
ret = 0;
memset(ssid, 0, sizeof(ssid));
ret = get_ssid(RADIO_2G, WLAN_MODE_AP, 0, ssid);
//ret = nvram_get_ap_ssid(RADIO_2G, 0, ssid); //specifal characters
if (ret == T_FAILURE) {
websWrite(wp, T(""));
} else {
essid = get_translate_javascript_char(0,ssid);
strcpy(ssid, essid);
websWrite(wp, T("%s"), ssid);
}
return 0;
}
//Added by Andy Yu in 2013/11/1: 5G Main_SSID
int getWLAN5GMainSSID(int eid, webs_t wp, int argc, char_t **argv)
{
int ret;
char ssid[256];
char *essid;
ret = 0;
memset(ssid, 0, sizeof(ssid));
ret = get_ssid(RADIO_5G, WLAN_MODE_AP, 0, ssid);
//ret = nvram_get_ap_ssid(RADIO_5G, 0, ssid);
if (ret == T_FAILURE) {
websWrite(wp, T(""));
} else {
essid = get_translate_javascript_char(0,ssid);
strcpy(ssid, essid);
websWrite(wp, T("%s"), ssid);
}
return 0;
}
//Added by Andy Yu in 2013/07/17: ChannelSelectWay
int getWLANChannelSelectWay(int eid, webs_t wp, int argc, char_t **argv)
{
int ret = 0;
int mode = 0;
ret = get_channel_select_mode(RADIO_2G, &mode);
//ret = nvram_get_ap_channel_select_mode(RADIO_2G, &mode);
if (ret == T_FAILURE) {
printf("ERROR: Get Channel Select Way failure\n");
websWrite(wp, T(""));
return -1;
} else {
websWrite(wp, T("%d"), mode);
}
return 0;
}
//Added by Andy Yu in 2013/11/1: ChannelSelectWay5G
int getWLAN5GChannelSelectWay(int eid, webs_t wp, int argc, char_t **argv)
{
int ret = 0;
int mode = 0;
ret = get_channel_select_mode(RADIO_5G, &mode);
//ret = nvram_get_ap_channel_select_mode(RADIO_5G, &mode);
if (ret == T_FAILURE) {
printf("ERROR: Get Channel Select Way failure\n");
websWrite(wp, T(""));
return -1;
} else {
websWrite(wp, T("%d"), mode);
}
websWrite(wp, T(""));
return 0;
}
//Added by Andy Yu in 2013/07/17: Wireless Mode
int getWLANWirelessMode(int eid, webs_t wp, int argc, char_t **argv)
{
int ret = 0;
int mode = 0;
//ret = get_wirelessmode(RADIO_2G, &mode);
ret = get_wirelessmode(RADIO_2G, &mode);
if (ret == T_FAILURE) {
printf("ERROR: Get 802.11 Mode failure\n");
//websWrite(wp, T("9")); //bgn
websWrite(wp, T("8")); //11an
return 0;
} else {
websWrite(wp, T("%d"), mode);
}
return 0;
}
/*----Added by Andy Yu in 2013/11/4: 5G Wireless Mode----*/
int getWLAN5GWirelessMode(int eid, webs_t wp, int argc, char_t **argv)
{
int ret = 0;
int mode = 0;
//ret = get_wirelessmode(RADIO_5G, &mode);
ret = get_wirelessmode(RADIO_5G, &mode);
if (ret == T_FAILURE) {
printf("ERROR: Get 802.11 Mode failure\n");
websWrite(wp, T("8"));
return 0;
} else {
websWrite(wp, T("%d"), mode);
}
return 0;
}
int getWLAN5GLinkRate(int eid, webs_t wp, int argc, char_t **argv)
{
char TempBuf[32];
FILE *fp = NULL;
//system("iwconfig ra0 | grep 'Rate' | sed 's/^.*Rate\=//g' | sed 's/\ .*$//g' > /tmp/link_rate");
system("/sbin/ezp-wps-set 1 1 0 0");
if (NULL == (fp = fopen("/tmp/link_rate", "r")))
{
websWrite(wp, T("540M"));
return 0;
}
fscanf(fp, "%s", TempBuf);
fclose(fp);
system("rm -f /tmp/link_rate");
if (strlen(TempBuf)>0)
{
websWrite(wp, T("%sM"), TempBuf);
}else{
websWrite(wp, T("540M"));
}
return 0;
}
/*+++++Added by Andy Yu in 2013/11/4: 5G Link Status+++++*/
int getWLAN5GLinkStatus(int eid, webs_t wp, int argc, char_t **argv)
{
#if 0
char TempBuf[32];
/*ezplib_get_attr_val("wl1_mode_rule", 0, "mode", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "wisp")){
websWrite(wp, T("450M"));
return 0;
}*/
ezplib_get_attr_val("wl5g_basic_rule", 0, "enable", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "1")){
websWrite(wp, T("450M"));
}else{
websWrite(wp, T("Down"));
}
return 0;
#endif
int ret = 0;
int radio_status = 0;
ret = get_radio_status(RADIO_5G, &radio_status);
if (ret == -1) {
printf("ERROR:Get Radio Staus Failure!\n");
websWrite(wp, T("OFF"));
return 0;
}
if (radio_status == 1) {
websWrite(wp, T("ON"));
} else {
websWrite(wp, T("OFF"));
}
return 0;
}
int getWANUpTime(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fwanlink;
int updays, uphours, upminutes, upseconds;
unsigned long wanuptime, disptime;
//struct sysinfo info;
char TempBuf[32];
unsigned long wancurrtime;
ezplib_get_attr_val("wan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
wanuptime = atol(TempBuf);
system("sed 's/\\..*$//g' /proc/uptime > /tmp/wancurrtime");
fwanlink = fopen("/tmp/wancurrtime", "r");
fscanf(fwanlink,"%lu",&wancurrtime);
fclose(fwanlink);
system("rm -f /tmp/wancurrtime");
disptime = wancurrtime - wanuptime;
updays = (int) disptime / (60*60*24);
upminutes = (int) disptime / 60;
uphours = (upminutes / 60) % 24;
upminutes %= 60;
upseconds = ((int) disptime)%60;
if (updays){
return websWrite(wp, T("%d day%s, %s%d:%s%d:%s%d") ,
updays, (updays != 1) ? "s" : "",
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}else{
return websWrite(wp, T("%s%d:%s%d:%s%d") ,
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}
}
int getLANUpTime(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *flanlink;
int updays, uphours, upminutes, upseconds;
unsigned long lanuptime, disptime;
//struct sysinfo info;
char TempBuf[32];
unsigned long lancurrtime;
ezplib_get_attr_val("lan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
lanuptime = atol(TempBuf);
system("sed 's/\\..*$//g' /proc/uptime > /tmp/lancurrtime");
flanlink = fopen("/tmp/lancurrtime", "r");
fscanf(flanlink,"%lu",&lancurrtime);
fclose(flanlink);
system("rm -f /tmp/lancurrtime");
disptime = lancurrtime - lanuptime;
updays = (int) disptime / (60*60*24);
upminutes = (int) disptime / 60;
uphours = (upminutes / 60) % 24;
upminutes %= 60;
upseconds = ((int) disptime)%60;
if (updays){
return websWrite(wp, T("%d day%s, %s%d:%s%d:%s%d") ,
updays, (updays != 1) ? "s" : "",
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}else{
return websWrite(wp, T("%s%d:%s%d:%s%d") ,
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}
}
int getWLANUpTime(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fwlanlink;
int updays, uphours, upminutes, upseconds;
unsigned long wlanuptime, disptime;
//struct sysinfo info;
char TempBuf[32];
unsigned long wlancurrtime;
ezplib_get_attr_val("wlan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
wlanuptime = atol(TempBuf);
system("sed 's/\\..*$//g' /proc/uptime > /tmp/wlancurrtime");
fwlanlink = fopen("/tmp/wlancurrtime", "r");
fscanf(fwlanlink,"%lu",&wlancurrtime);
fclose(fwlanlink);
system("rm -f /tmp/wlancurrtime");
disptime = wlancurrtime - wlanuptime;
updays = (int) disptime / (60*60*24);
upminutes = (int) disptime / 60;
uphours = (upminutes / 60) % 24;
upminutes %= 60;
upseconds = ((int) disptime)%60;
if (updays){
return websWrite(wp, T("%d day%s, %s%d:%s%d:%s%d") ,
updays, (updays != 1) ? "s" : "",
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}else{
return websWrite(wp, T("%s%d:%s%d:%s%d") ,
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}
}
/*
* This ASP function is for javascript usage, ex:
*
* <script type="text/javascript">
* var a = new Array();
* a = [<% getAllNICStatisticASP(); %>]; //ex: a = ["lo","10","1000", "20", "2000","eth2"];
* document.write(a)
* </script>
*
* Javascript could get info with getAllNICStatisticASP().
*
* We dont produce table-related tag in this ASP function .It's
* more extensive since ASP just handle data and Javascript present them,
* although the data form is only for Javascript now.
*
* TODO: a lot, there are many ASP functions binding with table-relted tag...
*/
int getAllNICStatisticASP(int eid, webs_t wp, int argc, char_t **argv)
{
char result[1024];
char buf[1024];
int rc = 0, pos = 0, skip_line = 2;
int first_time_flag = 1;
FILE *fp = fopen(PROC_IF_STATISTIC, "r");
if(!fp){
printf("no proc?\n");
return -1;
}
while(fgets(buf, 1024, fp)){
char *ifname, *semiColon;
if(skip_line != 0){
skip_line--;
continue;
}
if(! (semiColon = strchr(buf, ':')) )
continue;
*semiColon = '\0';
ifname = buf;
ifname = strip_space(ifname);
if(first_time_flag){
pos = snprintf(result+rc, 1024-rc, "\"%s\"", ifname);
rc += pos;
first_time_flag = 0;
}else{
pos = snprintf(result+rc, 1024-rc, ",\"%s\"", ifname);
rc += pos;
}
pos = snprintf(result+rc, 1024-rc, ",\"%lld\"", getIfStatistic(ifname, RXPACKET));
rc += pos;
pos = snprintf(result+rc, 1024-rc, ",\"%lld\"", getIfStatistic(ifname, RXBYTE));
rc += pos;
pos = snprintf(result+rc, 1024-rc, ",\"%lld\"", getIfStatistic(ifname, TXPACKET));
rc += pos;
pos = snprintf(result+rc, 1024-rc, ",\"%lld\"", getIfStatistic(ifname, TXBYTE));
rc += pos;
}
fclose(fp);
websWrite(wp, T("%s"), result);
return 0;
}
int getMemTotalASP(int eid, webs_t wp, int argc, char_t **argv)
{
char buf[1024], *semiColon, *key, *value;
FILE *fp = fopen(PROC_MEM_STATISTIC, "r");
if(!fp){
websWrite(wp, T("no proc?\n"));
return -1;
}
while(fgets(buf, 1024, fp)){
if(! (semiColon = strchr(buf, ':')) )
continue;
*semiColon = '\0';
key = buf;
value = semiColon + 1;
if(!strcmp(key, "MemTotal")){
value = strip_space(value);
websWrite(wp, T("%s"), value);
fclose(fp);
return 0;
}
}
websWrite(wp, T(""));
fclose(fp);
return -1;
}
/*static int getCurrentTimeASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t hour[2], min[2], sec[2];
int num;
FILE *fp = popen("date +%H", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(hour, 3, fp);
pclose(fp);
nvram_bufset(RT2860_NVRAM, "syshour", hour);
FILE *fp_1 = popen("date +%M", "r");
if(!fp_1){
websWrite(wp, T("none"));
return 0;
}
fgets(min, 3, fp_1);
pclose(fp_1);
nvram_bufset(RT2860_NVRAM, "sysmin", min);
FILE *fp_2 = popen("date +%S", "r");
if(!fp_2){
websWrite(wp, T("none"));
return 0;
}
fgets(sec, 3, fp_2);
pclose(fp_2);
nvram_bufset(RT2860_NVRAM, "syssec", sec);
//return websWrite(wp, T("%s"), buf);
return 0;
}
*/
//gordon add for CurrentDate 20081219//last modified 20090121
static int getCurrentYear(int eid, webs_t wp, int argc, char_t **argv)
{
char_t year[4];
FILE *fp = popen("date +%Y", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(year, 5, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",year);
websWrite(wp, T("%s"), year);
return 0;
}
static int getCurrentMon(int eid, webs_t wp, int argc, char_t **argv)
{
char_t mon[2];
FILE *fp = popen("date +%m", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(mon, 3, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",mon);
websWrite(wp, T("%s"), mon);
return 0;
}
static int getCurrentDay(int eid, webs_t wp, int argc, char_t **argv)
{
char_t day[2];
FILE *fp = popen("date +%d", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(day, 3, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",day);
websWrite(wp, T("%s"), day);
return 0;
}
static int getCurrentHour(int eid, webs_t wp, int argc, char_t **argv)
{
char_t hour[2];
FILE *fp = popen("date +%H", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(hour, 3, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",hour);
websWrite(wp, T("%s"), hour);
return 0;
}
static int getCurrentMin(int eid, webs_t wp, int argc, char_t **argv)
{
char_t min[2];
FILE *fp = popen("date +%M", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(min, 3, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",min);
websWrite(wp, T("%s"), min);
return 0;
}
static int getCurrentSec(int eid, webs_t wp, int argc, char_t **argv)
{
char_t sec[2];
FILE *fp = popen("date +%S", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(sec, 3, fp);
pclose(fp);
//printf("run!!!!!!!!!!%s\n",sec);
websWrite(wp, T("%s"), sec);
return 0;
}
/*static int getCurrentDateASP(int eid, webs_t wp, int argc, char_t **argv)
{
char_t year[4], month[2], date[2];
int num;
FILE *fp = popen("date +%Y", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(year, 5, fp);
pclose(fp);
nvram_bufset(RT2860_NVRAM, "sysyear", year);
FILE *fp_1 = popen("date +%m", "r");
if(!fp_1){
websWrite(wp, T("none"));
return 0;
}
fgets(month, 3, fp_1);
pclose(fp_1);
nvram_bufset(RT2860_NVRAM, "sysmonth", month);
FILE *fp_2 = popen("date +%d", "r");
if(!fp_2){
websWrite(wp, T("none"));
return 0;
}
fgets(date, 3, fp_2);
pclose(fp_2);
nvram_bufset(RT2860_NVRAM, "sysdate", date);
//return websWrite(wp, T("%s"), buf);
return 0;
}*/
int getSystemTime(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
FILE *fp = popen("date +%T", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(buf, 32, fp);
pclose(fp);
websWrite(wp, T("%s"), buf);
return 0;
}
//gordon add for infoDate 20090203
int getSystemDate(int eid, webs_t wp, int argc, char_t **argv)
{
char_t buf[32];
FILE *fp = popen("date +%Y/%m/%d", "r");
if(!fp){
websWrite(wp, T("none"));
return 0;
}
fgets(buf, 32, fp);
pclose(fp);
websWrite(wp, T("%s"), buf);
return 0;
}
#define LOG_MAX (16384)
int loglist(int eid, webs_t wp, int argc, char_t **argv)//Gordon add for systemlog 20081230
{
FILE *fp1 = NULL;
char *log1;
char tm[32],msg[256];
char display_msg[300];
char *LOG_index, *show_all;
int print_index=0; //control show log or not.
int z,i;
//LOG_index = nvram_bufget(RT2860_NVRAM, "log_index");
LOG_index = nvram_safe_get("log_index");
char dhcp_buf[2],dhcpcli_buf[2],web_buf[2],dns_buf[2],ppp_buf[2];
char upnp_buf[2],ddns_buf[2],sys_buf[2],ntp_buf[2];
char vpn_buf[2],enable_buf[2];
int show_flag=0;//when select show_all,0 not show log 1 show log
ezplib_get_attr_val("log_rule", 0, "dhcp_serv", dhcp_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "dhcp_cli", dhcpcli_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "web_mgmt", web_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "dns", dns_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "ppp", ppp_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "upnp", upnp_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "ddns", ddns_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "sys_warning", sys_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "ntp", ntp_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "vpn", vpn_buf, 2, EZPLIB_USE_CLI);
ezplib_get_attr_val("log_rule", 0, "enable", enable_buf, 2, EZPLIB_USE_CLI);
int linenum=0, charnum=0, tmnum=0, msgnum=0, a=0, line=0, tmstart=0, msgsize=0;
fp1 = popen("logread -k USR", "r");
if(!fp1){
websWrite(wp, "-1");
goto error;
}
log1 = malloc(LOG_MAX * sizeof(char));
if(!log1){
websWrite(wp, "-1");
goto error;
}
memset(log1, 0, LOG_MAX);
fread(log1, 1, LOG_MAX, fp1);
pclose(fp1);
for(charnum=0;charnum<LOG_MAX;charnum++)
{
if((log1[charnum]==00)&&(log1[charnum+1]==00)&&(log1[charnum+2]==00)&&(log1[charnum+3]==00))
{
//printf("run 111111\n");
free(log1);
return 0;
}
if(!strcmp(LOG_index,"show_all"))//ALL LOG
{
print_index=1;
//<web>->Management
if((log1[charnum]==60)&&(log1[charnum+1]==77)&&(log1[charnum+2]==97)&&(log1[charnum+3]==110)
&&(log1[charnum+4]==97)&&(log1[charnum+5]==103)&&(log1[charnum+6]==101)
&&(log1[charnum+7]==109)&&(log1[charnum+8]==101)&&(log1[charnum+9]==110)
&&(log1[charnum+10]==116)&&(log1[charnum+11]==62)&&!strcmp(web_buf, "0"))
{
print_index=0;
}
//<dns>
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==78)&&(log1[charnum+3]==83)&&(log1[charnum+4]==62)&&!strcmp(dns_buf, "0"))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=0;
}
//<ppp>
if((log1[charnum]==60)&&(log1[charnum+1]==80)&&(log1[charnum+2]==80)&&(log1[charnum+3]==80)&&(log1[charnum+4]==62)&&!strcmp(ppp_buf, "0"))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=0;
}
//<upnp>
if((log1[charnum]==60)&&(log1[charnum+1]==85)&&(log1[charnum+2]==80)&&(log1[charnum+3]==110)&&(log1[charnum+4]==80)&&(log1[charnum+5]==62)&&!strcmp(upnp_buf, "0"))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=0;
}
//<ntpclient>
if((log1[charnum]==60)&&(log1[charnum+1]==78)&&(log1[charnum+2]==84)&&(log1[charnum+3]==80)&&(log1[charnum+4]==67)&&(log1[charnum+5]==108)&&(log1[charnum+6]==105)&&(log1[charnum+7]==101)&&(log1[charnum+8]==110)&&(log1[charnum+9]==116)&&(log1[charnum+10]==62)&&!strcmp(ntp_buf, "0"))
{
//printf("######run mask NTPClient !!!\n");
print_index=0;
}
//<syswarning>
if((log1[charnum]==60)&&(log1[charnum+1]==83)&&(log1[charnum+2]==121)&&(log1[charnum+3]==115)&&(log1[charnum+4]==116)&&(log1[charnum+5]==101)&&(log1[charnum+6]==109)&&(log1[charnum+7]==87)&&(log1[charnum+8]==97)&&(log1[charnum+9]==114)&&(log1[charnum+10]==110)&&(log1[charnum+11]==105)&&(log1[charnum+12]==110)&&(log1[charnum+13]==103)&&(log1[charnum+14]==62)&&!strcmp(sys_buf, "0"))
{
//printf("######run mask "warn kernel" !!!\n");
print_index=0;
}
//<dhcp_serv>
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==72)&&(log1[charnum+3]==67)&&(log1[charnum+4]==80)&&(log1[charnum+5]==83)&&(log1[charnum+6]==101)&&(log1[charnum+7]==114)&&(log1[charnum+8]==118)&&(log1[charnum+9]==101)&&(log1[charnum+10]==114)&&(log1[charnum+11]==62)&&!strcmp(dhcp_buf, "0"))
{
//printf("######run mask dhcp server is zero!!!\n");
print_index=0;
}
//<dhcp_client>
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==72)&&(log1[charnum+3]==67)&&(log1[charnum+4]==80)&&(log1[charnum+5]==67)&&(log1[charnum+6]==108)&&(log1[charnum+7]==105)&&(log1[charnum+8]==101)&&(log1[charnum+9]==110)&&(log1[charnum+10]==116)&&(log1[charnum+11]==62)&&!strcmp(dhcpcli_buf, "0"))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=0;
}
//<ddns>
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==68)&&(log1[charnum+3]==78)&&(log1[charnum+4]==83)&&(log1[charnum+5]==62)&&!strcmp(ddns_buf, "0"))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=0;
}
//printf("######run SHOW ALL 111111!!!\n");
//<ddns>
if((log1[charnum]==60)&&(log1[charnum+1]==118)&&(log1[charnum+2]==112)&&(log1[charnum+3]==110)&&(log1[charnum+4]==62)&&!strcmp(vpn_buf, "0"))
{
print_index=0;
} //vpn
}
if(!strcmp(LOG_index,"System_Maintenance"))//SystemMaintenance
{
//printf("######run SHOW SystemMaintenance<WEB> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==77)&&(log1[charnum+2]==97)&&(log1[charnum+3]==110)
&&(log1[charnum+4]==97)&&(log1[charnum+5]==103)&&(log1[charnum+6]==101)
&&(log1[charnum+7]==109)&&(log1[charnum+8]==101)&&(log1[charnum+9]==110)
&&(log1[charnum+10]==116)&&(log1[charnum+11]==62))
{
//printf("%c%c%c%c%c\n",log1[charnum],log1[charnum+1],log1[charnum+2],log1[charnum+3],log1[charnum+4]);
print_index=1;
}
}
if(!strcmp(LOG_index,"dns"))//DNS
{
//printf("######run SHOW DNS<DNS> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==78)&&(log1[charnum+3]==83)&&(log1[charnum+4]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
if(!strcmp(LOG_index,"PPP"))//PPP
{
//printf("######run SHOW PPP<PPP> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==80)&&(log1[charnum+2]==80)&&(log1[charnum+3]==80)&&(log1[charnum+4]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
if(!strcmp(LOG_index,"UPnP"))//UPNP
{
//printf("######run SHOW UPNP<UPnP> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==85)&&(log1[charnum+2]==80)&&(log1[charnum+3]==110)&&(log1[charnum+4]==80)&&(log1[charnum+5]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
// Tommy, add syslog 2009/10/22 01:46
if(!strcmp(LOG_index,"NTPClient"))//ntpclient
{
//printf("######run SHOW ntpclient<NTPClient> !!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==78)&&(log1[charnum+2]==84)&&(log1[charnum+3]==80)&&(log1[charnum+4]==67)&&(log1[charnum+5]==108)&&(log1[charnum+6]==105)&&(log1[charnum+7]==101)&&(log1[charnum+8]==110)&&(log1[charnum+9]==116)&&(log1[charnum+10]==62))
{
//printf("######run mask NTPClient !!!\n");
print_index=1;
}
}
// Tommy, add syslog 2009/10/22 01:46
if(!strcmp(LOG_index,"WLAN")) //WLAN
{
//printf("######run SHOW Wireless<Wireless> !!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==87)&&(log1[charnum+2]==105)&&(log1[charnum+3]==114)&&(log1[charnum+4]==101)&&(log1[charnum+5]==108)&&(log1[charnum+6]==101)&&(log1[charnum+7]==115)&&(log1[charnum+8]==115)&&(log1[charnum+9]==62))
{
//printf("######run mask Wireless !!!\n");
print_index=1;
}
}
// Tommy, add syslog 2009/10/22 01:46
if(!strcmp(LOG_index,"SYSwarning")) //SYSwarning
{
//printf("######run SHOW kernel and waring<SystemWarning> !!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==83)&&(log1[charnum+2]==121)&&(log1[charnum+3]==115)&&(log1[charnum+4]==116)&&(log1[charnum+5]==101)&&(log1[charnum+6]==109)&&(log1[charnum+7]==87)&&(log1[charnum+8]==97)&&(log1[charnum+9]==114)&&(log1[charnum+10]==110)&&(log1[charnum+11]==105)&&(log1[charnum+12]==110)&&(log1[charnum+13]==103)&&(log1[charnum+14]==62))
{
//printf("######run mask "warn kernel" !!!\n");
print_index=1;
}
}
//---------- aron add 2009.10.23
if(!strcmp(LOG_index,"dhcpServer"))
{
//printf("######run SHOW dhcpServer<DHCPServer> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==72)&&(log1[charnum+3]==67)&&(log1[charnum+4]==80)&&(log1[charnum+5]==83)&&(log1[charnum+6]==101)&&(log1[charnum+7]==114)&&(log1[charnum+8]==118)&&(log1[charnum+9]==101)&&(log1[charnum+10]==114)&&(log1[charnum+11]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
if(!strcmp(LOG_index,"dhcpClient"))
{
//printf("######run SHOW dhcpClient<DHCPClient> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==72)&&(log1[charnum+3]==67)&&(log1[charnum+4]==80)&&(log1[charnum+5]==67)&&(log1[charnum+6]==108)&&(log1[charnum+7]==105)&&(log1[charnum+8]==101)&&(log1[charnum+9]==110)&&(log1[charnum+10]==116)&&(log1[charnum+11]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
if(!strcmp(LOG_index,"ddns"))
{
//printf("######run SHOW ddns<DDNS> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==68)&&(log1[charnum+2]==68)&&(log1[charnum+3]==78)&&(log1[charnum+4]==83)&&(log1[charnum+5]==62))
{
//printf("######run mask SystemMaintenance 222222!!!\n");
print_index=1;
}
}
if(!strcmp(LOG_index,"vpn"))
{
//printf("######run SHOW vpn<VPN> 111111!!!\n");
if((log1[charnum]==60)&&(log1[charnum+1]==118)&&(log1[charnum+2]==112)&&(log1[charnum+3]==110)&&(log1[charnum+4]==62))
{
print_index=1;
}
}
//-------------------------------
//---steve add 2009/10/22
if(!strcmp(LOG_index,"Firewall"))//Firewall
{
//Steve add tset Firewall
//printf("######run SHOW Firewall<Firewall>!!\n");
if( (log1[charnum]==60)&&(log1[charnum+1]==70)&&(log1[charnum+2]==105)&&(log1[charnum+3]==114)&&(log1[charnum+4]==101)&&(log1[charnum+5]==119)&&(log1[charnum+6]==97)&&(log1[charnum+7]==108)&&(log1[charnum+8]==108)&&(log1[charnum+9]==62))
{
print_index=1;
}
}
//----------------------------------
if(!strcmp(LOG_index,"show_all")&&log1[charnum]!=10&&print_index==0){
//printf("print_index=======0\n");
show_flag=0;
}
if(log1[charnum]==10)
{
//printf("run 222222\n");
++linenum;
memset(tm, 0, 32);
memset(msg, 0, 256);
memset(display_msg,0,300);
//printf("run 33333\n");
for(tmnum=0;tmnum<=15;tmnum++)
{
//tm[a]=log1[tmstart];
msg[a]=log1[tmstart];
a=a+1;
tmstart=tmstart+1;
}
msgsize=charnum-tmstart;
//a=0;
for(msgnum=0;msgnum<=msgsize;msgnum++)
{
msg[a]=log1[tmstart];
a=a+1;
tmstart=tmstart+1;
}
tmstart=charnum+1;
a=0;
// Deal the content of msg <WEB> , <PPP> ....
z=0;
for (i=0;i<sizeof(msg);i++){
if ((msg[i] == '<') || (msg[i] == '>')){
if (msg[i] == '<'){
display_msg[z] = '&';
z++;
display_msg[z] = 'l';
z++;
display_msg[z] = 't';
z++;
display_msg[z] = ';';
z++;
}
if (msg[i] == '>'){
display_msg[z] = '&';
z++;
display_msg[z] = 'g';
z++;
display_msg[z] = 't';
z++;
display_msg[z] = ';';
z++;
}
}else{
display_msg[z] = msg[i];
z++;
}
}
if(show_flag==1){
print_index=0;
show_flag=0;
}
//printf("@@@@print_index=[%d]",print_index);
if(print_index==1)
{
websWrite(wp, T("<tr>"
"<td nowrap><center>"
"<span class=""table_left"">%d</span>"
"</center></td>"
"<td nowrap>"
"<span class=table_font>%s</span>"
"</td>"
"<td nowrap><span class=""table_right"">"
"</span></td>"
"</tr>"),linenum,display_msg);
print_index=0;
}
else
{
--linenum;
print_index=0;
}
}
}
//free(tm);
//free(msg);
//free(display_msg);
free(log1);
return 0;
error:
if(!fp1)
pclose(fp1);
websDone(wp, 200);
return 0;
}
int getMemLeftASP(int eid, webs_t wp, int argc, char_t **argv)
{
char buf[1024], *semiColon, *key, *value;
FILE *fp = fopen(PROC_MEM_STATISTIC, "r");
if(!fp){
websWrite(wp, T("no proc?\n"));
return -1;
}
while(fgets(buf, 1024, fp)){
if(! (semiColon = strchr(buf, ':')) )
continue;
*semiColon = '\0';
key = buf;
value = semiColon + 1;
if(!strcmp(key, "MemFree")){
value = strip_space(value);
websWrite(wp, T("%s"), value);
fclose(fp);
return 0;
}
}
websWrite(wp, T(""));
fclose(fp);
return -1;
}
/*
* Function£º¸ù¾Ý×Ö·û´®¿ªÊ¼¡¢½áÊøË÷Òý½ØÈ¡×Ö·û´®
* Input£ºÄ¿±ê×Ö·û´®¡¢¿ªÊ¼Ë÷Òý¡¢½áÊøË÷Òý
* Ë÷Òý´Ó0¿ªÊ¼
* Output£º½ØÈ¡ºóµÄ½á¹û×Ö·û´®£¨°üº¬¿ªÊ¼Ë÷Òý×Ö·ûºÍ½áÊøË÷Òý×Ö·û£©
* Èç¹û½ØÈ¡Ê§°Ü£¬·µ»ØNULL
* Other£º1¡¢µ÷ÓÃÕßÔÚʹÓ÷µ»ØÖµÇ°£¬±ØÐëÏÈÅжÏÊÇ·ñΪNULL
* 2¡¢µ÷ÓÃÕßÔÚÓÃÍê·µ»ØÖµºó£¬±ØÐëÊÖ¶¯ÊÍ·ÅÄÚ´æ
*/
char *subStringByIndex(char *string, int begin, int end)
{
char *result = NULL;
int resultCount = 0;
if (NULL == string || begin < 0 || end > (strlen(string) - 1) || (end - begin) < 0)
{
printf("Error parameter input in function of subStringByIndex.\n");
return NULL;
}
resultCount = end - begin + 1;
result = (char *)malloc(sizeof(char) * resultCount + 1);
if(NULL == result)
{
printf("Error malloc memory in function of subStringByIndex.\n");
return NULL;
}
strncpy(result, string + begin, resultCount);
result[resultCount] = '\0';
return result;
}
static void systemrebooting(webs_t wp, char_t *path, char_t *query)
{
//char *lan_ip;
//lan_ip = nvram_bufget(RT2860_NVRAM, "lan_ipaddr");
char_t *year = NULL,*mon = NULL,*day = NULL;
char_t *hour = NULL,*min = NULL,*sec = NULL;
char_t date_str[32];
FILE *fp = popen("date -Iseconds", "r");
if(!fp){
return 0;
}
fgets(date_str, 33, fp);
pclose(fp);
year = subStringByIndex(date_str, 0, 3);
if (NULL != year){
ezplib_replace_attr("ntp_rule", 0, "year", year);
free(year);
}
mon = subStringByIndex(date_str, 5, 6);
if(NULL != mon){
ezplib_replace_attr("ntp_rule", 0, "mon", mon);
free(mon);
}
day = subStringByIndex(date_str, 8, 9);
if(NULL != day){
ezplib_replace_attr("ntp_rule", 0, "date", day);
free(day);
}
hour = subStringByIndex(date_str, 11, 12);
if(NULL != hour){
ezplib_replace_attr("ntp_rule", 0, "hour", hour);
free(hour);
}
min = subStringByIndex(date_str, 14, 15);
if(NULL != min){
ezplib_replace_attr("ntp_rule", 0, "min", min);
free(min);
}
sec = subStringByIndex(date_str, 17, 18);
if(NULL != sec){
ezplib_replace_attr("ntp_rule", 0, "sec", sec);
free(sec);
}
nvram_commit();
system("sleep 3 && reboot &");
websHeader(wp);
//websWrite(wp, T("please wait 40 seconds for reboot . . .\n"));
websWrite(wp, T("<script>\n"));
websWrite(wp, T("function waitingpage(){\n"));
websWrite(wp, T("top.location.href = '/local/advance/proceeding_reboot.asp';\n"));
websWrite(wp, T("}\n"));
websWrite(wp, T("waitingpage();\n"));
//websWrite(wp, T("self.setTimeout('refresh_all()', %s);\n"), REFRESH_TIMEOUT);
websWrite(wp, T("</script>\n"));
websFooter(wp);
websDone(wp, 200);
}
static void LoadDefaultSettings(webs_t wp, char_t *path, char_t *query)
{
char *value;
char buf[BUF_256];
char cmd[1024];
doSystem("nvram default");
system("echo 1111111>/dev/console");
//To make sure the Web UI can redirect to default LAN IP
ezplib_get_attr_val("lan_static_rule_default", 0, "ipaddr_normal", buf, TMP_LEN, EZPLIB_USE_CLI);
value = buf;
nvram_set("lan0_ipaddr", value);
doSystem("nvram commit");
snprintf(cmd, 1024, "logger EZP_USR %s\n ","Nvram factory successful" );
system(cmd);
system("sleep 3 && reboot &");
websHeader(wp);
//websWrite(wp, T("please wait 40 seconds for reboot . . .\n"));
websWrite(wp, T("<script>\n"));
websWrite(wp, T("function waitingpage(){\n"));
websWrite(wp, T("top.location.href = '/local/advance/proceeding.asp';\n"));
websWrite(wp, T("}\n"));
websWrite(wp, T("waitingpage();\n"));
//websWrite(wp, T("self.setTimeout('refresh_all()', %s);\n"), REFRESH_TIMEOUT);
websWrite(wp, T("</script>\n"));
websFooter(wp);
websDone(wp, 200);
}
/*
* callee must free memory.
*/
/*
static char *getLog(char *filename)
{
FILE *fp;
struct stat filestat;
char *log;
if(stat(filename, &filestat) == -1)
return NULL;
// printf("%d\n", filestat.st_size);
log = (char *)malloc(sizeof(char) * (filestat.st_size + 1) );
if(!log)
return NULL;
if(!(fp = fopen(filename, "r"))){
return NULL;
}
if( fread(log, 1, filestat.st_size, fp) != filestat.st_size){
printf("read not enough\n");
free(log);
return NULL;
}
log[filestat.st_size] = '\0';
fclose(fp);
return log;
}
*/
static void clearlog(webs_t wp, char_t *path, char_t *query)
{
// AXIM: clear log
#if 0
doSystem("killall -q klogd");
doSystem("killall -q syslogd");
doSystem("syslogd -C8 1>/dev/null 2>&1");
doSystem("klogd 1>/dev/null 2>&1");
#else
system("/bin/ezp-rstlog");
#endif
setWebMessage(0, NULL);
websRedirect(wp, "/local/advance/syslog_gordon.asp");
}
void management_init(void)
{
FILE *fp = NULL;
doSystem("killall ntp.sh");
doSystem("ntp.sh &");//modifyed by Gordon 20090226
doSystem("ddns.sh");
// Tommy, move udps to execute after factory test ready and rcS file execute "udps&" 2009/10/23 11:34
#if 1
doSystem("udps &");//modifyed by Gordon 20090312
#endif
//WPSRestart();
// doSystem("killall -q klogd");
// doSystem("killall -q syslogd");
if (NULL == (fp = fopen("/tmp/syslodg_exist", "r")))
{
doSystem("echo '1' > /tmp/syslodg_exist");
doSystem("syslogd -C8 1>/dev/null 2>&1");
// Tommy , enable klog,2009/10/15 02:54
doSystem("klogd 1>/dev/null 2>&1");
}
// doSystem("klogd 1>/dev/null 2>&1");
}
void management_fini(void)
{
doSystem("killall -q klogd");
doSystem("killall -q syslogd");
}
int checkAutoUploadFirmware(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp = NULL;
char_t file_size[100];
char_t file_date[15];
//doSystem("ls -l /var/upload/zyfw_fw_file | sed 's/ \\/var.*$//g' | sed 's/^.* //g' > /var/upload/zyfw_fw_file_size");
//----------- aron modify 2010.07.09
/*
doSystem("date -r /var/upload/zyfw_fw_file | cut -d ' ' -f 1 > /var/tempDate");
if((fp = fopen("/var/tempDate", "r")) != NULL)
{
fscanf(fp, "%s", file_date);
fclose(fp);
doSystem("rm -rf /var/tempDate");
}
doSystem("ls -le /var/upload/zyfw_fw_file | sed 's/ \\%s.*$//g' | sed 's/^.* //g' > /var/upload/zyfw_fw_file_size", file_date);
*/
//doSystem("filename='/var/upload/zyfw_fw_file' ; ls '$filename' -al | awk '{print $5}' > /var/upload/zyfw_fw_file_size");
doSystem("ls /var/upload/zyfw_fw_file -al | awk '{print $5}' > /var/upload/zyfw_fw_file_size");
//-------------------------------------
if (NULL == (fp = fopen("/var/upload/zyfw_fw_file_size", "r")))
{
websWrite(wp, T("0"));
}
else
{
fscanf(fp, "%s", file_size);
fclose(fp);
if ((file_size[0]>'0')&&(file_size[0]<='9'))
websWrite(wp, T("%s"), file_size);
else
websWrite(wp, T("0"));
}
return 1;
}
int kill_wget(int eid, webs_t wp, int argc, char_t **argv)
{
doSystem("killall wget");
return 1;
}
#endif //Steve220
// Add for 3G +++++++++++++++++++
//
// return : 0: not exist ; 1: exist
//
static int wan3GEnable=0;
int Check3GExist()
{
char value[32] = {0};
FILE *fp;
char wan3GLink[32];
system("ifconfig | grep 'ppp0' > /tmp/ppp0.txt");
if (NULL != (fp = fopen("/tmp/ppp0.txt", "r"))){
fscanf(fp, "%s", wan3GLink);
fclose(fp);
system("rm -f /tmp/ppp0.txt");
ezplib_get_attr_val("wan0_proto", 0, "curr", value, 32, EZPLIB_USE_CLI);
if ((!strcmp(value, "wwan")) && (!strcmp(wan3GLink, "ppp0"))){
wan3GEnable = 1;
return 1;
}else{
wan3GEnable = 0;
return 0;
}
}else{
wan3GEnable = 0;
return 0;
}
}
static int get3GSetting(int eid, webs_t wp, int argc, char_t **argv)
{
char value[32] = {0};
ezplib_get_attr_val("wan0_proto", 0, "curr", value, 32, EZPLIB_USE_CLI);
if (!strcmp(value, "wwan")){
// HOWTO : get3G.sh should be called by USB adapter pulgin. (AXIMCOM help)
//system("/usr/sbin/get3G.sh");
return websWrite(wp, T("1"));
}else{
return websWrite(wp, T("0"));
}
}
static int getSIMstatus(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
char str_SIM[32];
char str_Ready[32];
if (Check3GExist() == 0){
return websWrite(wp, T("0")); //SIM Not Ready
}
if (NULL != (fp = fopen("/tmp/SIM.txt", "r"))) {
fscanf(fp, "%s %s", str_SIM, str_Ready);
fclose(fp);
if (!strcmp(str_Ready, "ready")){
return websWrite(wp, T("1")); // SIM ready
}else{
return websWrite(wp, T("0")); //SIM Not Ready
}
}else{
return websWrite(wp, T("0")); //SIM Not Ready
}
}
static int getWan3GIp(int eid, webs_t wp, int argc, char_t **argv)
{
return websWrite(wp, T("1"));
}
static int getWan3GNetmask(int eid, webs_t wp, int argc, char_t **argv)
{
return websWrite(wp, T("1"));
}
static int getWan3GDHCP(int eid, webs_t wp, int argc, char_t **argv)
{
return websWrite(wp, T("DHCP"));
}
static int getWAN3GLinkStatus(int eid, webs_t wp, int argc, char_t **argv)
{
char *value;
FILE *fp;
char wan3GLink[32];
#if 0
system("ifconfig | grep 'ppp0' > /tmp/ppp0.txt");
if (NULL != (fp = fopen("/tmp/ppp0.txt", "r"))){
fscanf(fp, "%s", wan3GLink);
fclose(fp);
system("rm -f /tmp/ppp0.txt");
value = nvram_get("wan0_proto");
if ((!strcmp(value, "wwan")) && (!strcmp(wan3GLink, "ppp0"))){
return websWrite(wp, T("Up"));
}else{
return websWrite(wp, T("Down"));
}
}else{
return websWrite(wp, T("Down"));
}
#else
if (wan3GEnable == 1){
return websWrite(wp, T("Up"));
}else{
return websWrite(wp, T("Down"));
}
#endif
}
static int get3GConnStatus(int eid, webs_t wp, int argc, char_t **argv)
{
char buf[TMP_LEN];
ezplib_get_attr_val("wan_wwan_rule", 0, "mode", buf, TMP_LEN, EZPLIB_USE_CLI);
if (!strcmp(buf, "auto")){
return websWrite(wp, T("AUTO"));
}else if (!strcmp(buf, "hsdpa")){
return websWrite(wp, T("HSDPA / 3.5G"));
}else if (!strcmp(buf, "umts")){
return websWrite(wp, T("UMTS / 3G"));
}else if (!strcmp(buf, "edge")){
return websWrite(wp, T("EDGE / 2.5G"));
}else if (!strcmp(buf, "gprs")){
return websWrite(wp, T("GPRS / 2G"));
}else{
return websWrite(wp, T("Un-known"));
}
}
static char wan3GISP[128];
static int get3GISP(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
//char cmd[512];
//system("cat /tmp/reg.txt | grep 'Registered on Home network:' | sed 's/^.*Registered on Home network: //g' | sed 's/^.*\"\\(.*\\)\".*$/\\1/'> /tmp/ISP.txt");
//sprintf(cmd, "%s", "cat /tmp/reg.txt | grep 'Registered on Home network:' | sed 's/^.*Registered on Home network: //g' | sed 's/^.*\"\(.*\)\".*$/\1/' > /tmp/ISP.txt");
//system(cmd);
system("cat /tmp/reg.txt | grep 'Registered on Home network:' | sed 's/^.*Registered on Home network: //g' > /tmp/ISP.txt");
system("cat /tmp/ISP.txt | sed 's/^.*\"\\(.*\\)\".*$/\\1/' > /tmp/getISP.txt");
if (NULL != (fp = fopen("/tmp/getISP.txt", "r"))){
fscanf(fp, "%s", wan3GISP);
fclose(fp);
system("rm -f /tmp/ISP.txt");
system("rm -f /tmp/getISP.txt");
return websWrite(wp, T("%s"),wan3GISP);
}else{
return websWrite(wp, T(""));
}
}
static int wan3GSSI;
static int get3GSignalStrength(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
char cmd[512];
char *value;
char wan3GLink[32];
if (wan3GEnable == 0){
return websWrite(wp, T("0"));
}
system("/usr/sbin/getSSI.sh");
system("cat /tmp/sig.txt | grep 'Signal Quality:' | sed 's/^.*Signal Quality: //g' > /tmp/SSI.txt");
system("cat /tmp/SSI.txt | sed 's/,.*$//g' > /tmp/getSSI.txt");
//system("cat /tmp/sig.txt | grep 'Signal Quality:' | sed 's/^.*Signal Quality: //g' | sed 's/,.*$//g' > /tmp/SSI.txt");
//sprintf(cmd, "%s", "cat /tmp/sig.txt | grep 'Signal Quality:' | sed 's/^.*Signal Quality: //g' | sed 's/,.*$//g' > /tmp/SSI.txt");
//system(cmd);
if (NULL != (fp = fopen("/tmp/getSSI.txt", "r"))){
fscanf(fp, "%d", &wan3GSSI);
fclose(fp);
system("rm -f /tmp/SSI.txt");
system("rm -f /tmp/getSSI.txt");
system("rm -f /tmp/sig.txt");
if ((wan3GSSI >= 0) || (wan3GSSI <= 31)){
wan3GSSI = 113 - wan3GSSI*2;
}else{
wan3GSSI = 113;
}
return websWrite(wp, T("-%d"),wan3GSSI);
}else{
return websWrite(wp, T(""));
}
}
static int get3GConnConnUpTime(int eid, webs_t wp, int argc, char_t **argv)
{
int updays, uphours, upminutes, upseconds;
unsigned long wanuptime, disptime;
char TempBuf[32];
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
ezplib_get_attr_val("wan_st_rule", 0, "uptime", TempBuf, 32, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "")){
strcpy(TempBuf, "0");
}
wanuptime = atol(TempBuf);
disptime = wanuptime;
updays = (int) disptime / (60*60*24);
upminutes = (int) disptime / 60;
uphours = (upminutes / 60) % 24;
upminutes %= 60;
upseconds = ((int) disptime)%60;
if (updays){
return websWrite(wp, T("%d day%s, %s%d:%s%d:%s%d") ,
updays, (updays != 1) ? "s" : "",
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}else{
return websWrite(wp, T("%s%d:%s%d:%s%d") ,
(uphours < 10) ? "0" : "",uphours,
(upminutes < 10) ? "0" : "",upminutes,
(upseconds < 10) ? "0" : "",upseconds);
}
}
static char wan3Gmanufacturer[128];
static int get3GManufacturer(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
system("cat /tmp/info.txt | grep 'Manufacturer:' | sed 's/^.*Manufacturer: //g' > /tmp/manufacturer.txt");
if (NULL != (fp = fopen("/tmp/manufacturer.txt", "r"))){
fscanf(fp, "%s", wan3Gmanufacturer);
fclose(fp);
system("rm -f /tmp/manufacturer.txt");
return websWrite(wp, T("%s"),wan3Gmanufacturer);
}else{
return websWrite(wp, T(""));
}
}
static char wan3Gmodel[128];
static int get3GModel(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
system("cat /tmp/info.txt | grep 'Model:' | sed 's/^.*Model: //g' > /tmp/Model.txt");
if (NULL != (fp = fopen("/tmp/Model.txt", "r"))){
fscanf(fp, "%s", wan3Gmodel);
fclose(fp);
system("rm -f /tmp/Model.txt");
return websWrite(wp, T("%s"),wan3Gmodel);
}else{
return websWrite(wp, T(""));
}
}
static char wan3GRev[128];
static int get3GFW(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
system("cat /tmp/info.txt | grep 'Revision:' | sed 's/^.*Revision: //g' > /tmp/Rev.txt");
if (NULL != (fp = fopen("/tmp/Rev.txt", "r"))){
fscanf(fp, "%s", wan3GRev);
fclose(fp);
system("rm -f /tmp/Rev.txt");
return websWrite(wp, T("%s"),wan3GRev);
}else{
return websWrite(wp, T(""));
}
}
static char wan3GCardIEMI[128];
static int get3GIMEI(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
if (wan3GEnable == 0){
return websWrite(wp, T(""));
}
system("cat /tmp/info.txt | grep 'IMEI:' | sed 's/^.*IMEI: //g' > /tmp/CardIEMI.txt");
if (NULL != (fp = fopen("/tmp/CardIEMI.txt", "r"))){
fscanf(fp, "%s", wan3GCardIEMI);
fclose(fp);
system("rm -f /tmp/CardIEMI.txt");
return websWrite(wp, T("%s"),wan3GCardIEMI);
}else{
return websWrite(wp, T(""));
}
}
static int getSIMIMEI(int eid, webs_t wp, int argc, char_t **argv)
{
return websWrite(wp, T(""));
}
// Add for 3G -------------------
// Add for IPv6 +++++++++++++++
static int getIPv6ConnType(int eid, webs_t wp, int argc, char_t **argv)
{
char *value;
value = nvram_get("wan0_protov6");
if (!strcmp(value, "static"))
return websWrite(wp, T("Ethernet"));
else if(!strcmp(value, "dhcp"))
return websWrite(wp, T("DHCPv6"));
else if(!strcmp(value, "pppoe"))
return websWrite(wp, T("PPPoE"));
else if(!strcmp(value, "link-local"))
return websWrite(wp, T("Link-local only"));
}
static int getIPv6LanAddr(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
char link_local_addr[100];
memset(link_local_addr, 0, 100);
char tmp_cmd[128] = {0};
sprintf(tmp_cmd,"ifconfig %s | grep 'Scope:Global' | sed 's/^.*inet6 addr: //g' | sed 's/ Scope.*$//g' > /tmp/br0ipv6",nvram_safe_get("lan0_ifname"));
//system("ifconfig br0 | grep 'Scope:Global' | sed 's/^.*inet6 addr: //g' | sed 's/ Scope.*$//g' > /etc/br0ipv6");
system(tmp_cmd);
if((fp = fopen("/tmp/br0ipv6", "r")) != NULL)
{
fscanf(fp, "%s", link_local_addr);
fclose(fp);
websWrite(wp, T("%s"), link_local_addr);
}
return 1;
}
static int getIPv6StaticDns(int eid, webs_t wp, int argc, char_t **argv)
{
int type, req=0;
char *value;
char buf[TMP_LEN];
if (ejArgs(argc, argv, T("%d"), &type) == 1) {
if (1 == type)
req = 1;
else if (2 == type)
req = 2;
else
return websWrite(wp, T(""));
}
if(req == 1)
{
//value = nvram_safe_get("wan0_dns");
ezplib_get_attr_val("wan_staticv6_rule", 0, "dns1", buf, TMP_LEN, EZPLIB_USE_CLI);
}
else if(req ==2)
{
//value = nvram_safe_get("wan0_dns2");
ezplib_get_attr_val("wan_staticv6_rule", 0, "dns2", buf, TMP_LEN, EZPLIB_USE_CLI);
}
return websWrite(wp, T("%s"), buf);
}
static int getIPv6DHCPDns(int eid, webs_t wp, int argc, char_t **argv)
{
int type, req=0;
char *value;
char buf[TMP_LEN];
if (ejArgs(argc, argv, T("%d"), &type) == 1) {
if (1 == type)
req = 1;
else if (2 == type)
req = 2;
else
return websWrite(wp, T(""));
}
if(req == 1)
{
//value = nvram_safe_get("wan0_dns");
ezplib_get_attr_val("wan_dnsv6_rule", 0, "dns1", buf, TMP_LEN, EZPLIB_USE_CLI);
}
else if(req ==2)
{
//value = nvram_safe_get("wan0_dns2");
ezplib_get_attr_val("wan_dnsv6_rule", 0, "dns1", buf, TMP_LEN, EZPLIB_USE_CLI);
}
return websWrite(wp, T("%s"), buf);
}
static int getIPv6DhcpWanAddr(int eid, webs_t wp, int argc, char_t **argv)
{
FILE *fp;
char addr[100];
char_t TempBuf[32];
memset(addr, 0, 100);
//ezplib_get_attr_val("wl_mode_rule", 0, "mode", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
ezplib_get_attr_val("system_mode", 0, "name", TempBuf, SHORT_BUF_LEN, EZPLIB_USE_CLI);
if (!strcmp(TempBuf, "normal")){
system("ifconfig vlan2 | grep 'Scope:Global' | sed 's/^.*inet6 addr: //g' | sed 's/ Scope.*$//g' > /etc/wanipv6");
}else if (!strcmp(TempBuf, "wisp0")){
system("ifconfig apclii0 | grep 'Scope:Global' | sed 's/^.*inet6 addr: //g' | sed 's/ Scope.*$//g' > /etc/wanipv6");
}else if (!strcmp(TempBuf, "wisp_ur")){
system("ifconfig apclii0 | grep 'Scope:Global' | sed 's/^.*inet6 addr: //g' | sed 's/ Scope.*$//g' > /etc/wanipv6");
}
if((fp = fopen("/etc/wanipv6", "r")) != NULL)
{
fscanf(fp, "%s", addr);
fclose(fp);
websWrite(wp, T("%s"), addr);
}
return 1;
}
static int getIPv6DhcpWanDateway(int eid, webs_t wp, int argc, char_t **argv)
{
#if 1
char_t buf[32];
char *value;
value = nvram_get("wan0_gatewayv6");
websWrite(wp, T("%s"), value);
return 0;
#else
FILE *fp;
char addr[100];
char_t TempBuf[32];
memset(addr, 0, 100);
system("ip -6 route | grep \"default via 2\" | cut -f3 -d\" \" > /etc/wanipv6");
if((fp = fopen("/etc/wanipv6", "r")) != NULL)
{
fscanf(fp, "%s", addr);
fclose(fp);
websWrite(wp, T("%s"), addr);
}
if (!strcmp(addr, "")){
system("ip -6 route | grep \"default via fe\" | cut -f3 -d\" \" > /etc/wanipv6");
if((fp = fopen("/etc/wanipv6", "r")) != NULL)
{
fscanf(fp, "%s", addr);
fclose(fp);
websWrite(wp, T("%s"), addr);
}
}
#endif
return 1;
}
// Add for IPv6 ---------------
//=================================================================
void formDefineManagement(void)
{
websFormDefine(T("setSysAdm"), setSysAdm);
websFormDefine(T("setSysLang"), setSysLang);
websFormDefine(T("logsetting"), logsetting);
websFormDefine(T("showlog"), showlog);
websFormDefine(T("NTP"), NTP);
websFormDefine(T("NTPSyncWithHost"), NTPSyncWithHost);
websAspDefine(T("getCurrentYear"), getCurrentYear);
websAspDefine(T("getCurrentMon"), getCurrentMon);
websAspDefine(T("getCurrentDay"), getCurrentDay);
websAspDefine(T("getCurrentHour"), getCurrentHour);
websAspDefine(T("getCurrentMin"), getCurrentMin);
websAspDefine(T("getCurrentSec"), getCurrentSec);
//websAspDefine(T("getCurrentTimeASP"), getCurrentTimeASP);
//websAspDefine(T("getCurrentDateASP"), getCurrentDateASP);//Gordon added
websAspDefine(T("getSystemTime"), getSystemTime);//Gordon added 20090203
websAspDefine(T("getSystemDate"), getSystemDate);//Gordon added 20090203
websAspDefine(T("loglist"), loglist);//Gordon added
websFormDefine(T("DDNS"), DDNS);
websAspDefine(T("getMemLeftASP"), getMemLeftASP);
websAspDefine(T("getMemTotalASP"), getMemTotalASP);
websAspDefine(T("GetPortIfBytesPerSecASP"), GetPortIfBytesPerSecASP);
websAspDefine(T("getPortsStatistics"), getPortsStatistics);
// Tommy, Add WLAN Statistics, 2009/2/4 09:23
#if 1
#if 0
websAspDefine(T("getWLANRxByteASP"), getWLANRxByteASP);
websAspDefine(T("getWLANTxByteASP"), getWLANTxByteASP);
websAspDefine(T("getWLANRxPacketASP"), getWLANRxPacketASP);
websAspDefine(T("getWLANTxPacketASP"), getWLANTxPacketASP);
websAspDefine(T("getWLAN1RxByteASP"), getWLAN1RxByteASP);
websAspDefine(T("getWLAN1TxByteASP"), getWLAN1TxByteASP);
websAspDefine(T("getWLAN1RxPacketASP"), getWLAN1RxPacketASP);
websAspDefine(T("getWLAN1TxPacketASP"), getWLAN1TxPacketASP);
websAspDefine(T("getWLANSSID"), getWLANSSID);
websAspDefine(T("getWLANSSIDEnable"), getWLANSSIDEnable);
#endif
websAspDefine(T("getWANLinkStatus"), getWANLinkStatus);
websAspDefine(T("getLANLinkStatus"), getLANLinkStatus);
websAspDefine(T("getWANUpTime"), getWANUpTime);
websAspDefine(T("getLANUpTime"), getLANUpTime);
websAspDefine(T("getWLANLinkStatus"), getWLANLinkStatus);
//Added by Andy Yu in 2013/07/17: Main_SSID, Channel_Select_Way, Wireless_Mode
websAspDefine(T("getWLANMainSSID"), getWLANMainSSID);
websAspDefine(T("getWLAN5GMainSSID"), getWLAN5GMainSSID);
websAspDefine(T("getWLANChannelSelectWay"), getWLANChannelSelectWay);
websAspDefine(T("getWLAN5GChannelSelectWay"), getWLAN5GChannelSelectWay);
websAspDefine(T("getWLANWirelessMode"), getWLANWirelessMode);
websAspDefine(T("getWLAN5GWirelessMode"), getWLAN5GWirelessMode);
websAspDefine(T("getWLAN5GLinkStatus"), getWLAN5GLinkStatus);
websAspDefine(T("getWLANLinkRate"), getWLANLinkRate);
websAspDefine(T("getWLAN5GLinkRate"), getWLAN5GLinkRate);
websAspDefine(T("getWLANUpTime"), getWLANUpTime);
websAspDefine(T("GetWLANIfBytesPerSecASP"), GetWLANIfBytesPerSecASP);
websAspDefine(T("getWLANStatistics"), getWLANStatistics);
#endif
// Tommy, Add WAN/LAN/WLAN Collisions field, 2009/2/4 09:23
#if 0
websAspDefine(T("getWANCollsASP"), getWANCollsASP);
websAspDefine(T("getLANCollsASP"), getLANCollsASP);
websAspDefine(T("getWLANCollsASP"), getWLANCollsASP);
websAspDefine(T("getWLAN1CollsASP"), getWLAN1CollsASP);
#endif
websAspDefine(T("getAllNICStatisticASP"), getAllNICStatisticASP);
websAspDefine(T("showSystemCommandASP"), showSystemCommandASP);
websFormDefine(T("SystemCommand"), SystemCommand);
websFormDefine(T("LoadDefaultSettings"), LoadDefaultSettings);
websFormDefine(T("systemrebooting"), systemrebooting);//Gordon added
websFormDefine(T("clearlog"), clearlog);
websFormDefine(T("loglist"), loglist);//Gordon added
#if 1//Arthur Chow 2008-12-16: For login.asp/login_fail.asp
websFormDefine(T("web_login"), web_login);
websFormDefine(T("setSysPass"), setSysPass);
websFormDefine(T("setSysPassEasy"), setSysPassEasy);
websFormDefine(T("setSysPassLogin"), setSysPassLogin);
websFormDefine(T("maintenance_general"), maintenance_general);
#endif
#if 1//Arthur Chow 2009-02-04: For detecting/checking wan type
websAspDefine(T("detectEthernetWanType"), detectEthernetWanType);
websAspDefine(T("checkEthernetWanType"), checkEthernetWanType);
websAspDefine(T("set_language"), set_language);
#endif
#if 1//Arthur Chow 2009-02-09: For get Yahoo Weather
websAspDefine(T("detectWeather"), detectWeather);
websAspDefine(T("checkWeather"), checkWeather);
#endif
#if 1//Arthur Chow 2009-03-02: For getWebMessage
websAspDefine(T("getWebMessage"), getWebMessage);
websAspDefine(T("getWebMessageFlag"), getWebMessageFlag);
#endif
websAspDefine(T("checkAutoUploadFirmware"), checkAutoUploadFirmware);
websAspDefine(T("kill_wget"), kill_wget);
// Add for 3G +++++++++++++++
websAspDefine(T("get3GSetting"), get3GSetting);
websAspDefine(T("getSIMstatus"), getSIMstatus);
websAspDefine(T("getWan3GIp"), getWan3GIp);
websAspDefine(T("getWan3GNetmask"), getWan3GNetmask);
websAspDefine(T("getWan3GDHCP"), getWan3GDHCP);
websAspDefine(T("getWAN3GLinkStatus"), getWAN3GLinkStatus);
websAspDefine(T("get3GConnStatus"), get3GConnStatus);
websAspDefine(T("get3GISP"), get3GISP);
websAspDefine(T("getWan3GIp"), getWan3GIp);
websAspDefine(T("get3GSignalStrength"), get3GSignalStrength);
websAspDefine(T("get3GConnConnUpTime"), get3GConnConnUpTime);
websAspDefine(T("get3GManufacturer"), get3GManufacturer);
websAspDefine(T("get3GModel"), get3GModel);
websAspDefine(T("get3GFW"), get3GFW);
websAspDefine(T("get3GIMEI"), get3GIMEI);
websAspDefine(T("getSIMIMEI"), getSIMIMEI);
// Add for 3G ---------------
// Add for IPv6 +++++++++++++++
websAspDefine(T("getIPv6ConnType"), getIPv6ConnType);
websAspDefine(T("getIPv6LanAddr"), getIPv6LanAddr);
websAspDefine(T("getIPv6StaticDns"), getIPv6StaticDns);
websAspDefine(T("getIPv6DHCPDns"), getIPv6DHCPDns);
websAspDefine(T("getIPv6DhcpWanAddr"), getIPv6DhcpWanAddr);
websAspDefine(T("getIPv6DhcpWanDateway"), getIPv6DhcpWanDateway);
// Add for IPv6 ---------------
formDefineWPS();
}
| gpl-2.0 |
FPLD/project0 | vendor/magento/module-catalog/Block/Adminhtml/Product/Edit/Action/Attribute/Tab/Attributes.php | 5430 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
// @codingStandardsIgnoreFile
/**
* Adminhtml catalog product edit action attributes update tab block
*
* @author Magento Core Team <[email protected]>
*/
namespace Magento\Catalog\Block\Adminhtml\Product\Edit\Action\Attribute\Tab;
use Magento\Framework\Data\Form\Element\AbstractElement;
/**
* @SuppressWarnings(PHPMD.DepthOfInheritance)
*/
class Attributes extends \Magento\Catalog\Block\Adminhtml\Form implements
\Magento\Backend\Block\Widget\Tab\TabInterface
{
/**
* @var \Magento\Catalog\Model\ProductFactory
*/
protected $_productFactory;
/**
* @var \Magento\Catalog\Helper\Product\Edit\Action\Attribute
*/
protected $_attributeAction;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param \Magento\Framework\Data\FormFactory $formFactory
* @param \Magento\Catalog\Model\ProductFactory $productFactory
* @param \Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Catalog\Model\ProductFactory $productFactory,
\Magento\Catalog\Helper\Product\Edit\Action\Attribute $attributeAction,
array $data = []
) {
$this->_attributeAction = $attributeAction;
$this->_productFactory = $productFactory;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* @return void
*/
protected function _construct()
{
parent::_construct();
$this->setShowGlobalIcon(true);
}
/**
* @return void
*/
protected function _prepareForm()
{
$this->setFormExcludedFieldList(
[
'category_ids',
'gallery',
'image',
'media_gallery',
'quantity_and_stock_status',
'tier_price',
]
);
$this->_eventManager->dispatch(
'adminhtml_catalog_product_form_prepare_excluded_field_list',
['object' => $this]
);
/** @var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$fieldset = $form->addFieldset('fields', ['legend' => __('Attributes')]);
$attributes = $this->getAttributes();
/**
* Initialize product object as form property
* for using it in elements generation
*/
$form->setDataObject($this->_productFactory->create());
$this->_setFieldset($attributes, $fieldset, $this->getFormExcludedFieldList());
$form->setFieldNameSuffix('attributes');
$this->setForm($form);
}
/**
* Retrieve attributes for product mass update
*
* @return \Magento\Framework\DataObject[]
*/
public function getAttributes()
{
return $this->_attributeAction->getAttributes()->getItems();
}
/**
* Additional element types for product attributes
*
* @return array
*/
protected function _getAdditionalElementTypes()
{
return [
'price' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Price',
'weight' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Weight',
'image' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Image',
'boolean' => 'Magento\Catalog\Block\Adminhtml\Product\Helper\Form\Boolean'
];
}
/**
* Custom additional element html
*
* @param AbstractElement $element
* @return string
*/
protected function _getAdditionalElementHtml($element)
{
// Add name attribute to checkboxes that correspond to multiselect elements
$nameAttributeHtml = $element->getExtType() === 'multiple' ? 'name="' . $element->getId() . '_checkbox"' : '';
$elementId = $element->getId();
$dataAttribute = "data-disable='{$elementId}'";
$dataCheckboxName = "toggle_" . "{$elementId}";
$checkboxLabel = __('Change');
$html = <<<HTML
<span class="attribute-change-checkbox">
<input type="checkbox" id="$dataCheckboxName" name="$dataCheckboxName" class="checkbox" $nameAttributeHtml onclick="toogleFieldEditMode(this, '{$elementId}')" $dataAttribute />
<label class="label" for="$dataCheckboxName">
{$checkboxLabel}
</label>
</span>
HTML;
if ($elementId === 'weight') {
$html .= <<<HTML
<script>require(['Magento_Catalog/js/product/weight-handler'], function (weightHandle) {
weightHandle.hideWeightSwitcher();
});</script>
HTML;
}
return $html;
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabLabel()
{
return __('Attributes');
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabTitle()
{
return __('Attributes');
}
/**
* @return bool
*/
public function canShowTab()
{
return true;
}
/**
* @return bool
*/
public function isHidden()
{
return false;
}
}
| gpl-2.0 |
SuriyaaKudoIsc/wikia-app-test | extensions/SemanticWebBrowser/lib/EasyRdf/Serialiser/Rapper.php | 5338 | <?php
/**
* EasyRdf
*
* LICENSE
*
* Copyright (c) 2009-2010 Nicholas J Humfrey. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author 'Nicholas J Humfrey" may be used to endorse or
* promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2010 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
* @version $Id: Rapper.php 98993 2011-10-05 12:20:17Z bkaempgen $
*/
/**
* Class to serialise an EasyRdf_Graph to RDF
* using the 'rapper' command line tool.
*
* Note: the built-in N-Triples serialiser is used to pass data to Rapper.
*
* @package EasyRdf
* @copyright Copyright (c) 2009-2010 Nicholas J Humfrey
* @license http://www.opensource.org/licenses/bsd-license.php
*/
class EasyRdf_Serialiser_Rapper extends EasyRdf_Serialiser_Ntriples
{
private $_rapperCmd = null;
/**
* Constructor
*
* @param string $rapperCmd Optional path to the rapper command to use.
* @return object EasyRdf_Serialiser_Rapper
*/
public function __construct($rapperCmd='rapper')
{
exec("which ".escapeshellarg($rapperCmd), $output, $retval);
if ($retval == 0) {
$this->_rapperCmd = $rapperCmd;
} else {
throw new EasyRdf_Exception(
"The command '$rapperCmd' is not available on this system."
);
}
}
/**
* Serialise an EasyRdf_Graph to the RDF format of choice.
*
* @param object EasyRdf_Graph $graph An EasyRdf_Graph object.
* @param string $format The name of the format to convert to.
* @return string The RDF in the new desired format.
*/
public function serialise($graph, $format)
{
parent::checkSerialiseParams($graph, $format);
$ntriples = parent::serialise($graph, 'ntriples');
// Open a pipe to the rapper command
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
// Hack to produce more concise RDF/XML
if ($format == 'rdfxml') $format = 'rdfxml-abbrev';
$process = proc_open(
escapeshellcmd($this->_rapperCmd).
" --quiet ".
" --input ntriples ".
" --output " . escapeshellarg($format).
" - ". 'unknown://', # FIXME: how can this be improved?
$descriptorspec, $pipes, '/tmp', null
);
if (is_resource($process)) {
// $pipes now looks like this:
// 0 => writeable handle connected to child stdin
// 1 => readable handle connected to child stdout
// 2 => readable handle connected to child stderr
fwrite($pipes[0], $ntriples);
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[2]);
// It is important that you close any pipes before calling
// proc_close in order to avoid a deadlock
$returnValue = proc_close($process);
if ($returnValue) {
throw new EasyRdf_Exception(
"Failed to convert RDF: ".$error
);
}
} else {
throw new EasyRdf_Exception(
"Failed to execute rapper command."
);
}
return $output;
}
}
// FIXME: do this automatically
EasyRdf_Format::register('dot', 'Graphviz');
EasyRdf_Format::register('json-triples', 'RDF/JSON Triples');
EasyRdf_Format::registerSerialiser('dot', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('json-triples', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('rdfxml', 'EasyRdf_Serialiser_Rapper');
EasyRdf_Format::registerSerialiser('turtle', 'EasyRdf_Serialiser_Rapper');
| gpl-2.0 |
geany/geany | scintilla/src/CellBuffer.h | 8348 | // Scintilla source code edit control
/** @file CellBuffer.h
** Manages the text of the document.
**/
// Copyright 1998-2004 by Neil Hodgson <[email protected]>
// The License.txt file describes the conditions under which this software may be distributed.
#ifndef CELLBUFFER_H
#define CELLBUFFER_H
namespace Scintilla::Internal {
// Interface to per-line data that wants to see each line insertion and deletion
class PerLine {
public:
virtual ~PerLine() {}
virtual void Init()=0;
virtual void InsertLine(Sci::Line line)=0;
virtual void InsertLines(Sci::Line line, Sci::Line lines) = 0;
virtual void RemoveLine(Sci::Line line)=0;
};
/**
* The line vector contains information about each of the lines in a cell buffer.
*/
class ILineVector;
enum class ActionType { insert, remove, start, container };
/**
* Actions are used to store all the information required to perform one undo/redo step.
*/
class Action {
public:
ActionType at;
Sci::Position position;
std::unique_ptr<char[]> data;
Sci::Position lenData;
bool mayCoalesce;
Action() noexcept;
// Deleted so Action objects can not be copied.
Action(const Action &other) = delete;
Action &operator=(const Action &other) = delete;
Action &operator=(const Action &&other) = delete;
// Move constructor allows vector to be resized without reallocating.
Action(Action &&other) noexcept = default;
~Action();
void Create(ActionType at_, Sci::Position position_=0, const char *data_=nullptr, Sci::Position lenData_=0, bool mayCoalesce_=true);
void Clear() noexcept;
};
/**
*
*/
class UndoHistory {
std::vector<Action> actions;
int maxAction;
int currentAction;
int undoSequenceDepth;
int savePoint;
int tentativePoint;
void EnsureUndoRoom();
public:
UndoHistory();
// Deleted so UndoHistory objects can not be copied.
UndoHistory(const UndoHistory &) = delete;
UndoHistory(UndoHistory &&) = delete;
void operator=(const UndoHistory &) = delete;
void operator=(UndoHistory &&) = delete;
~UndoHistory();
const char *AppendAction(ActionType at, Sci::Position position, const char *data, Sci::Position lengthData, bool &startSequence, bool mayCoalesce=true);
void BeginUndoAction();
void EndUndoAction();
void DropUndoSequence();
void DeleteUndoHistory();
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint() noexcept;
bool IsSavePoint() const noexcept;
// Tentative actions are used for input composition so that it can be undone cleanly
void TentativeStart();
void TentativeCommit();
bool TentativeActive() const noexcept;
int TentativeSteps() noexcept;
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo() const noexcept;
int StartUndo();
const Action &GetUndoStep() const;
void CompletedUndoStep();
bool CanRedo() const noexcept;
int StartRedo();
const Action &GetRedoStep() const;
void CompletedRedoStep();
};
struct SplitView {
const char *segment1 = nullptr;
size_t length1 = 0;
const char *segment2 = nullptr;
size_t length = 0;
bool operator==(const SplitView &other) const noexcept {
return segment1 == other.segment1 && length1 == other.length1 &&
segment2 == other.segment2 && length == other.length;
}
bool operator!=(const SplitView &other) const noexcept {
return !(*this == other);
}
char CharAt(size_t position) const noexcept {
if (position < length1) {
return segment1[position];
}
if (position < length) {
return segment2[position];
}
return 0;
}
};
/**
* Holder for an expandable array of characters that supports undo and line markers.
* Based on article "Data Structures in a Bit-Mapped Text Editor"
* by Wilfred J. Hansen, Byte January 1987, page 183.
*/
class CellBuffer {
private:
bool hasStyles;
bool largeDocument;
SplitVector<char> substance;
SplitVector<char> style;
bool readOnly;
bool utf8Substance;
Scintilla::LineEndType utf8LineEnds;
bool collectingUndo;
UndoHistory uh;
std::unique_ptr<ILineVector> plv;
bool UTF8LineEndOverlaps(Sci::Position position) const noexcept;
bool UTF8IsCharacterBoundary(Sci::Position position) const;
void ResetLineEnds();
void RecalculateIndexLineStarts(Sci::Line lineFirst, Sci::Line lineLast);
bool MaintainingLineCharacterIndex() const noexcept;
/// Actions without undo
void BasicInsertString(Sci::Position position, const char *s, Sci::Position insertLength);
void BasicDeleteChars(Sci::Position position, Sci::Position deleteLength);
public:
CellBuffer(bool hasStyles_, bool largeDocument_);
// Deleted so CellBuffer objects can not be copied.
CellBuffer(const CellBuffer &) = delete;
CellBuffer(CellBuffer &&) = delete;
void operator=(const CellBuffer &) = delete;
void operator=(CellBuffer &&) = delete;
~CellBuffer();
/// Retrieving positions outside the range of the buffer works and returns 0
char CharAt(Sci::Position position) const noexcept;
unsigned char UCharAt(Sci::Position position) const noexcept;
void GetCharRange(char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
char StyleAt(Sci::Position position) const noexcept;
void GetStyleRange(unsigned char *buffer, Sci::Position position, Sci::Position lengthRetrieve) const;
const char *BufferPointer();
const char *RangePointer(Sci::Position position, Sci::Position rangeLength) noexcept;
Sci::Position GapPosition() const noexcept;
SplitView AllView() const noexcept;
Sci::Position Length() const noexcept;
void Allocate(Sci::Position newSize);
void SetUTF8Substance(bool utf8Substance_) noexcept;
Scintilla::LineEndType GetLineEndTypes() const noexcept { return utf8LineEnds; }
void SetLineEndTypes(Scintilla::LineEndType utf8LineEnds_);
bool ContainsLineEnd(const char *s, Sci::Position length) const noexcept;
void SetPerLine(PerLine *pl) noexcept;
Scintilla::LineCharacterIndexType LineCharacterIndex() const noexcept;
void AllocateLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex);
void ReleaseLineCharacterIndex(Scintilla::LineCharacterIndexType lineCharacterIndex);
Sci::Line Lines() const noexcept;
void AllocateLines(Sci::Line lines);
Sci::Position LineStart(Sci::Line line) const noexcept;
Sci::Position IndexLineStart(Sci::Line line, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept;
Sci::Line LineFromPosition(Sci::Position pos) const noexcept;
Sci::Line LineFromPositionIndex(Sci::Position pos, Scintilla::LineCharacterIndexType lineCharacterIndex) const noexcept;
void InsertLine(Sci::Line line, Sci::Position position, bool lineStart);
void RemoveLine(Sci::Line line);
const char *InsertString(Sci::Position position, const char *s, Sci::Position insertLength, bool &startSequence);
/// Setting styles for positions outside the range of the buffer is safe and has no effect.
/// @return true if the style of a character is changed.
bool SetStyleAt(Sci::Position position, char styleValue) noexcept;
bool SetStyleFor(Sci::Position position, Sci::Position lengthStyle, char styleValue) noexcept;
const char *DeleteChars(Sci::Position position, Sci::Position deleteLength, bool &startSequence);
bool IsReadOnly() const noexcept;
void SetReadOnly(bool set) noexcept;
bool IsLarge() const noexcept;
bool HasStyles() const noexcept;
/// The save point is a marker in the undo stack where the container has stated that
/// the buffer was saved. Undo and redo can move over the save point.
void SetSavePoint();
bool IsSavePoint() const noexcept;
void TentativeStart();
void TentativeCommit();
bool TentativeActive() const noexcept;
int TentativeSteps() noexcept;
bool SetUndoCollection(bool collectUndo);
bool IsCollectingUndo() const noexcept;
void BeginUndoAction();
void EndUndoAction();
void AddUndoAction(Sci::Position token, bool mayCoalesce);
void DeleteUndoHistory();
/// To perform an undo, StartUndo is called to retrieve the number of steps, then UndoStep is
/// called that many times. Similarly for redo.
bool CanUndo() const noexcept;
int StartUndo();
const Action &GetUndoStep() const;
void PerformUndoStep();
bool CanRedo() const noexcept;
int StartRedo();
const Action &GetRedoStep() const;
void PerformRedoStep();
};
}
#endif
| gpl-2.0 |
NicoleRobin/glibc | sysdeps/sparc/sparc32/sem_post.c | 2404 | /* sem_post -- post to a POSIX semaphore. Generic futex-using version.
Copyright (C) 2003-2017 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Contributed by Jakub Jelinek <[email protected]>, 2003.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
#include <atomic.h>
#include <errno.h>
#include <sysdep.h>
#include <lowlevellock.h>
#include <internaltypes.h>
#include <semaphore.h>
#include <futex-internal.h>
#include <shlib-compat.h>
/* See sem_wait for an explanation of the algorithm. */
int
__new_sem_post (sem_t *sem)
{
struct new_sem *isem = (struct new_sem *) sem;
int private = isem->private;
unsigned int v;
__sparc32_atomic_do_lock24 (&isem->pad);
v = isem->value;
if ((v >> SEM_VALUE_SHIFT) == SEM_VALUE_MAX)
{
__sparc32_atomic_do_unlock24 (&isem->pad);
__set_errno (EOVERFLOW);
return -1;
}
isem->value = v + (1 << SEM_VALUE_SHIFT);
__sparc32_atomic_do_unlock24 (&isem->pad);
if ((v & SEM_NWAITERS_MASK) != 0)
futex_wake (&isem->value, 1, private);
return 0;
}
versioned_symbol (libpthread, __new_sem_post, sem_post, GLIBC_2_1);
#if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
int
attribute_compat_text_section
__old_sem_post (sem_t *sem)
{
int *futex = (int *) sem;
/* We must need to synchronize with consumers of this token, so the atomic
increment must have release MO semantics. */
atomic_write_barrier ();
(void) atomic_increment_val (futex);
/* We always have to assume it is a shared semaphore. */
int err = lll_futex_wake (futex, 1, LLL_SHARED);
if (__builtin_expect (err, 0) < 0)
{
__set_errno (-err);
return -1;
}
return 0;
}
compat_symbol (libpthread, __old_sem_post, sem_post, GLIBC_2_0);
#endif
| gpl-2.0 |
cnvogelg/fs-uae | dist/windows/clib.py | 323 | #!/usr/bin/env python3
import os
import sys
import subprocess
if os.getenv("MSYSTEM") == "MINGW32":
mingw_dir = "/mingw32"
elif os.getenv("MSYSTEM") == "MINGW64":
mingw_dir = "/mingw64"
p = subprocess.Popen([
"sh", "-c",
"cp {}/bin/{} {}".format(mingw_dir, sys.argv[1], sys.argv[2])])
sys.exit(p.wait())
| gpl-2.0 |
rhuitl/uClinux | user/net-snmp/include/net-snmp/agent/watcher.h | 4857 | /*
* watcher.h
*/
#ifndef NETSNMP_WATCHER_H
#define NETSNMP_WATCHER_H
#ifdef __cplusplus
extern "C" {
#endif
/** @ingroup watcher
* @{
*/
/*
* if handler flag has this bit set, the timestamp will be
* treated as a pointer to the timestamp. If this bit is
* not set (the default), the timestamp is a struct timeval
* that must be compared to the agent starttime.
*/
#define NETSNMP_WATCHER_DIRECT MIB_HANDLER_CUSTOM1
/** The size of the watched object is constant.
* @hideinitializer
*/
#define WATCHER_FIXED_SIZE 0x01
/** The maximum size of the watched object is stored in max_size.
* If WATCHER_SIZE_STRLEN is set then it is supposed that max_size + 1
* bytes could be stored in the buffer.
* @hideinitializer
*/
#define WATCHER_MAX_SIZE 0x02
/** If set then the variable data_size_p points to is supposed to hold the
* current size of the watched object and will be updated on writes.
* @hideinitializer
* @since Net-SNMP 5.5
*/
#define WATCHER_SIZE_IS_PTR 0x04
/** If set then data is suppposed to be a zero-terminated character array
* and both data_size and data_size_p are ignored. Additionally \\0 is a
* forbidden character in the data set.
* @hideinitializer
* @since Net-SNMP 5.5
*/
#define WATCHER_SIZE_STRLEN 0x08
typedef struct netsnmp_watcher_info_s {
void *data;
size_t data_size;
size_t max_size;
u_char type;
int flags;
size_t *data_size_p;
} netsnmp_watcher_info;
/** @} */
int netsnmp_register_watched_instance( netsnmp_handler_registration *reginfo,
netsnmp_watcher_info *winfo);
int netsnmp_register_watched_scalar( netsnmp_handler_registration *reginfo,
netsnmp_watcher_info *winfo);
int netsnmp_register_watched_timestamp(netsnmp_handler_registration *reginfo,
marker_t timestamp);
int netsnmp_watched_timestamp_register(netsnmp_mib_handler *whandler,
netsnmp_handler_registration *reginfo,
marker_t timestamp);
int netsnmp_register_watched_spinlock(netsnmp_handler_registration *reginfo,
int *spinlock);
/*
* Convenience registration calls
*/
int netsnmp_register_ulong_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
u_long * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_read_only_ulong_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
u_long * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_long_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
long * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_read_only_long_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
long * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_int_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
int * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_read_only_int_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
int * it,
Netsnmp_Node_Handler * subhandler);
int netsnmp_register_read_only_counter32_scalar(const char *name,
const oid * reg_oid, size_t reg_oid_len,
u_long * it,
Netsnmp_Node_Handler * subhandler);
#define WATCHER_HANDLER_NAME "watcher"
netsnmp_mib_handler *netsnmp_get_watcher_handler(void);
netsnmp_watcher_info *
netsnmp_init_watcher_info(netsnmp_watcher_info *, void *, size_t, u_char, int);
netsnmp_watcher_info *
netsnmp_init_watcher_info6(netsnmp_watcher_info *,
void *, size_t, u_char, int, size_t, size_t*);
netsnmp_watcher_info *
netsnmp_create_watcher_info(void *, size_t, u_char, int);
netsnmp_watcher_info *
netsnmp_create_watcher_info6(void *, size_t, u_char, int, size_t, size_t*);
Netsnmp_Node_Handler netsnmp_watcher_helper_handler;
netsnmp_mib_handler *netsnmp_get_watched_timestamp_handler(void);
Netsnmp_Node_Handler netsnmp_watched_timestamp_handler;
netsnmp_mib_handler *netsnmp_get_watched_spinlock_handler(void);
Netsnmp_Node_Handler netsnmp_watched_spinlock_handler;
#ifdef __cplusplus
}
#endif
#endif /** NETSNMP_WATCHER_H */
| gpl-2.0 |
aebert1/BigTransport | build/tmp/recompileMc/sources/net/minecraft/util/text/ITextComponent.java | 12605 | package net.minecraft.util.text;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.util.EnumTypeAdapterFactory;
import net.minecraft.util.JsonUtils;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public interface ITextComponent extends Iterable<ITextComponent>
{
ITextComponent setChatStyle(Style style);
Style getChatStyle();
/**
* Appends the given text to the end of this component.
*/
ITextComponent appendText(String text);
/**
* Appends the given component to the end of this one.
*/
ITextComponent appendSibling(ITextComponent component);
/**
* Gets the text of this component, without any special formatting codes added, for chat. TODO: why is this two
* different methods?
*/
String getUnformattedTextForChat();
/**
* Get the text of this component, <em>and all child components</em>, with all special formatting codes removed.
*/
String getUnformattedText();
/**
* Gets the text of this component, with formatting codes added for rendering.
*/
String getFormattedText();
List<ITextComponent> getSiblings();
/**
* Creates a copy of this component. Almost a deep copy, except the style is shallow-copied.
*/
ITextComponent createCopy();
public static class Serializer implements JsonDeserializer<ITextComponent>, JsonSerializer<ITextComponent>
{
private static final Gson GSON;
public ITextComponent deserialize(JsonElement p_deserialize_1_, Type p_deserialize_2_, JsonDeserializationContext p_deserialize_3_) throws JsonParseException
{
if (p_deserialize_1_.isJsonPrimitive())
{
return new TextComponentString(p_deserialize_1_.getAsString());
}
else if (!p_deserialize_1_.isJsonObject())
{
if (p_deserialize_1_.isJsonArray())
{
JsonArray jsonarray1 = p_deserialize_1_.getAsJsonArray();
ITextComponent itextcomponent1 = null;
for (JsonElement jsonelement : jsonarray1)
{
ITextComponent itextcomponent2 = this.deserialize(jsonelement, jsonelement.getClass(), p_deserialize_3_);
if (itextcomponent1 == null)
{
itextcomponent1 = itextcomponent2;
}
else
{
itextcomponent1.appendSibling(itextcomponent2);
}
}
return itextcomponent1;
}
else
{
throw new JsonParseException("Don\'t know how to turn " + p_deserialize_1_.toString() + " into a Component");
}
}
else
{
JsonObject jsonobject = p_deserialize_1_.getAsJsonObject();
ITextComponent itextcomponent;
if (jsonobject.has("text"))
{
itextcomponent = new TextComponentString(jsonobject.get("text").getAsString());
}
else if (jsonobject.has("translate"))
{
String s = jsonobject.get("translate").getAsString();
if (jsonobject.has("with"))
{
JsonArray jsonarray = jsonobject.getAsJsonArray("with");
Object[] aobject = new Object[jsonarray.size()];
for (int i = 0; i < aobject.length; ++i)
{
aobject[i] = this.deserialize(jsonarray.get(i), p_deserialize_2_, p_deserialize_3_);
if (aobject[i] instanceof TextComponentString)
{
TextComponentString textcomponentstring = (TextComponentString)aobject[i];
if (textcomponentstring.getChatStyle().isEmpty() && textcomponentstring.getSiblings().isEmpty())
{
aobject[i] = textcomponentstring.getChatComponentText_TextValue();
}
}
}
itextcomponent = new TextComponentTranslation(s, aobject);
}
else
{
itextcomponent = new TextComponentTranslation(s, new Object[0]);
}
}
else if (jsonobject.has("score"))
{
JsonObject jsonobject1 = jsonobject.getAsJsonObject("score");
if (!jsonobject1.has("name") || !jsonobject1.has("objective"))
{
throw new JsonParseException("A score component needs a least a name and an objective");
}
itextcomponent = new TextComponentScore(JsonUtils.getString(jsonobject1, "name"), JsonUtils.getString(jsonobject1, "objective"));
if (jsonobject1.has("value"))
{
((TextComponentScore)itextcomponent).setValue(JsonUtils.getString(jsonobject1, "value"));
}
}
else
{
if (!jsonobject.has("selector"))
{
throw new JsonParseException("Don\'t know how to turn " + p_deserialize_1_.toString() + " into a Component");
}
itextcomponent = new TextComponentSelector(JsonUtils.getString(jsonobject, "selector"));
}
if (jsonobject.has("extra"))
{
JsonArray jsonarray2 = jsonobject.getAsJsonArray("extra");
if (jsonarray2.size() <= 0)
{
throw new JsonParseException("Unexpected empty array of components");
}
for (int j = 0; j < jsonarray2.size(); ++j)
{
itextcomponent.appendSibling(this.deserialize(jsonarray2.get(j), p_deserialize_2_, p_deserialize_3_));
}
}
itextcomponent.setChatStyle((Style)p_deserialize_3_.deserialize(p_deserialize_1_, Style.class));
return itextcomponent;
}
}
private void serializeChatStyle(Style style, JsonObject object, JsonSerializationContext ctx)
{
JsonElement jsonelement = ctx.serialize(style);
if (jsonelement.isJsonObject())
{
JsonObject jsonobject = (JsonObject)jsonelement;
for (Entry<String, JsonElement> entry : jsonobject.entrySet())
{
object.add((String)entry.getKey(), (JsonElement)entry.getValue());
}
}
}
public JsonElement serialize(ITextComponent p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
JsonObject jsonobject = new JsonObject();
if (!p_serialize_1_.getChatStyle().isEmpty())
{
this.serializeChatStyle(p_serialize_1_.getChatStyle(), jsonobject, p_serialize_3_);
}
if (!p_serialize_1_.getSiblings().isEmpty())
{
JsonArray jsonarray = new JsonArray();
for (ITextComponent itextcomponent : p_serialize_1_.getSiblings())
{
jsonarray.add(this.serialize((ITextComponent)itextcomponent, itextcomponent.getClass(), p_serialize_3_));
}
jsonobject.add("extra", jsonarray);
}
if (p_serialize_1_ instanceof TextComponentString)
{
jsonobject.addProperty("text", ((TextComponentString)p_serialize_1_).getChatComponentText_TextValue());
}
else if (p_serialize_1_ instanceof TextComponentTranslation)
{
TextComponentTranslation textcomponenttranslation = (TextComponentTranslation)p_serialize_1_;
jsonobject.addProperty("translate", textcomponenttranslation.getKey());
if (textcomponenttranslation.getFormatArgs() != null && textcomponenttranslation.getFormatArgs().length > 0)
{
JsonArray jsonarray1 = new JsonArray();
for (Object object : textcomponenttranslation.getFormatArgs())
{
if (object instanceof ITextComponent)
{
jsonarray1.add(this.serialize((ITextComponent)((ITextComponent)object), object.getClass(), p_serialize_3_));
}
else
{
jsonarray1.add(new JsonPrimitive(String.valueOf(object)));
}
}
jsonobject.add("with", jsonarray1);
}
}
else if (p_serialize_1_ instanceof TextComponentScore)
{
TextComponentScore textcomponentscore = (TextComponentScore)p_serialize_1_;
JsonObject jsonobject1 = new JsonObject();
jsonobject1.addProperty("name", textcomponentscore.getName());
jsonobject1.addProperty("objective", textcomponentscore.getObjective());
jsonobject1.addProperty("value", textcomponentscore.getUnformattedTextForChat());
jsonobject.add("score", jsonobject1);
}
else
{
if (!(p_serialize_1_ instanceof TextComponentSelector))
{
throw new IllegalArgumentException("Don\'t know how to serialize " + p_serialize_1_ + " as a Component");
}
TextComponentSelector textcomponentselector = (TextComponentSelector)p_serialize_1_;
jsonobject.addProperty("selector", textcomponentselector.getSelector());
}
return jsonobject;
}
public static String componentToJson(ITextComponent component)
{
return GSON.toJson((Object)component);
}
public static ITextComponent jsonToComponent(String json)
{
return (ITextComponent)JsonUtils.gsonDeserialize(GSON, json, ITextComponent.class, false);
}
public static ITextComponent fromJsonLenient(String json)
{
return (ITextComponent)JsonUtils.gsonDeserialize(GSON, json, ITextComponent.class, true);
}
static
{
GsonBuilder gsonbuilder = new GsonBuilder();
gsonbuilder.registerTypeHierarchyAdapter(ITextComponent.class, new ITextComponent.Serializer());
gsonbuilder.registerTypeHierarchyAdapter(Style.class, new Style.Serializer());
gsonbuilder.registerTypeAdapterFactory(new EnumTypeAdapterFactory());
GSON = gsonbuilder.create();
}
}
} | gpl-3.0 |
robert1978/CometVisu | source/class/cv/ui/structure/pure/Refresh.js | 1913 | /* Refresh.js
*
* copyright (c) 2010-2017, Christian Mayer and the CometVisu contributers.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
/**
* With the widget refresh, the visu is added a switch, which allows the visu to reload the displayed data.
*
* @author Christian Mayer
* @since 2014
*/
qx.Class.define('cv.ui.structure.pure.Refresh', {
extend: cv.ui.structure.AbstractWidget,
include: [cv.ui.common.Operate, cv.ui.common.HasAnimatedButton, cv.ui.common.BasicUpdate],
/*
******************************************************
PROPERTIES
******************************************************
*/
properties: {
sendValue: { check: "String", nullable: true }
},
/*
******************************************************
MEMBERS
******************************************************
*/
members: {
// overridden
_onDomReady: function() {
this.base(arguments);
this.defaultUpdate(undefined, this.getSendValue());
},
// overridden
_getInnerDomString: function () {
return '<div class="actor switchUnpressed"><div class="value">-</div></div>';
},
_action: function() {
cv.TemplateEngine.getInstance().visu.restart(true);
}
}
}); | gpl-3.0 |
dwoods/gn-maps | geonode/base/migrations/0001_initial.py | 25336 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ContactRole'
db.create_table('base_contactrole', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])),
('contact', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Profile'])),
('role', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['people.Role'])),
))
db.send_create_signal('base', ['ContactRole'])
# Adding unique constraint on 'ContactRole', fields ['contact', 'resource', 'role']
db.create_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id'])
# Adding model 'TopicCategory'
db.create_table('base_topiccategory', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('name', self.gf('django.db.models.fields.CharField')(max_length=50)),
('slug', self.gf('django.db.models.fields.SlugField')(max_length=50, db_index=True)),
('description', self.gf('django.db.models.fields.TextField')(blank=True)),
))
db.send_create_signal('base', ['TopicCategory'])
# Adding model 'Thumbnail'
db.create_table('base_thumbnail', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('thumb_file', self.gf('django.db.models.fields.files.FileField')(max_length=100)),
('thumb_spec', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('version', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=0, null=True)),
))
db.send_create_signal('base', ['Thumbnail'])
# Adding model 'ResourceBase'
db.create_table('base_resourcebase', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('uuid', self.gf('django.db.models.fields.CharField')(max_length=36)),
('owner', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'], null=True, blank=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('date', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('date_type', self.gf('django.db.models.fields.CharField')(default='publication', max_length=255)),
('edition', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('abstract', self.gf('django.db.models.fields.TextField')(blank=True)),
('purpose', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('maintenance_frequency', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('keywords_region', self.gf('django.db.models.fields.CharField')(default='USA', max_length=3)),
('constraints_use', self.gf('django.db.models.fields.CharField')(default='copyright', max_length=255)),
('constraints_other', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('spatial_representation_type', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True)),
('language', self.gf('django.db.models.fields.CharField')(default='eng', max_length=3)),
('category', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.TopicCategory'], null=True, blank=True)),
('temporal_extent_start', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('temporal_extent_end', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('supplemental_information', self.gf('django.db.models.fields.TextField')(default=u'No information provided')),
('distribution_url', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('distribution_description', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('data_quality_statement', self.gf('django.db.models.fields.TextField')(null=True, blank=True)),
('bbox_x0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_x1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_y0', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('bbox_y1', self.gf('django.db.models.fields.DecimalField')(null=True, max_digits=19, decimal_places=10, blank=True)),
('srid', self.gf('django.db.models.fields.CharField')(default='EPSG:4326', max_length=255)),
('csw_typename', self.gf('django.db.models.fields.CharField')(default='gmd:MD_Metadata', max_length=32)),
('csw_schema', self.gf('django.db.models.fields.CharField')(default='http://www.isotc211.org/2005/gmd', max_length=64)),
('csw_mdsource', self.gf('django.db.models.fields.CharField')(default='local', max_length=256)),
('csw_insert_date', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, null=True, blank=True)),
('csw_type', self.gf('django.db.models.fields.CharField')(default='dataset', max_length=32)),
('csw_anytext', self.gf('django.db.models.fields.TextField')(null=True)),
('csw_wkt_geometry', self.gf('django.db.models.fields.TextField')(default='SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))')),
('metadata_uploaded', self.gf('django.db.models.fields.BooleanField')(default=False)),
('metadata_xml', self.gf('django.db.models.fields.TextField')(default='<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>', null=True, blank=True)),
('thumbnail', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.Thumbnail'], null=True, blank=True)),
))
db.send_create_signal('base', ['ResourceBase'])
# Adding model 'Link'
db.create_table('base_link', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('resource', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['base.ResourceBase'])),
('extension', self.gf('django.db.models.fields.CharField')(max_length=255)),
('link_type', self.gf('django.db.models.fields.CharField')(max_length=255)),
('name', self.gf('django.db.models.fields.CharField')(max_length=255)),
('mime', self.gf('django.db.models.fields.CharField')(max_length=255)),
('url', self.gf('django.db.models.fields.TextField')(unique=True, max_length=1000)),
))
db.send_create_signal('base', ['Link'])
def backwards(self, orm):
# Removing unique constraint on 'ContactRole', fields ['contact', 'resource', 'role']
db.delete_unique('base_contactrole', ['contact_id', 'resource_id', 'role_id'])
# Deleting model 'ContactRole'
db.delete_table('base_contactrole')
# Deleting model 'TopicCategory'
db.delete_table('base_topiccategory')
# Deleting model 'Thumbnail'
db.delete_table('base_thumbnail')
# Deleting model 'ResourceBase'
db.delete_table('base_resourcebase')
# Deleting model 'Link'
db.delete_table('base_link')
models = {
'actstream.action': {
'Meta': {'ordering': "('-timestamp',)", 'object_name': 'Action'},
'action_object_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'action_object'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'action_object_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'actor_content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'actor'", 'to': "orm['contenttypes.ContentType']"}),
'actor_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'data': ('jsonfield.fields.JSONField', [], {'null': 'True', 'blank': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'target_content_type': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'target'", 'null': 'True', 'to': "orm['contenttypes.ContentType']"}),
'target_object_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'timestamp': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 384488)'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388268)'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 4, 15, 4, 16, 51, 388203)'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'relationships': ('django.db.models.fields.related.ManyToManyField', [], {'related_name': "'related_to'", 'symmetrical': 'False', 'through': "orm['relationships.Relationship']", 'to': "orm['auth.User']"}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'base.contactrole': {
'Meta': {'unique_together': "(('contact', 'resource', 'role'),)", 'object_name': 'ContactRole'},
'contact': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Profile']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}),
'role': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['people.Role']"})
},
'base.link': {
'Meta': {'object_name': 'Link'},
'extension': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'link_type': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'mime': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'resource': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.ResourceBase']"}),
'url': ('django.db.models.fields.TextField', [], {'unique': 'True', 'max_length': '1000'})
},
'base.resourcebase': {
'Meta': {'object_name': 'ResourceBase'},
'abstract': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'bbox_x0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_x1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_y0': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'bbox_y1': ('django.db.models.fields.DecimalField', [], {'null': 'True', 'max_digits': '19', 'decimal_places': '10', 'blank': 'True'}),
'category': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.TopicCategory']", 'null': 'True', 'blank': 'True'}),
'constraints_other': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'constraints_use': ('django.db.models.fields.CharField', [], {'default': "'copyright'", 'max_length': '255'}),
'contacts': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['people.Profile']", 'through': "orm['base.ContactRole']", 'symmetrical': 'False'}),
'csw_anytext': ('django.db.models.fields.TextField', [], {'null': 'True'}),
'csw_insert_date': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'blank': 'True'}),
'csw_mdsource': ('django.db.models.fields.CharField', [], {'default': "'local'", 'max_length': '256'}),
'csw_schema': ('django.db.models.fields.CharField', [], {'default': "'http://www.isotc211.org/2005/gmd'", 'max_length': '64'}),
'csw_type': ('django.db.models.fields.CharField', [], {'default': "'dataset'", 'max_length': '32'}),
'csw_typename': ('django.db.models.fields.CharField', [], {'default': "'gmd:MD_Metadata'", 'max_length': '32'}),
'csw_wkt_geometry': ('django.db.models.fields.TextField', [], {'default': "'SRID=4326;POLYGON((-180 -90,-180 90,180 90,180 -90,-180 -90))'"}),
'data_quality_statement': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'date_type': ('django.db.models.fields.CharField', [], {'default': "'publication'", 'max_length': '255'}),
'distribution_description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'distribution_url': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'edition': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'keywords_region': ('django.db.models.fields.CharField', [], {'default': "'USA'", 'max_length': '3'}),
'language': ('django.db.models.fields.CharField', [], {'default': "'eng'", 'max_length': '3'}),
'maintenance_frequency': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'metadata_uploaded': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'metadata_xml': ('django.db.models.fields.TextField', [], {'default': '\'<gmd:MD_Metadata xmlns:gmd="http://www.isotc211.org/2005/gmd"/>\'', 'null': 'True', 'blank': 'True'}),
'owner': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'null': 'True', 'blank': 'True'}),
'purpose': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'spatial_representation_type': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'srid': ('django.db.models.fields.CharField', [], {'default': "'EPSG:4326'", 'max_length': '255'}),
'supplemental_information': ('django.db.models.fields.TextField', [], {'default': "u'No information provided'"}),
'temporal_extent_end': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'temporal_extent_start': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'thumbnail': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['base.Thumbnail']", 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'uuid': ('django.db.models.fields.CharField', [], {'max_length': '36'})
},
'base.thumbnail': {
'Meta': {'object_name': 'Thumbnail'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'thumb_file': ('django.db.models.fields.files.FileField', [], {'max_length': '100'}),
'thumb_spec': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'version': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '0', 'null': 'True'})
},
'base.topiccategory': {
'Meta': {'ordering': "('name',)", 'object_name': 'TopicCategory'},
'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}),
'slug': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'db_index': 'True'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'people.profile': {
'Meta': {'object_name': 'Profile'},
'area': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True', 'blank': 'True'}),
'delivery': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'null': 'True', 'blank': 'True'}),
'fax': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'organization': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'position': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'profile': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'blank': 'True', 'related_name': "'profile'", 'unique': 'True', 'null': 'True', 'to': "orm['auth.User']"}),
'voice': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'zipcode': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'people.role': {
'Meta': {'object_name': 'Role'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'})
},
'relationships.relationship': {
'Meta': {'ordering': "('created',)", 'unique_together': "(('from_user', 'to_user', 'status', 'site'),)", 'object_name': 'Relationship'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'from_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'from_users'", 'to': "orm['auth.User']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'site': ('django.db.models.fields.related.ForeignKey', [], {'default': '1', 'related_name': "'relationships'", 'to': "orm['sites.Site']"}),
'status': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['relationships.RelationshipStatus']"}),
'to_user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'to_users'", 'to': "orm['auth.User']"}),
'weight': ('django.db.models.fields.FloatField', [], {'default': '1.0', 'null': 'True', 'blank': 'True'})
},
'relationships.relationshipstatus': {
'Meta': {'ordering': "('name',)", 'object_name': 'RelationshipStatus'},
'from_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'login_required': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'private': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'symmetrical_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'to_slug': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'verb': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'sites.site': {
'Meta': {'ordering': "('domain',)", 'object_name': 'Site', 'db_table': "'django_site'"},
'domain': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'taggit.tag': {
'Meta': {'object_name': 'Tag'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'slug': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '100', 'db_index': 'True'})
},
'taggit.taggeditem': {
'Meta': {'object_name': 'TaggedItem'},
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_tagged_items'", 'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'object_id': ('django.db.models.fields.IntegerField', [], {'db_index': 'True'}),
'tag': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'taggit_taggeditem_items'", 'to': "orm['taggit.Tag']"})
}
}
complete_apps = ['base']
| gpl-3.0 |
kyithar/Ski-Rental | include/betweenness_centrality.h | 1572 | /*
* ccnSim is a scalable chunk-level simulator for Content Centric
* Networks (CCN), that we developed in the context of ANR Connect
* (http://www.anr-connect.org/)
*
* People:
* Giuseppe Rossini (lead developer, mailto [email protected])
* Raffaele Chiocchetti (developer, mailto [email protected])
* Dario Rossi (occasional debugger, mailto [email protected])
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef BET_POLICY_H_
#define BET_POLICY_H_
#include "decision_policy.h"
//Betwenness centrality policy.
class Betweenness : public DecisionPolicy{
public:
Betweenness(double b):btw(b){;}//Store node betweenness
virtual bool data_to_cache(ccn_data *data_pkt){
bool decision = false;
//Store the chunk only if you are the node with the highest betweennees
if (data_pkt->getBtw()==btw)
decision = true;
return decision;
}
private:
double btw;//node betweenness
};
#endif
| gpl-3.0 |
JavaProphet/AvunaHTTPD-Java | src/org/avuna/httpd/mail/imap/command/IMAPCommandCreate.java | 1747 | /* Avuna HTTPD - General Server Applications Copyright (C) 2015 Maxwell Bruce This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.avuna.httpd.mail.imap.command;
import java.io.IOException;
import org.avuna.httpd.hosts.HostMail;
import org.avuna.httpd.mail.imap.IMAPCommand;
import org.avuna.httpd.mail.imap.IMAPWork;
import org.avuna.httpd.mail.mailbox.Mailbox;
public class IMAPCommandCreate extends IMAPCommand {
public IMAPCommandCreate(String comm, int minState, int maxState, HostMail host) {
super(comm, minState, maxState, host);
}
@Override
public void run(IMAPWork focus, String letters, String[] args) throws IOException {
if (args.length >= 1) {
String ms = args[0];
if (ms.startsWith("\"")) {
ms = ms.substring(1);
}
if (ms.endsWith("\"")) {
ms = ms.substring(0, ms.length() - 1);
}
if (focus.authUser.getMailbox(ms) != null) {
focus.writeLine(letters, "NO Mailbox Exists.");
}else {
focus.authUser.mailboxes.add(new Mailbox(focus.authUser, ms));
focus.writeLine(letters, "OK Mailbox created.");
}
}else {
focus.writeLine(letters, "BAD No mailbox.");
}
}
}
| gpl-3.0 |
zabubaev/dsploit | src/it/evilsocket/dsploit/gui/dialogs/ChoiceDialog.java | 2193 | /*
* This file is part of the dSploit.
*
* Copyleft of Simone Margaritelli aka evilsocket <[email protected]>
*
* dSploit is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* dSploit is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with dSploit. If not, see <http://www.gnu.org/licenses/>.
*/
package it.evilsocket.dsploit.gui.dialogs;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
public class ChoiceDialog extends AlertDialog
{
public interface ChoiceDialogListener
{
public void onChoice( int choice );
}
public ChoiceDialog( final Activity activity, String title, String[] choices, final ChoiceDialogListener listener ) {
super( activity );
this.setTitle( title );
LinearLayout layout = new LinearLayout( activity );
layout.setPadding( 10, 10, 10, 10 );
for( int i = 0; i < choices.length; i++ )
{
Button choice = new Button( activity );
choice.setLayoutParams( new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 0.5f ) );
choice.setTag( "" + i );
choice.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
ChoiceDialog.this.dismiss();
listener.onChoice( Integer.parseInt( (String)v.getTag() ) );
}
});
choice.setText( choices[i] );
layout.addView( choice );
}
setView( layout );
this.setButton( "Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
}
}
| gpl-3.0 |
nipunn1313/parity | js/src/ui/Form/PasswordStrength/passwordStrength.css | 905 | /* Copyright 2015-2017 Parity Technologies (UK) Ltd.
/* This file is part of Parity.
/*
/* Parity is free software: you can redistribute it and/or modify
/* it under the terms of the GNU General Public License as published by
/* the Free Software Foundation, either version 3 of the License, or
/* (at your option) any later version.
/*
/* Parity is distributed in the hope that it will be useful,
/* but WITHOUT ANY WARRANTY; without even the implied warranty of
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/* GNU General Public License for more details.
/*
/* You should have received a copy of the GNU General Public License
/* along with Parity. If not, see <http://www.gnu.org/licenses/>.
*/
.strength {
margin-top: 1.25em;
}
.feedback {
font-size: 0.75em;
}
.label {
user-select: none;
line-height: 18px;
font-size: 12px;
color: rgba(255, 255, 255, 0.498039);
}
| gpl-3.0 |
kylethayer/bioladder | wiki/maintenance/benchmarks/benchmarkCSSMin.php | 2049 | <?php
/**
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Benchmark
* @author Timo Tijhof
*/
require_once __DIR__ . '/Benchmarker.php';
/**
* Maintenance script that benchmarks CSSMin.
*
* @ingroup Benchmark
*/
class BenchmarkCSSMin extends Benchmarker {
public function __construct() {
parent::__construct();
$this->addDescription( 'Benchmarks CSSMin.' );
$this->addOption( 'file', 'Path to CSS file (may be gzipped)', false, true );
$this->addOption( 'out', 'Echo output of one run to stdout for inspection', false, false );
}
public function execute() {
$file = $this->getOption( 'file', __DIR__ . '/cssmin/styles.css' );
$filename = basename( $file );
$css = $this->loadFile( $file );
if ( $this->hasOption( 'out' ) ) {
echo "## minify\n\n",
CSSMin::minify( $css ),
"\n\n";
echo "## remap\n\n",
CSSMin::remap( $css, dirname( $file ), 'https://example.org/test/', true ),
"\n";
return;
}
$this->bench( [
"minify ($filename)" => [
'function' => [ CSSMin::class, 'minify' ],
'args' => [ $css ]
],
"remap ($filename)" => [
'function' => [ CSSMin::class, 'remap' ],
'args' => [ $css, dirname( $file ), 'https://example.org/test/', true ]
],
] );
}
}
$maintClass = BenchmarkCSSMin::class;
require_once RUN_MAINTENANCE_IF_MAIN;
| gpl-3.0 |
dr4g0nsr/mplayer-skyviia-8860 | mplayer_android/libmpcodecs/vf_noformat.c | 1967 | /*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "config.h"
#include "mp_msg.h"
#include "help_mp.h"
#include "img_format.h"
#include "mp_image.h"
#include "vf.h"
#include "m_option.h"
#include "m_struct.h"
static struct vf_priv_s {
unsigned int fmt;
} const vf_priv_dflt = {
IMGFMT_YV12
};
//===========================================================================//
static int query_format(struct vf_instance *vf, unsigned int fmt){
if(fmt!=vf->priv->fmt)
return vf_next_query_format(vf,fmt);
return 0;
}
static int vf_open(vf_instance_t *vf, char *args){
vf->query_format=query_format;
vf->default_caps=0;
return 1;
}
#define ST_OFF(f) M_ST_OFF(struct vf_priv_s,f)
static const m_option_t vf_opts_fields[] = {
{"fmt", ST_OFF(fmt), CONF_TYPE_IMGFMT, 0,0 ,0, NULL},
{ NULL, NULL, 0, 0, 0, 0, NULL }
};
static const m_struct_t vf_opts = {
"noformat",
sizeof(struct vf_priv_s),
&vf_priv_dflt,
vf_opts_fields
};
const vf_info_t vf_info_noformat = {
"disallow one output format",
"noformat",
"Joey",
"",
vf_open,
&vf_opts
};
//===========================================================================//
| gpl-3.0 |
aol/jzmq | src/org/zeromq/ZMQQueue.java | 2634 | package org.zeromq;
import java.io.Closeable;
import java.io.IOException;
import org.zeromq.ZMQ.Context;
import org.zeromq.ZMQ.Socket;
/**
* ZeroMQ Queue Device implementation.
*
* @author Alois Belaska <[email protected]>
*/
public class ZMQQueue implements Runnable, Closeable {
private final ZMQ.Poller poller;
private final ZMQ.Socket inSocket;
private final ZMQ.Socket outSocket;
/**
* Class constructor.
*
* @param context a 0MQ context previously created.
* @param inSocket input socket
* @param outSocket output socket
*/
public ZMQQueue(Context context, Socket inSocket, Socket outSocket) {
this.inSocket = inSocket;
this.outSocket = outSocket;
this.poller = context.poller(2);
this.poller.register(inSocket, ZMQ.Poller.POLLIN);
this.poller.register(outSocket, ZMQ.Poller.POLLIN);
}
/**
* Queuing of requests and replies.
*/
@Override
public void run() {
byte[] msg = null;
boolean more = true;
while (!Thread.currentThread().isInterrupted()) {
try {
// wait while there are either requests or replies to process
if (poller.poll(-1) < 0) {
break;
}
// process a request
if (poller.pollin(0)) {
more = true;
while (more) {
msg = inSocket.recv(0);
more = inSocket.hasReceiveMore();
if (msg != null) {
outSocket.send(msg, more ? ZMQ.SNDMORE : 0);
}
}
}
// process a reply
if (poller.pollin(1)) {
more = true;
while (more) {
msg = outSocket.recv(0);
more = outSocket.hasReceiveMore();
if (msg != null) {
inSocket.send(msg, more ? ZMQ.SNDMORE : 0);
}
}
}
} catch (ZMQException e) {
// context destroyed, exit
if (ZMQ.Error.ETERM.getCode() == e.getErrorCode()) {
break;
}
throw e;
}
}
}
/**
* Unregisters input and output sockets.
*/
@Override
public void close() throws IOException {
poller.unregister(this.inSocket);
poller.unregister(this.outSocket);
}
}
| gpl-3.0 |
Radarr/Radarr | frontend/src/Components/Modal/ModalFooter.js | 485 | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './ModalFooter.css';
class ModalFooter extends Component {
//
// Render
render() {
const {
children,
...otherProps
} = this.props;
return (
<div
className={styles.modalFooter}
{...otherProps}
>
{children}
</div>
);
}
}
ModalFooter.propTypes = {
children: PropTypes.node
};
export default ModalFooter;
| gpl-3.0 |
j0k3r/pdfparser | src/Smalot/PdfParser/Font/FontType3.php | 1227 | <?php
/**
* @file
* This file is part of the PdfParser library.
*
* @author Sébastien MALOT <[email protected]>
* @date 2017-01-03
* @license LGPLv3
* @url <https://github.com/smalot/pdfparser>
*
* PdfParser is a pdf library written in PHP, extraction oriented.
* Copyright (C) 2017 - Sébastien MALOT <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program.
* If not, see <http://www.pdfparser.org/sites/default/LICENSE.txt>.
*
*/
namespace Smalot\PdfParser\Font;
use Smalot\PdfParser\Font;
/**
* Class FontType3
*
* @package Smalot\PdfParser\Font
*/
class FontType3 extends Font
{
}
| gpl-3.0 |
OpenInfRA/core | openinfra_core/src/main/java/de/btu/openinfra/backend/db/rbac/TopicCharacteristicToAttributeTypeGroupRbac.java | 1063 | package de.btu.openinfra.backend.db.rbac;
import java.util.UUID;
import de.btu.openinfra.backend.db.OpenInfraSchemas;
import de.btu.openinfra.backend.db.daos.TopicCharacteristicToAttributeTypeGroupDao;
import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroup;
import de.btu.openinfra.backend.db.jpa.model.AttributeTypeGroupToTopicCharacteristic;
import de.btu.openinfra.backend.db.jpa.model.TopicCharacteristic;
import de.btu.openinfra.backend.db.pojos.TopicCharacteristicToAttributeTypeGroupPojo;
public class TopicCharacteristicToAttributeTypeGroupRbac extends
OpenInfraValueValueRbac<TopicCharacteristicToAttributeTypeGroupPojo,
AttributeTypeGroupToTopicCharacteristic, AttributeTypeGroup,
TopicCharacteristic, TopicCharacteristicToAttributeTypeGroupDao> {
public TopicCharacteristicToAttributeTypeGroupRbac(
UUID currentProjectId,
OpenInfraSchemas schema) {
super(currentProjectId, schema, AttributeTypeGroup.class,
TopicCharacteristic.class,
TopicCharacteristicToAttributeTypeGroupDao.class);
}
}
| gpl-3.0 |
mbertrand/cga-worldmap | docs/Makefile | 4594 | # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/GeoNode.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/GeoNode.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/GeoNode"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/GeoNode"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
| gpl-3.0 |
Dmitchell94/MCForge-Vanilla-Original | sharkbite.thresher/Ctcp/CtcpUtil.cs | 2431 | /*
* Thresher IRC client library
* Copyright (C) 2002 Aaron Hunter <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* See the gpl.txt file located in the top-level-directory of
* the archive of this library for complete text of license.
*/
using System;
using System.Diagnostics;
using System.Globalization;
namespace Sharkbite.Irc
{
/// <summary>
/// Constants and utility methods to support CTCP.
/// </summary>
/// <remarks>The CTCP constants should be used to test incoming
/// CTCP queries for their type and as the CTCP command
/// for outgoing ones.</remarks>
public sealed class CtcpUtil
{
/// <summary>CTCP Finger.</summary>
public const string Finger = "FINGER";
/// <summary>CTCP USERINFO.</summary>
public const string UserInfo = "USERINFO";
/// <summary>CTCP VERSION.</summary>
public const string Version = "VERSION";
/// <summary>CTCP SOURCE.</summary>
public const string Source = "SOURCE";
/// <summary>CTCP CLIENTINFO.</summary>
public const string ClientInfo = "CLIENTINFO";
/// <summary>CTCP ERRMSG.</summary>
public const string ErrorMessage = "ERRMSG";
/// <summary>CTCP PING.</summary>
public const string Ping = "PING";
/// <summary>CTCP TIME.</summary>
public const string Time = "TIME";
internal static TraceSwitch CtcpTrace = new TraceSwitch("CtcpTraceSwitch", "Debug level for CTCP classes.");
//Should never be called so make it private
private CtcpUtil(){}
/// <summary>
/// Generate a timestamp string suitable for the CTCP Ping command.
/// </summary>
/// <returns>The current time as a string.</returns>
public static string CreateTimestamp()
{
return DateTime.Now.ToFileTime().ToString( CultureInfo.InvariantCulture );
}
}
}
| gpl-3.0 |
somniumio/Somnium | vendor/cache/ruby/2.3.0/gems/tzinfo-data-1.2017.2/lib/tzinfo/data/definitions/Europe/Minsk.rb | 4340 | # encoding: UTF-8
# This file contains data derived from the IANA Time Zone Database
# (http://www.iana.org/time-zones).
module TZInfo
module Data
module Definitions
module Europe
module Minsk
include TimezoneDefinition
timezone 'Europe/Minsk' do |tz|
tz.offset :o0, 6616, 0, :LMT
tz.offset :o1, 6600, 0, :MMT
tz.offset :o2, 7200, 0, :EET
tz.offset :o3, 10800, 0, :MSK
tz.offset :o4, 3600, 3600, :CEST
tz.offset :o5, 3600, 0, :CET
tz.offset :o6, 10800, 3600, :MSD
tz.offset :o7, 7200, 3600, :EEST
tz.offset :o8, 10800, 0, :'+03'
tz.transition 1879, 12, :o1, -2840147416, 26003326573, 10800
tz.transition 1924, 5, :o2, -1441158600, 349042669, 144
tz.transition 1930, 6, :o3, -1247536800, 29113781, 12
tz.transition 1941, 6, :o4, -899780400, 19441387, 8
tz.transition 1942, 11, :o5, -857257200, 58335973, 24
tz.transition 1943, 3, :o4, -844556400, 58339501, 24
tz.transition 1943, 10, :o5, -828226800, 58344037, 24
tz.transition 1944, 4, :o4, -812502000, 58348405, 24
tz.transition 1944, 7, :o3, -804650400, 29175293, 12
tz.transition 1981, 3, :o6, 354920400
tz.transition 1981, 9, :o3, 370728000
tz.transition 1982, 3, :o6, 386456400
tz.transition 1982, 9, :o3, 402264000
tz.transition 1983, 3, :o6, 417992400
tz.transition 1983, 9, :o3, 433800000
tz.transition 1984, 3, :o6, 449614800
tz.transition 1984, 9, :o3, 465346800
tz.transition 1985, 3, :o6, 481071600
tz.transition 1985, 9, :o3, 496796400
tz.transition 1986, 3, :o6, 512521200
tz.transition 1986, 9, :o3, 528246000
tz.transition 1987, 3, :o6, 543970800
tz.transition 1987, 9, :o3, 559695600
tz.transition 1988, 3, :o6, 575420400
tz.transition 1988, 9, :o3, 591145200
tz.transition 1989, 3, :o6, 606870000
tz.transition 1989, 9, :o3, 622594800
tz.transition 1991, 3, :o7, 670374000
tz.transition 1991, 9, :o2, 686102400
tz.transition 1992, 3, :o7, 701827200
tz.transition 1992, 9, :o2, 717552000
tz.transition 1993, 3, :o7, 733276800
tz.transition 1993, 9, :o2, 749001600
tz.transition 1994, 3, :o7, 764726400
tz.transition 1994, 9, :o2, 780451200
tz.transition 1995, 3, :o7, 796176000
tz.transition 1995, 9, :o2, 811900800
tz.transition 1996, 3, :o7, 828230400
tz.transition 1996, 10, :o2, 846374400
tz.transition 1997, 3, :o7, 859680000
tz.transition 1997, 10, :o2, 877824000
tz.transition 1998, 3, :o7, 891129600
tz.transition 1998, 10, :o2, 909273600
tz.transition 1999, 3, :o7, 922579200
tz.transition 1999, 10, :o2, 941328000
tz.transition 2000, 3, :o7, 954028800
tz.transition 2000, 10, :o2, 972777600
tz.transition 2001, 3, :o7, 985478400
tz.transition 2001, 10, :o2, 1004227200
tz.transition 2002, 3, :o7, 1017532800
tz.transition 2002, 10, :o2, 1035676800
tz.transition 2003, 3, :o7, 1048982400
tz.transition 2003, 10, :o2, 1067126400
tz.transition 2004, 3, :o7, 1080432000
tz.transition 2004, 10, :o2, 1099180800
tz.transition 2005, 3, :o7, 1111881600
tz.transition 2005, 10, :o2, 1130630400
tz.transition 2006, 3, :o7, 1143331200
tz.transition 2006, 10, :o2, 1162080000
tz.transition 2007, 3, :o7, 1174780800
tz.transition 2007, 10, :o2, 1193529600
tz.transition 2008, 3, :o7, 1206835200
tz.transition 2008, 10, :o2, 1224979200
tz.transition 2009, 3, :o7, 1238284800
tz.transition 2009, 10, :o2, 1256428800
tz.transition 2010, 3, :o7, 1269734400
tz.transition 2010, 10, :o2, 1288483200
tz.transition 2011, 3, :o8, 1301184000
end
end
end
end
end
end
| gpl-3.0 |
ernestovi/ups | spip/plugins-dist/svp/base/svp_declarer.php | 10636 | <?php
/**
* Déclarations relatives à la base de données
*
* @plugin SVP pour SPIP
* @license GPL
* @package SPIP\SVP\Pipelines
**/
/**
* Déclarer les objets éditoriaux de SVP
*
* - Dépot : table spip_depots
* - Plugin : table spip_plugins
* - Paquet : table spip_paquets
*
* @pipeline declarer_tables_objets_sql
* @param array $tables
* Description des tables
* @return array
* Description complétée des tables
*/
function svp_declarer_tables_objets_sql($tables) {
include_spip('inc/config');
// Table des depots
$tables['spip_depots'] = array(
// Base de donnees
'table_objet' => 'depots',
'type' => 'depot',
'field' => array(
"id_depot" => "bigint(21) NOT NULL",
"titre" => "text DEFAULT '' NOT NULL",
"descriptif" => "text DEFAULT '' NOT NULL",
"type" => "varchar(10) DEFAULT '' NOT NULL",
"url_serveur" => "varchar(255) DEFAULT '' NOT NULL",
// url du serveur svn ou git
"url_brouteur" => "varchar(255) DEFAULT '' NOT NULL",
// url de l'interface de gestion du repository (trac, redmine...)
"url_archives" => "varchar(255) DEFAULT '' NOT NULL",
// url de base des zips
"url_commits" => "varchar(255) DEFAULT '' NOT NULL",
// url du flux rss des commits du serveur svn ou git
"xml_paquets" => "varchar(255) DEFAULT '' NOT NULL",
// chemin complet du fichier xml du depot
"sha_paquets" => "varchar(40) DEFAULT '' NOT NULL",
"nbr_paquets" => "integer DEFAULT 0 NOT NULL",
"nbr_plugins" => "integer DEFAULT 0 NOT NULL",
"nbr_autres" => "integer DEFAULT 0 NOT NULL",
// autres contributions, non plugin
"maj" => "timestamp"
),
'key' => array(
"PRIMARY KEY" => "id_depot"
),
'tables_jointures' => array('id_plugin' => 'depots_plugins'),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'depot',
'url_voir' => 'depot',
'url_edit' => 'depot_edit',
'editable' => lire_config('svp/depot_editable', 'non'),
'champs_editables' => array('titre', 'descriptif'),
'icone_objet' => 'depot',
// Textes standard
'texte_retour' => 'icone_retour',
'texte_modifier' => 'svp:bouton_modifier_depot',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_depot',
'texte_objets' => 'svp:titre_depots',
'info_aucun_objet' => 'svp:info_aucun_depot',
'info_1_objet' => 'svp:info_1_depot',
'info_nb_objets' => 'svp:info_nb_depots',
'texte_logo_objet' => 'svp:titre_logo_depot',
);
// Table des plugins
$tables['spip_plugins'] = array(
// Base de donnees
'table_objet' => 'plugins',
'type' => 'plugin',
'field' => array(
"id_plugin" => "bigint(21) NOT NULL",
"prefixe" => "varchar(30) DEFAULT '' NOT NULL",
"nom" => "text DEFAULT '' NOT NULL",
"slogan" => "text DEFAULT '' NOT NULL",
"categorie" => "varchar(100) DEFAULT '' NOT NULL",
"tags" => "text DEFAULT '' NOT NULL",
"vmax" => "varchar(24) DEFAULT '' NOT NULL", // version la plus elevee des paquets du plugin
"date_crea" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // la plus ancienne des paquets du plugin
"date_modif" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL", // la plus recente des paquets du plugin
"compatibilite_spip" => "varchar(24) DEFAULT '' NOT NULL", // union des intervalles des paquets du plugin
"branches_spip" => "varchar(255) DEFAULT '' NOT NULL"
), // union des branches spip supportees par les paquets du plugin
'key' => array(
"PRIMARY KEY" => "id_plugin",
"KEY prefixe" => "prefixe"
),
'tables_jointures' => array('id_depot' => 'depots_plugins'),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "prefixe AS titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'plugin',
'url_voir' => 'plugin',
'editable' => 'non',
'champs_editables' => array(),
'rechercher_champs' => array('prefixe' => 8, 'nom' => 8, 'slogan' => 4),
'rechercher_jointures' => array('paquet' => array('auteur' => 8, 'description' => 2)),
'icone_objet' => 'plugin',
// Textes standard
'texte_retour' => 'icone_retour',
'texte_modifier' => '',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_plugin',
'texte_objets' => 'svp:titre_plugins',
'info_aucun_objet' => 'svp:info_aucun_plugin',
'info_1_objet' => 'svp:info_1_plugin',
'info_nb_objets' => 'svp:info_nb_plugins',
'texte_logo_objet' => 'svp:titre_logo_plugin',
);
$tables['spip_paquets'] = array(
// Base de donnees
'table_objet' => 'paquets',
'type' => 'paquet',
'field' => array(
"id_paquet" => "bigint(21) NOT NULL",
"id_plugin" => "bigint(21) NOT NULL",
"prefixe" => "varchar(30) DEFAULT '' NOT NULL",
"logo" => "varchar(255) DEFAULT '' NOT NULL",
// chemin du logo depuis la racine du plugin
"version" => "varchar(24) DEFAULT '' NOT NULL",
"version_base" => "varchar(24) DEFAULT '' NOT NULL",
"compatibilite_spip" => "varchar(24) DEFAULT '' NOT NULL",
"branches_spip" => "varchar(255) DEFAULT '' NOT NULL",
// branches spip supportees (cf meta)
"description" => "text DEFAULT '' NOT NULL",
"auteur" => "text DEFAULT '' NOT NULL",
"credit" => "text DEFAULT '' NOT NULL",
"licence" => "text DEFAULT '' NOT NULL",
"copyright" => "text DEFAULT '' NOT NULL",
"lien_doc" => "text DEFAULT '' NOT NULL",
// lien vers la documentation
"lien_demo" => "text DEFAULT '' NOT NULL",
// lien vers le site de demo
"lien_dev" => "text DEFAULT '' NOT NULL",
// lien vers le site de dev
"etat" => "varchar(16) DEFAULT '' NOT NULL",
"etatnum" => "int(1) DEFAULT 0 NOT NULL",
// 0 aucune indication - 1 exp - 2 dev - 3 test - 4 stable
"dependances" => "text DEFAULT '' NOT NULL",
"procure" => "text DEFAULT '' NOT NULL",
"date_crea" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
"date_modif" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
"id_depot" => "bigint(21) DEFAULT 0 NOT NULL",
// 0 pour un paquet local
"nom_archive" => "VARCHAR(255) DEFAULT '' NOT NULL",
// nom du zip du paquet, depuis l'adresse de la zone
"nbo_archive" => "integer DEFAULT 0 NOT NULL",
// taille de l'archive en octets
"maj_archive" => "datetime DEFAULT '0000-00-00 00:00:00' NOT NULL",
// date de mise a jour de l'archive
"src_archive" => "VARCHAR(255) DEFAULT '' NOT NULL",
// source de l'archive sur le depot
"traductions" => "text DEFAULT '' NOT NULL",
// tableau serialise par module des langues traduites et de leurs traducteurs
"actif" => "varchar(3) DEFAULT 'non' NOT NULL",
// est actif ? oui / non
"installe" => "varchar(3) DEFAULT 'non' NOT NULL",
// est desinstallable ? oui / non
"recent" => "int(2) DEFAULT 0 NOT NULL",
// a ete utilise recemment ? > 0 : oui
"maj_version" => "VARCHAR(255) DEFAULT '' NOT NULL",
// version superieure existante (mise a jour possible)
"superieur" => "varchar(3) DEFAULT 'non' NOT NULL",
// superieur : version plus recente disponible (distant) d'un plugin (actif?) existant
"obsolete" => "varchar(3) DEFAULT 'non' NOT NULL",
// obsolete : version plus ancienne (locale) disponible d'un plugin local existant
"attente" => "varchar(3) DEFAULT 'non' NOT NULL",
// attente : plugin semi actif (il etait actif, mais il lui manque maintenant une dependance : il reste coche actif jusqu'a resolution ou desactivation manuelle)
"constante" => "VARCHAR(30) DEFAULT '' NOT NULL",
// nom de la constante _DIR_(PLUGINS|EXTENSIONS|PLUGINS_SUPP)
"signature" => "VARCHAR(32) DEFAULT '' NOT NULL"
), // hash MD5 d'un paquet
'key' => array(
"PRIMARY KEY" => "id_paquet",
"KEY id_plugin" => "id_plugin"
),
'join' => array(
"id_paquet" => "id_paquet",
"id_plugin" => "id_plugin"
),
'principale' => 'oui',
// Titre, date et gestion du statut
'titre' => "nom_archive AS titre, '' AS lang",
// Edition, affichage et recherche
'page' => 'paquet',
'url_voir' => '',
'editable' => 'non',
'champs_editables' => array(),
'rechercher_champs' => array(),
'rechercher_jointures' => array(),
'icone_objet' => 'paquet',
// Textes standard
'texte_retour' => '',
'texte_modifier' => '',
'texte_creer' => '',
'texte_creer_associer' => '',
'texte_signale_edition' => '',
'texte_objet' => 'svp:titre_paquet',
'texte_objets' => 'svp:titre_paquets',
'info_aucun_objet' => 'svp:info_aucun_paquet',
'info_1_objet' => 'svp:info_1_paquet',
'info_nb_objets' => 'svp:info_nb_paquets',
'texte_logo_objet' => '',
);
return $tables;
}
/**
* Déclarer les tables de liaisons de SVP
*
* Déclare la table spip_depots_plugins
*
* @pipeline declarer_tables_auxiliaires
* @param array $tables_auxiliaires
* Description des tables auxiliaires
* @return array
* Description complétée des tables auxiliaires
*/
function svp_declarer_tables_auxiliaires($tables_auxiliaires) {
// Tables de liens entre plugins et depots : spip_depots_plugins
$spip_depots_plugins = array(
"id_depot" => "bigint(21) NOT NULL",
"id_plugin" => "bigint(21) NOT NULL"
);
$spip_depots_plugins_key = array(
"PRIMARY KEY" => "id_depot, id_plugin"
);
$tables_auxiliaires['spip_depots_plugins'] =
array('field' => &$spip_depots_plugins, 'key' => &$spip_depots_plugins_key);
return $tables_auxiliaires;
}
/**
* Déclare les alias de boucle et traitements automatiques de certaines balises
*
* @pipeline declarer_tables_interfaces
* @param array $interface
* Déclarations d'interface pour le compilateur
* @return array
* Déclarations d'interface pour le compilateur
*/
function svp_declarer_tables_interfaces($interface) {
// Les tables : permet d'appeler une boucle avec le *type* de la table uniquement
$interface['table_des_tables']['depots'] = 'depots';
$interface['table_des_tables']['plugins'] = 'plugins';
$interface['table_des_tables']['paquets'] = 'paquets';
$interface['table_des_tables']['depots_plugins'] = 'depots_plugins';
// Les traitements
// - table spip_plugins
$interface['table_des_traitements']['SLOGAN']['plugins'] = _TRAITEMENT_RACCOURCIS;
$interface['table_des_traitements']['VMAX']['plugins'] = 'denormaliser_version(%s)';
// - table spip_paquets
$interface['table_des_traitements']['DESCRIPTION']['paquets'] = _TRAITEMENT_RACCOURCIS;
$interface['table_des_traitements']['VERSION']['paquets'] = 'denormaliser_version(%s)';
$interface['table_des_traitements']['MAJ_VERSION']['paquets'] = 'denormaliser_version(%s)';
return $interface;
}
| gpl-3.0 |
malin1993ml/h-store | third_party/cpp/berkeleydb/docs/programmer_reference/preface.html | 5321 | <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Preface</title>
<link rel="stylesheet" href="gettingStarted.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
<link rel="up" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
<link rel="prev" href="index.html" title="Berkeley DB Programmer's Reference Guide" />
<link rel="next" href="moreinfo.html" title="For More Information" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.1.6.1</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">Preface</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<th width="60%" align="center"> </th>
<td width="20%" align="right"> <a accesskey="n" href="moreinfo.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="preface" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title"><a id="preface"></a>Preface</h2>
</div>
</div>
</div>
<div class="toc">
<p>
<b>Table of Contents</b>
</p>
<dl>
<dt>
<span class="sect1">
<a href="preface.html#conventions">Conventions Used in this Book</a>
</span>
</dt>
<dt>
<span class="sect1">
<a href="moreinfo.html">For More Information</a>
</span>
</dt>
<dd>
<dl>
<dt>
<span class="sect2">
<a href="moreinfo.html#contact_us">Contact Us</a>
</span>
</dt>
</dl>
</dd>
</dl>
</div>
<p>
Welcome to Berkeley DB (DB). This document provides an
introduction and usage notes for skilled programmers who wish
to use the Berkeley DB APIs.
</p>
<p>
This document reflects Berkeley DB 12<span class="emphasis"><em>c</em></span> Release 1, which provides
DB library version 12.1.6.1.
</p>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="conventions"></a>Conventions Used in this Book</h2>
</div>
</div>
</div>
<p>
The following typographical conventions are used within
in this manual:
</p>
<p>
Structure names are represented in
<code class="classname">monospaced font</code>, as are
<code class="methodname">method names</code>. For example:
"<code class="methodname">DB->open()</code> is a method on
a <code class="classname">DB</code> handle."
</p>
<p>
Variable or non-literal text is presented in
<span class="emphasis"><em>italics</em></span>. For example: "Go to your
<span class="emphasis"><em>DB_INSTALL</em></span> directory."
</p>
<p>
Program examples are displayed in a
<code class="classname">monospaced font</code> on a shaded
background. For example:
</p>
<pre class="programlisting">/* File: gettingstarted_common.h */
typedef struct stock_dbs {
DB *inventory_dbp; /* Database containing inventory information */
DB *vendor_dbp; /* Database containing vendor information */
char *db_home_dir; /* Directory containing the database files */
char *inventory_db_name; /* Name of the inventory database */
char *vendor_db_name; /* Name of the vendor database */
} STOCK_DBS; </pre>
<div class="note" style="margin-left: 0.5in; margin-right: 0.5in;">
<h3 class="title">Note</h3>
<p>
Finally, notes of interest are represented using a
note block such as this.
</p>
</div>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="index.html">Prev</a> </td>
<td width="20%" align="center"> </td>
<td width="40%" align="right"> <a accesskey="n" href="moreinfo.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Berkeley DB Programmer's Reference Guide </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> For More Information</td>
</tr>
</table>
</div>
</body>
</html>
| gpl-3.0 |
hassiumsoft/hasscms-packages | hass-attachment/misc/attachment-update.css | 209 | /*------------------------------------*\
#更新页面
\*------------------------------------*/
.attachment_image {
overflow: hidden;
}
.attachment_image img{
max-width:100%;
max-height:700px;
}
| gpl-3.0 |
ramack/Liberty | src/wrappers/ewlc/plugins/xml/c/manually-written-header.h | 298 | #include <libxml/xmlmemory.h>
#include <libxml/parser.h>
xmlChar *xml_node_get_name (xmlNode *a_node);
xmlNode *xml_node_get_children (xmlNode *a_node);
xmlNode *xml_node_get_children (xmlNode *a_node);
xmlNode *xml_node_get_parent (xmlNode *a_node);
xmlNode *xml_node_get_next (xmlNode *a_node);
| gpl-3.0 |
geminy/aidear | oss/qt/qt-everywhere-opensource-src-5.9.0/qttools/src/designer/src/lib/shared/codedialog_p.h | 2678 | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of Qt Designer. This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//
#ifndef CODEPREVIEWDIALOG_H
#define CODEPREVIEWDIALOG_H
#include "shared_global_p.h"
#include <QtWidgets/QDialog>
QT_BEGIN_NAMESPACE
class QDesignerFormWindowInterface;
namespace qdesigner_internal {
// Dialog for viewing code.
class QDESIGNER_SHARED_EXPORT CodeDialog : public QDialog
{
Q_OBJECT
explicit CodeDialog(QWidget *parent = 0);
public:
virtual ~CodeDialog();
static bool generateCode(const QDesignerFormWindowInterface *fw,
QString *code,
QString *errorMessage);
static bool showCodeDialog(const QDesignerFormWindowInterface *fw,
QWidget *parent,
QString *errorMessage);
private slots:
void slotSaveAs();
#ifndef QT_NO_CLIPBOARD
void copyAll();
#endif
private:
void setCode(const QString &code);
QString code() const;
void setFormFileName(const QString &f);
QString formFileName() const;
void warning(const QString &msg);
struct CodeDialogPrivate;
CodeDialogPrivate *m_impl;
};
} // namespace qdesigner_internal
QT_END_NAMESPACE
#endif // CODEPREVIEWDIALOG_H
| gpl-3.0 |
Zengwn/ViewTouch-POS-System | main/temphash.cc | 401 |
#include <stdio.h>
#include "license_hash.hh"
#ifdef DMALLOC
#include <dmalloc.h>
#endif
#define STRLONG 4096
int main(int argc, const char* argv[])
{
char license[STRLONG];
if (argc > 1)
{
if (GenerateTempKey(license, 4096, argv[1]) == 0)
printf("%s", license);
}
else
{
printf("Usage: %s <hardware ID>\n", argv[0]);
}
return 0;
}
| gpl-3.0 |
Franck-MOREAU/dolibarr | htdocs/societe/class/societe.class.php | 125850 | <?php
/* Copyright (C) 2002-2006 Rodolphe Quiedeville <[email protected]>
* Copyright (C) 2004-2015 Laurent Destailleur <[email protected]>
* Copyright (C) 2004 Eric Seigne <[email protected]>
* Copyright (C) 2003 Brian Fraval <[email protected]>
* Copyright (C) 2006 Andre Cianfarani <[email protected]>
* Copyright (C) 2005-2016 Regis Houssin <[email protected]>
* Copyright (C) 2008 Patrick Raguin <[email protected]>
* Copyright (C) 2010-2014 Juanjo Menent <[email protected]>
* Copyright (C) 2013 Florian Henry <[email protected]>
* Copyright (C) 2013 Alexandre Spangaro <[email protected]>
* Copyright (C) 2013 Peter Fontaine <[email protected]>
* Copyright (C) 2014-2015 Marcos García <[email protected]>
* Copyright (C) 2015 Raphaël Doursenaud <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/societe/class/societe.class.php
* \ingroup societe
* \brief File for third party class
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/multicurrency/class/multicurrency.class.php';
/**
* Class to manage third parties objects (customers, suppliers, prospects...)
*/
class Societe extends CommonObject
{
public $element='societe';
public $table_element = 'societe';
public $fk_element='fk_soc';
protected $childtables=array("supplier_proposal","propal","commande","facture","contrat","facture_fourn","commande_fournisseur","projet","expedition"); // To test if we can delete object
/**
* 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
* @var int
*/
protected $ismultientitymanaged = 1;
public $entity;
/**
* Thirdparty name
* @var string
* @deprecated Use $name instead
* @see name
*/
public $nom;
/**
* Alias names (commercial, trademark or alias names)
* @var string
*/
public $name_alias;
public $particulier;
public $address;
public $zip;
public $town;
/**
* Thirdparty status : 0=activity ceased, 1= in activity
* @var int
*/
var $status;
/**
* Id of department
* @var int
*/
var $state_id;
var $state_code;
var $state;
/**
* State code
* @var string
* @deprecated Use state_code instead
* @see state_code
*/
var $departement_code;
/**
* @var string
* @deprecated Use state instead
* @see state
*/
var $departement;
/**
* @var string
* @deprecated Use country instead
* @see country
*/
var $pays;
/**
* Phone number
* @var string
*/
var $phone;
/**
* Fax number
* @var string
*/
var $fax;
/**
* Email
* @var string
*/
var $email;
/**
* Skype username
* @var string
*/
var $skype;
/**
* Webpage
* @var string
*/
var $url;
//! barcode
/**
* Barcode value
* @var string
*/
var $barcode;
// 6 professional id (usage depends on country)
/**
* Professional ID 1 (Ex: Siren in France)
* @var string
*/
var $idprof1;
/**
* Professional ID 2 (Ex: Siret in France)
* @var string
*/
var $idprof2;
/**
* Professional ID 3 (Ex: Ape in France)
* @var string
*/
var $idprof3;
/**
* Professional ID 4 (Ex: RCS in France)
* @var string
*/
var $idprof4;
/**
* Professional ID 5
* @var string
*/
var $idprof5;
/**
* Professional ID 6
* @var string
*/
var $idprof6;
var $prefix_comm;
var $tva_assuj;
/**
* Intracommunitary VAT ID
* @var string
*/
var $tva_intra;
// Local taxes
var $localtax1_assuj;
var $localtax1_value;
var $localtax2_assuj;
var $localtax2_value;
var $managers;
var $capital;
var $typent_id;
var $typent_code;
var $effectif;
var $effectif_id;
var $forme_juridique_code;
var $forme_juridique;
var $remise_percent;
var $mode_reglement_supplier_id;
var $cond_reglement_supplier_id;
var $fk_prospectlevel;
var $name_bis;
//Log data
/**
* Date of last update
* @var string
*/
var $date_modification;
/**
* User that made last update
* @var string
*/
var $user_modification;
/**
* Date of creation
* @var string
*/
var $date_creation;
/**
* User that created the thirdparty
* @var User
*/
var $user_creation;
var $specimen;
/**
* 0=no customer, 1=customer, 2=prospect, 3=customer and prospect
* @var int
*/
var $client;
/**
* 0=no prospect, 1=prospect
* @var int
*/
var $prospect;
/**
* 0=no supplier, 1=supplier
* @var int
*/
var $fournisseur;
/**
* Client code. E.g: CU2014-003
* @var string
*/
var $code_client;
/**
* Supplier code. E.g: SU2014-003
* @var string
*/
var $code_fournisseur;
/**
* Accounting code for client
* @var string
*/
var $code_compta;
/**
* Accounting code for suppliers
* @var string
*/
var $code_compta_fournisseur;
/**
* @var string
* @deprecated Note is split in public and private notes
* @see note_public, note_private
*/
var $note;
/**
* Private note
* @var string
*/
var $note_private;
/**
* Public note
* @var string
*/
var $note_public;
//! code statut prospect
var $stcomm_id;
var $statut_commercial;
/**
* Assigned price level
* @var int
*/
var $price_level;
var $outstanding_limit;
/**
* Id of sales representative to link (used for thirdparty creation). Not filled by a fetch, because we can have several sales representatives.
* @var int
*/
var $commercial_id;
/**
* Id of parent thirdparty (if one)
* @var int
*/
var $parent;
/**
* Default language code of thirdparty (en_US, ...)
* @var string
*/
var $default_lang;
var $ref;
var $ref_int;
/**
* External user reference.
* This is to allow external systems to store their id and make self-developed synchronizing functions easier to
* build.
* @var string
*/
var $ref_ext;
/**
* Import key.
* Set when the thirdparty has been created through an import process. This is to relate those created thirdparties
* to an import process
* @var string
*/
var $import_key;
/**
* Supplier WebServices URL
* @var string
*/
var $webservices_url;
/**
* Supplier WebServices Key
* @var string
*/
var $webservices_key;
var $logo;
var $logo_small;
var $logo_mini;
var $array_options;
// Incoterms
var $fk_incoterms;
var $location_incoterms;
var $libelle_incoterms; //Used into tooltip
// Multicurrency
var $fk_multicurrency;
var $multicurrency_code;
/**
* To contains a clone of this when we need to save old properties of object
* @var Societe
*/
var $oldcopy;
/**
* Constructor
*
* @param DoliDB $db Database handler
*/
public function __construct($db)
{
$this->db = $db;
$this->client = 0;
$this->prospect = 0;
$this->fournisseur = 0;
$this->typent_id = 0;
$this->effectif_id = 0;
$this->forme_juridique_code = 0;
$this->tva_assuj = 1;
$this->status = 1;
return 1;
}
/**
* Create third party in database
*
* @param User $user Object of user that ask creation
* @return int >= 0 if OK, < 0 if KO
*/
function create($user)
{
global $langs,$conf;
$error=0;
// Clean parameters
if (empty($this->status)) $this->status=0;
$this->name=$this->name?trim($this->name):trim($this->nom);
if (! empty($conf->global->MAIN_FIRST_TO_UPPER)) $this->name=ucwords($this->name);
$this->nom=$this->name; // For backward compatibility
if (empty($this->client)) $this->client=0;
if (empty($this->fournisseur)) $this->fournisseur=0;
$this->import_key = trim($this->import_key);
if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
if (empty($this->fk_multicurrency))
{
$this->multicurrency_code = '';
$this->fk_multicurrency = 0;
}
dol_syslog(get_class($this)."::create ".$this->name);
// Check parameters
if (! empty($conf->global->SOCIETE_MAIL_REQUIRED) && ! isValidEMail($this->email))
{
$langs->load("errors");
$this->error = $langs->trans("ErrorBadEMail",$this->email);
return -1;
}
$now=dol_now();
$this->db->begin();
// For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
if ($this->code_client == -1) $this->get_codeclient($this,0);
if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
// Check more parameters
// If error, this->errors[] is filled
$result = $this->verify();
if ($result >= 0)
{
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe (nom, name_alias, entity, datec, fk_user_creat, canvas, status, ref_int, ref_ext, fk_stcomm, fk_incoterms, location_incoterms ,import_key, fk_multicurrency, multicurrency_code)";
$sql.= " VALUES ('".$this->db->escape($this->name)."', '".$this->db->escape($this->name_alias)."', ".$conf->entity.", '".$this->db->idate($now)."'";
$sql.= ", ".(! empty($user->id) ? "'".$user->id."'":"null");
$sql.= ", ".(! empty($this->canvas) ? "'".$this->db->escape($this->canvas)."'":"null");
$sql.= ", ".$this->status;
$sql.= ", ".(! empty($this->ref_int) ? "'".$this->db->escape($this->ref_int)."'":"null");
$sql.= ", ".(! empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'":"null");
$sql.= ", 0";
$sql.= ", ".(int) $this->fk_incoterms;
$sql.= ", '".$this->db->escape($this->location_incoterms)."'";
$sql.= ", ".(! empty($this->import_key) ? "'".$this->db->escape($this->import_key)."'":"null");
$sql.= ", ".(int) $this->fk_multicurrency;
$sql.= ", '".$this->db->escape($this->multicurrency_code)."')";
dol_syslog(get_class($this)."::create", LOG_DEBUG);
$result=$this->db->query($sql);
if ($result)
{
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."societe");
$ret = $this->update($this->id,$user,0,1,1,'add');
// Ajout du commercial affecte
if ($this->commercial_id != '' && $this->commercial_id != -1)
{
$this->add_commercial($user, $this->commercial_id);
}
// si un commercial cree un client il lui est affecte automatiquement
else if (empty($user->rights->societe->client->voir))
{
$this->add_commercial($user, $user->id);
}
if ($ret >= 0)
{
// Call trigger
$result=$this->call_trigger('COMPANY_CREATE',$user);
if ($result < 0) $error++;
// End call triggers
}
else $error++;
if (! $error)
{
dol_syslog(get_class($this)."::Create success id=".$this->id);
$this->db->commit();
return $this->id;
}
else
{
dol_syslog(get_class($this)."::Create echec update ".$this->error, LOG_ERR);
$this->db->rollback();
return -3;
}
}
else
{
if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
{
$this->error=$langs->trans("ErrorCompanyNameAlreadyExists",$this->name);
$result=-1;
}
else
{
$this->error=$this->db->lasterror();
$result=-2;
}
$this->db->rollback();
return $result;
}
}
else
{
$this->db->rollback();
dol_syslog(get_class($this)."::Create fails verify ".join(',',$this->errors), LOG_WARNING);
return -3;
}
}
/**
* Create a contact/address from thirdparty
*
* @param User $user Object user
* @return int <0 if KO, >0 if OK
*/
function create_individual(User $user)
{
require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
$contact=new Contact($this->db);
$contact->name = $this->name_bis;
$contact->firstname = $this->firstname;
$contact->civility_id = $this->civility_id;
$contact->socid = $this->id; // fk_soc
$contact->statut = 1;
$contact->priv = 0;
$contact->country_id = $this->country_id;
$contact->state_id = $this->state_id;
$contact->address = $this->address;
$contact->email = $this->email;
$contact->zip = $this->zip;
$contact->town = $this->town;
$contact->phone_pro = $this->phone;
$result = $contact->create($user);
if ($result < 0)
{
$this->error = $contact->error;
$this->errors = $contact->errors;
dol_syslog(get_class($this)."::create_individual ERROR:" . $this->error, LOG_ERR);
}
return $result;
}
/**
* Check properties of third party are ok (like name, third party codes, ...)
* Used before an add or update.
*
* @return int 0 if OK, <0 if KO
*/
function verify()
{
$this->errors=array();
$result = 0;
$this->name = trim($this->name);
$this->nom=$this->name; // For backward compatibility
if (! $this->name)
{
$this->errors[] = 'ErrorBadThirdPartyName';
$result = -2;
}
if ($this->client)
{
$rescode = $this->check_codeclient();
if ($rescode <> 0)
{
if ($rescode == -1)
{
$this->errors[] = 'ErrorBadCustomerCodeSyntax';
}
if ($rescode == -2)
{
$this->errors[] = 'ErrorCustomerCodeRequired';
}
if ($rescode == -3)
{
$this->errors[] = 'ErrorCustomerCodeAlreadyUsed';
}
if ($rescode == -4)
{
$this->errors[] = 'ErrorPrefixRequired';
}
$result = -3;
}
}
if ($this->fournisseur)
{
$rescode = $this->check_codefournisseur();
if ($rescode <> 0)
{
if ($rescode == -1)
{
$this->errors[] = 'ErrorBadSupplierCodeSyntax';
}
if ($rescode == -2)
{
$this->errors[] = 'ErrorSupplierCodeRequired';
}
if ($rescode == -3)
{
$this->errors[] = 'ErrorSupplierCodeAlreadyUsed';
}
if ($rescode == -5)
{
$this->errors[] = 'ErrorprefixRequired';
}
$result = -3;
}
}
return $result;
}
/**
* Update parameters of third party
*
* @param int $id id societe
* @param User $user Utilisateur qui demande la mise a jour
* @param int $call_trigger 0=non, 1=oui
* @param int $allowmodcodeclient Inclut modif code client et code compta
* @param int $allowmodcodefournisseur Inclut modif code fournisseur et code compta fournisseur
* @param string $action 'add' or 'update'
* @param int $nosyncmember Do not synchronize info of linked member
* @return int <0 if KO, >=0 if OK
*/
function update($id, $user='', $call_trigger=1, $allowmodcodeclient=0, $allowmodcodefournisseur=0, $action='update', $nosyncmember=1)
{
global $langs,$conf,$hookmanager;
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
$error=0;
dol_syslog(get_class($this)."::Update id=".$id." call_trigger=".$call_trigger." allowmodcodeclient=".$allowmodcodeclient." allowmodcodefournisseur=".$allowmodcodefournisseur);
$now=dol_now();
// Clean parameters
$this->id = $id;
$this->name = $this->name?trim($this->name):trim($this->nom);
$this->nom = $this->name; // For backward compatibility
$this->name_alias = trim($this->name_alias);
$this->ref_ext = trim($this->ref_ext);
$this->address = $this->address?trim($this->address):trim($this->address);
$this->zip = $this->zip?trim($this->zip):trim($this->zip);
$this->town = $this->town?trim($this->town):trim($this->town);
$this->state_id = trim($this->state_id);
$this->country_id = ($this->country_id > 0)?$this->country_id:0;
$this->phone = trim($this->phone);
$this->phone = preg_replace("/\s/","",$this->phone);
$this->phone = preg_replace("/\./","",$this->phone);
$this->fax = trim($this->fax);
$this->fax = preg_replace("/\s/","",$this->fax);
$this->fax = preg_replace("/\./","",$this->fax);
$this->email = trim($this->email);
$this->skype = trim($this->skype);
$this->url = $this->url?clean_url($this->url,0):'';
$this->idprof1 = trim($this->idprof1);
$this->idprof2 = trim($this->idprof2);
$this->idprof3 = trim($this->idprof3);
$this->idprof4 = trim($this->idprof4);
$this->idprof5 = (! empty($this->idprof5)?trim($this->idprof5):'');
$this->idprof6 = (! empty($this->idprof6)?trim($this->idprof6):'');
$this->prefix_comm = trim($this->prefix_comm);
$this->outstanding_limit = price2num($this->outstanding_limit);
$this->tva_assuj = trim($this->tva_assuj);
$this->tva_intra = dol_sanitizeFileName($this->tva_intra,'');
if (empty($this->status)) $this->status = 0;
if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
if (empty($this->fk_multicurrency))
{
$this->multicurrency_code = '';
$this->fk_multicurrency = 0;
}
// Local taxes
$this->localtax1_assuj=trim($this->localtax1_assuj);
$this->localtax2_assuj=trim($this->localtax2_assuj);
$this->localtax1_value=trim($this->localtax1_value);
$this->localtax2_value=trim($this->localtax2_value);
if ($this->capital != '') $this->capital=price2num(trim($this->capital));
if (! is_numeric($this->capital)) $this->capital = ''; // '' = undef
$this->effectif_id=trim($this->effectif_id);
$this->forme_juridique_code=trim($this->forme_juridique_code);
//Gencod
$this->barcode=trim($this->barcode);
// For automatic creation
if ($this->code_client == -1) $this->get_codeclient($this,0);
if ($this->code_fournisseur == -1) $this->get_codefournisseur($this,1);
$this->code_compta=trim($this->code_compta);
$this->code_compta_fournisseur=trim($this->code_compta_fournisseur);
// Check parameters
if (! empty($conf->global->SOCIETE_MAIL_REQUIRED) && ! isValidEMail($this->email))
{
$langs->load("errors");
$this->error = $langs->trans("ErrorBadEMail",$this->email);
return -1;
}
if (! is_numeric($this->client) && ! is_numeric($this->fournisseur))
{
$langs->load("errors");
$this->error = $langs->trans("BadValueForParameterClientOrSupplier");
return -1;
}
$customer=false;
if (! empty($allowmodcodeclient) && ! empty($this->client))
{
// Attention get_codecompta peut modifier le code suivant le module utilise
if (empty($this->code_compta))
{
$ret=$this->get_codecompta('customer');
if ($ret < 0) return -1;
}
$customer=true;
}
$supplier=false;
if (! empty($allowmodcodefournisseur) && ! empty($this->fournisseur))
{
// Attention get_codecompta peut modifier le code suivant le module utilise
if (empty($this->code_compta_fournisseur))
{
$ret=$this->get_codecompta('supplier');
if ($ret < 0) return -1;
}
$supplier=true;
}
//Web services
$this->webservices_url = $this->webservices_url?clean_url($this->webservices_url,0):'';
$this->webservices_key = trim($this->webservices_key);
//Incoterms
$this->fk_incoterms = (int) $this->fk_incoterms;
$this->location_incoterms = trim($this->location_incoterms);
$this->db->begin();
// Check name is required and codes are ok or unique.
// If error, this->errors[] is filled
$result = 0;
if ($action != 'add') $result = $this->verify(); // We don't check when update called during a create because verify was already done
if ($result >= 0)
{
dol_syslog(get_class($this)."::update verify ok or not done");
$sql = "UPDATE ".MAIN_DB_PREFIX."societe SET ";
$sql .= "nom = '" . $this->db->escape($this->name) ."'"; // Required
$sql .= ",name_alias = '" . $this->db->escape($this->name_alias) ."'";
$sql .= ",ref_ext = " .(! empty($this->ref_ext)?"'".$this->db->escape($this->ref_ext) ."'":"null");
$sql .= ",address = '" . $this->db->escape($this->address) ."'";
$sql .= ",zip = ".(! empty($this->zip)?"'".$this->db->escape($this->zip)."'":"null");
$sql .= ",town = ".(! empty($this->town)?"'".$this->db->escape($this->town)."'":"null");
$sql .= ",fk_departement = '" . (! empty($this->state_id)?$this->state_id:'0') ."'";
$sql .= ",fk_pays = '" . (! empty($this->country_id)?$this->country_id:'0') ."'";
$sql .= ",phone = ".(! empty($this->phone)?"'".$this->db->escape($this->phone)."'":"null");
$sql .= ",fax = ".(! empty($this->fax)?"'".$this->db->escape($this->fax)."'":"null");
$sql .= ",email = ".(! empty($this->email)?"'".$this->db->escape($this->email)."'":"null");
$sql .= ",skype = ".(! empty($this->skype)?"'".$this->db->escape($this->skype)."'":"null");
$sql .= ",url = ".(! empty($this->url)?"'".$this->db->escape($this->url)."'":"null");
$sql .= ",siren = '". $this->db->escape($this->idprof1) ."'";
$sql .= ",siret = '". $this->db->escape($this->idprof2) ."'";
$sql .= ",ape = '". $this->db->escape($this->idprof3) ."'";
$sql .= ",idprof4 = '". $this->db->escape($this->idprof4) ."'";
$sql .= ",idprof5 = '". $this->db->escape($this->idprof5) ."'";
$sql .= ",idprof6 = '". $this->db->escape($this->idprof6) ."'";
$sql .= ",tva_assuj = ".($this->tva_assuj!=''?"'".$this->tva_assuj."'":"null");
$sql .= ",tva_intra = '" . $this->db->escape($this->tva_intra) ."'";
$sql .= ",status = " .$this->status;
// Local taxes
$sql .= ",localtax1_assuj = ".($this->localtax1_assuj!=''?"'".$this->localtax1_assuj."'":"null");
$sql .= ",localtax2_assuj = ".($this->localtax2_assuj!=''?"'".$this->localtax2_assuj."'":"null");
if($this->localtax1_assuj==1)
{
if($this->localtax1_value!='')
{
$sql .=",localtax1_value =".$this->localtax1_value;
}
else $sql .=",localtax1_value =0.000";
}
else $sql .=",localtax1_value =0.000";
if($this->localtax2_assuj==1)
{
if($this->localtax2_value!='')
{
$sql .=",localtax2_value =".$this->localtax2_value;
}
else $sql .=",localtax2_value =0.000";
}
else $sql .=",localtax2_value =0.000";
$sql .= ",capital = ".($this->capital == '' ? "null" : $this->capital);
$sql .= ",prefix_comm = ".(! empty($this->prefix_comm)?"'".$this->db->escape($this->prefix_comm)."'":"null");
$sql .= ",fk_effectif = ".(! empty($this->effectif_id)?"'".$this->db->escape($this->effectif_id)."'":"null");
if (isset($this->stcomm_id))
{
$sql .= ",fk_stcomm='".$this->stcomm_id."'";
}
$sql .= ",fk_typent = ".(! empty($this->typent_id)?"'".$this->db->escape($this->typent_id)."'":"0");
$sql .= ",fk_forme_juridique = ".(! empty($this->forme_juridique_code)?"'".$this->db->escape($this->forme_juridique_code)."'":"null");
$sql .= ",mode_reglement = ".(! empty($this->mode_reglement_id)?"'".$this->db->escape($this->mode_reglement_id)."'":"null");
$sql .= ",cond_reglement = ".(! empty($this->cond_reglement_id)?"'".$this->db->escape($this->cond_reglement_id)."'":"null");
$sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
$sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
$sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
$sql .= ",client = " . (! empty($this->client)?$this->client:0);
$sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
$sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
$sql .= ",default_lang = ".(! empty($this->default_lang)?"'".$this->db->escape($this->default_lang)."'":"null");
$sql .= ",logo = ".(! empty($this->logo)?"'".$this->db->escape($this->logo)."'":"null");
$sql .= ",outstanding_limit= ".($this->outstanding_limit!=''?$this->outstanding_limit:'null');
$sql .= ",fk_prospectlevel='".$this->fk_prospectlevel."'";
$sql .= ",webservices_url = ".(! empty($this->webservices_url)?"'".$this->db->escape($this->webservices_url)."'":"null");
$sql .= ",webservices_key = ".(! empty($this->webservices_key)?"'".$this->db->escape($this->webservices_key)."'":"null");
//Incoterms
$sql.= ", fk_incoterms = ".$this->fk_incoterms;
$sql.= ", location_incoterms = ".(! empty($this->location_incoterms)?"'".$this->db->escape($this->location_incoterms)."'":"null");
if ($customer)
{
$sql .= ", code_client = ".(! empty($this->code_client)?"'".$this->db->escape($this->code_client)."'":"null");
$sql .= ", code_compta = ".(! empty($this->code_compta)?"'".$this->db->escape($this->code_compta)."'":"null");
}
if ($supplier)
{
$sql .= ", code_fournisseur = ".(! empty($this->code_fournisseur)?"'".$this->db->escape($this->code_fournisseur)."'":"null");
$sql .= ", code_compta_fournisseur = ".(! empty($this->code_compta_fournisseur)?"'".$this->db->escape($this->code_compta_fournisseur)."'":"null");
}
$sql .= ", fk_user_modif = ".(! empty($user->id)?"'".$user->id."'":"null");
$sql .= ", fk_multicurrency = ".(int) $this->fk_multicurrency;
$sql .= ', multicurrency_code = \''.$this->db->escape($this->multicurrency_code)."'";
$sql .= " WHERE rowid = '" . $id ."'";
dol_syslog(get_class($this)."::Update", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
unset($this->country_code); // We clean this because it may have been changed after an update of country_id
unset($this->country);
unset($this->state_code);
unset($this->state);
$nbrowsaffected = $this->db->affected_rows($resql);
if (! $error && $nbrowsaffected)
{
// Update information on linked member if it is an update
if (! $nosyncmember && ! empty($conf->adherent->enabled))
{
require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
dol_syslog(get_class($this)."::update update linked member");
$lmember=new Adherent($this->db);
$result=$lmember->fetch(0, 0, $this->id);
if ($result > 0)
{
$lmember->societe=$this->name;
//$lmember->firstname=$this->firstname?$this->firstname:$lmember->firstname; // We keep firstname and lastname of member unchanged
//$lmember->lastname=$this->lastname?$this->lastname:$lmember->lastname; // We keep firstname and lastname of member unchanged
$lmember->address=$this->address;
$lmember->email=$this->email;
$lmember->skype=$this->skype;
$lmember->phone=$this->phone;
$result=$lmember->update($user,0,1,1,1); // Use nosync to 1 to avoid cyclic updates
if ($result < 0)
{
$this->error=$lmember->error;
dol_syslog(get_class($this)."::update ".$this->error,LOG_ERR);
$error++;
}
}
else if ($result < 0)
{
$this->error=$lmember->error;
$error++;
}
}
}
$action='update';
// Actions on extra fields (by external module or standard code)
// TODO le hook fait double emploi avec le trigger !!
$hookmanager->initHooks(array('thirdpartydao'));
$parameters=array('socid'=>$this->id);
$reshook=$hookmanager->executeHooks('insertExtraFields',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if (empty($reshook))
{
if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
{
$result=$this->insertExtraFields();
if ($result < 0)
{
$error++;
}
}
}
else if ($reshook < 0) $error++;
if (! $error && $call_trigger)
{
// Call trigger
$result=$this->call_trigger('COMPANY_MODIFY',$user);
if ($result < 0) $error++;
// End call triggers
}
if (! $error)
{
dol_syslog(get_class($this)."::Update success");
$this->db->commit();
return 1;
}
else
{
$this->db->rollback();
return -1;
}
}
else
{
if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
{
// Doublon
$this->error = $langs->trans("ErrorDuplicateField");
$result = -1;
}
else
{
$result = -2;
}
$this->db->rollback();
return $result;
}
}
else
{
$this->db->rollback();
dol_syslog(get_class($this)."::Update fails verify ".join(',',$this->errors), LOG_WARNING);
return -3;
}
}
/**
* Load a third party from database into memory
*
* @param int $rowid Id of third party to load
* @param string $ref Reference of third party, name (Warning, this can return several records)
* @param string $ref_ext External reference of third party (Warning, this information is a free field not provided by Dolibarr)
* @param string $ref_int Internal reference of third party
* @param string $idprof1 Prof id 1 of third party (Warning, this can return several records)
* @param string $idprof2 Prof id 2 of third party (Warning, this can return several records)
* @param string $idprof3 Prof id 3 of third party (Warning, this can return several records)
* @param string $idprof4 Prof id 4 of third party (Warning, this can return several records)
* @param string $idprof5 Prof id 5 of third party (Warning, this can return several records)
* @param string $idprof6 Prof id 6 of third party (Warning, this can return several records)
* @return int >0 if OK, <0 if KO or if two records found for same ref or idprof, 0 if not found.
*/
function fetch($rowid, $ref='', $ref_ext='', $ref_int='', $idprof1='',$idprof2='',$idprof3='',$idprof4='',$idprof5='',$idprof6='')
{
global $langs;
global $conf;
if (empty($rowid) && empty($ref) && empty($ref_ext) && empty($ref_int) && empty($idprof1) && empty($idprof2) && empty($idprof3) && empty($idprof4) && empty($idprof5) && empty($idprof6)) return -1;
$sql = 'SELECT s.rowid, s.nom as name, s.name_alias, s.entity, s.ref_ext, s.ref_int, s.address, s.datec as date_creation, s.prefix_comm';
$sql .= ', s.status';
$sql .= ', s.price_level';
$sql .= ', s.tms as date_modification';
$sql .= ', s.phone, s.fax, s.email, s.skype, s.url, s.zip, s.town, s.note_private, s.note_public, s.model_pdf, s.client, s.fournisseur';
$sql .= ', s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6';
$sql .= ', s.capital, s.tva_intra';
$sql .= ', s.fk_typent as typent_id';
$sql .= ', s.fk_effectif as effectif_id';
$sql .= ', s.fk_forme_juridique as forme_juridique_code';
$sql .= ', s.webservices_url, s.webservices_key';
$sql .= ', s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur, s.parent, s.barcode';
$sql .= ', s.fk_departement, s.fk_pays as country_id, s.fk_stcomm, s.remise_client, s.mode_reglement, s.cond_reglement, s.fk_account, s.tva_assuj';
$sql .= ', s.mode_reglement_supplier, s.cond_reglement_supplier, s.localtax1_assuj, s.localtax1_value, s.localtax2_assuj, s.localtax2_value, s.fk_prospectlevel, s.default_lang, s.logo';
$sql .= ', s.fk_shipping_method';
$sql .= ', s.outstanding_limit, s.import_key, s.canvas, s.fk_incoterms, s.location_incoterms';
$sql .= ', s.fk_multicurrency, s.multicurrency_code';
$sql .= ', fj.libelle as forme_juridique';
$sql .= ', e.libelle as effectif';
$sql .= ', c.code as country_code, c.label as country';
$sql .= ', d.code_departement as state_code, d.nom as state';
$sql .= ', st.libelle as stcomm';
$sql .= ', te.code as typent_code';
$sql .= ', i.libelle as libelle_incoterms';
$sql .= ' FROM '.MAIN_DB_PREFIX.'societe as s';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_effectif as e ON s.fk_effectif = e.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON s.fk_pays = c.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_stcomm as st ON s.fk_stcomm = st.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_forme_juridique as fj ON s.fk_forme_juridique = fj.code';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON s.fk_departement = d.rowid';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_typent as te ON s.fk_typent = te.id';
$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_incoterms as i ON s.fk_incoterms = i.rowid';
if ($rowid) $sql .= ' WHERE s.rowid = '.$rowid;
else if ($ref) $sql .= " WHERE s.nom = '".$this->db->escape($ref)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($ref_ext) $sql .= " WHERE s.ref_ext = '".$this->db->escape($ref_ext)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($ref_int) $sql .= " WHERE s.ref_int = '".$this->db->escape($ref_int)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof1) $sql .= " WHERE s.siren = '".$this->db->escape($idprof1)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof2) $sql .= " WHERE s.siret = '".$this->db->escape($idprof2)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof3) $sql .= " WHERE s.ape = '".$this->db->escape($idprof3)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof4) $sql .= " WHERE s.idprof4 = '".$this->db->escape($idprof4)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof5) $sql .= " WHERE s.idprof5 = '".$this->db->escape($idprof5)."' AND s.entity IN (".getEntity($this->element, 1).")";
else if ($idprof6) $sql .= " WHERE s.idprof6 = '".$this->db->escape($idprof6)."' AND s.entity IN (".getEntity($this->element, 1).")";
$resql=$this->db->query($sql);
dol_syslog(get_class($this)."::fetch ".$sql);
if ($resql)
{
$num=$this->db->num_rows($resql);
if ($num > 1)
{
$this->error='Fetch found several records. Rename one of tirdparties to avoid duplicate.';
dol_syslog($this->error, LOG_ERR);
$result = -2;
}
elseif ($num) // $num = 1
{
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->entity = $obj->entity;
$this->canvas = $obj->canvas;
$this->ref = $obj->rowid;
$this->name = $obj->name;
$this->nom = $obj->name; // deprecated
$this->name_alias = $obj->name_alias;
$this->ref_ext = $obj->ref_ext;
$this->ref_int = $obj->ref_int;
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_modification = $this->db->jdate($obj->date_modification);
$this->address = $obj->address;
$this->zip = $obj->zip;
$this->town = $obj->town;
$this->country_id = $obj->country_id;
$this->country_code = $obj->country_id?$obj->country_code:'';
$this->country = $obj->country_id?($langs->trans('Country'.$obj->country_code)!='Country'.$obj->country_code?$langs->transnoentities('Country'.$obj->country_code):$obj->country):'';
$this->state_id = $obj->fk_departement;
$this->state_code = $obj->state_code;
$this->state = ($obj->state!='-'?$obj->state:'');
$transcode=$langs->trans('StatusProspect'.$obj->fk_stcomm);
$libelle=($transcode!='StatusProspect'.$obj->fk_stcomm?$transcode:$obj->stcomm);
$this->stcomm_id = $obj->fk_stcomm; // id statut commercial
$this->statut_commercial = $libelle; // libelle statut commercial
$this->email = $obj->email;
$this->skype = $obj->skype;
$this->url = $obj->url;
$this->phone = $obj->phone;
$this->fax = $obj->fax;
$this->parent = $obj->parent;
$this->idprof1 = $obj->idprof1;
$this->idprof2 = $obj->idprof2;
$this->idprof3 = $obj->idprof3;
$this->idprof4 = $obj->idprof4;
$this->idprof5 = $obj->idprof5;
$this->idprof6 = $obj->idprof6;
$this->capital = $obj->capital;
$this->code_client = $obj->code_client;
$this->code_fournisseur = $obj->code_fournisseur;
$this->code_compta = $obj->code_compta;
$this->code_compta_fournisseur = $obj->code_compta_fournisseur;
$this->barcode = $obj->barcode;
$this->tva_assuj = $obj->tva_assuj;
$this->tva_intra = $obj->tva_intra;
$this->status = $obj->status;
// Local Taxes
$this->localtax1_assuj = $obj->localtax1_assuj;
$this->localtax2_assuj = $obj->localtax2_assuj;
$this->localtax1_value = $obj->localtax1_value;
$this->localtax2_value = $obj->localtax2_value;
$this->typent_id = $obj->typent_id;
$this->typent_code = $obj->typent_code;
$this->effectif_id = $obj->effectif_id;
$this->effectif = $obj->effectif_id?$obj->effectif:'';
$this->forme_juridique_code= $obj->forme_juridique_code;
$this->forme_juridique = $obj->forme_juridique_code?$obj->forme_juridique:'';
$this->fk_prospectlevel = $obj->fk_prospectlevel;
$this->prefix_comm = $obj->prefix_comm;
$this->remise_percent = $obj->remise_client;
$this->mode_reglement_id = $obj->mode_reglement;
$this->cond_reglement_id = $obj->cond_reglement;
$this->mode_reglement_supplier_id = $obj->mode_reglement_supplier;
$this->cond_reglement_supplier_id = $obj->cond_reglement_supplier;
$this->shipping_method_id = ($obj->fk_shipping_method>0)?$obj->fk_shipping_method:null;
$this->fk_account = $obj->fk_account;
$this->client = $obj->client;
$this->fournisseur = $obj->fournisseur;
$this->note = $obj->note_private; // TODO Deprecated for backward comtability
$this->note_private = $obj->note_private;
$this->note_public = $obj->note_public;
$this->modelpdf = $obj->model_pdf;
$this->default_lang = $obj->default_lang;
$this->logo = $obj->logo;
$this->webservices_url = $obj->webservices_url;
$this->webservices_key = $obj->webservices_key;
$this->outstanding_limit = $obj->outstanding_limit;
// multiprix
$this->price_level = $obj->price_level;
$this->import_key = $obj->import_key;
//Incoterms
$this->fk_incoterms = $obj->fk_incoterms;
$this->location_incoterms = $obj->location_incoterms;
$this->libelle_incoterms = $obj->libelle_incoterms;
// multicurrency
$this->fk_multicurrency = $obj->fk_multicurrency;
$this->multicurrency_code = $obj->multicurrency_code;
$result = 1;
// Retreive all extrafield for thirdparty
// fetch optionals attributes and labels
require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
$extrafields=new ExtraFields($this->db);
$extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
$this->fetch_optionals($this->id,$extralabels);
}
else
{
$result = 0;
}
$this->db->free($resql);
}
else
{
$this->error=$this->db->lasterror();
$result = -3;
}
// Use first price level if level not defined for third party
if (! empty($conf->global->PRODUIT_MULTIPRICES) && empty($this->price_level)) $this->price_level=1;
return $result;
}
/**
* Search and fetch thirparties by name
*
* @param string $name Name
* @param int $type Type of thirdparties (0=any, 1=customer, 2=prospect, 3=supplier)
* @param array $filters Array of couple field name/value to filter the companies with the same name
* @param boolean $exact Exact string search (true/false)
* @param boolean $case Case sensitive (true/false)
* @param boolean $similar Add test if string inside name into database, or name into database inside string. Do not use this: Not compatible with other database.
* @param string $clause Clause for filters
* @return array|int <0 if KO, array of thirdparties object if OK
*/
function searchByName($name, $type='0', $filters = array(), $exact = false, $case = false, $similar = false, $clause = 'AND')
{
$thirdparties = array();
dol_syslog("searchByName name=".$name." type=".$type." exact=".$exact);
// Check parameter
if (empty($name))
{
$this->errors[]='ErrorBadValueForParameter';
return -1;
}
// Generation requete recherche
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe";
$sql.= " WHERE entity IN (".getEntity('category',1).")";
if (! empty($type))
{
if ($type == 1 || $type == 2)
$sql.= " AND client = ".$type;
elseif ($type == 3)
$sql.= " AND fournisseur = 1";
}
if (! empty($name))
{
if (! $exact)
{
if (preg_match('/^([\*])?[^*]+([\*])?$/', $name, $regs) && count($regs) > 1)
{
$name = str_replace('*', '%', $name);
}
else
{
$name = '%'.$name.'%';
}
}
$sql.= " AND ";
if (is_array($filters) && ! empty($filters))
$sql.= "(";
if ($similar)
{
// For test similitude (string inside name into database, or name into database inside string)
// Do not use this. Not compatible with other database.
$sql.= "(LOCATE('".$this->db->escape($name)."', nom) > 0 OR LOCATE(nom, '".$this->db->escape($name)."') > 0)";
}
else
{
if (! $case)
$sql.= "nom LIKE '".$this->db->escape($name)."'";
else
$sql.= "nom LIKE BINARY '".$this->db->escape($name)."'";
}
}
if (is_array($filters) && ! empty($filters))
{
foreach($filters as $field => $value)
{
if (! $exact)
{
if (preg_match('/^([\*])?[^*]+([\*])?$/', $value, $regs) && count($regs) > 1)
{
$value = str_replace('*', '%', $value);
}
else
{
$value = '%'.$value.'%';
}
}
if (! $case)
$sql.= " ".$clause." ".$field." LIKE '".$this->db->escape($value)."'";
else
$sql.= " ".$clause." ".$field." LIKE BINARY '".$this->db->escape($value)."'";
}
if (! empty($name))
$sql.= ")";
}
$res = $this->db->query($sql);
if ($res)
{
while ($rec = $this->db->fetch_array($res))
{
$soc = new Societe($this->db);
$soc->fetch($rec['rowid']);
$thirdparties[] = $soc;
}
return $thirdparties;
}
else
{
$this->error=$this->db->lasterror();
return -1;
}
}
/**
* Delete a third party from database and all its dependencies (contacts, rib...)
*
* @param int $id Id of third party to delete
* @param User $fuser User who ask to delete thirparty
* @param int $call_trigger 0=No, 1=yes
* @return int <0 if KO, 0 if nothing done, >0 if OK
*/
function delete($id, User $fuser=null, $call_trigger=1)
{
global $langs, $conf, $user;
if (empty($fuser)) $fuser=$user;
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
$entity=isset($this->entity)?$this->entity:$conf->entity;
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
$error = 0;
// Test if child exists
$objectisused = $this->isObjectUsed($id);
if (empty($objectisused))
{
$this->db->begin();
// User is mandatory for trigger call
if (! $error && $call_trigger)
{
// Call trigger
$result=$this->call_trigger('COMPANY_DELETE',$fuser);
if ($result < 0) $error++;
// End call triggers
}
if (! $error)
{
require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
$static_cat = new Categorie($this->db);
$toute_categs = array();
// Fill $toute_categs array with an array of (type => array of ("Categorie" instance))
if ($this->client || $this->prospect)
{
$toute_categs ['societe'] = $static_cat->containing($this->id,Categorie::TYPE_CUSTOMER);
}
if ($this->fournisseur)
{
$toute_categs ['fournisseur'] = $static_cat->containing($this->id,Categorie::TYPE_SUPPLIER);
}
// Remove each "Categorie"
foreach ($toute_categs as $type => $categs_type)
{
foreach ($categs_type as $cat)
{
$cat->del_type($this, $type);
}
}
}
// Remove contacts
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error .= $this->db->lasterror();
}
}
// Update link in member table
if (! $error)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
$sql.= " SET fk_soc = NULL WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error .= $this->db->lasterror();
dol_syslog(get_class($this)."::delete erreur -1 ".$this->error, LOG_ERR);
}
}
// Remove ban
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_rib";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove societe_remise
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove societe_remise_except
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise_except";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Remove associated users
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " WHERE fk_soc = " . $id;
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
// Removed extrafields
if ((! $error) && (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
{
$result=$this->deleteExtraFields();
if ($result < 0)
{
$error++;
dol_syslog(get_class($this)."::delete error -3 ".$this->error, LOG_ERR);
}
}
// Remove third party
if (! $error)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe";
$sql.= " WHERE rowid = " . $id;
dol_syslog(get_class($this)."::delete", LOG_DEBUG);
if (! $this->db->query($sql))
{
$error++;
$this->error = $this->db->lasterror();
}
}
if (! $error)
{
$this->db->commit();
// Delete directory
if (! empty($conf->societe->multidir_output[$entity]))
{
$docdir = $conf->societe->multidir_output[$entity] . "/" . $id;
if (dol_is_dir($docdir))
{
dol_delete_dir_recursive($docdir);
}
}
return 1;
}
else
{
dol_syslog($this->error, LOG_ERR);
$this->db->rollback();
return -1;
}
}
else dol_syslog("Can't remove thirdparty with id ".$id.". There is ".$objectisused." childs", LOG_WARNING);
return 0;
}
/**
* Define third party as a customer
*
* @return int <0 if KO, >0 if OK
*/
function set_as_client()
{
if ($this->id)
{
$newclient=1;
if ($this->client == 2 || $this->client == 3) $newclient=3; //If prospect, we keep prospect tag
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql.= " SET client = ".$newclient;
$sql.= " WHERE rowid = " . $this->id;
$resql=$this->db->query($sql);
if ($resql)
{
$this->client = $newclient;
return 1;
}
else return -1;
}
return 0;
}
/**
* Definit la societe comme un client
*
* @param float $remise Valeur en % de la remise
* @param string $note Note/Motif de modification de la remise
* @param User $user Utilisateur qui definie la remise
* @return int <0 if KO, >0 if OK
*/
function set_remise_client($remise, $note, User $user)
{
global $conf, $langs;
// Nettoyage parametres
$note=trim($note);
if (! $note)
{
$this->error=$langs->trans("ErrorFieldRequired",$langs->trans("Note"));
return -2;
}
dol_syslog(get_class($this)."::set_remise_client ".$remise.", ".$note.", ".$user->id);
if ($this->id)
{
$this->db->begin();
$now=dol_now();
// Positionne remise courante
$sql = "UPDATE ".MAIN_DB_PREFIX."societe ";
$sql.= " SET remise_client = '".$this->db->escape($remise)."'";
$sql.= " WHERE rowid = " . $this->id .";";
$resql=$this->db->query($sql);
if (! $resql)
{
$this->db->rollback();
$this->error=$this->db->error();
return -1;
}
// Ecrit trace dans historique des remises
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
$sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
$sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
$sql.= " '".$this->db->escape($note)."',";
$sql.= " ".$user->id;
$sql.= ")";
$resql=$this->db->query($sql);
if (! $resql)
{
$this->db->rollback();
$this->error=$this->db->lasterror();
return -1;
}
$this->db->commit();
return 1;
}
}
/**
* Add a discount for third party
*
* @param float $remise Amount of discount
* @param User $user User adding discount
* @param string $desc Reason of discount
* @param float $tva_tx VAT rate
* @return int <0 if KO, id of discount record if OK
*/
function set_remise_except($remise, User $user, $desc, $tva_tx=0)
{
global $langs;
// Clean parameters
$remise = price2num($remise);
$desc = trim($desc);
// Check parameters
if (! $remise > 0)
{
$this->error=$langs->trans("ErrorWrongValueForParameter","1");
return -1;
}
if (! $desc)
{
$this->error=$langs->trans("ErrorWrongValueForParameter","3");
return -2;
}
if ($this->id)
{
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discount = new DiscountAbsolute($this->db);
$discount->fk_soc=$this->id;
$discount->amount_ht=price2num($remise,'MT');
$discount->amount_tva=price2num($remise*$tva_tx/100,'MT');
$discount->amount_ttc=price2num($discount->amount_ht+$discount->amount_tva,'MT');
$discount->tva_tx=price2num($tva_tx,'MT');
$discount->description=$desc;
$result=$discount->create($user);
if ($result > 0)
{
return $result;
}
else
{
$this->error=$discount->error;
return -3;
}
}
else return 0;
}
/**
* Renvoie montant TTC des reductions/avoirs en cours disponibles de la societe
*
* @param User $user Filtre sur un user auteur des remises
* @param string $filter Filtre autre
* @param integer $maxvalue Filter on max value for discount
* @return int <0 if KO, Credit note amount otherwise
*/
function getAvailableDiscounts($user='',$filter='',$maxvalue=0)
{
require_once DOL_DOCUMENT_ROOT.'/core/class/discount.class.php';
$discountstatic=new DiscountAbsolute($this->db);
$result=$discountstatic->getAvailableDiscounts($this,$user,$filter,$maxvalue);
if ($result >= 0)
{
return $result;
}
else
{
$this->error=$discountstatic->error;
return -1;
}
}
/**
* Return array of sales representatives
*
* @param User $user Object user
* @return array Array of sales representatives of third party
*/
function getSalesRepresentatives(User $user)
{
global $conf;
$reparray=array();
$sql = "SELECT DISTINCT u.rowid, u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo";
$sql.= " FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc, ".MAIN_DB_PREFIX."user as u";
if (! empty($conf->multicompany->enabled) && ! empty($conf->multicompany->transverse_mode))
{
$sql.= ", ".MAIN_DB_PREFIX."usergroup_user as ug";
$sql.= " WHERE ((ug.fk_user = sc.fk_user";
$sql.= " AND ug.entity = ".$conf->entity.")";
$sql.= " OR u.admin = 1)";
}
else
$sql.= " WHERE entity in (0, ".$conf->entity.")";
$sql.= " AND u.rowid = sc.fk_user AND sc.fk_soc =".$this->id;
$resql = $this->db->query($sql);
if ($resql)
{
$num = $this->db->num_rows($resql);
$i=0;
while ($i < $num)
{
$obj = $this->db->fetch_object($resql);
$reparray[$i]['id']=$obj->rowid;
$reparray[$i]['lastname']=$obj->lastname;
$reparray[$i]['firstname']=$obj->firstname;
$reparray[$i]['email']=$obj->email;
$reparray[$i]['statut']=$obj->statut;
$reparray[$i]['entity']=$obj->entity;
$reparray[$i]['login']=$obj->login;
$reparray[$i]['photo']=$obj->photo;
$i++;
}
return $reparray;
}
else {
dol_print_error($this->db);
return -1;
}
}
/**
* Set the price level
*
* @param int $price_level Level of price
* @param User $user Use making change
* @return int <0 if KO, >0 if OK
*/
function set_price_level($price_level, User $user)
{
if ($this->id)
{
$now=dol_now();
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql .= " SET price_level = '".$this->db->escape($price_level)."'";
$sql .= " WHERE rowid = " . $this->id;
if (! $this->db->query($sql))
{
dol_print_error($this->db);
return -1;
}
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_prices";
$sql .= " (datec, fk_soc, price_level, fk_user_author)";
$sql .= " VALUES ('".$this->db->idate($now)."',".$this->id.",'".$this->db->escape($price_level)."',".$user->id.")";
if (! $this->db->query($sql))
{
dol_print_error($this->db);
return -1;
}
return 1;
}
return -1;
}
/**
* Add link to sales representative
*
* @param User $user Object user
* @param int $commid Id of user
* @return void
*/
function add_commercial(User $user, $commid)
{
if ($this->id > 0 && $commid > 0)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
$this->db->query($sql);
$sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_commerciaux";
$sql.= " ( fk_soc, fk_user )";
$sql.= " VALUES (".$this->id.",".$commid.")";
if (! $this->db->query($sql) )
{
dol_syslog(get_class($this)."::add_commercial Erreur");
}
}
}
/**
* Add link to sales representative
*
* @param User $user Object user
* @param int $commid Id of user
* @return void
*/
function del_commercial(User $user, $commid)
{
if ($this->id > 0 && $commid > 0)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_commerciaux ";
$sql .= " WHERE fk_soc = ".$this->id." AND fk_user =".$commid;
if (! $this->db->query($sql) )
{
dol_syslog(get_class($this)."::del_commercial Erreur");
}
}
}
/**
* Return a link on thirdparty (with picto)
*
* @param int $withpicto Add picto into link (0=No picto, 1=Include picto with link, 2=Picto only)
* @param string $option Target of link ('', 'customer', 'prospect', 'supplier', 'project')
* @param int $maxlen Max length of name
* @param int $notooltip 1=Disable tooltip
* @return string String with URL
*/
function getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0)
{
global $conf, $langs, $hookmanager;
if (! empty($conf->dol_no_mouse_hover)) $notooltip=1; // Force disable tooltips
$name=$this->name?$this->name:$this->nom;
if (! empty($conf->global->SOCIETE_ADD_REF_IN_LIST) && (!empty($withpicto)))
{
if (($this->client) && (! empty ( $this->code_client ))) {
$code = $this->code_client . ' - ';
}
if (($this->fournisseur) && (! empty ( $this->code_fournisseur ))) {
$code .= $this->code_fournisseur . ' - ';
}
$name =$code.' '.$name;
}
if (!empty($this->name_alias)) $name .= ' ('.$this->name_alias.')';
$result=''; $label='';
$linkstart=''; $linkend='';
$label.= '<div width="100%">';
if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
{
$label.= '<u>' . $langs->trans("ShowCustomer") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
}
else if ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
{
$label.= '<u>' . $langs->trans("ShowProspect") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
}
else if ($option == 'supplier')
{
$label.= '<u>' . $langs->trans("ShowSupplier") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
}
else if ($option == 'agenda')
{
$label.= '<u>' . $langs->trans("ShowAgenda") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
}
else if ($option == 'project')
{
$label.= '<u>' . $langs->trans("ShowProject") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
}
else if ($option == 'margin')
{
$label.= '<u>' . $langs->trans("ShowMargin") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
}
// By default
if (empty($linkstart))
{
$label.= '<u>' . $langs->trans("ShowCompany") . '</u>';
$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/soc.php?socid='.$this->id;
}
if (! empty($this->name))
{
$label.= '<br><b>' . $langs->trans('Name') . ':</b> '. $this->name;
if (! empty($this->name_alias)) $label.=' ('.$this->name_alias.')';
}
if (! empty($this->code_client) && $this->client)
$label.= '<br><b>' . $langs->trans('CustomerCode') . ':</b> '. $this->code_client;
if (! empty($this->code_fournisseur) && $this->fournisseur)
$label.= '<br><b>' . $langs->trans('SupplierCode') . ':</b> '. $this->code_fournisseur;
if (! empty($conf->accounting->enabled) && $this->client)
$label.= '<br><b>' . $langs->trans('CustomerAccountancyCode') . ':</b> '. $this->code_compta_client;
if (! empty($conf->accounting->enabled) && $this->fournisseur)
$label.= '<br><b>' . $langs->trans('SupplierAccountancyCode') . ':</b> '. $this->code_compta_fournisseur;
if (! empty($this->logo))
{
$label.= '</br><div class="photointooltip">';
//if (! is_object($form)) $form = new Form($db);
$label.= Form::showphoto('societe', $this, 80, 0, 0, 'photowithmargin', 'mini');
$label.= '</div><div style="clear: both;"></div>';
}
$label.= '</div>';
// Add type of canvas
$linkstart.=(!empty($this->canvas)?'&canvas='.$this->canvas:'').'"';
$linkclose='';
if (empty($notooltip))
{
if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
{
$label=$langs->trans("ShowCompany");
$linkclose.=' alt="'.dol_escape_htmltag($label, 1).'"';
}
$linkclose.= ' title="'.dol_escape_htmltag($label, 1).'"';
$linkclose.=' class="classfortooltip"';
if (! is_object($hookmanager))
{
include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
$hookmanager=new HookManager($this->db);
}
$hookmanager->initHooks(array('societedao'));
$parameters=array('id'=>$this->id);
$reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if ($reshook > 0) $linkclose = $hookmanager->resPrint;
}
$linkstart.=$linkclose.'>';
$linkend='</a>';
if ($withpicto) $result.=($linkstart.img_object(($notooltip?'':$label), 'company', ($notooltip?'':'class="classfortooltip"'), 0, 0, $notooltip?0:1).$linkend);
if ($withpicto && $withpicto != 2) $result.=' ';
if ($withpicto != 2) $result.=$linkstart.($maxlen?dol_trunc($name,$maxlen):$name).$linkend;
return $result;
}
/**
* Return label of status (activity, closed)
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
* @return string Libelle
*/
function getLibStatut($mode=0)
{
return $this->LibStatut($this->status,$mode);
}
/**
* Renvoi le libelle d'un statut donne
*
* @param int $statut Id statut
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
* @return string Libelle du statut
*/
function LibStatut($statut,$mode=0)
{
global $langs;
$langs->load('companies');
if ($mode == 0)
{
if ($statut==0) return $langs->trans("ActivityCeased");
if ($statut==1) return $langs->trans("InActivity");
}
if ($mode == 1)
{
if ($statut==0) return $langs->trans("ActivityCeased");
if ($statut==1) return $langs->trans("InActivity");
}
if ($mode == 2)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
}
if ($mode == 3)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
}
if ($mode == 4)
{
if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
}
if ($mode == 5)
{
if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
}
}
/**
* Return list of contacts emails existing for third party
*
* @param int $addthirdparty 1=Add also a record for thirdparty email
* @return array Array of contacts emails
*/
function thirdparty_and_contact_email_array($addthirdparty=0)
{
global $langs;
$contact_emails = $this->contact_property_array('email',1);
if ($this->email && $addthirdparty)
{
if (empty($this->name)) $this->name=$this->nom;
$contact_emails['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->email.">";
}
return $contact_emails;
}
/**
* Return list of contacts mobile phone existing for third party
*
* @return array Array of contacts emails
*/
function thirdparty_and_contact_phone_array()
{
global $langs;
$contact_phone = $this->contact_property_array('mobile');
if (! empty($this->phone)) // If a phone of thirdparty is defined, we add it ot mobile of contacts
{
if (empty($this->name)) $this->name=$this->nom;
// TODO: Tester si tel non deja present dans tableau contact
$contact_phone['thirdparty']=$langs->trans("ThirdParty").': '.dol_trunc($this->name,16)." <".$this->phone.">";
}
return $contact_phone;
}
/**
* Return list of contacts emails or mobile existing for third party
*
* @param string $mode 'email' or 'mobile'
* @param int $hidedisabled 1=Hide contact if disabled
* @return array Array of contacts emails or mobile array(id=>'Name <email>')
*/
function contact_property_array($mode='email', $hidedisabled=0)
{
global $langs;
$contact_property = array();
$sql = "SELECT rowid, email, statut, phone_mobile, lastname, poste, firstname";
$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$sepa="("; $sepb=")";
if ($mode == 'email')
{
$sepa="<"; $sepb=">";
}
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
if ($mode == 'email') $property=$obj->email;
else if ($mode == 'mobile') $property=$obj->phone_mobile;
else $property=$obj->$mode;
// Show all contact. If hidedisabled is 1, showonly contacts with status = 1
if ($obj->statut == 1 || empty($hidedisabled))
{
if (empty($property))
{
if ($mode == 'email') $property=$langs->trans("NoEMail");
else if ($mode == 'mobile') $property=$langs->trans("NoMobilePhone");
}
if (!empty($obj->poste))
{
$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).($obj->poste?" - ".$obj->poste:"").(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
}
else
{
$contact_property[$obj->rowid] = trim(dolGetFirstLastname($obj->firstname,$obj->lastname)).(($mode != 'poste' && $property)?" ".$sepa.$property.$sepb:'');
}
}
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contact_property;
}
/**
* Renvoie la liste des contacts de cette societe
*
* @return array tableau des contacts
*/
function contact_array()
{
$contacts = array();
$sql = "SELECT rowid, lastname, firstname FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
$contacts[$obj->rowid] = dolGetFirstLastname($obj->firstname,$obj->lastname);
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contacts;
}
/**
* Renvoie la liste des contacts de cette societe
*
* @return array $contacts tableau des contacts
*/
function contact_array_objects()
{
require_once DOL_DOCUMENT_ROOT . '/contact/class/contact.class.php';
$contacts = array();
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."socpeople WHERE fk_soc = '".$this->id."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$i = 0;
while ($i < $nump)
{
$obj = $this->db->fetch_object($resql);
$contact = new Contact($this->db);
$contact->fetch($obj->rowid);
$contacts[] = $contact;
$i++;
}
}
}
else
{
dol_print_error($this->db);
}
return $contacts;
}
/**
* Return property of contact from its id
*
* @param int $rowid id of contact
* @param string $mode 'email' or 'mobile'
* @return string Email of contact with format: "Full name <email>"
*/
function contact_get_property($rowid,$mode)
{
$contact_property='';
if (empty($rowid)) return '';
$sql = "SELECT rowid, email, phone_mobile, lastname, firstname";
$sql.= " FROM ".MAIN_DB_PREFIX."socpeople";
$sql.= " WHERE rowid = '".$rowid."'";
$resql=$this->db->query($sql);
if ($resql)
{
$nump = $this->db->num_rows($resql);
if ($nump)
{
$obj = $this->db->fetch_object($resql);
if ($mode == 'email') $contact_property = dolGetFirstLastname($obj->firstname, $obj->lastname)." <".$obj->email.">";
else if ($mode == 'mobile') $contact_property = $obj->phone_mobile;
}
return $contact_property;
}
else
{
dol_print_error($this->db);
}
}
/**
* Return bank number property of thirdparty (label or rum)
*
* @param string $mode 'label' or 'rum'
* @return string Bank number
*/
function display_rib($mode='label')
{
require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
$bac = new CompanyBankAccount($this->db);
$bac->fetch(0,$this->id);
if ($mode == 'label')
{
return $bac->getRibLabel(true);
}
elseif ($mode == 'rum')
{
if (empty($bac->rum))
{
require_once DOL_DOCUMENT_ROOT . '/compta/prelevement/class/bonprelevement.class.php';
$prelevement = new BonPrelevement($this->db);
$bac->fetch_thirdparty();
$bac->rum = $prelevement->buildRumNumber($bac->thirdparty->code_client, $bac->datec, $bac->id);
}
return $bac->rum;
}
return 'BadParameterToFunctionDisplayRib';
}
/**
* Return Array of RIB
*
* @return array|int 0 if KO, Array of CompanyBanckAccount if OK
*/
function get_all_rib()
{
require_once DOL_DOCUMENT_ROOT . '/societe/class/companybankaccount.class.php';
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."societe_rib WHERE fk_soc = ".$this->id;
$result = $this->db->query($sql);
if (!$result) {
$this->error++;
$this->errors[] = $this->db->lasterror;
return 0;
} else {
$num_rows = $this->db->num_rows($result);
$rib_array = array();
if ($num_rows) {
while ($obj = $this->db->fetch_object($result)) {
$rib = new CompanyBankAccount($this->db);
$rib->fetch($obj->rowid);
$rib_array[] = $rib;
}
}
return $rib_array;
}
}
/**
* Attribut un code client a partir du module de controle des codes.
* Return value is stored into this->code_client
*
* @param Societe $objsoc Object thirdparty
* @param int $type Should be 0 to say customer
* @return void
*/
function get_codeclient($objsoc=0,$type=0)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
$this->code_client = $mod->getNextValue($objsoc,$type);
$this->prefixCustomerIsRequired = $mod->prefixIsRequired;
dol_syslog(get_class($this)."::get_codeclient code_client=".$this->code_client." module=".$module);
}
}
/**
* Attribut un code fournisseur a partir du module de controle des codes.
* Return value is stored into this->code_fournisseur
*
* @param Societe $objsoc Object thirdparty
* @param int $type Should be 1 to say supplier
* @return void
*/
function get_codefournisseur($objsoc=0,$type=1)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
$this->code_fournisseur = $mod->getNextValue($objsoc,$type);
dol_syslog(get_class($this)."::get_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
}
}
/**
* Verifie si un code client est modifiable en fonction des parametres
* du module de controle des codes.
*
* @return int 0=No, 1=Yes
*/
function codeclient_modifiable()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::codeclient_modifiable code_client=".$this->code_client." module=".$module);
if ($mod->code_modifiable_null && ! $this->code_client) return 1;
if ($mod->code_modifiable_invalide && $this->check_codeclient() < 0) return 1;
if ($mod->code_modifiable) return 1; // A mettre en dernier
return 0;
}
else
{
return 0;
}
}
/**
* Verifie si un code fournisseur est modifiable dans configuration du module de controle des codes
*
* @return int 0=No, 1=Yes
*/
function codefournisseur_modifiable()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::codefournisseur_modifiable code_founisseur=".$this->code_fournisseur." module=".$module);
if ($mod->code_modifiable_null && ! $this->code_fournisseur) return 1;
if ($mod->code_modifiable_invalide && $this->check_codefournisseur() < 0) return 1;
if ($mod->code_modifiable) return 1; // A mettre en dernier
return 0;
}
else
{
return 0;
}
}
/**
* Check customer code
*
* @return int 0 if OK
* -1 ErrorBadCustomerCodeSyntax
* -2 ErrorCustomerCodeRequired
* -3 ErrorCustomerCodeAlreadyUsed
* -4 ErrorPrefixRequired
*/
function check_codeclient()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::check_codeclient code_client=".$this->code_client." module=".$module);
$result = $mod->verif($this->db, $this->code_client, $this, 0);
return $result;
}
else
{
return 0;
}
}
/**
* Check supplier code
*
* @return int 0 if OK
* -1 ErrorBadCustomerCodeSyntax
* -2 ErrorCustomerCodeRequired
* -3 ErrorCustomerCodeAlreadyUsed
* -4 ErrorPrefixRequired
*/
function check_codefournisseur()
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECLIENT_ADDON))
{
$module=$conf->global->SOCIETE_CODECLIENT_ADDON;
$dirsociete=array_merge(array('/core/modules/societe/'),$conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
$res=dol_include_once($dirroot.$module.'.php');
if ($res) break;
}
$mod = new $module();
dol_syslog(get_class($this)."::check_codefournisseur code_fournisseur=".$this->code_fournisseur." module=".$module);
$result = $mod->verif($this->db, $this->code_fournisseur, $this, 1);
return $result;
}
else
{
return 0;
}
}
/**
* Renvoie un code compta, suivant le module de code compta.
* Peut etre identique a celui saisit ou genere automatiquement.
* A ce jour seule la generation automatique est implementee
*
* @param string $type Type of thirdparty ('customer' or 'supplier')
* @return string Code compta si ok, 0 si aucun, <0 si ko
*/
function get_codecompta($type)
{
global $conf;
if (! empty($conf->global->SOCIETE_CODECOMPTA_ADDON))
{
$file='';
$dirsociete=array_merge(array('/core/modules/societe/'), $conf->modules_parts['societe']);
foreach ($dirsociete as $dirroot)
{
if (file_exists(DOL_DOCUMENT_ROOT.'/'.$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php"))
{
$file=$dirroot.$conf->global->SOCIETE_CODECOMPTA_ADDON.".php";
break;
}
}
if (! empty($file))
{
dol_include_once($file);
$classname = $conf->global->SOCIETE_CODECOMPTA_ADDON;
$mod = new $classname;
// Defini code compta dans $mod->code
$result = $mod->get_code($this->db, $this, $type);
if ($type == 'customer') $this->code_compta = $mod->code;
else if ($type == 'supplier') $this->code_compta_fournisseur = $mod->code;
return $result;
}
else
{
$this->error = 'ErrorAccountancyCodeNotDefined';
return -1;
}
}
else
{
if ($type == 'customer') $this->code_compta = '';
else if ($type == 'supplier') $this->code_compta_fournisseur = '';
return 0;
}
}
/**
* Define parent commany of current company
*
* @param int $id Id of thirdparty to set or '' to remove
* @return int <0 if KO, >0 if OK
*/
function set_parent($id)
{
if ($this->id)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."societe";
$sql.= " SET parent = ".($id > 0 ? $id : "null");
$sql.= " WHERE rowid = " . $this->id;
dol_syslog(get_class($this).'::set_parent', LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$this->parent = $id;
return 1;
}
else
{
return -1;
}
}
else return -1;
}
/**
* Returns if a profid sould be verified
*
* @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
* @return boolean true , false
*/
function id_prof_verifiable($idprof)
{
global $conf;
switch($idprof)
{
case 1:
$ret=(!$conf->global->SOCIETE_IDPROF1_UNIQUE?false:true);
break;
case 2:
$ret=(!$conf->global->SOCIETE_IDPROF2_UNIQUE?false:true);
break;
case 3:
$ret=(!$conf->global->SOCIETE_IDPROF3_UNIQUE?false:true);
break;
case 4:
$ret=(!$conf->global->SOCIETE_IDPROF4_UNIQUE?false:true);
break;
default:
$ret=false;
}
return $ret;
}
/**
* Verify if a profid exists into database for others thirds
*
* @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param string $value Value of profid
* @param int $socid Id of thirdparty if update
* @return boolean true if exists, false if not
*/
function id_prof_exists($idprof,$value,$socid=0)
{
switch($idprof)
{
case 1:
$field="siren";
break;
case 2:
$field="siret";
break;
case 3:
$field="ape";
break;
case 4:
$field="idprof4";
break;
}
//Verify duplicate entries
$sql = "SELECT COUNT(*) as idprof FROM ".MAIN_DB_PREFIX."societe WHERE ".$field." = '".$value."' AND entity IN (".getEntity('societe',1).")";
if($socid) $sql .= " AND rowid <> ".$socid;
$resql = $this->db->query($sql);
if ($resql)
{
$obj = $this->db->fetch_object($resql);
$count = $obj->idprof;
}
else
{
$count = 0;
print $this->db->error();
}
$this->db->free($resql);
if ($count > 0) return true;
else return false;
}
/**
* Verifie la validite d'un identifiant professionnel en fonction du pays de la societe (siren, siret, ...)
*
* @param int $idprof 1,2,3,4 (Exemple: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param Societe $soc Objet societe
* @return int <=0 if KO, >0 if OK
* TODO better to have this in a lib than into a business class
*/
function id_prof_check($idprof,$soc)
{
global $conf;
$ok=1;
if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return 1;
// Verifie SIREN si pays FR
if ($idprof == 1 && $soc->country_code == 'FR')
{
$chaine=trim($this->idprof1);
$chaine=preg_replace('/(\s)/','',$chaine);
if (dol_strlen($chaine) != 9) return -1;
$sum = 0;
for ($i = 0 ; $i < 10 ; $i = $i+2)
{
$sum = $sum + substr($this->idprof1, (8 - $i), 1);
}
for ($i = 1 ; $i < 9 ; $i = $i+2)
{
$ps = 2 * substr($this->idprof1, (8 - $i), 1);
if ($ps > 9)
{
$ps = substr($ps, 0,1) + substr($ps, 1, 1);
}
$sum = $sum + $ps;
}
if (substr($sum, -1) != 0) return -1;
}
// Verifie SIRET si pays FR
if ($idprof == 2 && $soc->country_code == 'FR')
{
$chaine=trim($this->idprof2);
$chaine=preg_replace('/(\s)/','',$chaine);
if (dol_strlen($chaine) != 14) return -1;
}
//Verify CIF/NIF/NIE if pays ES
//Returns: 1 if NIF ok, 2 if CIF ok, 3 if NIE ok, -1 if NIF bad, -2 if CIF bad, -3 if NIE bad, 0 if unexpected bad
if ($idprof == 1 && $soc->country_code == 'ES')
{
$string=trim($this->idprof1);
$string=preg_replace('/(\s)/','',$string);
$string = strtoupper($string);
for ($i = 0; $i < 9; $i ++)
$num[$i] = substr($string, $i, 1);
//Check format
if (!preg_match('/((^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$)/', $string))
return 0;
//Check NIF
if (preg_match('/(^[0-9]{8}[A-Z]{1}$)/', $string))
if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 0, 8) % 23, 1))
return 1;
else
return -1;
//algorithm checking type code CIF
$sum = $num[2] + $num[4] + $num[6];
for ($i = 1; $i < 8; $i += 2)
$sum += substr((2 * $num[$i]),0,1) + substr((2 * $num[$i]),1,1);
$n = 10 - substr($sum, strlen($sum) - 1, 1);
//Chek special NIF
if (preg_match('/^[KLM]{1}/', $string))
if ($num[8] == chr(64 + $n) || $num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr($string, 1, 8) % 23, 1))
return 1;
else
return -1;
//Check CIF
if (preg_match('/^[ABCDEFGHJNPQRSUVW]{1}/', $string))
if ($num[8] == chr(64 + $n) || $num[8] == substr($n, strlen($n) - 1, 1))
return 2;
else
return -2;
//Check NIE T
if (preg_match('/^[T]{1}/', $string))
if ($num[8] == preg_match('/^[T]{1}[A-Z0-9]{8}$/', $string))
return 3;
else
return -3;
//Check NIE XYZ
if (preg_match('/^[XYZ]{1}/', $string))
if ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(str_replace(array('X','Y','Z'), array('0','1','2'), $string), 0, 8) % 23, 1))
return 3;
else
return -3;
//Can not be verified
return -4;
}
return $ok;
}
/**
* Return an url to check online a professional id or empty string
*
* @param int $idprof 1,2,3,4 (Example: 1=siren,2=siret,3=naf,4=rcs/rm)
* @param Societe $thirdparty Object thirdparty
* @return string Url or empty string if no URL known
* TODO better in a lib than into business class
*/
function id_prof_url($idprof,$thirdparty)
{
global $conf,$langs,$hookmanager;
$url='';
$action = '';
$hookmanager->initHooks(array('idprofurl'));
$parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
$reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
if (empty($reshook))
{
if (! empty($conf->global->MAIN_DISABLEPROFIDRULES)) return '';
// TODO Move links to validate professional ID into a dictionary table "country" + "link"
if ($idprof == 1 && $thirdparty->country_code == 'FR') $url='http://www.societe.com/cgi-bin/search?champs='.$thirdparty->idprof1; // See also http://avis-situation-sirene.insee.fr/
//if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/'; // Link no more valid
if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
}
else
{
return $hookmanager->resPrint;
}
return '';
}
/**
* Indique si la societe a des projets
*
* @return bool true si la societe a des projets, false sinon
*/
function has_projects()
{
$sql = 'SELECT COUNT(*) as numproj FROM '.MAIN_DB_PREFIX.'projet WHERE fk_soc = ' . $this->id;
$resql = $this->db->query($sql);
if ($resql)
{
$obj = $this->db->fetch_object($resql);
$count = $obj->numproj;
}
else
{
$count = 0;
print $this->db->error();
}
$this->db->free($resql);
return ($count > 0);
}
/**
* Load information for tab info
*
* @param int $id Id of thirdparty to load
* @return void
*/
function info($id)
{
$sql = "SELECT s.rowid, s.nom as name, s.datec as date_creation, tms as date_modification,";
$sql.= " fk_user_creat, fk_user_modif";
$sql.= " FROM ".MAIN_DB_PREFIX."societe as s";
$sql.= " WHERE s.rowid = ".$id;
$result=$this->db->query($sql);
if ($result)
{
if ($this->db->num_rows($result))
{
$obj = $this->db->fetch_object($result);
$this->id = $obj->rowid;
if ($obj->fk_user_creat) {
$cuser = new User($this->db);
$cuser->fetch($obj->fk_user_creat);
$this->user_creation = $cuser;
}
if ($obj->fk_user_modif) {
$muser = new User($this->db);
$muser->fetch($obj->fk_user_modif);
$this->user_modification = $muser;
}
$this->ref = $obj->name;
$this->date_creation = $this->db->jdate($obj->date_creation);
$this->date_modification = $this->db->jdate($obj->date_modification);
}
$this->db->free($result);
}
else
{
dol_print_error($this->db);
}
}
/**
* Return if third party is a company (Business) or an end user (Consumer)
*
* @return boolean true=is a company, false=a and user
*/
function isACompany()
{
global $conf;
// Define if third party is treated as company (or not) when nature is unknown
$isacompany=empty($conf->global->MAIN_UNKNOWN_CUSTOMERS_ARE_COMPANIES)?0:1; // 0 by default
if (! empty($this->tva_intra)) $isacompany=1;
else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_PRIVATE'))) $isacompany=0;
else if (! empty($this->typent_code) && in_array($this->typent_code,array('TE_SMALL','TE_MEDIUM','TE_LARGE'))) $isacompany=1;
return $isacompany;
}
/**
* Charge la liste des categories fournisseurs
*
* @return int 0 if success, <> 0 if error
*/
function LoadSupplierCateg()
{
$this->SupplierCategories = array();
$sql = "SELECT rowid, label";
$sql.= " FROM ".MAIN_DB_PREFIX."categorie";
$sql.= " WHERE type = ".Categorie::TYPE_SUPPLIER;
$resql=$this->db->query($sql);
if ($resql)
{
while ($obj = $this->db->fetch_object($resql) )
{
$this->SupplierCategories[$obj->rowid] = $obj->label;
}
return 0;
}
else
{
return -1;
}
}
/**
* Charge la liste des categories fournisseurs
*
* @param int $categorie_id Id of category
* @return int 0 if success, <> 0 if error
*/
function AddFournisseurInCategory($categorie_id)
{
if ($categorie_id > 0)
{
$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_fournisseur (fk_categorie, fk_soc) ";
$sql.= " VALUES ('".$categorie_id."','".$this->id."');";
if ($resql=$this->db->query($sql)) return 0;
}
else
{
return 0;
}
return -1;
}
/**
* Create a third party into database from a member object
*
* @param Adherent $member Object member
* @param string $socname Name of third party to force
* @return int <0 if KO, id of created account if OK
*/
function create_from_member(Adherent $member,$socname='')
{
global $user,$langs;
$name = $socname?$socname:$member->societe;
if (empty($name)) $name=$member->getFullName($langs);
// Positionne parametres
$this->nom=$name; // TODO deprecated
$this->name=$name;
$this->address=$member->address;
$this->zip=$member->zip;
$this->town=$member->town;
$this->country_code=$member->country_code;
$this->country_id=$member->country_id;
$this->phone=$member->phone; // Prof phone
$this->email=$member->email;
$this->skype=$member->skype;
$this->client = 1; // A member is a customer by default
$this->code_client = -1;
$this->code_fournisseur = -1;
$this->db->begin();
// Cree et positionne $this->id
$result=$this->create($user);
if ($result >= 0)
{
$sql = "UPDATE ".MAIN_DB_PREFIX."adherent";
$sql.= " SET fk_soc=".$this->id;
$sql.= " WHERE rowid=".$member->id;
dol_syslog(get_class($this)."::create_from_member", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$this->db->commit();
return $this->id;
}
else
{
$this->error=$this->db->error();
$this->db->rollback();
return -1;
}
}
else
{
// $this->error deja positionne
dol_syslog(get_class($this)."::create_from_member - 2 - ".$this->error." - ".join(',',$this->errors), LOG_ERR);
$this->db->rollback();
return $result;
}
}
/**
* Set properties with value into $conf
*
* @param Conf $conf Conf object (possibility to use another entity)
* @return void
*/
function setMysoc(Conf $conf)
{
global $langs;
$this->id=0;
$this->name=empty($conf->global->MAIN_INFO_SOCIETE_NOM)?'':$conf->global->MAIN_INFO_SOCIETE_NOM;
$this->address=empty($conf->global->MAIN_INFO_SOCIETE_ADDRESS)?'':$conf->global->MAIN_INFO_SOCIETE_ADDRESS;
$this->zip=empty($conf->global->MAIN_INFO_SOCIETE_ZIP)?'':$conf->global->MAIN_INFO_SOCIETE_ZIP;
$this->town=empty($conf->global->MAIN_INFO_SOCIETE_TOWN)?'':$conf->global->MAIN_INFO_SOCIETE_TOWN;
$this->state_id=empty($conf->global->MAIN_INFO_SOCIETE_STATE)?'':$conf->global->MAIN_INFO_SOCIETE_STATE;
/* Disabled: we don't want any SQL request into method setMySoc. This method set object from env only.
If we need label, label must be loaded by output that need it from id (label depends on output language)
require_once DOL_DOCUMENT_ROOT .'/core/lib/company.lib.php';
if (!empty($conf->global->MAIN_INFO_SOCIETE_STATE)) {
$this->state_id= $conf->global->MAIN_INFO_SOCIETE_STATE;
$this->state = getState($this->state_id);
}
*/
$this->note_private=empty($conf->global->MAIN_INFO_SOCIETE_NOTE)?'':$conf->global->MAIN_INFO_SOCIETE_NOTE;
$this->nom=$this->name; // deprecated
// We define country_id, country_code and country
$country_id=$country_code=$country_label='';
if (! empty($conf->global->MAIN_INFO_SOCIETE_COUNTRY))
{
$tmp=explode(':',$conf->global->MAIN_INFO_SOCIETE_COUNTRY);
$country_id=$tmp[0];
if (! empty($tmp[1])) // If $conf->global->MAIN_INFO_SOCIETE_COUNTRY is "id:code:label"
{
$country_code=$tmp[1];
$country_label=$tmp[2];
}
else // For backward compatibility
{
dol_syslog("Your country setup use an old syntax. Reedit it using setup area.", LOG_ERR);
include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
$country_code=getCountry($country_id,2,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore
$country_label=getCountry($country_id,0,$this->db); // This need a SQL request, but it's the old feature that should not be used anymore
}
}
$this->country_id=$country_id;
$this->country_code=$country_code;
$this->country=$country_label;
if (is_object($langs)) $this->country=($langs->trans('Country'.$country_code)!='Country'.$country_code)?$langs->trans('Country'.$country_code):$country_label;
$this->phone=empty($conf->global->MAIN_INFO_SOCIETE_TEL)?'':$conf->global->MAIN_INFO_SOCIETE_TEL;
$this->fax=empty($conf->global->MAIN_INFO_SOCIETE_FAX)?'':$conf->global->MAIN_INFO_SOCIETE_FAX;
$this->url=empty($conf->global->MAIN_INFO_SOCIETE_WEB)?'':$conf->global->MAIN_INFO_SOCIETE_WEB;
// Id prof generiques
$this->idprof1=empty($conf->global->MAIN_INFO_SIREN)?'':$conf->global->MAIN_INFO_SIREN;
$this->idprof2=empty($conf->global->MAIN_INFO_SIRET)?'':$conf->global->MAIN_INFO_SIRET;
$this->idprof3=empty($conf->global->MAIN_INFO_APE)?'':$conf->global->MAIN_INFO_APE;
$this->idprof4=empty($conf->global->MAIN_INFO_RCS)?'':$conf->global->MAIN_INFO_RCS;
$this->idprof5=empty($conf->global->MAIN_INFO_PROFID5)?'':$conf->global->MAIN_INFO_PROFID5;
$this->idprof6=empty($conf->global->MAIN_INFO_PROFID6)?'':$conf->global->MAIN_INFO_PROFID6;
$this->tva_intra=empty($conf->global->MAIN_INFO_TVAINTRA)?'':$conf->global->MAIN_INFO_TVAINTRA; // VAT number, not necessarly INTRA.
$this->managers=empty($conf->global->MAIN_INFO_SOCIETE_MANAGERS)?'':$conf->global->MAIN_INFO_SOCIETE_MANAGERS;
$this->capital=empty($conf->global->MAIN_INFO_CAPITAL)?'':$conf->global->MAIN_INFO_CAPITAL;
$this->forme_juridique_code=empty($conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE)?'':$conf->global->MAIN_INFO_SOCIETE_FORME_JURIDIQUE;
$this->email=empty($conf->global->MAIN_INFO_SOCIETE_MAIL)?'':$conf->global->MAIN_INFO_SOCIETE_MAIL;
$this->logo=empty($conf->global->MAIN_INFO_SOCIETE_LOGO)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO;
$this->logo_small=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_SMALL;
$this->logo_mini=empty($conf->global->MAIN_INFO_SOCIETE_LOGO_MINI)?'':$conf->global->MAIN_INFO_SOCIETE_LOGO_MINI;
// Define if company use vat or not
$this->tva_assuj=$conf->global->FACTURE_TVAOPTION;
// Define if company use local taxes
$this->localtax1_assuj=((isset($conf->global->FACTURE_LOCAL_TAX1_OPTION) && ($conf->global->FACTURE_LOCAL_TAX1_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX1_OPTION=='localtax1on'))?1:0);
$this->localtax2_assuj=((isset($conf->global->FACTURE_LOCAL_TAX2_OPTION) && ($conf->global->FACTURE_LOCAL_TAX2_OPTION=='1' || $conf->global->FACTURE_LOCAL_TAX2_OPTION=='localtax2on'))?1:0);
}
/**
* Initialise an instance with random values.
* Used to build previews or test instances.
* id must be 0 if object instance is a specimen.
*
* @return void
*/
function initAsSpecimen()
{
$now=dol_now();
// Initialize parameters
$this->id=0;
$this->name = 'THIRDPARTY SPECIMEN '.dol_print_date($now,'dayhourlog');
$this->nom = $this->name; // For backward compatibility
$this->ref_ext = 'Ref ext';
$this->specimen=1;
$this->address='21 jump street';
$this->zip='99999';
$this->town='MyTown';
$this->state_id=1;
$this->state_code='AA';
$this->state='MyState';
$this->country_id=1;
$this->country_code='FR';
$this->email='[email protected]';
$this->skype='tom.hanson';
$this->url='http://www.specimen.com';
$this->phone='0909090901';
$this->fax='0909090909';
$this->code_client='CC-'.dol_print_date($now,'dayhourlog');
$this->code_fournisseur='SC-'.dol_print_date($now,'dayhourlog');
$this->capital=10000;
$this->client=1;
$this->prospect=1;
$this->fournisseur=1;
$this->tva_assuj=1;
$this->tva_intra='EU1234567';
$this->note_public='This is a comment (public)';
$this->note_private='This is a comment (private)';
$this->idprof1='idprof1';
$this->idprof2='idprof2';
$this->idprof3='idprof3';
$this->idprof4='idprof4';
$this->idprof5='idprof5';
$this->idprof6='idprof6';
}
/**
* Check if we must use localtax feature or not according to country (country of $mysoc in most cases).
*
* @param int $localTaxNum To get info for only localtax1 or localtax2
* @return boolean true or false
*/
function useLocalTax($localTaxNum=0)
{
$sql = "SELECT t.localtax1, t.localtax2";
$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND t.active = 1";
if (empty($localTaxNum)) $sql .= " AND (t.localtax1_type <> '0' OR t.localtax2_type <> '0')";
elseif ($localTaxNum == 1) $sql .= " AND t.localtax1_type <> '0'";
elseif ($localTaxNum == 2) $sql .= " AND t.localtax2_type <> '0'";
dol_syslog("useLocalTax", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
return ($this->db->num_rows($resql) > 0);
}
else return false;
}
/**
* Check if we must use NPR Vat (french stupid rule) or not according to country (country of $mysoc in most cases).
*
* @return boolean true or false
*/
function useNPR()
{
$sql = "SELECT t.rowid";
$sql .= " FROM ".MAIN_DB_PREFIX."c_tva as t, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE t.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND t.active = 1 AND t.recuperableonly = 1";
dol_syslog("useNPR", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
return ($this->db->num_rows($resql) > 0);
}
else return false;
}
/**
* Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
*
* @return boolean true or false
*/
function useRevenueStamp()
{
$sql = "SELECT COUNT(*) as nb";
$sql .= " FROM ".MAIN_DB_PREFIX."c_revenuestamp as r, ".MAIN_DB_PREFIX."c_country as c";
$sql .= " WHERE r.fk_pays = c.rowid AND c.code = '".$this->country_code."'";
$sql .= " AND r.active = 1";
dol_syslog("useRevenueStamp", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$obj=$this->db->fetch_object($resql);
return (($obj->nb > 0)?true:false);
}
else
{
$this->error=$this->db->lasterror();
return false;
}
}
/**
* Return prostect level
*
* @return string Libelle
*/
function getLibProspLevel()
{
return $this->LibProspLevel($this->fk_prospectlevel);
}
/**
* Return label of prospect level
*
* @param int $fk_prospectlevel Prospect level
* @return string label of level
*/
function LibProspLevel($fk_prospectlevel)
{
global $langs;
$lib=$langs->trans("ProspectLevel".$fk_prospectlevel);
// If lib not found in language file, we get label from cache/databse
if ($lib == $langs->trans("ProspectLevel".$fk_prospectlevel))
{
$lib=$langs->getLabelFromKey($this->db,$fk_prospectlevel,'c_prospectlevel','code','label');
}
return $lib;
}
/**
* Set prospect level
*
* @param User $user Utilisateur qui definie la remise
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_prospect_level(User $user)
{
return $this->update($this->id, $user);
}
/**
* Return status of prospect
*
* @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
* @param string $label Label to use for status for added status
* @return string Libelle
*/
function getLibProspCommStatut($mode=0, $label='')
{
return $this->LibProspCommStatut($this->stcomm_id, $mode, $label);
}
/**
* Return label of a given status
*
* @param int|string $statut Id or code for prospection status
* @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
* @param string $label Label to use for status for added status
* @return string Libelle du statut
*/
function LibProspCommStatut($statut, $mode=0, $label='')
{
global $langs;
$langs->load('customers');
if ($mode == 2)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
if ($mode == 3)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1);
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0);
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1);
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2);
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3);
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0);
}
}
if ($mode == 4)
{
if ($statut == '-1' || $statut == 'ST_NO') return img_action($langs->trans("StatusProspect-1"),-1).' '.$langs->trans("StatusProspect-1");
elseif ($statut == '0' || $statut == 'ST_NEVER') return img_action($langs->trans("StatusProspect0"), 0).' '.$langs->trans("StatusProspect0");
elseif ($statut == '1' || $statut == 'ST_TODO') return img_action($langs->trans("StatusProspect1"), 1).' '.$langs->trans("StatusProspect1");
elseif ($statut == '2' || $statut == 'ST_PEND') return img_action($langs->trans("StatusProspect2"), 2).' '.$langs->trans("StatusProspect2");
elseif ($statut == '3' || $statut == 'ST_DONE') return img_action($langs->trans("StatusProspect3"), 3).' '.$langs->trans("StatusProspect3");
else
{
return img_action(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label, 0).' '.(($langs->trans("StatusProspect".$statut) != "StatusProspect".$statut) ? $langs->trans("StatusProspect".$statut) : $label);
}
}
return "Error, mode/status not found";
}
/**
* Set commnunication level
*
* @param User $user User making change
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_commnucation_level($user)
{
return $this->update($this->id, $user);
}
/**
* Set outstanding value
*
* @param User $user User making change
* @return int <0 if KO, >0 if OK
* @deprecated Use update function instead
*/
function set_OutstandingBill(User $user)
{
return $this->update($this->id, $user);
}
/**
* Return amount of bill not paid
*
* @return int Amount in debt for thirdparty
*/
function get_OutstandingBill()
{
/* Accurate value of remain to pay is to sum remaintopay for each invoice
$paiement = $invoice->getSommePaiement();
$creditnotes=$invoice->getSumCreditNotesUsed();
$deposits=$invoice->getSumDepositsUsed();
$alreadypayed=price2num($paiement + $creditnotes + $deposits,'MT');
$remaintopay=price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits,'MT');
*/
$sql = "SELECT rowid, total_ttc FROM ".MAIN_DB_PREFIX."facture as f";
$sql .= " WHERE fk_soc = ". $this->id;
$sql .= " AND paye = 0";
$sql .= " AND fk_statut <> 0"; // Not a draft
//$sql .= " AND (fk_statut <> 3 OR close_code <> 'abandon')"; // Not abandonned for undefined reason
$sql .= " AND fk_statut <> 3"; // Not abandonned
$sql .= " AND fk_statut <> 2"; // Not clasified as paid
dol_syslog("get_OutstandingBill", LOG_DEBUG);
$resql=$this->db->query($sql);
if ($resql)
{
$outstandingBill = 0;
require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
$facturestatic=new Facture($this->db);
while($obj=$this->db->fetch_object($resql)) {
$facturestatic->id=$obj->rowid;
$paiement = $facturestatic->getSommePaiement();
$creditnotes = $facturestatic->getSumCreditNotesUsed();
$deposits = $facturestatic->getSumDepositsUsed();
$outstandingBill+= $obj->total_ttc - $paiement - $creditnotes - $deposits;
}
return $outstandingBill;
}
else
return 0;
}
/**
* Return label of status customer is prospect/customer
*
* @return string Label
*/
function getLibCustProspStatut()
{
return $this->LibCustProspStatut($this->client);
}
/**
* Renvoi le libelle d'un statut donne
*
* @param int $statut Id statut
* @return string Libelle du statut
*/
function LibCustProspStatut($statut)
{
global $langs;
$langs->load('companies');
if ($statut==0) return $langs->trans("NorProspectNorCustomer");
if ($statut==1) return $langs->trans("Customer");
if ($statut==2) return $langs->trans("Prospect");
if ($statut==3) return $langs->trans("ProspectCustomer");
}
/**
* Create a document onto disk according to template module.
*
* @param string $modele Generator to use. Caller must set it to obj->modelpdf or GETPOST('modelpdf') for example.
* @param Translate $outputlangs objet lang a utiliser pour traduction
* @param int $hidedetails Hide details of lines
* @param int $hidedesc Hide description
* @param int $hideref Hide ref
* @param null|array $moreparams Array to provide more information
* @return int <0 if KO, >0 if OK
*/
public function generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
{
global $conf,$user,$langs;
if (! empty($moreparams) && ! empty($moreparams['use_companybankid']))
{
$modelpath = "core/modules/bank/doc/";
include_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
$companybankaccount = new CompanyBankAccount($this->db);
$result = $companybankaccount->fetch($moreparams['use_companybankid']);
if (! $result) dol_print_error($this->db, $companybankaccount->error, $companybankaccount->errors);
$result=$companybankaccount->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
}
else
{
// Positionne le modele sur le nom du modele a utiliser
if (! dol_strlen($modele))
{
if (! empty($conf->global->COMPANY_ADDON_PDF))
{
$modele = $conf->global->COMPANY_ADDON_PDF;
}
else
{
print $langs->trans("Error")." ".$langs->trans("Error_COMPANY_ADDON_PDF_NotDefined");
return 0;
}
}
$modelpath = "core/modules/societe/doc/";
$result=$this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
}
return $result;
}
/**
* Sets object to supplied categories.
*
* Deletes object from existing categories not supplied.
* Adds it to non existing supplied categories.
* Existing categories are left untouch.
*
* @param int[]|int $categories Category or categories IDs
* @param string $type Category type (customer or supplier)
*/
public function setCategories($categories, $type)
{
// Decode type
if ($type == 'customer') {
$type_id = Categorie::TYPE_CUSTOMER;
$type_text = 'customer';
} elseif ($type == 'supplier') {
$type_id = Categorie::TYPE_SUPPLIER;
$type_text = 'supplier';
} else {
dol_syslog(__METHOD__ . ': Type ' . $type . 'is an unknown company category type. Done nothing.', LOG_ERR);
return;
}
// Handle single category
if (!is_array($categories)) {
$categories = array($categories);
}
// Get current categories
require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
$c = new Categorie($this->db);
$existing = $c->containing($this->id, $type_id, 'id');
// Diff
if (is_array($existing)) {
$to_del = array_diff($existing, $categories);
$to_add = array_diff($categories, $existing);
} else {
$to_del = array(); // Nothing to delete
$to_add = $categories;
}
// Process
foreach ($to_del as $del) {
if ($c->fetch($del) > 0) {
$c->del_type($this, $type_text);
}
}
foreach ($to_add as $add) {
if ($c->fetch($add) > 0) {
$c->add_type($this, $type_text);
}
}
return;
}
/**
* Function used to replace a thirdparty id with another one.
* It must be used within a transaction to avoid trouble
*
* @param DoliDB $db Database handler
* @param int $origin_id Old thirdparty id
* @param int $dest_id New thirdparty id
* @return bool
*/
public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
{
/**
* Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some
* Because this function is meant to be executed within a transaction, we won't take care of it.
*/
$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
$sql .= ' WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN ( ';
$sql .= ' SELECT fk_user ';
$sql .= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux ';
$sql .= ' WHERE fk_soc = '.(int) $origin_id.') ';
$query = $db->query($sql);
while ($result = $db->fetch_object($query)) {
$db->query('DELETE FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE rowid = '.$result->rowid);
}
/**
* llx_societe_extrafields table must not be here because we don't care about the old thirdparty data
* Do not include llx_societe because it will be replaced later
*/
$tables = array(
'societe_address',
'societe_commerciaux',
'societe_log',
'societe_prices',
'societe_remise',
'societe_remise_except',
'societe_rib'
);
return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
}
}
| gpl-3.0 |
kzoacn/Grimoire | Template of Other Teams/Fantasy Legend/Raw-Template/Source/Data-Structure/Heavy-Light-Decomposition-Chain.tex | 379 | \begin{lstlisting}
void modify(int x, int y) {
int fx = t[x], fy = t[y];
while (fx != fy) {
if (d[fx] > d[fy]) {
modify(1, 1, n, w[fx], w[x]);
x = f[fx]; fx = t[x];
}
else{
modify(1, 1, n, w[fy], w[y]);
y = f[fy]; fy = t[y];
}
}
if (x != y) {
if (d[x] < d[y]) modify(1, 1, n, w[z[x]], w[y]);
else modify(1, 1, n, w[z[y]], w[x]);
}
}
\end{lstlisting}
| gpl-3.0 |
madmouser1/aubio | python/demos/demo_pitch.py | 3193 | #! /usr/bin/env python
import sys
from aubio import source, pitch, freqtomidi
if len(sys.argv) < 2:
print "Usage: %s <filename> [samplerate]" % sys.argv[0]
sys.exit(1)
filename = sys.argv[1]
downsample = 1
samplerate = 44100 / downsample
if len( sys.argv ) > 2: samplerate = int(sys.argv[2])
win_s = 4096 / downsample # fft size
hop_s = 512 / downsample # hop size
s = source(filename, samplerate, hop_s)
samplerate = s.samplerate
tolerance = 0.8
pitch_o = pitch("yin", win_s, hop_s, samplerate)
pitch_o.set_unit("midi")
pitch_o.set_tolerance(tolerance)
pitches = []
confidences = []
# total number of frames read
total_frames = 0
while True:
samples, read = s()
pitch = pitch_o(samples)[0]
#pitch = int(round(pitch))
confidence = pitch_o.get_confidence()
#if confidence < 0.8: pitch = 0.
#print "%f %f %f" % (total_frames / float(samplerate), pitch, confidence)
pitches += [pitch]
confidences += [confidence]
total_frames += read
if read < hop_s: break
if 0: sys.exit(0)
#print pitches
from numpy import array, ma
import matplotlib.pyplot as plt
from demo_waveform_plot import get_waveform_plot, set_xlabels_sample2time
skip = 1
pitches = array(pitches[skip:])
confidences = array(confidences[skip:])
times = [t * hop_s for t in range(len(pitches))]
fig = plt.figure()
ax1 = fig.add_subplot(311)
ax1 = get_waveform_plot(filename, samplerate = samplerate, block_size = hop_s, ax = ax1)
plt.setp(ax1.get_xticklabels(), visible = False)
ax1.set_xlabel('')
def array_from_text_file(filename, dtype = 'float'):
import os.path
from numpy import array
filename = os.path.join(os.path.dirname(__file__), filename)
return array([line.split() for line in open(filename).readlines()],
dtype = dtype)
ax2 = fig.add_subplot(312, sharex = ax1)
import sys, os.path
ground_truth = os.path.splitext(filename)[0] + '.f0.Corrected'
if os.path.isfile(ground_truth):
ground_truth = array_from_text_file(ground_truth)
true_freqs = ground_truth[:,2]
true_freqs = ma.masked_where(true_freqs < 2, true_freqs)
true_times = float(samplerate) * ground_truth[:,0]
ax2.plot(true_times, true_freqs, 'r')
ax2.axis( ymin = 0.9 * true_freqs.min(), ymax = 1.1 * true_freqs.max() )
# plot raw pitches
ax2.plot(times, pitches, '.g')
# plot cleaned up pitches
cleaned_pitches = pitches
#cleaned_pitches = ma.masked_where(cleaned_pitches < 0, cleaned_pitches)
#cleaned_pitches = ma.masked_where(cleaned_pitches > 120, cleaned_pitches)
cleaned_pitches = ma.masked_where(confidences < tolerance, cleaned_pitches)
ax2.plot(times, cleaned_pitches, '.-')
#ax2.axis( ymin = 0.9 * cleaned_pitches.min(), ymax = 1.1 * cleaned_pitches.max() )
#ax2.axis( ymin = 55, ymax = 70 )
plt.setp(ax2.get_xticklabels(), visible = False)
ax2.set_ylabel('f0 (midi)')
# plot confidence
ax3 = fig.add_subplot(313, sharex = ax1)
# plot the confidence
ax3.plot(times, confidences)
# draw a line at tolerance
ax3.plot(times, [tolerance]*len(confidences))
ax3.axis( xmin = times[0], xmax = times[-1])
ax3.set_ylabel('condidence')
set_xlabels_sample2time(ax3, times[-1], samplerate)
plt.show()
#plt.savefig(os.path.basename(filename) + '.svg')
| gpl-3.0 |
alephobjects/Marlin | Marlin/example_configurations/BQ/WITBOX/Configuration_adv.h | 60239 | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* Configuration_adv.h
*
* Advanced settings.
* Only change these if you know exactly what you're doing.
* Some of these settings can damage your printer if improperly set!
*
* Basic settings can be found in Configuration.h
*
*/
#ifndef CONFIGURATION_ADV_H
#define CONFIGURATION_ADV_H
#define CONFIGURATION_ADV_H_VERSION 010100
// @section temperature
//===========================================================================
//=============================Thermal Settings ============================
//===========================================================================
#if DISABLED(PIDTEMPBED)
#define BED_CHECK_INTERVAL 5000 // ms between checks in bang-bang control
#if ENABLED(BED_LIMIT_SWITCHING)
#define BED_HYSTERESIS 2 // Only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS
#endif
#endif
/**
* Thermal Protection protects your printer from damage and fire if a
* thermistor falls out or temperature sensors fail in any way.
*
* The issue: If a thermistor falls out or a temperature sensor fails,
* Marlin can no longer sense the actual temperature. Since a disconnected
* thermistor reads as a low temperature, the firmware will keep the heater on.
*
* The solution: Once the temperature reaches the target, start observing.
* If the temperature stays too far below the target (hysteresis) for too long (period),
* the firmware will halt the machine as a safety precaution.
*
* If you get false positives for "Thermal Runaway" increase THERMAL_PROTECTION_HYSTERESIS and/or THERMAL_PROTECTION_PERIOD
*/
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
#define THERMAL_PROTECTION_PERIOD 40 // Seconds
#define THERMAL_PROTECTION_HYSTERESIS 4 // Degrees Celsius
/**
* Whenever an M104 or M109 increases the target temperature the firmware will wait for the
* WATCH_TEMP_PERIOD to expire, and if the temperature hasn't increased by WATCH_TEMP_INCREASE
* degrees, the machine is halted, requiring a hard reset. This test restarts with any M104/M109,
* but only if the current temperature is far enough below the target for a reliable test.
*
* If you get false positives for "Heating failed" increase WATCH_TEMP_PERIOD and/or decrease WATCH_TEMP_INCREASE
* WATCH_TEMP_INCREASE should not be below 2.
*/
#define WATCH_TEMP_PERIOD 20 // Seconds
#define WATCH_TEMP_INCREASE 2 // Degrees Celsius
#endif
/**
* Thermal Protection parameters for the bed are just as above for hotends.
*/
#if ENABLED(THERMAL_PROTECTION_BED)
#define THERMAL_PROTECTION_BED_PERIOD 20 // Seconds
#define THERMAL_PROTECTION_BED_HYSTERESIS 2 // Degrees Celsius
/**
* Whenever an M140 or M190 increases the target temperature the firmware will wait for the
* WATCH_BED_TEMP_PERIOD to expire, and if the temperature hasn't increased by WATCH_BED_TEMP_INCREASE
* degrees, the machine is halted, requiring a hard reset. This test restarts with any M140/M190,
* but only if the current temperature is far enough below the target for a reliable test.
*
* If you get too many "Heating failed" errors, increase WATCH_BED_TEMP_PERIOD and/or decrease
* WATCH_BED_TEMP_INCREASE. (WATCH_BED_TEMP_INCREASE should not be below 2.)
*/
#define WATCH_BED_TEMP_PERIOD 60 // Seconds
#define WATCH_BED_TEMP_INCREASE 2 // Degrees Celsius
#endif
#if ENABLED(PIDTEMP)
// this adds an experimental additional term to the heating power, proportional to the extrusion speed.
// if Kc is chosen well, the additional required power due to increased melting should be compensated.
//#define PID_EXTRUSION_SCALING
#if ENABLED(PID_EXTRUSION_SCALING)
#define DEFAULT_Kc (100) //heating power=Kc*(e_speed)
#define LPQ_MAX_LEN 50
#endif
#endif
/**
* Automatic Temperature:
* The hotend target temperature is calculated by all the buffered lines of gcode.
* The maximum buffered steps/sec of the extruder motor is called "se".
* Start autotemp mode with M109 S<mintemp> B<maxtemp> F<factor>
* The target temperature is set to mintemp+factor*se[steps/sec] and is limited by
* mintemp and maxtemp. Turn this off by executing M109 without F*
* Also, if the temperature is set to a value below mintemp, it will not be changed by autotemp.
* On an Ultimaker, some initial testing worked with M109 S215 B260 F1 in the start.gcode
*/
#define AUTOTEMP
#if ENABLED(AUTOTEMP)
#define AUTOTEMP_OLDWEIGHT 0.98
#endif
// Show Temperature ADC value
// Enable for M105 to include ADC values read from temperature sensors.
//#define SHOW_TEMP_ADC_VALUES
/**
* High Temperature Thermistor Support
*
* Thermistors able to support high temperature tend to have a hard time getting
* good readings at room and lower temperatures. This means HEATER_X_RAW_LO_TEMP
* will probably be caught when the heating element first turns on during the
* preheating process, which will trigger a min_temp_error as a safety measure
* and force stop everything.
* To circumvent this limitation, we allow for a preheat time (during which,
* min_temp_error won't be triggered) and add a min_temp buffer to handle
* aberrant readings.
*
* If you want to enable this feature for your hotend thermistor(s)
* uncomment and set values > 0 in the constants below
*/
// The number of consecutive low temperature errors that can occur
// before a min_temp_error is triggered. (Shouldn't be more than 10.)
//#define MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED 0
// The number of milliseconds a hotend will preheat before starting to check
// the temperature. This value should NOT be set to the time it takes the
// hot end to reach the target temperature, but the time it takes to reach
// the minimum temperature your thermistor can read. The lower the better/safer.
// This shouldn't need to be more than 30 seconds (30000)
//#define MILLISECONDS_PREHEAT_TIME 0
// @section extruder
// Extruder runout prevention.
// If the machine is idle and the temperature over MINTEMP
// then extrude some filament every couple of SECONDS.
//#define EXTRUDER_RUNOUT_PREVENT
#if ENABLED(EXTRUDER_RUNOUT_PREVENT)
#define EXTRUDER_RUNOUT_MINTEMP 190
#define EXTRUDER_RUNOUT_SECONDS 30
#define EXTRUDER_RUNOUT_SPEED 1500 // mm/m
#define EXTRUDER_RUNOUT_EXTRUDE 5 // mm
#endif
// @section temperature
//These defines help to calibrate the AD595 sensor in case you get wrong temperature measurements.
//The measured temperature is defined as "actualTemp = (measuredTemp * TEMP_SENSOR_AD595_GAIN) + TEMP_SENSOR_AD595_OFFSET"
#define TEMP_SENSOR_AD595_OFFSET 0.0
#define TEMP_SENSOR_AD595_GAIN 1.0
/**
* Controller Fan
* To cool down the stepper drivers and MOSFETs.
*
* The fan will turn on automatically whenever any stepper is enabled
* and turn off after a set period after all steppers are turned off.
*/
//#define USE_CONTROLLER_FAN
#if ENABLED(USE_CONTROLLER_FAN)
//#define CONTROLLER_FAN_PIN FAN1_PIN // Set a custom pin for the controller fan
#define CONTROLLERFAN_SECS 60 // Duration in seconds for the fan to run after all motors are disabled
#define CONTROLLERFAN_SPEED 255 // 255 == full speed
#endif
// When first starting the main fan, run it at full speed for the
// given number of milliseconds. This gets the fan spinning reliably
// before setting a PWM value. (Does not work with software PWM for fan on Sanguinololu)
//#define FAN_KICKSTART_TIME 100
// This defines the minimal speed for the main fan, run in PWM mode
// to enable uncomment and set minimal PWM speed for reliable running (1-255)
// if fan speed is [1 - (FAN_MIN_PWM-1)] it is set to FAN_MIN_PWM
//#define FAN_MIN_PWM 50
// @section extruder
/**
* Extruder cooling fans
*
* Extruder auto fans automatically turn on when their extruders'
* temperatures go above EXTRUDER_AUTO_FAN_TEMPERATURE.
*
* Your board's pins file specifies the recommended pins. Override those here
* or set to -1 to disable completely.
*
* Multiple extruders can be assigned to the same pin in which case
* the fan will turn on when any selected extruder is above the threshold.
*/
#define E0_AUTO_FAN_PIN -1
#define E1_AUTO_FAN_PIN -1
#define E2_AUTO_FAN_PIN -1
#define E3_AUTO_FAN_PIN -1
#define E4_AUTO_FAN_PIN -1
#define EXTRUDER_AUTO_FAN_TEMPERATURE 50
#define EXTRUDER_AUTO_FAN_SPEED 255 // == full speed
/**
* Part-Cooling Fan Multiplexer
*
* This feature allows you to digitally multiplex the fan output.
* The multiplexer is automatically switched at tool-change.
* Set FANMUX[012]_PINs below for up to 2, 4, or 8 multiplexed fans.
*/
#define FANMUX0_PIN -1
#define FANMUX1_PIN -1
#define FANMUX2_PIN -1
/**
* M355 Case Light on-off / brightness
*/
//#define CASE_LIGHT_ENABLE
#if ENABLED(CASE_LIGHT_ENABLE)
//#define CASE_LIGHT_PIN 4 // Override the default pin if needed
#define INVERT_CASE_LIGHT false // Set true if Case Light is ON when pin is LOW
#define CASE_LIGHT_DEFAULT_ON true // Set default power-up state on
#define CASE_LIGHT_DEFAULT_BRIGHTNESS 105 // Set default power-up brightness (0-255, requires PWM pin)
//#define MENU_ITEM_CASE_LIGHT // Add a Case Light option to the LCD main menu
#endif
//===========================================================================
//============================ Mechanical Settings ==========================
//===========================================================================
// @section homing
// If you want endstops to stay on (by default) even when not homing
// enable this option. Override at any time with M120, M121.
#define ENDSTOPS_ALWAYS_ON_DEFAULT
// @section extras
//#define Z_LATE_ENABLE // Enable Z the last moment. Needed if your Z driver overheats.
// Dual X Steppers
// Uncomment this option to drive two X axis motors.
// The next unused E driver will be assigned to the second X stepper.
//#define X_DUAL_STEPPER_DRIVERS
#if ENABLED(X_DUAL_STEPPER_DRIVERS)
// Set true if the two X motors need to rotate in opposite directions
#define INVERT_X2_VS_X_DIR true
#endif
// Dual Y Steppers
// Uncomment this option to drive two Y axis motors.
// The next unused E driver will be assigned to the second Y stepper.
//#define Y_DUAL_STEPPER_DRIVERS
#if ENABLED(Y_DUAL_STEPPER_DRIVERS)
// Set true if the two Y motors need to rotate in opposite directions
#define INVERT_Y2_VS_Y_DIR true
#endif
// A single Z stepper driver is usually used to drive 2 stepper motors.
// Uncomment this option to use a separate stepper driver for each Z axis motor.
// The next unused E driver will be assigned to the second Z stepper.
//#define Z_DUAL_STEPPER_DRIVERS
#if ENABLED(Z_DUAL_STEPPER_DRIVERS)
// Z_DUAL_ENDSTOPS is a feature to enable the use of 2 endstops for both Z steppers - Let's call them Z stepper and Z2 stepper.
// That way the machine is capable to align the bed during home, since both Z steppers are homed.
// There is also an implementation of M666 (software endstops adjustment) to this feature.
// After Z homing, this adjustment is applied to just one of the steppers in order to align the bed.
// One just need to home the Z axis and measure the distance difference between both Z axis and apply the math: Z adjust = Z - Z2.
// If the Z stepper axis is closer to the bed, the measure Z > Z2 (yes, it is.. think about it) and the Z adjust would be positive.
// Play a little bit with small adjustments (0.5mm) and check the behaviour.
// The M119 (endstops report) will start reporting the Z2 Endstop as well.
//#define Z_DUAL_ENDSTOPS
#if ENABLED(Z_DUAL_ENDSTOPS)
#define Z2_USE_ENDSTOP _XMAX_
#define Z_DUAL_ENDSTOPS_ADJUSTMENT 0 // Use M666 to determine/test this value
#endif
#endif // Z_DUAL_STEPPER_DRIVERS
// Enable this for dual x-carriage printers.
// A dual x-carriage design has the advantage that the inactive extruder can be parked which
// prevents hot-end ooze contaminating the print. It also reduces the weight of each x-carriage
// allowing faster printing speeds. Connect your X2 stepper to the first unused E plug.
//#define DUAL_X_CARRIAGE
#if ENABLED(DUAL_X_CARRIAGE)
// Configuration for second X-carriage
// Note: the first x-carriage is defined as the x-carriage which homes to the minimum endstop;
// the second x-carriage always homes to the maximum endstop.
#define X2_MIN_POS 80 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage
#define X2_MAX_POS 353 // set maximum to the distance between toolheads when both heads are homed
#define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position
#define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position
// However: In this mode the HOTEND_OFFSET_X value for the second extruder provides a software
// override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops
// without modifying the firmware (through the "M218 T1 X???" command).
// Remember: you should set the second extruder x-offset to 0 in your slicer.
// There are a few selectable movement modes for dual x-carriages using M605 S<mode>
// Mode 0 (DXC_FULL_CONTROL_MODE): Full control. The slicer has full control over both x-carriages and can achieve optimal travel results
// as long as it supports dual x-carriages. (M605 S0)
// Mode 1 (DXC_AUTO_PARK_MODE) : Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so
// that additional slicer support is not required. (M605 S1)
// Mode 2 (DXC_DUPLICATION_MODE) : Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all
// actions of the first x-carriage. This allows the printer to print 2 arbitrary items at
// once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm])
// This is the default power-up mode which can be later using M605.
#define DEFAULT_DUAL_X_CARRIAGE_MODE DXC_FULL_CONTROL_MODE
// Default settings in "Auto-park Mode"
#define TOOLCHANGE_PARK_ZLIFT 0.2 // the distance to raise Z axis when parking an extruder
#define TOOLCHANGE_UNPARK_ZLIFT 1 // the distance to raise Z axis when unparking an extruder
// Default x offset in duplication mode (typically set to half print bed width)
#define DEFAULT_DUPLICATION_X_OFFSET 100
#endif // DUAL_X_CARRIAGE
// Activate a solenoid on the active extruder with M380. Disable all with M381.
// Define SOL0_PIN, SOL1_PIN, etc., for each extruder that has a solenoid.
//#define EXT_SOLENOID
// @section homing
//homing hits the endstop, then retracts by this distance, before it tries to slowly bump again:
#define X_HOME_BUMP_MM 5
#define Y_HOME_BUMP_MM 5
#define Z_HOME_BUMP_MM 2
#define HOMING_BUMP_DIVISOR {2, 2, 4} // Re-Bump Speed Divisor (Divides the Homing Feedrate)
//#define QUICK_HOME //if this is defined, if both x and y are to be homed, a diagonal move will be performed initially.
// When G28 is called, this option will make Y home before X
//#define HOME_Y_BEFORE_X
// @section machine
#define AXIS_RELATIVE_MODES {false, false, false, false}
// Allow duplication mode with a basic dual-nozzle extruder
//#define DUAL_NOZZLE_DUPLICATION_MODE
// By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step.
#define INVERT_X_STEP_PIN false
#define INVERT_Y_STEP_PIN false
#define INVERT_Z_STEP_PIN false
#define INVERT_E_STEP_PIN false
// Default stepper release if idle. Set to 0 to deactivate.
// Steppers will shut down DEFAULT_STEPPER_DEACTIVE_TIME seconds after the last move when DISABLE_INACTIVE_? is true.
// Time can be set by M18 and M84.
#define DEFAULT_STEPPER_DEACTIVE_TIME 60
#define DISABLE_INACTIVE_X true
#define DISABLE_INACTIVE_Y true
#define DISABLE_INACTIVE_Z true // set to false if the nozzle will fall down on your printed part when print has finished.
#define DISABLE_INACTIVE_E true
#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate
#define DEFAULT_MINTRAVELFEEDRATE 0.0
//#define HOME_AFTER_DEACTIVATE // Require rehoming after steppers are deactivated
// @section lcd
#if ENABLED(ULTIPANEL)
#define MANUAL_FEEDRATE {120*60, 120*60, 18*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel
#define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder
#endif
// @section extras
// minimum time in microseconds that a movement needs to take if the buffer is emptied.
#define DEFAULT_MINSEGMENTTIME 20000
// If defined the movements slow down when the look ahead buffer is only half full
#define SLOWDOWN
// Frequency limit
// See nophead's blog for more info
// Not working O
//#define XY_FREQUENCY_LIMIT 15
// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end
// of the buffer and all stops. This should not be much greater than zero and should only be changed
// if unwanted behavior is observed on a user's machine when running at very slow speeds.
#define MINIMUM_PLANNER_SPEED 0.05 // (mm/sec)
// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU.
#define MICROSTEP_MODES {16,16,16,16,16} // [1,2,4,8,16]
/**
* @section stepper motor current
*
* Some boards have a means of setting the stepper motor current via firmware.
*
* The power on motor currents are set by:
* PWM_MOTOR_CURRENT - used by MINIRAMBO & ULTIMAIN_2
* known compatible chips: A4982
* DIGIPOT_MOTOR_CURRENT - used by BQ_ZUM_MEGA_3D, RAMBO & SCOOVO_X9H
* known compatible chips: AD5206
* DAC_MOTOR_CURRENT_DEFAULT - used by PRINTRBOARD_REVF & RIGIDBOARD_V2
* known compatible chips: MCP4728
* DIGIPOT_I2C_MOTOR_CURRENTS - used by 5DPRINT, AZTEEG_X3_PRO, MIGHTYBOARD_REVE
* known compatible chips: MCP4451, MCP4018
*
* Motor currents can also be set by M907 - M910 and by the LCD.
* M907 - applies to all.
* M908 - BQ_ZUM_MEGA_3D, RAMBO, PRINTRBOARD_REVF, RIGIDBOARD_V2 & SCOOVO_X9H
* M909, M910 & LCD - only PRINTRBOARD_REVF & RIGIDBOARD_V2
*/
//#define PWM_MOTOR_CURRENT { 1300, 1300, 1250 } // Values in milliamps
//#define DIGIPOT_MOTOR_CURRENT { 135,135,135,135,135 } // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A)
//#define DAC_MOTOR_CURRENT_DEFAULT { 70, 80, 90, 80 } // Default drive percent - X, Y, Z, E axis
// Uncomment to enable an I2C based DIGIPOT like on the Azteeg X3 Pro
//#define DIGIPOT_I2C
//#define DIGIPOT_MCP4018 // Requires library from https://github.com/stawel/SlowSoftI2CMaster
#define DIGIPOT_I2C_NUM_CHANNELS 8 // 5DPRINT: 4 AZTEEG_X3_PRO: 8
// Actual motor currents in Amps, need as many here as DIGIPOT_I2C_NUM_CHANNELS
#define DIGIPOT_I2C_MOTOR_CURRENTS { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 } // AZTEEG_X3_PRO
//===========================================================================
//=============================Additional Features===========================
//===========================================================================
#define ENCODER_RATE_MULTIPLIER // If defined, certain menu edit operations automatically multiply the steps when the encoder is moved quickly
#define ENCODER_10X_STEPS_PER_SEC 75 // If the encoder steps per sec exceeds this value, multiply steps moved x10 to quickly advance the value
#define ENCODER_100X_STEPS_PER_SEC 160 // If the encoder steps per sec exceeds this value, multiply steps moved x100 to really quickly advance the value
//#define CHDK 4 //Pin for triggering CHDK to take a picture see how to use it here http://captain-slow.dk/2014/03/09/3d-printing-timelapses/
#define CHDK_DELAY 50 //How long in ms the pin should stay HIGH before going LOW again
// @section lcd
// Include a page of printer information in the LCD Main Menu
//#define LCD_INFO_MENU
// Scroll a longer status message into view
//#define STATUS_MESSAGE_SCROLLING
// On the Info Screen, display XY with one decimal place when possible
//#define LCD_DECIMAL_SMALL_XY
// The timeout (in ms) to return to the status screen from sub-menus
//#define LCD_TIMEOUT_TO_STATUS 15000
#if ENABLED(SDSUPPORT)
// Some RAMPS and other boards don't detect when an SD card is inserted. You can work
// around this by connecting a push button or single throw switch to the pin defined
// as SD_DETECT_PIN in your board's pins definitions.
// This setting should be disabled unless you are using a push button, pulling the pin to ground.
// Note: This is always disabled for ULTIPANEL (except ELB_FULL_GRAPHIC_CONTROLLER).
#define SD_DETECT_INVERTED
#define SD_FINISHED_STEPPERRELEASE true //if sd support and the file is finished: disable steppers?
#define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the z enabled so your bed stays in place.
#define SDCARD_RATHERRECENTFIRST //reverse file order of sd card menu display. Its sorted practically after the file system block order.
// if a file is deleted, it frees a block. hence, the order is not purely chronological. To still have auto0.g accessible, there is again the option to do that.
// using:
//#define MENU_ADDAUTOSTART
/**
* Sort SD file listings in alphabetical order.
*
* With this option enabled, items on SD cards will be sorted
* by name for easier navigation.
*
* By default...
*
* - Use the slowest -but safest- method for sorting.
* - Folders are sorted to the top.
* - The sort key is statically allocated.
* - No added G-code (M34) support.
* - 40 item sorting limit. (Items after the first 40 are unsorted.)
*
* SD sorting uses static allocation (as set by SDSORT_LIMIT), allowing the
* compiler to calculate the worst-case usage and throw an error if the SRAM
* limit is exceeded.
*
* - SDSORT_USES_RAM provides faster sorting via a static directory buffer.
* - SDSORT_USES_STACK does the same, but uses a local stack-based buffer.
* - SDSORT_CACHE_NAMES will retain the sorted file listing in RAM. (Expensive!)
* - SDSORT_DYNAMIC_RAM only uses RAM when the SD menu is visible. (Use with caution!)
*/
//#define SDCARD_SORT_ALPHA
// SD Card Sorting options
#if ENABLED(SDCARD_SORT_ALPHA)
#define SDSORT_LIMIT 40 // Maximum number of sorted items (10-256).
#define FOLDER_SORTING -1 // -1=above 0=none 1=below
#define SDSORT_GCODE false // Allow turning sorting on/off with LCD and M34 g-code.
#define SDSORT_USES_RAM false // Pre-allocate a static array for faster pre-sorting.
#define SDSORT_USES_STACK false // Prefer the stack for pre-sorting to give back some SRAM. (Negated by next 2 options.)
#define SDSORT_CACHE_NAMES false // Keep sorted items in RAM longer for speedy performance. Most expensive option.
#define SDSORT_DYNAMIC_RAM false // Use dynamic allocation (within SD menus). Least expensive option. Set SDSORT_LIMIT before use!
#endif
// Show a progress bar on HD44780 LCDs for SD printing
//#define LCD_PROGRESS_BAR
#if ENABLED(LCD_PROGRESS_BAR)
// Amount of time (ms) to show the bar
#define PROGRESS_BAR_BAR_TIME 2000
// Amount of time (ms) to show the status message
#define PROGRESS_BAR_MSG_TIME 3000
// Amount of time (ms) to retain the status message (0=forever)
#define PROGRESS_MSG_EXPIRE 0
// Enable this to show messages for MSG_TIME then hide them
//#define PROGRESS_MSG_ONCE
// Add a menu item to test the progress bar:
//#define LCD_PROGRESS_BAR_TEST
#endif
// This allows hosts to request long names for files and folders with M33
//#define LONG_FILENAME_HOST_SUPPORT
// This option allows you to abort SD printing when any endstop is triggered.
// This feature must be enabled with "M540 S1" or from the LCD menu.
// To have any effect, endstops must be enabled during SD printing.
//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
#endif // SDSUPPORT
/**
* Additional options for Graphical Displays
*
* Use the optimizations here to improve printing performance,
* which can be adversely affected by graphical display drawing,
* especially when doing several short moves, and when printing
* on DELTA and SCARA machines.
*
* Some of these options may result in the display lagging behind
* controller events, as there is a trade-off between reliable
* printing performance versus fast display updates.
*/
#if ENABLED(DOGLCD)
// Enable to save many cycles by drawing a hollow frame on the Info Screen
#define XYZ_HOLLOW_FRAME
// Enable to save many cycles by drawing a hollow frame on Menu Screens
#define MENU_HOLLOW_FRAME
// A bigger font is available for edit items. Costs 3120 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_BIG_EDIT_FONT
// A smaller font may be used on the Info Screen. Costs 2300 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_SMALL_INFOFONT
// Enable this option and reduce the value to optimize screen updates.
// The normal delay is 10µs. Use the lowest value that still gives a reliable display.
//#define DOGM_SPI_DELAY_US 5
#endif // DOGLCD
// @section safety
// The hardware watchdog should reset the microcontroller disabling all outputs,
// in case the firmware gets stuck and doesn't do temperature regulation.
#define USE_WATCHDOG
#if ENABLED(USE_WATCHDOG)
// If you have a watchdog reboot in an ArduinoMega2560 then the device will hang forever, as a watchdog reset will leave the watchdog on.
// The "WATCHDOG_RESET_MANUAL" goes around this by not using the hardware reset.
// However, THIS FEATURE IS UNSAFE!, as it will only work if interrupts are disabled. And the code could hang in an interrupt routine with interrupts disabled.
//#define WATCHDOG_RESET_MANUAL
#endif
// @section lcd
/**
* Babystepping enables movement of the axes by tiny increments without changing
* the current position values. This feature is used primarily to adjust the Z
* axis in the first layer of a print in real-time.
*
* Warning: Does not respect endstops!
*/
//#define BABYSTEPPING
#if ENABLED(BABYSTEPPING)
#define BABYSTEP_XY // Also enable X/Y Babystepping. Not supported on DELTA!
#define BABYSTEP_INVERT_Z false // Change if Z babysteps should go the other way
#define BABYSTEP_MULTIPLICATOR 1 // Babysteps are very small. Increase for faster motion.
//#define BABYSTEP_ZPROBE_OFFSET // Enable to combine M851 and Babystepping
//#define DOUBLECLICK_FOR_Z_BABYSTEPPING // Double-click on the Status Screen for Z Babystepping.
#define DOUBLECLICK_MAX_INTERVAL 1250 // Maximum interval between clicks, in milliseconds.
// Note: Extra time may be added to mitigate controller latency.
#endif
// @section extruder
// extruder advance constant (s2/mm3)
//
// advance (steps) = STEPS_PER_CUBIC_MM_E * EXTRUDER_ADVANCE_K * cubic mm per second ^ 2
//
// Hooke's law says: force = k * distance
// Bernoulli's principle says: v ^ 2 / 2 + g . h + pressure / density = constant
// so: v ^ 2 is proportional to number of steps we advance the extruder
//#define ADVANCE
#if ENABLED(ADVANCE)
#define EXTRUDER_ADVANCE_K .0
#define D_FILAMENT 1.75
#endif
/**
* Implementation of linear pressure control
*
* Assumption: advance = k * (delta velocity)
* K=0 means advance disabled.
* See Marlin documentation for calibration instructions.
*/
//#define LIN_ADVANCE
#if ENABLED(LIN_ADVANCE)
#define LIN_ADVANCE_K 75
/**
* Some Slicers produce Gcode with randomly jumping extrusion widths occasionally.
* For example within a 0.4mm perimeter it may produce a single segment of 0.05mm width.
* While this is harmless for normal printing (the fluid nature of the filament will
* close this very, very tiny gap), it throws off the LIN_ADVANCE pressure adaption.
*
* For this case LIN_ADVANCE_E_D_RATIO can be used to set the extrusion:distance ratio
* to a fixed value. Note that using a fixed ratio will lead to wrong nozzle pressures
* if the slicer is using variable widths or layer heights within one print!
*
* This option sets the default E:D ratio at startup. Use `M900` to override this value.
*
* Example: `M900 W0.4 H0.2 D1.75`, where:
* - W is the extrusion width in mm
* - H is the layer height in mm
* - D is the filament diameter in mm
*
* Example: `M900 R0.0458` to set the ratio directly.
*
* Set to 0 to auto-detect the ratio based on given Gcode G1 print moves.
*
* Slic3r (including Průša Control) produces Gcode compatible with the automatic mode.
* Cura (as of this writing) may produce Gcode incompatible with the automatic mode.
*/
#define LIN_ADVANCE_E_D_RATIO 0 // The calculated ratio (or 0) according to the formula W * H / ((D / 2) ^ 2 * PI)
// Example: 0.4 * 0.2 / ((1.75 / 2) ^ 2 * PI) = 0.033260135
#endif
// @section leveling
// Default mesh area is an area with an inset margin on the print area.
// Below are the macros that are used to define the borders for the mesh area,
// made available here for specialized needs, ie dual extruder setup.
#if ENABLED(MESH_BED_LEVELING)
#define MESH_MIN_X MESH_INSET
#define MESH_MAX_X (X_BED_SIZE - (MESH_INSET))
#define MESH_MIN_Y MESH_INSET
#define MESH_MAX_Y (Y_BED_SIZE - (MESH_INSET))
#elif ENABLED(AUTO_BED_LEVELING_UBL)
#define UBL_MESH_MIN_X UBL_MESH_INSET
#define UBL_MESH_MAX_X (X_BED_SIZE - (UBL_MESH_INSET))
#define UBL_MESH_MIN_Y UBL_MESH_INSET
#define UBL_MESH_MAX_Y (Y_BED_SIZE - (UBL_MESH_INSET))
// If this is defined, the currently active mesh will be saved in the
// current slot on M500.
#define UBL_SAVE_ACTIVE_ON_M500
#endif
// @section extras
//
// G2/G3 Arc Support
//
#define ARC_SUPPORT // Disable this feature to save ~3226 bytes
#if ENABLED(ARC_SUPPORT)
#define MM_PER_ARC_SEGMENT 1 // Length of each arc segment
#define N_ARC_CORRECTION 25 // Number of intertpolated segments between corrections
//#define ARC_P_CIRCLES // Enable the 'P' parameter to specify complete circles
//#define CNC_WORKSPACE_PLANES // Allow G2/G3 to operate in XY, ZX, or YZ planes
#endif
// Support for G5 with XYZE destination and IJPQ offsets. Requires ~2666 bytes.
//#define BEZIER_CURVE_SUPPORT
// G38.2 and G38.3 Probe Target
// Enable PROBE_DOUBLE_TOUCH if you want G38 to double touch
//#define G38_PROBE_TARGET
#if ENABLED(G38_PROBE_TARGET)
#define G38_MINIMUM_MOVE 0.0275 // minimum distance in mm that will produce a move (determined using the print statement in check_move)
#endif
// Moves (or segments) with fewer steps than this will be joined with the next move
#define MIN_STEPS_PER_SEGMENT 6
// The minimum pulse width (in µs) for stepping a stepper.
// Set this if you find stepping unreliable, or if using a very fast CPU.
#define MINIMUM_STEPPER_PULSE 0 // (µs) The smallest stepper pulse allowed
// @section temperature
// Control heater 0 and heater 1 in parallel.
//#define HEATERS_PARALLEL
//===========================================================================
//================================= Buffers =================================
//===========================================================================
// @section hidden
// The number of linear motions that can be in the plan at any give time.
// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2, i.g. 8,16,32 because shifts and ors are used to do the ring-buffering.
#if ENABLED(SDSUPPORT)
#define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller
#else
#define BLOCK_BUFFER_SIZE 16 // maximize block buffer
#endif
// @section serial
// The ASCII buffer for serial input
#define MAX_CMD_SIZE 96
#define BUFSIZE 4
// Transfer Buffer Size
// To save 386 bytes of PROGMEM (and TX_BUFFER_SIZE+3 bytes of RAM) set to 0.
// To buffer a simple "ok" you need 4 bytes.
// For ADVANCED_OK (M105) you need 32 bytes.
// For debug-echo: 128 bytes for the optimal speed.
// Other output doesn't need to be that speedy.
// :[0, 2, 4, 8, 16, 32, 64, 128, 256]
#define TX_BUFFER_SIZE 0
// Enable an emergency-command parser to intercept certain commands as they
// enter the serial receive buffer, so they cannot be blocked.
// Currently handles M108, M112, M410
// Does not work on boards using AT90USB (USBCON) processors!
//#define EMERGENCY_PARSER
// Bad Serial-connections can miss a received command by sending an 'ok'
// Therefore some clients abort after 30 seconds in a timeout.
// Some other clients start sending commands while receiving a 'wait'.
// This "wait" is only sent when the buffer is empty. 1 second is a good value here.
//#define NO_TIMEOUTS 1000 // Milliseconds
// Some clients will have this feature soon. This could make the NO_TIMEOUTS unnecessary.
//#define ADVANCED_OK
// @section extras
/**
* Firmware-based and LCD-controlled retract
*
* Add G10 / G11 commands for automatic firmware-based retract / recover.
* Use M207 and M208 to define parameters for retract / recover.
*
* Use M209 to enable or disable auto-retract.
* With auto-retract enabled, all G1 E moves within the set range
* will be converted to firmware-based retract/recover moves.
*
* Be sure to turn off auto-retract during filament change.
*
* Note that M207 / M208 / M209 settings are saved to EEPROM.
*
*/
//#define FWRETRACT // ONLY PARTIALLY TESTED
#if ENABLED(FWRETRACT)
#define MIN_AUTORETRACT 0.1 // When auto-retract is on, convert E moves of this length and over
#define MAX_AUTORETRACT 10.0 // Upper limit for auto-retract conversion
#define RETRACT_LENGTH 3 // Default retract length (positive mm)
#define RETRACT_LENGTH_SWAP 13 // Default swap retract length (positive mm), for extruder change
#define RETRACT_FEEDRATE 45 // Default feedrate for retracting (mm/s)
#define RETRACT_ZLIFT 0 // Default retract Z-lift
#define RETRACT_RECOVER_LENGTH 0 // Default additional recover length (mm, added to retract length when recovering)
#define RETRACT_RECOVER_LENGTH_SWAP 0 // Default additional swap recover length (mm, added to retract length when recovering from extruder change)
#define RETRACT_RECOVER_FEEDRATE 8 // Default feedrate for recovering from retraction (mm/s)
#define RETRACT_RECOVER_FEEDRATE_SWAP 8 // Default feedrate for recovering from swap retraction (mm/s)
#endif
/**
* Advanced Pause
* Experimental feature for filament change support and for parking the nozzle when paused.
* Adds the GCode M600 for initiating filament change.
* If PARK_HEAD_ON_PAUSE enabled, adds the GCode M125 to pause printing and park the nozzle.
*
* Requires an LCD display.
* This feature is required for the default FILAMENT_RUNOUT_SCRIPT.
*/
//#define ADVANCED_PAUSE_FEATURE
#if ENABLED(ADVANCED_PAUSE_FEATURE)
#define PAUSE_PARK_X_POS 3 // X position of hotend
#define PAUSE_PARK_Y_POS 3 // Y position of hotend
#define PAUSE_PARK_Z_ADD 10 // Z addition of hotend (lift)
#define PAUSE_PARK_XY_FEEDRATE 100 // X and Y axes feedrate in mm/s (also used for delta printers Z axis)
#define PAUSE_PARK_Z_FEEDRATE 5 // Z axis feedrate in mm/s (not used for delta printers)
#define PAUSE_PARK_RETRACT_FEEDRATE 60 // Initial retract feedrate in mm/s
#define PAUSE_PARK_RETRACT_LENGTH 2 // Initial retract in mm
// It is a short retract used immediately after print interrupt before move to filament exchange position
#define FILAMENT_CHANGE_UNLOAD_FEEDRATE 10 // Unload filament feedrate in mm/s - filament unloading can be fast
#define FILAMENT_CHANGE_UNLOAD_LENGTH 100 // Unload filament length from hotend in mm
// Longer length for bowden printers to unload filament from whole bowden tube,
// shorter length for printers without bowden to unload filament from extruder only,
// 0 to disable unloading for manual unloading
#define FILAMENT_CHANGE_LOAD_FEEDRATE 6 // Load filament feedrate in mm/s - filament loading into the bowden tube can be fast
#define FILAMENT_CHANGE_LOAD_LENGTH 0 // Load filament length over hotend in mm
// Longer length for bowden printers to fast load filament into whole bowden tube over the hotend,
// Short or zero length for printers without bowden where loading is not used
#define ADVANCED_PAUSE_EXTRUDE_FEEDRATE 3 // Extrude filament feedrate in mm/s - must be slower than load feedrate
#define ADVANCED_PAUSE_EXTRUDE_LENGTH 50 // Extrude filament length in mm after filament is loaded over the hotend,
// 0 to disable for manual extrusion
// Filament can be extruded repeatedly from the filament exchange menu to fill the hotend,
// or until outcoming filament color is not clear for filament color change
#define PAUSE_PARK_NOZZLE_TIMEOUT 45 // Turn off nozzle if user doesn't change filament within this time limit in seconds
#define FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS 5 // Number of alert beeps before printer goes quiet
#define PAUSE_PARK_NO_STEPPER_TIMEOUT // Enable to have stepper motors hold position during filament change
// even if it takes longer than DEFAULT_STEPPER_DEACTIVE_TIME.
//#define PARK_HEAD_ON_PAUSE // Go to filament change position on pause, return to print position on resume
//#define HOME_BEFORE_FILAMENT_CHANGE // Ensure homing has been completed prior to parking for filament change
#endif
// @section tmc
/**
* Enable this section if you have TMC26X motor drivers.
* You will need to import the TMC26XStepper library into the Arduino IDE for this
* (https://github.com/trinamic/TMC26XStepper.git)
*/
//#define HAVE_TMCDRIVER
#if ENABLED(HAVE_TMCDRIVER)
//#define X_IS_TMC
//#define X2_IS_TMC
//#define Y_IS_TMC
//#define Y2_IS_TMC
//#define Z_IS_TMC
//#define Z2_IS_TMC
//#define E0_IS_TMC
//#define E1_IS_TMC
//#define E2_IS_TMC
//#define E3_IS_TMC
//#define E4_IS_TMC
#define X_MAX_CURRENT 1000 // in mA
#define X_SENSE_RESISTOR 91 // in mOhms
#define X_MICROSTEPS 16 // number of microsteps
#define X2_MAX_CURRENT 1000
#define X2_SENSE_RESISTOR 91
#define X2_MICROSTEPS 16
#define Y_MAX_CURRENT 1000
#define Y_SENSE_RESISTOR 91
#define Y_MICROSTEPS 16
#define Y2_MAX_CURRENT 1000
#define Y2_SENSE_RESISTOR 91
#define Y2_MICROSTEPS 16
#define Z_MAX_CURRENT 1000
#define Z_SENSE_RESISTOR 91
#define Z_MICROSTEPS 16
#define Z2_MAX_CURRENT 1000
#define Z2_SENSE_RESISTOR 91
#define Z2_MICROSTEPS 16
#define E0_MAX_CURRENT 1000
#define E0_SENSE_RESISTOR 91
#define E0_MICROSTEPS 16
#define E1_MAX_CURRENT 1000
#define E1_SENSE_RESISTOR 91
#define E1_MICROSTEPS 16
#define E2_MAX_CURRENT 1000
#define E2_SENSE_RESISTOR 91
#define E2_MICROSTEPS 16
#define E3_MAX_CURRENT 1000
#define E3_SENSE_RESISTOR 91
#define E3_MICROSTEPS 16
#define E4_MAX_CURRENT 1000
#define E4_SENSE_RESISTOR 91
#define E4_MICROSTEPS 16
#endif
// @section TMC2130
/**
* Enable this for SilentStepStick Trinamic TMC2130 SPI-configurable stepper drivers.
*
* You'll also need the TMC2130Stepper Arduino library
* (https://github.com/teemuatlut/TMC2130Stepper).
*
* To use TMC2130 stepper drivers in SPI mode connect your SPI2130 pins to
* the hardware SPI interface on your board and define the required CS pins
* in your `pins_MYBOARD.h` file. (e.g., RAMPS 1.4 uses AUX3 pins `X_CS_PIN 53`, `Y_CS_PIN 49`, etc.).
*/
//#define HAVE_TMC2130
#if ENABLED(HAVE_TMC2130)
// CHOOSE YOUR MOTORS HERE, THIS IS MANDATORY
//#define X_IS_TMC2130
//#define X2_IS_TMC2130
//#define Y_IS_TMC2130
//#define Y2_IS_TMC2130
//#define Z_IS_TMC2130
//#define Z2_IS_TMC2130
//#define E0_IS_TMC2130
//#define E1_IS_TMC2130
//#define E2_IS_TMC2130
//#define E3_IS_TMC2130
//#define E4_IS_TMC2130
/**
* Stepper driver settings
*/
#define R_SENSE 0.11 // R_sense resistor for SilentStepStick2130
#define HOLD_MULTIPLIER 0.5 // Scales down the holding current from run current
#define INTERPOLATE 1 // Interpolate X/Y/Z_MICROSTEPS to 256
#define X_CURRENT 1000 // rms current in mA. Multiply by 1.41 for peak current.
#define X_MICROSTEPS 16 // 0..256
#define Y_CURRENT 1000
#define Y_MICROSTEPS 16
#define Z_CURRENT 1000
#define Z_MICROSTEPS 16
//#define X2_CURRENT 1000
//#define X2_MICROSTEPS 16
//#define Y2_CURRENT 1000
//#define Y2_MICROSTEPS 16
//#define Z2_CURRENT 1000
//#define Z2_MICROSTEPS 16
//#define E0_CURRENT 1000
//#define E0_MICROSTEPS 16
//#define E1_CURRENT 1000
//#define E1_MICROSTEPS 16
//#define E2_CURRENT 1000
//#define E2_MICROSTEPS 16
//#define E3_CURRENT 1000
//#define E3_MICROSTEPS 16
//#define E4_CURRENT 1000
//#define E4_MICROSTEPS 16
/**
* Use Trinamic's ultra quiet stepping mode.
* When disabled, Marlin will use spreadCycle stepping mode.
*/
#define STEALTHCHOP
/**
* Let Marlin automatically control stepper current.
* This is still an experimental feature.
* Increase current every 5s by CURRENT_STEP until stepper temperature prewarn gets triggered,
* then decrease current by CURRENT_STEP until temperature prewarn is cleared.
* Adjusting starts from X/Y/Z/E_CURRENT but will not increase over AUTO_ADJUST_MAX
* Relevant g-codes:
* M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given.
* M906 S1 - Start adjusting current
* M906 S0 - Stop adjusting current
* M911 - Report stepper driver overtemperature pre-warn condition.
* M912 - Clear stepper driver overtemperature pre-warn condition flag.
*/
//#define AUTOMATIC_CURRENT_CONTROL
#if ENABLED(AUTOMATIC_CURRENT_CONTROL)
#define CURRENT_STEP 50 // [mA]
#define AUTO_ADJUST_MAX 1300 // [mA], 1300mA_rms = 1840mA_peak
#define REPORT_CURRENT_CHANGE
#endif
/**
* The driver will switch to spreadCycle when stepper speed is over HYBRID_THRESHOLD.
* This mode allows for faster movements at the expense of higher noise levels.
* STEALTHCHOP needs to be enabled.
* M913 X/Y/Z/E to live tune the setting
*/
//#define HYBRID_THRESHOLD
#define X_HYBRID_THRESHOLD 100 // [mm/s]
#define X2_HYBRID_THRESHOLD 100
#define Y_HYBRID_THRESHOLD 100
#define Y2_HYBRID_THRESHOLD 100
#define Z_HYBRID_THRESHOLD 4
#define Z2_HYBRID_THRESHOLD 4
#define E0_HYBRID_THRESHOLD 30
#define E1_HYBRID_THRESHOLD 30
#define E2_HYBRID_THRESHOLD 30
#define E3_HYBRID_THRESHOLD 30
#define E4_HYBRID_THRESHOLD 30
/**
* Use stallGuard2 to sense an obstacle and trigger an endstop.
* You need to place a wire from the driver's DIAG1 pin to the X/Y endstop pin.
* If used along with STEALTHCHOP, the movement will be louder when homing. This is normal.
*
* X/Y_HOMING_SENSITIVITY is used for tuning the trigger sensitivity.
* Higher values make the system LESS sensitive.
* Lower value make the system MORE sensitive.
* Too low values can lead to false positives, while too high values will collide the axis without triggering.
* It is advised to set X/Y_HOME_BUMP_MM to 0.
* M914 X/Y to live tune the setting
*/
//#define SENSORLESS_HOMING
#if ENABLED(SENSORLESS_HOMING)
#define X_HOMING_SENSITIVITY 19
#define Y_HOMING_SENSITIVITY 19
#endif
/**
* You can set your own advanced settings by filling in predefined functions.
* A list of available functions can be found on the library github page
* https://github.com/teemuatlut/TMC2130Stepper
*
* Example:
* #define TMC2130_ADV() { \
* stepperX.diag0_temp_prewarn(1); \
* stepperX.interpolate(0); \
* }
*/
#define TMC2130_ADV() { }
#endif // HAVE_TMC2130
// @section L6470
/**
* Enable this section if you have L6470 motor drivers.
* You need to import the L6470 library into the Arduino IDE for this.
* (https://github.com/ameyer/Arduino-L6470)
*/
//#define HAVE_L6470DRIVER
#if ENABLED(HAVE_L6470DRIVER)
//#define X_IS_L6470
//#define X2_IS_L6470
//#define Y_IS_L6470
//#define Y2_IS_L6470
//#define Z_IS_L6470
//#define Z2_IS_L6470
//#define E0_IS_L6470
//#define E1_IS_L6470
//#define E2_IS_L6470
//#define E3_IS_L6470
//#define E4_IS_L6470
#define X_MICROSTEPS 16 // number of microsteps
#define X_K_VAL 50 // 0 - 255, Higher values, are higher power. Be careful not to go too high
#define X_OVERCURRENT 2000 // maxc current in mA. If the current goes over this value, the driver will switch off
#define X_STALLCURRENT 1500 // current in mA where the driver will detect a stall
#define X2_MICROSTEPS 16
#define X2_K_VAL 50
#define X2_OVERCURRENT 2000
#define X2_STALLCURRENT 1500
#define Y_MICROSTEPS 16
#define Y_K_VAL 50
#define Y_OVERCURRENT 2000
#define Y_STALLCURRENT 1500
#define Y2_MICROSTEPS 16
#define Y2_K_VAL 50
#define Y2_OVERCURRENT 2000
#define Y2_STALLCURRENT 1500
#define Z_MICROSTEPS 16
#define Z_K_VAL 50
#define Z_OVERCURRENT 2000
#define Z_STALLCURRENT 1500
#define Z2_MICROSTEPS 16
#define Z2_K_VAL 50
#define Z2_OVERCURRENT 2000
#define Z2_STALLCURRENT 1500
#define E0_MICROSTEPS 16
#define E0_K_VAL 50
#define E0_OVERCURRENT 2000
#define E0_STALLCURRENT 1500
#define E1_MICROSTEPS 16
#define E1_K_VAL 50
#define E1_OVERCURRENT 2000
#define E1_STALLCURRENT 1500
#define E2_MICROSTEPS 16
#define E2_K_VAL 50
#define E2_OVERCURRENT 2000
#define E2_STALLCURRENT 1500
#define E3_MICROSTEPS 16
#define E3_K_VAL 50
#define E3_OVERCURRENT 2000
#define E3_STALLCURRENT 1500
#define E4_MICROSTEPS 16
#define E4_K_VAL 50
#define E4_OVERCURRENT 2000
#define E4_STALLCURRENT 1500
#endif
/**
* TWI/I2C BUS
*
* This feature is an EXPERIMENTAL feature so it shall not be used on production
* machines. Enabling this will allow you to send and receive I2C data from slave
* devices on the bus.
*
* ; Example #1
* ; This macro send the string "Marlin" to the slave device with address 0x63 (99)
* ; It uses multiple M260 commands with one B<base 10> arg
* M260 A99 ; Target slave address
* M260 B77 ; M
* M260 B97 ; a
* M260 B114 ; r
* M260 B108 ; l
* M260 B105 ; i
* M260 B110 ; n
* M260 S1 ; Send the current buffer
*
* ; Example #2
* ; Request 6 bytes from slave device with address 0x63 (99)
* M261 A99 B5
*
* ; Example #3
* ; Example serial output of a M261 request
* echo:i2c-reply: from:99 bytes:5 data:hello
*/
// @section i2cbus
//#define EXPERIMENTAL_I2CBUS
#define I2C_SLAVE_ADDRESS 0 // Set a value from 8 to 127 to act as a slave
// @section extras
/**
* Spindle & Laser control
*
* Add the M3, M4, and M5 commands to turn the spindle/laser on and off, and
* to set spindle speed, spindle direction, and laser power.
*
* SuperPid is a router/spindle speed controller used in the CNC milling community.
* Marlin can be used to turn the spindle on and off. It can also be used to set
* the spindle speed from 5,000 to 30,000 RPM.
*
* You'll need to select a pin for the ON/OFF function and optionally choose a 0-5V
* hardware PWM pin for the speed control and a pin for the rotation direction.
*
* See http://marlinfw.org/docs/configuration/laser_spindle.html for more config details.
*/
//#define SPINDLE_LASER_ENABLE
#if ENABLED(SPINDLE_LASER_ENABLE)
#define SPINDLE_LASER_ENABLE_INVERT false // set to "true" if the on/off function is reversed
#define SPINDLE_LASER_PWM true // set to true if your controller supports setting the speed/power
#define SPINDLE_LASER_PWM_INVERT true // set to "true" if the speed/power goes up when you want it to go slower
#define SPINDLE_LASER_POWERUP_DELAY 5000 // delay in milliseconds to allow the spindle/laser to come up to speed/power
#define SPINDLE_LASER_POWERDOWN_DELAY 5000 // delay in milliseconds to allow the spindle to stop
#define SPINDLE_DIR_CHANGE true // set to true if your spindle controller supports changing spindle direction
#define SPINDLE_INVERT_DIR false
#define SPINDLE_STOP_ON_DIR_CHANGE true // set to true if Marlin should stop the spindle before changing rotation direction
/**
* The M3 & M4 commands use the following equation to convert PWM duty cycle to speed/power
*
* SPEED/POWER = PWM duty cycle * SPEED_POWER_SLOPE + SPEED_POWER_INTERCEPT
* where PWM duty cycle varies from 0 to 255
*
* set the following for your controller (ALL MUST BE SET)
*/
#define SPEED_POWER_SLOPE 118.4
#define SPEED_POWER_INTERCEPT 0
#define SPEED_POWER_MIN 5000
#define SPEED_POWER_MAX 30000 // SuperPID router controller 0 - 30,000 RPM
//#define SPEED_POWER_SLOPE 0.3922
//#define SPEED_POWER_INTERCEPT 0
//#define SPEED_POWER_MIN 10
//#define SPEED_POWER_MAX 100 // 0-100%
#endif
/**
* M43 - display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
*/
//#define PINS_DEBUGGING
/**
* Auto-report temperatures with M155 S<seconds>
*/
#define AUTO_REPORT_TEMPERATURES
/**
* Include capabilities in M115 output
*/
#define EXTENDED_CAPABILITIES_REPORT
/**
* Volumetric extrusion default state
* Activate to make volumetric extrusion the default method,
* with DEFAULT_NOMINAL_FILAMENT_DIA as the default diameter.
*
* M200 D0 to disable, M200 Dn to set a new diameter.
*/
//#define VOLUMETRIC_DEFAULT_ON
/**
* Enable this option for a leaner build of Marlin that removes all
* workspace offsets, simplifying coordinate transformations, leveling, etc.
*
* - M206 and M428 are disabled.
* - G92 will revert to its behavior from Marlin 1.0.
*/
//#define NO_WORKSPACE_OFFSETS
/**
* Set the number of proportional font spaces required to fill up a typical character space.
* This can help to better align the output of commands like `G29 O` Mesh Output.
*
* For clients that use a fixed-width font (like OctoPrint), leave this set to 1.0.
* Otherwise, adjust according to your client and font.
*/
#define PROPORTIONAL_FONT_RATIO 1.0
/**
* Spend 28 bytes of SRAM to optimize the GCode parser
*/
#define FASTER_GCODE_PARSER
/**
* User-defined menu items that execute custom GCode
*/
//#define CUSTOM_USER_MENUS
#if ENABLED(CUSTOM_USER_MENUS)
#define USER_SCRIPT_DONE "M117 User Script Done"
#define USER_SCRIPT_AUDIBLE_FEEDBACK
#define USER_DESC_1 "Home & UBL Info"
#define USER_GCODE_1 "G28\nG29 W"
#define USER_DESC_2 "Preheat for PLA"
#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)
#define USER_DESC_3 "Preheat for ABS"
#define USER_GCODE_3 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_2_TEMP_HOTEND)
#define USER_DESC_4 "Heat Bed/Home/Level"
#define USER_GCODE_4 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nG28\nG29"
//#define USER_DESC_5 "Home & Info"
//#define USER_GCODE_5 "G28\nM503"
#endif
/**
* Specify an action command to send to the host when the printer is killed.
* Will be sent in the form '//action:ACTION_ON_KILL', e.g. '//action:poweroff'.
* The host must be configured to handle the action command.
*/
//#define ACTION_ON_KILL "poweroff"
//===========================================================================
//====================== I2C Position Encoder Settings ======================
//===========================================================================
/**
* I2C position encoders for closed loop control.
* Developed by Chris Barr at Aus3D.
*
* Wiki: http://wiki.aus3d.com.au/Magnetic_Encoder
* Github: https://github.com/Aus3D/MagneticEncoder
*
* Supplier: http://aus3d.com.au/magnetic-encoder-module
* Alternative Supplier: http://reliabuild3d.com/
*
* Reilabuild encoders have been modified to improve reliability.
*/
//#define I2C_POSITION_ENCODERS
#if ENABLED(I2C_POSITION_ENCODERS)
#define I2CPE_ENCODER_CNT 1 // The number of encoders installed; max of 5
// encoders supported currently.
#define I2CPE_ENC_1_ADDR I2CPE_PRESET_ADDR_X // I2C address of the encoder. 30-200.
#define I2CPE_ENC_1_AXIS X_AXIS // Axis the encoder module is installed on. <X|Y|Z|E>_AXIS.
#define I2CPE_ENC_1_TYPE I2CPE_ENC_TYPE_LINEAR // Type of encoder: I2CPE_ENC_TYPE_LINEAR -or-
// I2CPE_ENC_TYPE_ROTARY.
#define I2CPE_ENC_1_TICKS_UNIT 2048 // 1024 for magnetic strips with 2mm poles; 2048 for
// 1mm poles. For linear encoders this is ticks / mm,
// for rotary encoders this is ticks / revolution.
//#define I2CPE_ENC_1_TICKS_REV (16 * 200) // Only needed for rotary encoders; number of stepper
// steps per full revolution (motor steps/rev * microstepping)
//#define I2CPE_ENC_1_INVERT // Invert the direction of axis travel.
#define I2CPE_ENC_1_EC_METHOD I2CPE_ECM_NONE // Type of error error correction.
#define I2CPE_ENC_1_EC_THRESH 0.10 // Threshold size for error (in mm) above which the
// printer will attempt to correct the error; errors
// smaller than this are ignored to minimize effects of
// measurement noise / latency (filter).
#define I2CPE_ENC_2_ADDR I2CPE_PRESET_ADDR_Y // Same as above, but for encoder 2.
#define I2CPE_ENC_2_AXIS Y_AXIS
#define I2CPE_ENC_2_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_ENC_2_TICKS_UNIT 2048
//#define I2CPE_ENC_2_TICKS_REV (16 * 200)
//#define I2CPE_ENC_2_INVERT
#define I2CPE_ENC_2_EC_METHOD I2CPE_ECM_NONE
#define I2CPE_ENC_2_EC_THRESH 0.10
#define I2CPE_ENC_3_ADDR I2CPE_PRESET_ADDR_Z // Encoder 3. Add additional configuration options
#define I2CPE_ENC_3_AXIS Z_AXIS // as above, or use defaults below.
#define I2CPE_ENC_4_ADDR I2CPE_PRESET_ADDR_E // Encoder 4.
#define I2CPE_ENC_4_AXIS E_AXIS
#define I2CPE_ENC_5_ADDR 34 // Encoder 5.
#define I2CPE_ENC_5_AXIS E_AXIS
// Default settings for encoders which are enabled, but without settings configured above.
#define I2CPE_DEF_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_DEF_ENC_TICKS_UNIT 2048
#define I2CPE_DEF_TICKS_REV (16 * 200)
#define I2CPE_DEF_EC_METHOD I2CPE_ECM_NONE
#define I2CPE_DEF_EC_THRESH 0.1
//#define I2CPE_ERR_THRESH_ABORT 100.0 // Threshold size for error (in mm) error on any given
// axis after which the printer will abort. Comment out to
// disable abort behaviour.
#define I2CPE_TIME_TRUSTED 10000 // After an encoder fault, there must be no further fault
// for this amount of time (in ms) before the encoder
// is trusted again.
/**
* Position is checked every time a new command is executed from the buffer but during long moves,
* this setting determines the minimum update time between checks. A value of 100 works well with
* error rolling average when attempting to correct only for skips and not for vibration.
*/
#define I2CPE_MIN_UPD_TIME_MS 100 // Minimum time in miliseconds between encoder checks.
// Use a rolling average to identify persistant errors that indicate skips, as opposed to vibration and noise.
#define I2CPE_ERR_ROLLING_AVERAGE
#endif // I2C_POSITION_ENCODERS
/**
* Debug LED's using an 8x8 LED Matrix driven by a Max7219 chip. Fully assembled versions are available on
* eBay for under $2.00 (including shipping) and only require 3 signal wires.
*
* Check out auctions similar to this: https://www.ebay.com/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=332349290049&_sacat=0
*/
//#define MAX7219_DEBUG
#if ENABLED(MAX7219_DEBUG)
#define Max7219_clock 64 // 77 on Re-ARM // Configuration of the 3 pins to control the display
#define Max7219_data_in 57 // 78 on Re-ARM
#define Max7219_load 44 // 79 on Re-ARM
/*
* These are sample debug features that can be turned on and configured for your use.
* The developer will need to manage the use of the various LED's in the 8x8 matrix to avoid conflicts.
*/
#define MAX7219_DEBUG_PRINTER_ALIVE // Blink corner LED of 8x8 matrix from idle() routine if firmware is functioning
#define MAX7219_DEBUG_STEPPER_HEAD 3 // Display row position of stepper queue head on this line and the next line of LED matrix
#define MAX7219_DEBUG_STEPPER_TAIL 5 // Display row position of stepper queue tail on this line and the next line of LED matrix
#define MAX7219_DEBUG_STEPPER_QUEUE 0 // Display row position of stepper queue depth on this line and the next line of LED matrix
// If you have stuttering on your Delta printer, this option may help you understand how
// various tweaks you make to your configuration are affecting the printer.
#endif
#endif // CONFIGURATION_ADV_H
| gpl-3.0 |
brogowski/syncany-plugin-azureblobstorage | core/syncany-lib/src/main/java/org/syncany/plugins/transfer/oauth/OAuth.java | 2506 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011-2015 Philipp C. Heckel <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.plugins.transfer.oauth;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.syncany.plugins.transfer.TransferSettings;
/**
* This annotation is used to identify OAuth plugins by marking the corresponding
* {@link TransferSettings} class. An OAuth plugin will provide a 'token' field
* during the initialization process and the {@link OAuthGenerator} (provided via the
* help of the {@link #value()} field) will be able to check that token.
*
* @author Philipp Heckel <[email protected]>
* @author Christian Roth <[email protected]>
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface OAuth {
String PLUGIN_ID = "%pluginid%";
int RANDOM_PORT = -1;
/**
* @see OAuthGenerator
*/
Class<? extends OAuthGenerator> value();
/**
* The default Mode is {@link OAuthMode#SERVER}
*
* @see OAuthMode
*/
OAuthMode mode() default OAuthMode.SERVER;
/**
* If no specific port is provided (or {@value #RANDOM_PORT} is used), the {@link OAuthTokenWebListener} will choose a
* random port from the range of {@value OAuthTokenWebListener#PORT_LOWER} and
* {@value OAuthTokenWebListener#PORT_UPPER}.<br/>
* Needed if an OAuth provider uses preset and strict redirect URLs.
*/
int callbackPort() default RANDOM_PORT; // -1 is random
/**
* If no specific name is provided (or {@value #PLUGIN_ID} is used), the {@link OAuthTokenWebListener} will choose a
* random identifier for the OAuth process.<br/>
* Needed if an OAuth provider uses preset and strict redirect URLs.
*/
String callbackId() default PLUGIN_ID; // equals plugin id
}
| gpl-3.0 |
javierloza/KSquare | node_modules/npm/html/doc/cli/npm-logout.html | 4708 | <!doctype html>
<html>
<title>npm-logout</title>
<meta http-equiv="content-type" value="text/html;utf-8">
<link rel="stylesheet" type="text/css" href="../../static/style.css">
<link rel="canonical" href="https://www.npmjs.org/doc/cli/npm-logout.html">
<script async=true src="../../static/toc.js"></script>
<body>
<div id="wrapper">
<h1><a href="../cli/npm-logout.html">npm-logout</a></h1> <p>Log out of the registry</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm logout [--registry=url] [--scope=@orgname]
</code></pre><h2 id="description">DESCRIPTION</h2>
<p>When logged into a registry that supports token-based authentication, tell the
server to end this token's session. This will invalidate the token everywhere
you're using it, not just for the current environment.</p>
<p>When logged into a legacy registry that uses username and password authentication, this will
clear the credentials in your user configuration. In this case, it will <em>only</em> affect
the current environment.</p>
<p>If <code>--scope</code> is provided, this will find the credentials for the registry
connected to that scope, if set.</p>
<h2 id="configuration">CONFIGURATION</h2>
<h3 id="registry">registry</h3>
<p>Default: <a href="http://registry.npmjs.org/">http://registry.npmjs.org/</a></p>
<p>The base URL of the npm package registry. If <code>scope</code> is also specified,
it takes precedence.</p>
<h3 id="scope">scope</h3>
<p>Default: none</p>
<p>If specified, the user and login credentials given will be associated
with the specified scope. See <code><a href="../misc/npm-scope.html"><a href="../misc/npm-scope.html">npm-scope(7)</a></a></code>. You can use both at the same time,
e.g.</p>
<pre><code>npm adduser --registry=http://myregistry.example.com --scope=@myco
</code></pre><p>This will set a registry for the given scope and login or create a user for
that registry at the same time.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-adduser.html"><a href="../cli/npm-adduser.html">npm-adduser(1)</a></a></li>
<li><a href="../misc/npm-registry.html"><a href="../misc/npm-registry.html">npm-registry(7)</a></a></li>
<li><a href="../cli/npm-config.html"><a href="../cli/npm-config.html">npm-config(1)</a></a></li>
<li><a href="../misc/npm-config.html"><a href="../misc/npm-config.html">npm-config(7)</a></a></li>
<li><a href="../files/npmrc.html"><a href="../files/npmrc.html">npmrc(5)</a></a></li>
<li><a href="../cli/npm-whoami.html"><a href="../cli/npm-whoami.html">npm-whoami(1)</a></a></li>
</ul>
</div>
<table border=0 cellspacing=0 cellpadding=0 id=npmlogo>
<tr><td style="width:180px;height:10px;background:rgb(237,127,127)" colspan=18> </td></tr>
<tr><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td><td style="width:40px;height:10px;background:#fff" colspan=4> </td><td rowspan=4 style="width:10px;height:10px;background:rgb(237,127,127)"> </td><td colspan=6 style="width:60px;height:10px;background:#fff"> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=4> </td></tr>
<tr><td colspan=2 style="width:20px;height:30px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=4 colspan=2> </td><td style="width:10px;height:20px;background:rgb(237,127,127)" rowspan=2> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:20px;height:10px;background:#fff" rowspan=3 colspan=2> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td><td style="width:10px;height:10px;background:#fff" rowspan=3> </td><td style="width:10px;height:10px;background:rgb(237,127,127)" rowspan=3> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff" rowspan=2> </td></tr>
<tr><td style="width:10px;height:10px;background:#fff"> </td></tr>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
<p id="footer">npm-logout — [email protected]</p>
| gpl-3.0 |
tedvals/mywms | server.app/mywms.as/cactus/src/org/mywms/cactustest/ClearingItemServiceTest.java | 6345 | /*
* Copyright (c) 2007 by Fraunhofer IML, Dortmund.
* All rights reserved.
*
* Project: myWMS
*/
package org.mywms.cactustest;
import java.io.NotSerializableException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.mywms.model.ClearingItem;
import org.mywms.model.ClearingItemOption;
import org.mywms.model.ClearingItemOptionRetval;
import org.mywms.model.Client;
import org.mywms.res.BundleResolver;
/**
* @author aelbaz
* @version $Revision: 599 $ provided by $Author: trautm $
*/
public class ClearingItemServiceTest
extends CactusTestInit
{
private ClearingItem clearingItem1 = null, clearingItem11 = null,
clearingItem2 = null;
public void testCreateItem() throws NotSerializableException {
Client client = clientService.getSystemClient();
String host = "localhost";
String source1 = "Robot1";
String user1 = "Guest";
String messageResourceKey1 = "CLEARING_ITEM_MESSAGE_KEY";
String shortMessageResourceKey1 = "CLEARING_ITEM_SHORT_MESSAGE_KEY";
String[] messageParameters1 = {
"f_001", "f_002"
};
String[] shortMessageParameters1 = {
"f_001", "f_002"
};
ArrayList<ClearingItemOption> optionList =
new ArrayList<ClearingItemOption>();
ArrayList<ClearingItemOptionRetval> retvalList =
new ArrayList<ClearingItemOptionRetval>();
String[] messageParameters = {
"eins", "zwei"
};
ClearingItemOptionRetval retval1 = new ClearingItemOptionRetval();
ClearingItemOptionRetval retval2 = new ClearingItemOptionRetval();
retval1.setNameResourceKey("Date");
retval1.setType(Date.class);
retvalList.add(retval1);
retval2.setNameResourceKey("Dezimal");
retval2.setType(Integer.class);
retvalList.add(retval2);
ClearingItemOption options = new ClearingItemOption();
options.setMessageResourceKey("CLEARING_ITEM_OPTION_MESSAGE_KEY_1");
options.setMessageParameters(messageParameters);
options.setRetvals(retvalList);
optionList.add(options);
String boundleName1 = "org.mywms.res.mywms-clearing";
String boundleName2 = "org.mywms.res.mywms-clear";
clearingItem1 =
clearingItemService.create(
client,
host,
source1,
user1,
messageResourceKey1,
shortMessageResourceKey1,
boundleName1,
BundleResolver.class,
shortMessageParameters1,
messageParameters1,
optionList);
clearingItem1.setSolution("admin", options);
clearingItem1 = clearingItemService.merge(clearingItem1);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem1);
String source2 = "Robot2";
String user2 = "Guest2";
String message2 = "Das Problem liegt am Fach2";
String shortMessage2 = "Problem Nummer 2";
String messageResourceKey2 = "CLEARING_ITEM_MESSAGE_";
String shortMessageResourceKey2 = "CLEARING_ITEM_SHORT_MESSAGE_KEY";
String[] messageParameters2 = {
"f_001", "f_002"
};
String[] shortMessageParameters2 = {
"f_001", "f_002"
};
clearingItem11 =
clearingItemService.create(
client,
host,
source1,
user1,
messageResourceKey1,
shortMessageResourceKey1,
boundleName1,
BundleResolver.class,
shortMessageParameters1,
messageParameters1,
optionList);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem11);
clearingItem2 =
clearingItemService.create(
client,
host,
source2,
user2,
messageResourceKey2,
shortMessageResourceKey2,
boundleName2,
BundleResolver.class,
shortMessageParameters2,
messageParameters2,
optionList);
assertNotNull("Das Object wurde nicht erzeugt", clearingItem2);
}
public void testGetUser() {
List<String> listUsers = clearingItemService.getUser(null);
assertEquals("Guest", listUsers.get(0));
}
public void testGetSource() {
List<String> listSources = clearingItemService.getSources(null);
assertEquals("Robot1", listSources.get(0));
}
public void testGetHosts() {
List<String> listHosts = clearingItemService.getHosts(null);
assertEquals("localhost", listHosts.get(0));
}
public void testGetChronologicalLiVoidst() {
String client = clientService.getSystemClient().getNumber();
List<ClearingItem> list =
clearingItemService.getChronologicalList(
client,
"localhost",
"Robot1",
"user1",
3);
assertEquals("falsche Nummer", 0, list.size());
list =
clearingItemService.getChronologicalList(
client,
"localhost",
"Robot1",
"Guest",
2);
assertEquals("falsche Nummer", 2, list.size());
}
public void testGetNondealChronologicalList() {
String client = clientService.getSystemClient().getNumber();
List<ClearingItem> list =
clearingItemService.getNondealChronologicalList(
client,
"localhost",
"Robot1",
"Guest",
5);
assertEquals("falsche Nummer", 1, list.size());
}
}
| gpl-3.0 |
berkeleydave/graylog2-server | graylog2-radio/src/main/java/org/graylog2/radio/bindings/providers/RadioTransportProvider.java | 2065 | /**
* This file is part of Graylog.
*
* Graylog is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Graylog is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.radio.bindings.providers;
import com.codahale.metrics.MetricRegistry;
import org.graylog2.plugin.ServerStatus;
import org.graylog2.radio.Configuration;
import org.graylog2.radio.transports.RadioTransport;
import org.graylog2.radio.transports.amqp.AMQPProducer;
import org.graylog2.radio.transports.kafka.KafkaProducer;
import javax.inject.Inject;
import javax.inject.Provider;
/**
* @author Dennis Oelkers <[email protected]>
*/
public class RadioTransportProvider implements Provider<RadioTransport> {
private final Configuration configuration;
private final MetricRegistry metricRegistry;
private final ServerStatus serverStatus;
@Inject
public RadioTransportProvider(Configuration configuration, MetricRegistry metricRegistry, ServerStatus serverStatus) {
this.configuration = configuration;
this.metricRegistry = metricRegistry;
this.serverStatus = serverStatus;
}
@Override
public RadioTransport get() {
switch (configuration.getTransportType()) {
case AMQP:
return new AMQPProducer(metricRegistry, configuration, serverStatus);
case KAFKA:
return new KafkaProducer(serverStatus, configuration, metricRegistry);
default:
throw new RuntimeException("Cannot map transport type to transport.");
}
}
}
| gpl-3.0 |
anish/phatch | phatch/actions/transpose.py | 9462 | # Phatch - Photo Batch Processor
# Copyright (C) 2007-2008 www.stani.be
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see http://www.gnu.org/licenses/
#
# Phatch recommends SPE (http://pythonide.stani.be) for editing python files.
# Embedded icon is taken from www.openclipart.org (public domain)
# Follows PEP8
from core import models
from lib.reverse_translation import _t
#---PIL
def init():
global Image, imtools
from PIL import Image
from lib import imtools
def transpose(image, method, amount=100):
transposed = image.transpose(getattr(Image, method))
if amount < 100:
transposed = imtools.blend(image, transposed, amount / 100.0)
return transposed
#---Phatch
class Action(models.Action):
""""""
label = _t('Transpose')
author = 'Stani'
email = '[email protected]'
init = staticmethod(init)
pil = staticmethod(transpose)
version = '0.1'
tags = [_t('default'), _t('transform')]
__doc__ = _t('Flip or rotate 90 degrees')
def interface(self, fields):
fields[_t('Method')] = self.ImageTransposeField(
'Orientation')
fields[_t('Amount')] = self.SliderField(100, 1, 100)
def apply(self, photo, setting, cache):
#get info
info = photo.info
#dpi
method = self.get_field('Method', info)
#special case turn to its orientation
if method == 'ORIENTATION':
photo._exif_transposition_reverse = ()
info['orientation'] = 1
else:
amount = self.get_field('Amount', info)
layer = photo.get_layer()
layer.image = transpose(layer.image, method, amount)
return photo
icon = \
'x\xda\x01`\t\x9f\xf6\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x000\x00\
\x00\x000\x08\x06\x00\x00\x00W\x02\xf9\x87\x00\x00\x00\x04sBIT\x08\x08\x08\
\x08|\x08d\x88\x00\x00\t\x17IDATh\x81\xed\xd9{\x8c\x9c\xd5y\x06\xf0\xdf\x99o\
\xee3{\xb7Y_\xd6\xd8\xd8\xa6\xc4.\x94\xe2[q\xa0\x01\n\xa8n\xa4\xc4$\xa2T\t\
\xa9ZE\x15\x94^\x94J\xf9\xa3\x89Z\xb5RD\xa4\xa4Q/\x8a\x8aZH\xa2DjU\x13\xa5\
\x8dTTD\x1b \x89"\x07\x1a\xb0MK|\xc7\xb0x\xb1\x8d\xbd\xbe\xad\xed\xf5\xce^f\
\xe6\xeb\x1f\xdf7\xde\xf5\xb2\xbe\x82eU\xf2;:\xfaFG\xe7;\xf3<\xefy\xcf{\x9e\
\xf7L\x88\xe3\xd8\xffg\xcb\\m\x00\xef\xd7\xae\x11\xb8\xdav\x8d\xc0\xd5\xb6\
\x0f\x8c@\x08!\x84\xef\x85(\xbc\x1bz\xc2\xa9\xb0$\x8c\x86\x15\xeb\xeb\xf7\
\xaf\xfe\xa0\xe6?\x97e/\xf7\xc5 T5\xdd#\xb6J\xb0R\xc3J\x19\xbd\x08\xad1\x1d\
\xa7\xdb\x07C.\xf4\xa1\x1e_\xa1|}I\x04\x82P\xc4G\xc5>-\xf8\xa8\x8c\xd2L\xe3\
\xf2r\xe6\x98-;\x92\x9b\x85v\x9c\xc4\xc4\xfb\x87\xfb^\xbb(\x02A\xc8\xe3Q\xfc\
\x19z\'}\xccrK\xac\xf3\x11\xd7\x9b\xaf\xcf\\\x9d\xcd\x0ec\x13\x13\xf6\xd7\
\x06m;\xb2;\xc6,\xd4B\x08Wd\x15.H \x08\x0f\xe1k\xb8~\xf2\xa5\xc8}\xd6\xfa\
\x8c\x8f\xcb\xd5r\xbe\xfb\xf3\xe7\xfc\xd7\xde\x8d\xf6\xed?\xe8\xc4\x89S\x93/\
\x1f7\x81N\x1cD\xed\x83\x06\x9f`97\xf0\x02\xfe\x0e\xbf?\xb5\xff~\xb7\xfb|\
\xfc\xbb\xb6\x1c\xde\xe1+?\xf9\x86\xad\xdb\xde8\xdf\xfc\x01EW0\xdb\xcdH \x08\
\x1dx\x01\xab\xa6\xf6?\xe0\x1e\x9f\xac\xdd\xe7\xe1o\x7f\xc1\xd1\xc3C\x17\x9e\
=N\xa7\xbb\x82\xf6\x1e\x02A\xc8\xe2_M\x03\xff)\xeb\xdc3\xbc\xdacO>\xee\xf4\
\xf0EF\xc3\x15\x85\x9e\xd8L+\xf0\xb7\xb8oj\xc7\x1dn\xb5v\xe8\x16\x7f\xfc\x8f\
_566~\xfe\x19\x9b\x92h\x1f\xc5\x90Q\xd4\xb5\xd6\xe2\n\xd8Y\x04\x82\xb0\x04\
\x8fM\x1f\xf4[\xf5\xfb}\xf1\xa9\xbf\x9f\x19\xfc)\xec\x17;\xa6\xee\xa4\x9a\
\x13F\x8c9i\xdc~M\x9b1\x82\xc6\x95\x81?}\x05b\x7f*\x88\xa6v\x95\x15m\xdb\xf3\
\x96\xd3\'k\xe4\xce\x8c\xe30\xde2a\xa7~\xfblWw\x14\xc3)\xe0S\xe9\x88~\x1c\
\xc5\xc4\xe5\xa4\xd0^\xe1\x96X\xe6\xf7\xb2\xc2my\xe1\x95\xa0\xfe\xe7\xfd\xe2\
\xd1s\x13\x08>9}\x929\xbam\xdd\xb3\'\t\r)\xc4\x97\x9d\xb2\xc7v\x87\xbc\x86\
\xfdx\x17\xc7qZ\x12<\xa3\xe9\xf7!\x9cp\x89\x87\xd8RaiS\xf4\xe5\xaa\xdc\x839!\
\x93\x93\x91\x13~U\x9c_\x182\xe1\xa1\xa9\xce8C \x0c\x86\xeb\\\xa7g\xfad\x03\
\x0ei\x1cl&^?\x81\xe7\xf5\xdb\xea9\xbc\x89\xbd)\xf8\x96\xf7\xc7%1\xdfL\x9fu\
\x89\x8c\xb8\xa8\x10\xbaSh\x1b\x92\xfbRI\xe1\xb1\x9cL\xa1 \x92\x13\xc9\xc9\
\xc8\xca\xc8\x86\xcc\x83\x85\xc3\x85;B\x08/\xc5q\xdc<\x8b\x80\xa6\x1bg\x9a\
\xb4\xaea\xa82\x9c\xf8\xf2G\xb6\xdb\xe5\xdf\xb0U\x12\x1e\x83\x12\x99\xd0\xda\
\xacM\x93\x1b6\x86\x8b\x0b\x9d\x10~E\xf1\xb3\xb1\xf2\xe3\x1d\xa29\x05Yy\x91\
\x82lJ \x92\x15\x89d\xc4\x13\xe3Or|U\x08a,\x8e\xe3f\x88\xe3X\x08!\xe3\x9f\
\xfd\x82\x87\xed\x98i\xfa\xcc\xcf\x82\xe6\xef\xc4[\xed\xf24\xb6`\x0f\x8eH\
\xe2\xbd\x8e\xe6\xe5\xca\x84{t\xdc>!\xfezV\xb4\xba(+iyy\xd9\xb4\xe5\xe4R\xf8\
\x91H\xdc\x08\xf1\xe6\'FV\xff\xf8s[\x7f\x1e\xc7\xf1x\x8b@\x1e\xbdF\xecU\x9a!\
{7\xb1\xce\x13\x9e\xf7\x1f\xd8\x99\x82\xaf\xbd\x1f\xe0\x0f=\x14\xa2#O\xb7\
\x7f=\x93\x89\x1e-\xcaE%yE9EyE\x05\x05yy\xb9\x94J\xf2\xc9\x88dd\x1c\xec\xcf\
\xbc\xfa\xd7\x8b\x9f\xb9\x0f\xc3Ar\xdc\x94\xb1\xc4F\xff\xeb\x8es\xfc\xe2\x88\
c\xbe\xe9S>\xe7\xa7\xa8\xb5b\xf0R-\x84\x10\x10=\xbc\x7f\xc5\xf7F\xe6\r>\x90E\
YAIAIQIQQQ!]\x87|\x1aHUU\x19\x19e%\xcdS\x1d\x8dO\xb4\xff\xc5B\x0cfS\x02y7X\
\x9e\xdd\x10\x89\xee\xc8\x18\x9b)i\x94u\xfb#\xff\xe2\xb3\xd6\xc5\xd5x\xd3\
\xe5\x80O-B[c\xdb\xdc_\x7f\xa4\xf33\x0e4\xf6\xdb1\xb1]\xb1kX9\x94\x94\x94S\
\x1ae\xf9t=\x96[.;1\xcb\xc9\xc6)\x13\x1a\xfef\xf3\x86 \x11\x89\xc7\'\t\xcc\
\xf2\xe1\xfa\xf6\x86y\x9bz\x1cXuT}\xa6\xb3\'\xa3G\xd5\x8bA\xf8C|7\x16_RzL\
\xbd\x9f\xc7\xac\xa7\xff\xf3\xd9\xf0\xf4K\xcfZ\xbc\xac\xcb\'~\xe3\x17\xcd\n\
\xb3\x95U\x95T\x94T\x15U\x14\x94\xcd\xb7\xc0\xe9Z\xd1\x9aG\x1f\x10\xb7\xc5\
\x898\x1f\x03\x1d\xc8g%J1\xabfL\x89\x81\xc7\x07\xad\xfd\x87\xe5^\x9e\xbb\xfd\
\\8\xda\xf1O\xf8Z\x10\x9e\xc2\x93\xb1\xf8\xc0\xc5r@\xae\xef\x97\xab\xf3f\xdf\
U\xce\xae\xbc\xbd\xcf\x87\xae\x9b\xaf\xa2\xaa\xa2]Y\x9b\x8a\x0ee\x1dJ\xdau\
\x99\xad\xd4\xe8\xb1\xe6K\xf7\x8a\'\xe2$\xaf\xb5Z\xa2r\xa3 9_\xe7(\xfa5\xb7\
\xfb\x8e<mK\xca\xee\xfd\xca\n\xcf\xb6\xff\xb7\t\xf5\x0b\x81\xaa\xe3Y\xbc\x8e\
\xfe\x0e\x06\xe6)\x0c\xfc\x81\xeb\x07F\x1d\xcf\xffT\xbc\xac){sQvY).\xddTi\
\x94\x96\xb6\x87\xca\r\x95\xa8R\xacjS\xd5\xae\xa2]U\xa7\x8aNU\xdd*\xba\xf5\
\x98\xab\x14\xf7X\xf5\xed\xfb\xed\xd9\xdc\x9f\xa4\x8d\x1e\xad\x15h\xfa+\xeb\
\xb0%\x9b\xf2i\x18uRAS\x909u`\xc4\x0f\xbe\xb8\xc9\x83_\xb8\xdb\xce\x05{\xbd\
\xe6\xbc\x9a?\x8b\xf5X_AQ\xc6\xb8\xa6o\xd9\xd7\xa8\xca\x85\x8a|\xa6*\xab\xa4\
\xa8\x1aJ\xaa\xd9\x8a\x8a\x8a\x16\xf8\xaa\x0eU]\xaa\xbaTt\xe94\xc7<\x8b\x1d\
\xa9\x8f\xfa\xd8\xf7\x7f\xd3\x9e\x81\xfed\xdd\xc2\x14\xef7\'\xc5a&\xed\x1a\
\xc7\xb0!\xbbEI\xef\xc8\xb1Q\x1b\xfe\xf2\x05\x85\x8d9\x8f4\xd6\xebT=\xef2\
\x94P\x96Q\x96Q\x12)\x8a\xa2\xa2l\xa6$\xa7$?-\xcb\x94\xcel\xd4\xc2\x946W\x9f\
\xde\xb8\xcfWw>\xe5\x86/\xdfj\xd3\x8e\xd7\xce\xfe\x91Q\x89\x1ax\xd3q\x89<\
\x89[\xc2-\x8b\x8a\xe3\xc6,u\xb7\xac \x97\xf4\xee\xdbq\xd8\xae\xd7\x07\xfc\
\xf6\x82u\xee\xec\xb8U\x1cb\x87\x1c\x9b\xea\x049\x94\x84\x94@\xa4,\xab,\xa7$\
7%E\x16\x14\x15\x94\xce\x80Ozg\xbb\xce"\x8b,\xb4\xd8\xff\x9c\x1cp\xf77>\xed\
\xb9M/L\x82\x0e\x92\xf0\xd9\xe8m\xbb\xbdm\x97\xedv\xda`\xcc6\x1ci\x1ddE\xcc\
\xc5j\xcb|\xde\xcd\xd6(pV+R\x99_t\xd7\x9d+\xac]\xfaK\xc6+u?\xf1\x9aWl\x951\
\xa6"\xa3*R\x15\xa9\xc8\xa9\xc8\xa9*\xa8(\xa8\xa4\xb9\xa5\xa2\xac\xaaj\x91\
\x85nt\xa3\xf9\x16zg\xac\xe6\x99\xbd/\xfb\xe6\x0f\xbf\xef\xddC\x87\xde\xbb\
\xb4\xa7\xf1\xef\xb6\xd9\xedE\x89\xee:$\x911o\xe2p\x8b@$\xc9.7\xe2\xc3V\xf9\
\x13\x1f\xb2Pi\x1a\x89\xfc\xe4\xbc\x9d}m\xee]\xb5\xc6G\xfan\xd3\xddV\xaaG\
\xf9\x89l\xc6\xb8a\'\x8c\x186\xa6\xa6K\xd5l]ztj\xd7)\x8a\xcbq\xa3\x19\xc5\
\xfbF\x872\xcf\xecy\xd5\x86\x1f\xfd\xe0\xecK\x80\xe96\x8e\xe7\rx\xd5\xb7$\
\xfa\xeb\xdd4\x88Z*w\xb4E\xe0L~\xc6r\xac\xb5\xc2#n1_\xc7\x14\x02\xe7\xbb\xc3\
(P\xe8\xcc\xea\xed\xea1\xaf\xb3[_\xc7\xacf\xbd!\x1c8z,\xbcsh\xd0\xe0\xe01\
\x8d\xfa%\xd45\'\xb1\xc9Q\x1b=\xa1\xe9g\xd8%\x91\xecc\x92\xf8\xaf\x9f\x11sH\
\x04]\x92[\xe7`\x19VZd\xbd\xb5n\xb3@\xb8\xb2w\x0bS\xac\x8e74\xbd\xe2u\xfd\
\x9e\xc1\xab\xd8!\t\x9d\x9a\xb42ii\xb03>\x8d\xe3\xb8\x19B\x18\x93H\xe4d\xaa\
\xb7\x8d\x18\xf2\x8e\xe5\xeer\xb3Ns]\xd9B\xfd 6;l\xab\x17\xd5l\x91\x84\xcd\
\xee\x14Sm\xa6\xba"L\x17\x93\xe9~(\xa2[r\x99u\x13n2\xcb\x1a\xcb\xac\xb4X\x9b\
^\x89\xfc{\xbf\xd6*\x92\x06\xc5\xf6\x1a\xb6\xdb\x16\x87\xbd$\t\x977\xb0OR,\
\x8d\x9e\xab(z\x0f\x81\x94DF\xb2\'\xda\xd0\x8b\x05X\x8cE*n\xd2k\xb9\xc5\xfa\
\xccU\xd0\x9e\x8e*^\x04\xe0\x86dc\x8e\xe0\xb0X\xbfS\x0e\x180h\x871\xfdx\x1bo\
a@RS\x0fc\xfc|\xcawF\x02)\x89 \t\xb1b\nq\xb6$\xd5\xceK[\xaf\xb2>\xed\xfaT\
\xcc\xd6\xadS\xbb\xa2\x82HR\x0b\x06M\xb1\x11\r\xa7M\x186\xe6\xb4\x9a\t55\xc7\
\x1d\xf1\x86q\x07$\xb1}\xd0d\x8a<b\xb2\xcak\\\xa8\xde8\'\x81)D2)\x91\x02*\
\x12\x15\xd8-Q&\xdd\xe8\x92H\xdb\xaa$\xb0\xf2\xe9\xf8H\xe2\xf3\xba\xc4\xef\
\xadb\x7f$\x05xtJ\x1b\x92\xdcd\x8cH\xb2L\xfdb\xeb\x8d\x0b\x12\x98F$\x92\x1c\
\xbcy\x89z\xa8LiE\x93\xa7E\x94\xb6Vq?\x91\x92\x18O\x01\x8e\x98\xbc\x82\xa9\
\x99r\x19p\xa9\x85\xd2E\x13\x98B\xa4%\xadZ \xb3&=\x9e*\xa93-\x11\x8a\t\x91\
\xd6s\xea\x8dE\xab/\xbe\xdc\xd2\xf4\x92\t\xcc@\x86I\xbdh\x86\xe7\xa4\x82\xbf\
\xac\x1b\x8b\x0b`\xb8\xf6O\xfdU\xb6k\x04\xae\xb6]#p\xb5\xed\xff\x00\xffpD!\
\x93;\xfd \x00\x00\x00\x00IEND\xaeB`\x82j\x88\xbf\xb5'
| gpl-3.0 |
jrtdev/yum | yumfe/src/app/admin/holidays/holidays.component.ts | 5296 | import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { DatePipe, Location } from '@angular/common';
import { addYears, subYears, addDays, startOfMonth, endOfMonth, getMonth, getYear, isToday, isValid } from 'date-fns';
import { CalendarDateFormatter, CalendarMonthViewDay, CalendarEvent } from 'angular-calendar';
import { CustomDateFormatter } from './custom-date-formatter.provider';
import { Observable, BehaviorSubject, Subject } from 'rxjs/Rx';
import { AdminApi } from '../../remote';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { MatSnackBar } from '@angular/material';
@Component({
selector: 'app-holidays',
templateUrl: './holidays.component.html',
styleUrls: ['./holidays.component.css'],
providers: [
{
provide: CalendarDateFormatter,
useClass: CustomDateFormatter
}
],
encapsulation: ViewEncapsulation.None
})
export class HolidaysComponent implements OnInit {
public showLoadSpinner = true;
@ViewChild('picker')
public picker1: any;
// calendar properties https://mattlewis92.github.io/angular-calendar/
public view: string = 'month';
public viewYear: BehaviorSubject<Date> = new BehaviorSubject<Date>(new Date());
public viewYearNumber: number;
public locale: string = 'en';
public yearMonths: Date[] = [];
public refresh: Subject<any> = new Subject();
public holidaysSaveDisabled: boolean = false;
private sub: any;
//public holidays: CalendarMonthViewDay[] = [];
public holidays: Map<String, CalendarMonthViewDay> = new Map<String, CalendarMonthViewDay>();
constructor(private adminService: AdminApi, private datePipe: DatePipe,
private route: ActivatedRoute,
private location: Location,
public snackBar: MatSnackBar
//private router: Router
) { }
ngOnInit() {
this.viewYear.subscribe(date => {
this.showLoadSpinner = true;
this.viewYearNumber = date.getFullYear();
this.getHolidays(this.viewYearNumber);
})
this.sub = this.route.params.subscribe(params => {
let yearDate = new Date(+params['year'], 0, 1, 0, 0, 0); // (+) converts string 'year' to a number
if (isValid(yearDate)) {
this.viewYear.next(yearDate);
}
});
}
public getHolidays(year) {
this.location.replaceState("admin/globalSettings/holidays/"+year);
this.adminService.globalsettingsHolidaysYearGet(year).subscribe(holidays => {
// console.log(holidays);
this.holidays = new Map<String, CalendarMonthViewDay>();
for (let holiday of holidays) {
let dtStr = this.datePipe.transform(holiday, 'yyyy-MM-dd');
let calDay: CalendarMonthViewDayImp = new CalendarMonthViewDayImp();
calDay.date = holiday;
this.holidays.set(dtStr, calDay);
}
this.buildMonths(year);
this.refresh.next();
this.showLoadSpinner = false;
});
}
public setHolidays() {
this.holidaysSaveDisabled = true;
this.showLoadSpinner = true;
let holidays: string[] = Array.from(this.holidays, x => this.datePipe.transform(x[1].date, 'yyyy-MM-dd'));
this.adminService.globalsettingsHolidaysYearPost(this.viewYearNumber, holidays).subscribe(response => {
//console.log(response);
this.holidaysSaveDisabled = false;
this.showLoadSpinner = false;
this.openSnackBar('Holidays saved!', 'ok', true);
},
error => {
this.openSnackBar('Holidays could not be saved!', 'ok', false);
});
}
ngAfterViewInit() { }
buildMonths(year: number) {
for (let i = 0; i < 12; i++) {
this.yearMonths[i] = new Date(year, i);
}
//console.log("build");
}
prevYear() {
this.viewYear.next(subYears(this.viewYear.getValue(), 1));
}
nextYear() {
this.viewYear.next(addYears(this.viewYear.getValue(), 1));
}
clickedDate(day: CalendarMonthViewDay, monthDate: Date) {
if (monthDate.getMonth() !== day.date.getMonth()) {
return;
}
let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd');
let holiday: CalendarMonthViewDay = this.holidays.get(dtStr);
if (!holiday) {
day.cssClass = 'cal-day-selected';
this.holidays.set(dtStr, day);
} else {
delete day.cssClass;
this.holidays.delete(dtStr);
}
//console.log(this.holidays);
}
beforeMonthViewRender({ body }: { body: CalendarMonthViewDay[] }): void {
body.forEach(day => {
let dtStr = this.datePipe.transform(day.date, 'yyyy-MM-dd');
let holiday: CalendarMonthViewDay = this.holidays.get(dtStr);
if (holiday) {
day.cssClass = 'cal-day-selected';
}
});
}
// success and error snackBars
private openSnackBar(message: string, action: string, timeOut: boolean) {
if (timeOut) {
this.snackBar.open(message, action, {
duration: 5000,
extraClasses: ['success-snack-bar']
});
} else {
this.snackBar.open(message, action, {
extraClasses: ['error-snack-bar']
});
}
}
}
class CalendarMonthViewDayImp implements CalendarMonthViewDay {
inMonth: boolean;
events: CalendarEvent[];
backgroundColor?: string;
badgeTotal: number;
meta?: any;
date: Date;
isPast: any;
isToday;
isFuture;
isWeekend;
} | gpl-3.0 |
ColgateKas/cms | source/BaiRong.Core/ThirdParty/Alipay/openapi/Response/AlipaySecurityProdFingerprintApplyResponse.cs | 926 | using System;
using System.Xml.Serialization;
namespace Aop.Api.Response
{
/// <summary>
/// AlipaySecurityProdFingerprintApplyResponse.
/// </summary>
public class AlipaySecurityProdFingerprintApplyResponse : AopResponse
{
/// <summary>
/// IFAA标准中的校验类型,目前1为指纹
/// </summary>
[XmlElement("auth_type")]
public string AuthType { get; set; }
/// <summary>
/// 设备的唯一ID,IFAA标准体系中的设备的唯一标识,用于关联设备的开通状态
/// </summary>
[XmlElement("device_id")]
public string DeviceId { get; set; }
/// <summary>
/// IFAA标准中用于关联IFAA Server和业务方Server开通状态的token,此token用于后续校验和注销操作。
/// </summary>
[XmlElement("token")]
public string Token { get; set; }
}
}
| gpl-3.0 |
dcurado/mycenae | vendor/github.com/hashicorp/consul/tlsutil/config_test.go | 11385 | package tlsutil
import (
"crypto/tls"
"crypto/x509"
"io"
"io/ioutil"
"net"
"testing"
"github.com/hashicorp/yamux"
)
func TestConfig_AppendCA_None(t *testing.T) {
conf := &Config{}
pool := x509.NewCertPool()
err := conf.AppendCA(pool)
if err != nil {
t.Fatalf("err: %v", err)
}
if len(pool.Subjects()) != 0 {
t.Fatalf("bad: %v", pool.Subjects())
}
}
func TestConfig_CACertificate_Valid(t *testing.T) {
conf := &Config{
CAFile: "../test/ca/root.cer",
}
pool := x509.NewCertPool()
err := conf.AppendCA(pool)
if err != nil {
t.Fatalf("err: %v", err)
}
if len(pool.Subjects()) == 0 {
t.Fatalf("expected cert")
}
}
func TestConfig_KeyPair_None(t *testing.T) {
conf := &Config{}
cert, err := conf.KeyPair()
if err != nil {
t.Fatalf("err: %v", err)
}
if cert != nil {
t.Fatalf("bad: %v", cert)
}
}
func TestConfig_KeyPair_Valid(t *testing.T) {
conf := &Config{
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
}
cert, err := conf.KeyPair()
if err != nil {
t.Fatalf("err: %v", err)
}
if cert == nil {
t.Fatalf("expected cert")
}
}
func TestConfig_OutgoingTLS_MissingCA(t *testing.T) {
conf := &Config{
VerifyOutgoing: true,
}
tls, err := conf.OutgoingTLSConfig()
if err == nil {
t.Fatalf("expected err")
}
if tls != nil {
t.Fatalf("bad: %v", tls)
}
}
func TestConfig_OutgoingTLS_OnlyCA(t *testing.T) {
conf := &Config{
CAFile: "../test/ca/root.cer",
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls != nil {
t.Fatalf("expected no config")
}
}
func TestConfig_OutgoingTLS_VerifyOutgoing(t *testing.T) {
conf := &Config{
VerifyOutgoing: true,
CAFile: "../test/ca/root.cer",
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if len(tls.RootCAs.Subjects()) != 1 {
t.Fatalf("expect root cert")
}
if tls.ServerName != "" {
t.Fatalf("expect no server name verification")
}
if !tls.InsecureSkipVerify {
t.Fatalf("should skip built-in verification")
}
}
func TestConfig_OutgoingTLS_ServerName(t *testing.T) {
conf := &Config{
VerifyOutgoing: true,
CAFile: "../test/ca/root.cer",
ServerName: "consul.example.com",
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if len(tls.RootCAs.Subjects()) != 1 {
t.Fatalf("expect root cert")
}
if tls.ServerName != "consul.example.com" {
t.Fatalf("expect server name")
}
if tls.InsecureSkipVerify {
t.Fatalf("should not skip built-in verification")
}
}
func TestConfig_OutgoingTLS_VerifyHostname(t *testing.T) {
conf := &Config{
VerifyServerHostname: true,
CAFile: "../test/ca/root.cer",
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if len(tls.RootCAs.Subjects()) != 1 {
t.Fatalf("expect root cert")
}
if tls.ServerName != "VerifyServerHostname" {
t.Fatalf("expect server name")
}
if tls.InsecureSkipVerify {
t.Fatalf("should not skip built-in verification")
}
}
func TestConfig_OutgoingTLS_WithKeyPair(t *testing.T) {
conf := &Config{
VerifyOutgoing: true,
CAFile: "../test/ca/root.cer",
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if len(tls.RootCAs.Subjects()) != 1 {
t.Fatalf("expect root cert")
}
if !tls.InsecureSkipVerify {
t.Fatalf("should skip verification")
}
if len(tls.Certificates) != 1 {
t.Fatalf("expected client cert")
}
}
func TestConfig_OutgoingTLS_TLSMinVersion(t *testing.T) {
tlsVersions := []string{"tls10", "tls11", "tls12"}
for _, version := range tlsVersions {
conf := &Config{
VerifyOutgoing: true,
CAFile: "../test/ca/root.cer",
TLSMinVersion: version,
}
tls, err := conf.OutgoingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if tls.MinVersion != TLSLookup[version] {
t.Fatalf("expected tls min version: %v, %v", tls.MinVersion, TLSLookup[version])
}
}
}
func startTLSServer(config *Config) (net.Conn, chan error) {
errc := make(chan error, 1)
tlsConfigServer, err := config.IncomingTLSConfig()
if err != nil {
errc <- err
return nil, errc
}
client, server := net.Pipe()
// Use yamux to buffer the reads, otherwise it's easy to deadlock
muxConf := yamux.DefaultConfig()
serverSession, _ := yamux.Server(server, muxConf)
clientSession, _ := yamux.Client(client, muxConf)
clientConn, _ := clientSession.Open()
serverConn, _ := serverSession.Accept()
go func() {
tlsServer := tls.Server(serverConn, tlsConfigServer)
if err := tlsServer.Handshake(); err != nil {
errc <- err
}
close(errc)
// Because net.Pipe() is unbuffered, if both sides
// Close() simultaneously, we will deadlock as they
// both send an alert and then block. So we make the
// server read any data from the client until error or
// EOF, which will allow the client to Close(), and
// *then* we Close() the server.
io.Copy(ioutil.Discard, tlsServer)
tlsServer.Close()
}()
return clientConn, errc
}
func TestConfig_outgoingWrapper_OK(t *testing.T) {
config := &Config{
CAFile: "../test/hostname/CertAuth.crt",
CertFile: "../test/hostname/Alice.crt",
KeyFile: "../test/hostname/Alice.key",
VerifyServerHostname: true,
Domain: "consul",
}
client, errc := startTLSServer(config)
if client == nil {
t.Fatalf("startTLSServer err: %v", <-errc)
}
wrap, err := config.OutgoingTLSWrapper()
if err != nil {
t.Fatalf("OutgoingTLSWrapper err: %v", err)
}
tlsClient, err := wrap("dc1", client)
if err != nil {
t.Fatalf("wrapTLS err: %v", err)
}
defer tlsClient.Close()
if err := tlsClient.(*tls.Conn).Handshake(); err != nil {
t.Fatalf("write err: %v", err)
}
err = <-errc
if err != nil {
t.Fatalf("server: %v", err)
}
}
func TestConfig_outgoingWrapper_BadDC(t *testing.T) {
config := &Config{
CAFile: "../test/hostname/CertAuth.crt",
CertFile: "../test/hostname/Alice.crt",
KeyFile: "../test/hostname/Alice.key",
VerifyServerHostname: true,
Domain: "consul",
}
client, errc := startTLSServer(config)
if client == nil {
t.Fatalf("startTLSServer err: %v", <-errc)
}
wrap, err := config.OutgoingTLSWrapper()
if err != nil {
t.Fatalf("OutgoingTLSWrapper err: %v", err)
}
tlsClient, err := wrap("dc2", client)
if err != nil {
t.Fatalf("wrapTLS err: %v", err)
}
err = tlsClient.(*tls.Conn).Handshake()
if _, ok := err.(x509.HostnameError); !ok {
t.Fatalf("should get hostname err: %v", err)
}
tlsClient.Close()
<-errc
}
func TestConfig_outgoingWrapper_BadCert(t *testing.T) {
config := &Config{
CAFile: "../test/ca/root.cer",
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
VerifyServerHostname: true,
Domain: "consul",
}
client, errc := startTLSServer(config)
if client == nil {
t.Fatalf("startTLSServer err: %v", <-errc)
}
wrap, err := config.OutgoingTLSWrapper()
if err != nil {
t.Fatalf("OutgoingTLSWrapper err: %v", err)
}
tlsClient, err := wrap("dc1", client)
if err != nil {
t.Fatalf("wrapTLS err: %v", err)
}
err = tlsClient.(*tls.Conn).Handshake()
if _, ok := err.(x509.HostnameError); !ok {
t.Fatalf("should get hostname err: %v", err)
}
tlsClient.Close()
<-errc
}
func TestConfig_wrapTLS_OK(t *testing.T) {
config := &Config{
CAFile: "../test/ca/root.cer",
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
VerifyOutgoing: true,
}
client, errc := startTLSServer(config)
if client == nil {
t.Fatalf("startTLSServer err: %v", <-errc)
}
clientConfig, err := config.OutgoingTLSConfig()
if err != nil {
t.Fatalf("OutgoingTLSConfig err: %v", err)
}
tlsClient, err := WrapTLSClient(client, clientConfig)
if err != nil {
t.Fatalf("wrapTLS err: %v", err)
} else {
tlsClient.Close()
}
err = <-errc
if err != nil {
t.Fatalf("server: %v", err)
}
}
func TestConfig_wrapTLS_BadCert(t *testing.T) {
serverConfig := &Config{
CertFile: "../test/key/ssl-cert-snakeoil.pem",
KeyFile: "../test/key/ssl-cert-snakeoil.key",
}
client, errc := startTLSServer(serverConfig)
if client == nil {
t.Fatalf("startTLSServer err: %v", <-errc)
}
clientConfig := &Config{
CAFile: "../test/ca/root.cer",
VerifyOutgoing: true,
}
clientTLSConfig, err := clientConfig.OutgoingTLSConfig()
if err != nil {
t.Fatalf("OutgoingTLSConfig err: %v", err)
}
tlsClient, err := WrapTLSClient(client, clientTLSConfig)
if err == nil {
t.Fatalf("wrapTLS no err")
}
if tlsClient != nil {
t.Fatalf("returned a client")
}
err = <-errc
if err != nil {
t.Fatalf("server: %v", err)
}
}
func TestConfig_IncomingTLS(t *testing.T) {
conf := &Config{
VerifyIncoming: true,
CAFile: "../test/ca/root.cer",
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
}
tlsC, err := conf.IncomingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tlsC == nil {
t.Fatalf("expected config")
}
if len(tlsC.ClientCAs.Subjects()) != 1 {
t.Fatalf("expect client cert")
}
if tlsC.ClientAuth != tls.RequireAndVerifyClientCert {
t.Fatalf("should not skip verification")
}
if len(tlsC.Certificates) != 1 {
t.Fatalf("expected client cert")
}
}
func TestConfig_IncomingTLS_MissingCA(t *testing.T) {
conf := &Config{
VerifyIncoming: true,
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
}
_, err := conf.IncomingTLSConfig()
if err == nil {
t.Fatalf("expected err")
}
}
func TestConfig_IncomingTLS_MissingKey(t *testing.T) {
conf := &Config{
VerifyIncoming: true,
CAFile: "../test/ca/root.cer",
}
_, err := conf.IncomingTLSConfig()
if err == nil {
t.Fatalf("expected err")
}
}
func TestConfig_IncomingTLS_NoVerify(t *testing.T) {
conf := &Config{}
tlsC, err := conf.IncomingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tlsC == nil {
t.Fatalf("expected config")
}
if len(tlsC.ClientCAs.Subjects()) != 0 {
t.Fatalf("do not expect client cert")
}
if tlsC.ClientAuth != tls.NoClientCert {
t.Fatalf("should skip verification")
}
if len(tlsC.Certificates) != 0 {
t.Fatalf("unexpected client cert")
}
}
func TestConfig_IncomingTLS_TLSMinVersion(t *testing.T) {
tlsVersions := []string{"tls10", "tls11", "tls12"}
for _, version := range tlsVersions {
conf := &Config{
VerifyIncoming: true,
CAFile: "../test/ca/root.cer",
CertFile: "../test/key/ourdomain.cer",
KeyFile: "../test/key/ourdomain.key",
TLSMinVersion: version,
}
tls, err := conf.IncomingTLSConfig()
if err != nil {
t.Fatalf("err: %v", err)
}
if tls == nil {
t.Fatalf("expected config")
}
if tls.MinVersion != TLSLookup[version] {
t.Fatalf("expected tls min version: %v, %v", tls.MinVersion, TLSLookup[version])
}
}
}
| gpl-3.0 |
lev-kuznetsov/mev | web/src/main/javascript/edu/dfci/cccb/mev/web/javascript/analysisaccordioncollection/templates/tTestAccordion.tpl.html | 2836 | <div class="results-wrapper" id="tTestResultsTable" >
<div class="results-header clearfix">
<!-- <div class="btn-toolbar" role="toolbar" > -->
<div class="btn-toolbar" role="toolbar" mui-yank="action-menu">
<div class="btn-group">
<a class="btn" mev-analysis-start-button mev-analysis-type="analysisTypes['gsea']" mev-context-level="bottom">GSEA</a>
<a class="btn" mev-analysis-start-button mev-analysis-type="analysisTypes['pca']" mev-context-level="bottom" >PCA</a>
<a class="btn" mev-analysis-start-button mev-analysis-type="analysisTypes['hcl']" mev-context-level="bottom">HCL</a>
<a class="btn" mev-analysis-start-button mev-analysis-type="analysisTypes['wgcna']" mev-context-level="bottom">WGCNA</a>
<a class="btn" href="/dataset/{{project.dataset.datasetName}}/analysis/{{analysis.name}}?format=tsv">
<i class="icon-white icon-download"></i> Download
</a><a class="btn" data-target="#selectionAdd{{analysis.name}}" data-toggle="modal">
</i> Create Selections
</a><a class="btn" data-target="#exportDataset{{analysis.name}}" data-toggle="modal">
</i> New Dataset
</a><button class="btn" ng-click="applyToHeatmap()" >
<span>
</i> View Genes on Heatmap
</span>
</button>
</div>
</div>
</div>
<div class="results-body">
<div class="results-top">
<mev-boxplot data="boxPlotGenes"></mev-boxplot>
</div>
<div class="results-bottom">
<mev-results-table data="analysis.results" headers="headers" ordering="pValue"
mev-save-as="{name: analysis.name}"></mev-results-table>
</div>
</div>
</div>
<bsmodal bindid="{{'selectionAdd' + analysis.name}}" func="" header="Add New Selection for {{analysis.name}}">
<div class="row">
<form-group>
<form>
Name: <input type="text" class="input-small" ng-model="selectionParams.name">
<form>
</form-group>
</div>
<div class="row">
<a class="btn btn-success pull-right" ng-click="addSelections()" data-dismiss="modal" aria-hidden="true">
Create Selections
</a>
</div>
</bsmodal>
<bsmodal bindid="{{'exportDataset' + analysis.name}}" func="" header="Export New Dataset for {{analysis.name}}">
<div class="row">
<form-group>
<form>
Name: <input type="text" class="input-small" ng-model="exportParams.name">
<form>
</form-group>
</div>
<div class="row">
<a class="btn btn-success pull-right" ng-click="exportSelection()" data-dismiss="modal" aria-hidden="true">
Export New Dataset
</a>
</div>
</bsmodal> | gpl-3.0 |
BlackGround-ICG/Nitro | include/game_events_listener.h | 286 | #ifndef IJENGINE_EVENTS_LISTENER_H
#define IJENGINE_EVENTS_LISTENER_H
namespace ijengine
{
class GameEvent;
class GameEventsListener
{
public:
virtual ~GameEventsListener() = default;
virtual bool on_event(const GameEvent& event) = 0;
};
}
#endif
| gpl-3.0 |
JavaProphet/AvunaHTTPD-Java | src/org/avuna/httpd/http/ResponseGenerator.java | 4004 | /* Avuna HTTPD - General Server Applications Copyright (C) 2015 Maxwell Bruce This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.avuna.httpd.http;
import java.text.SimpleDateFormat;
import org.avuna.httpd.AvunaHTTPD;
import org.avuna.httpd.http.event.EventMethodLookup;
import org.avuna.httpd.http.networking.RequestPacket;
import org.avuna.httpd.http.networking.ResponsePacket;
/** Creates a http response coming from the server. */
public class ResponseGenerator {
/** Our constructor */
public ResponseGenerator() {
}
/** Date format that isn't being used. */
public static final SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
/** Processes a request and fills in the ResponsePacket
*
* @param request the request
* @param response the response to fill in
* @return returns the success of handling the request. */
public static boolean process(RequestPacket request, ResponsePacket response) {
// Check if httpVersion is compatible
if (!request.httpVersion.equals("HTTP/1.1")) {
// NOTE: StatusCode.NEEDS_HTTP_1_1??
if (request.httpVersion.equals("HTTP/1.0")) {
request.headers.addHeader("Host", "");
}
}
try {
// Logger.log("rg");
// response.headers.addHeader("Date", sdf.format(new Date())); timeless for optimization
response.headers.addHeader("Server", "Avuna/" + AvunaHTTPD.VERSION);
if (request.headers.hasHeader("Connection")) {
response.headers.addHeader("Connection", request.headers.getHeader("Connection"));
}
if (request.host == null) {
ResponseGenerator.generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested host was not found on this server. Please contratc your server administrator.");
return false;
}
EventMethodLookup elm = new EventMethodLookup(request.method, request, response);
request.host.eventBus.callEvent(elm);
if (!elm.isCanceled()) {
generateDefaultResponse(response, StatusCode.NOT_YET_IMPLEMENTED);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.NOT_YET_IMPLEMENTED, "The requested URL " + request.target + " via " + request.method.name + " is not yet implemented.");
return false;
}else {
// System.out.println((ah - start) / 1000000D + " start-ah");
// System.out.println((ah2 - ah) / 1000000D + " ah-ah2");
// System.out.println((ah3 - ah2) / 1000000D + " ah2-ah3");
// System.out.println((cur - ah3) / 1000000D + " ah3-cur");
return true;
}
}catch (Exception e) {
request.host.logger.logError(e);
generateDefaultResponse(response, StatusCode.INTERNAL_SERVER_ERROR);
response.body = AvunaHTTPD.fileManager.getErrorPage(request, request.target, StatusCode.INTERNAL_SERVER_ERROR, "The requested URL " + request.target + " caused a server failure.");
return false;
}
}
/** Generates the stausCode, httpVersion and reasonPhrase for the response
*
* @param response the response packet
* @param status the status to set. */
public static void generateDefaultResponse(ResponsePacket response, StatusCode status) {
response.statusCode = status.getStatus();
response.httpVersion = "HTTP/1.1";
response.reasonPhrase = status.getPhrase();
}
}
| gpl-3.0 |
lastweek/PCP | ECE695-Spring17/t3-scheduler/linux-4.10.6/drivers/net/tun.c | 60711 | /*
* TUN - Universal TUN/TAP device driver.
* Copyright (C) 1999-2002 Maxim Krasnyansky <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $
*/
/*
* Changes:
*
* Mike Kershaw <[email protected]> 2005/08/14
* Add TUNSETLINK ioctl to set the link encapsulation
*
* Mark Smith <[email protected]>
* Use eth_random_addr() for tap MAC address.
*
* Harald Roelle <[email protected]> 2004/04/20
* Fixes in packet dropping, queue length setting and queue wakeup.
* Increased default tx queue length.
* Added ethtool API.
* Minor cleanups
*
* Daniel Podlejski <[email protected]>
* Modifications for 2.3.99-pre5 kernel.
*/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#define DRV_NAME "tun"
#define DRV_VERSION "1.6"
#define DRV_DESCRIPTION "Universal TUN/TAP device driver"
#define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <[email protected]>"
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/kernel.h>
#include <linux/major.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/init.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/miscdevice.h>
#include <linux/ethtool.h>
#include <linux/rtnetlink.h>
#include <linux/compat.h>
#include <linux/if.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_tun.h>
#include <linux/if_vlan.h>
#include <linux/crc32.h>
#include <linux/nsproxy.h>
#include <linux/virtio_net.h>
#include <linux/rcupdate.h>
#include <net/net_namespace.h>
#include <net/netns/generic.h>
#include <net/rtnetlink.h>
#include <net/sock.h>
#include <linux/seq_file.h>
#include <linux/uio.h>
#include <linux/skb_array.h>
#include <linux/uaccess.h>
/* Uncomment to enable debugging */
/* #define TUN_DEBUG 1 */
#ifdef TUN_DEBUG
static int debug;
#define tun_debug(level, tun, fmt, args...) \
do { \
if (tun->debug) \
netdev_printk(level, tun->dev, fmt, ##args); \
} while (0)
#define DBG1(level, fmt, args...) \
do { \
if (debug == 2) \
printk(level fmt, ##args); \
} while (0)
#else
#define tun_debug(level, tun, fmt, args...) \
do { \
if (0) \
netdev_printk(level, tun->dev, fmt, ##args); \
} while (0)
#define DBG1(level, fmt, args...) \
do { \
if (0) \
printk(level fmt, ##args); \
} while (0)
#endif
/* TUN device flags */
/* IFF_ATTACH_QUEUE is never stored in device flags,
* overload it to mean fasync when stored there.
*/
#define TUN_FASYNC IFF_ATTACH_QUEUE
/* High bits in flags field are unused. */
#define TUN_VNET_LE 0x80000000
#define TUN_VNET_BE 0x40000000
#define TUN_FEATURES (IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR | \
IFF_MULTI_QUEUE)
#define GOODCOPY_LEN 128
#define FLT_EXACT_COUNT 8
struct tap_filter {
unsigned int count; /* Number of addrs. Zero means disabled */
u32 mask[2]; /* Mask of the hashed addrs */
unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN];
};
/* MAX_TAP_QUEUES 256 is chosen to allow rx/tx queues to be equal
* to max number of VCPUs in guest. */
#define MAX_TAP_QUEUES 256
#define MAX_TAP_FLOWS 4096
#define TUN_FLOW_EXPIRE (3 * HZ)
struct tun_pcpu_stats {
u64 rx_packets;
u64 rx_bytes;
u64 tx_packets;
u64 tx_bytes;
struct u64_stats_sync syncp;
u32 rx_dropped;
u32 tx_dropped;
u32 rx_frame_errors;
};
/* A tun_file connects an open character device to a tuntap netdevice. It
* also contains all socket related structures (except sock_fprog and tap_filter)
* to serve as one transmit queue for tuntap device. The sock_fprog and
* tap_filter were kept in tun_struct since they were used for filtering for the
* netdevice not for a specific queue (at least I didn't see the requirement for
* this).
*
* RCU usage:
* The tun_file and tun_struct are loosely coupled, the pointer from one to the
* other can only be read while rcu_read_lock or rtnl_lock is held.
*/
struct tun_file {
struct sock sk;
struct socket socket;
struct socket_wq wq;
struct tun_struct __rcu *tun;
struct fasync_struct *fasync;
/* only used for fasnyc */
unsigned int flags;
union {
u16 queue_index;
unsigned int ifindex;
};
struct list_head next;
struct tun_struct *detached;
struct skb_array tx_array;
};
struct tun_flow_entry {
struct hlist_node hash_link;
struct rcu_head rcu;
struct tun_struct *tun;
u32 rxhash;
u32 rps_rxhash;
int queue_index;
unsigned long updated;
};
#define TUN_NUM_FLOW_ENTRIES 1024
/* Since the socket were moved to tun_file, to preserve the behavior of persist
* device, socket filter, sndbuf and vnet header size were restore when the
* file were attached to a persist device.
*/
struct tun_struct {
struct tun_file __rcu *tfiles[MAX_TAP_QUEUES];
unsigned int numqueues;
unsigned int flags;
kuid_t owner;
kgid_t group;
struct net_device *dev;
netdev_features_t set_features;
#define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \
NETIF_F_TSO6|NETIF_F_UFO)
int align;
int vnet_hdr_sz;
int sndbuf;
struct tap_filter txflt;
struct sock_fprog fprog;
/* protected by rtnl lock */
bool filter_attached;
#ifdef TUN_DEBUG
int debug;
#endif
spinlock_t lock;
struct hlist_head flows[TUN_NUM_FLOW_ENTRIES];
struct timer_list flow_gc_timer;
unsigned long ageing_time;
unsigned int numdisabled;
struct list_head disabled;
void *security;
u32 flow_count;
struct tun_pcpu_stats __percpu *pcpu_stats;
};
#ifdef CONFIG_TUN_VNET_CROSS_LE
static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
{
return tun->flags & TUN_VNET_BE ? false :
virtio_legacy_is_little_endian();
}
static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
{
int be = !!(tun->flags & TUN_VNET_BE);
if (put_user(be, argp))
return -EFAULT;
return 0;
}
static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
{
int be;
if (get_user(be, argp))
return -EFAULT;
if (be)
tun->flags |= TUN_VNET_BE;
else
tun->flags &= ~TUN_VNET_BE;
return 0;
}
#else
static inline bool tun_legacy_is_little_endian(struct tun_struct *tun)
{
return virtio_legacy_is_little_endian();
}
static long tun_get_vnet_be(struct tun_struct *tun, int __user *argp)
{
return -EINVAL;
}
static long tun_set_vnet_be(struct tun_struct *tun, int __user *argp)
{
return -EINVAL;
}
#endif /* CONFIG_TUN_VNET_CROSS_LE */
static inline bool tun_is_little_endian(struct tun_struct *tun)
{
return tun->flags & TUN_VNET_LE ||
tun_legacy_is_little_endian(tun);
}
static inline u16 tun16_to_cpu(struct tun_struct *tun, __virtio16 val)
{
return __virtio16_to_cpu(tun_is_little_endian(tun), val);
}
static inline __virtio16 cpu_to_tun16(struct tun_struct *tun, u16 val)
{
return __cpu_to_virtio16(tun_is_little_endian(tun), val);
}
static inline u32 tun_hashfn(u32 rxhash)
{
return rxhash & 0x3ff;
}
static struct tun_flow_entry *tun_flow_find(struct hlist_head *head, u32 rxhash)
{
struct tun_flow_entry *e;
hlist_for_each_entry_rcu(e, head, hash_link) {
if (e->rxhash == rxhash)
return e;
}
return NULL;
}
static struct tun_flow_entry *tun_flow_create(struct tun_struct *tun,
struct hlist_head *head,
u32 rxhash, u16 queue_index)
{
struct tun_flow_entry *e = kmalloc(sizeof(*e), GFP_ATOMIC);
if (e) {
tun_debug(KERN_INFO, tun, "create flow: hash %u index %u\n",
rxhash, queue_index);
e->updated = jiffies;
e->rxhash = rxhash;
e->rps_rxhash = 0;
e->queue_index = queue_index;
e->tun = tun;
hlist_add_head_rcu(&e->hash_link, head);
++tun->flow_count;
}
return e;
}
static void tun_flow_delete(struct tun_struct *tun, struct tun_flow_entry *e)
{
tun_debug(KERN_INFO, tun, "delete flow: hash %u index %u\n",
e->rxhash, e->queue_index);
hlist_del_rcu(&e->hash_link);
kfree_rcu(e, rcu);
--tun->flow_count;
}
static void tun_flow_flush(struct tun_struct *tun)
{
int i;
spin_lock_bh(&tun->lock);
for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
struct tun_flow_entry *e;
struct hlist_node *n;
hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link)
tun_flow_delete(tun, e);
}
spin_unlock_bh(&tun->lock);
}
static void tun_flow_delete_by_queue(struct tun_struct *tun, u16 queue_index)
{
int i;
spin_lock_bh(&tun->lock);
for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
struct tun_flow_entry *e;
struct hlist_node *n;
hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
if (e->queue_index == queue_index)
tun_flow_delete(tun, e);
}
}
spin_unlock_bh(&tun->lock);
}
static void tun_flow_cleanup(unsigned long data)
{
struct tun_struct *tun = (struct tun_struct *)data;
unsigned long delay = tun->ageing_time;
unsigned long next_timer = jiffies + delay;
unsigned long count = 0;
int i;
tun_debug(KERN_INFO, tun, "tun_flow_cleanup\n");
spin_lock_bh(&tun->lock);
for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++) {
struct tun_flow_entry *e;
struct hlist_node *n;
hlist_for_each_entry_safe(e, n, &tun->flows[i], hash_link) {
unsigned long this_timer;
count++;
this_timer = e->updated + delay;
if (time_before_eq(this_timer, jiffies))
tun_flow_delete(tun, e);
else if (time_before(this_timer, next_timer))
next_timer = this_timer;
}
}
if (count)
mod_timer(&tun->flow_gc_timer, round_jiffies_up(next_timer));
spin_unlock_bh(&tun->lock);
}
static void tun_flow_update(struct tun_struct *tun, u32 rxhash,
struct tun_file *tfile)
{
struct hlist_head *head;
struct tun_flow_entry *e;
unsigned long delay = tun->ageing_time;
u16 queue_index = tfile->queue_index;
if (!rxhash)
return;
else
head = &tun->flows[tun_hashfn(rxhash)];
rcu_read_lock();
/* We may get a very small possibility of OOO during switching, not
* worth to optimize.*/
if (tun->numqueues == 1 || tfile->detached)
goto unlock;
e = tun_flow_find(head, rxhash);
if (likely(e)) {
/* TODO: keep queueing to old queue until it's empty? */
e->queue_index = queue_index;
e->updated = jiffies;
sock_rps_record_flow_hash(e->rps_rxhash);
} else {
spin_lock_bh(&tun->lock);
if (!tun_flow_find(head, rxhash) &&
tun->flow_count < MAX_TAP_FLOWS)
tun_flow_create(tun, head, rxhash, queue_index);
if (!timer_pending(&tun->flow_gc_timer))
mod_timer(&tun->flow_gc_timer,
round_jiffies_up(jiffies + delay));
spin_unlock_bh(&tun->lock);
}
unlock:
rcu_read_unlock();
}
/**
* Save the hash received in the stack receive path and update the
* flow_hash table accordingly.
*/
static inline void tun_flow_save_rps_rxhash(struct tun_flow_entry *e, u32 hash)
{
if (unlikely(e->rps_rxhash != hash))
e->rps_rxhash = hash;
}
/* We try to identify a flow through its rxhash first. The reason that
* we do not check rxq no. is because some cards(e.g 82599), chooses
* the rxq based on the txq where the last packet of the flow comes. As
* the userspace application move between processors, we may get a
* different rxq no. here. If we could not get rxhash, then we would
* hope the rxq no. may help here.
*/
static u16 tun_select_queue(struct net_device *dev, struct sk_buff *skb,
void *accel_priv, select_queue_fallback_t fallback)
{
struct tun_struct *tun = netdev_priv(dev);
struct tun_flow_entry *e;
u32 txq = 0;
u32 numqueues = 0;
rcu_read_lock();
numqueues = ACCESS_ONCE(tun->numqueues);
txq = skb_get_hash(skb);
if (txq) {
e = tun_flow_find(&tun->flows[tun_hashfn(txq)], txq);
if (e) {
tun_flow_save_rps_rxhash(e, txq);
txq = e->queue_index;
} else
/* use multiply and shift instead of expensive divide */
txq = ((u64)txq * numqueues) >> 32;
} else if (likely(skb_rx_queue_recorded(skb))) {
txq = skb_get_rx_queue(skb);
while (unlikely(txq >= numqueues))
txq -= numqueues;
}
rcu_read_unlock();
return txq;
}
static inline bool tun_not_capable(struct tun_struct *tun)
{
const struct cred *cred = current_cred();
struct net *net = dev_net(tun->dev);
return ((uid_valid(tun->owner) && !uid_eq(cred->euid, tun->owner)) ||
(gid_valid(tun->group) && !in_egroup_p(tun->group))) &&
!ns_capable(net->user_ns, CAP_NET_ADMIN);
}
static void tun_set_real_num_queues(struct tun_struct *tun)
{
netif_set_real_num_tx_queues(tun->dev, tun->numqueues);
netif_set_real_num_rx_queues(tun->dev, tun->numqueues);
}
static void tun_disable_queue(struct tun_struct *tun, struct tun_file *tfile)
{
tfile->detached = tun;
list_add_tail(&tfile->next, &tun->disabled);
++tun->numdisabled;
}
static struct tun_struct *tun_enable_queue(struct tun_file *tfile)
{
struct tun_struct *tun = tfile->detached;
tfile->detached = NULL;
list_del_init(&tfile->next);
--tun->numdisabled;
return tun;
}
static void tun_queue_purge(struct tun_file *tfile)
{
struct sk_buff *skb;
while ((skb = skb_array_consume(&tfile->tx_array)) != NULL)
kfree_skb(skb);
skb_queue_purge(&tfile->sk.sk_error_queue);
}
static void __tun_detach(struct tun_file *tfile, bool clean)
{
struct tun_file *ntfile;
struct tun_struct *tun;
tun = rtnl_dereference(tfile->tun);
if (tun && !tfile->detached) {
u16 index = tfile->queue_index;
BUG_ON(index >= tun->numqueues);
rcu_assign_pointer(tun->tfiles[index],
tun->tfiles[tun->numqueues - 1]);
ntfile = rtnl_dereference(tun->tfiles[index]);
ntfile->queue_index = index;
--tun->numqueues;
if (clean) {
RCU_INIT_POINTER(tfile->tun, NULL);
sock_put(&tfile->sk);
} else
tun_disable_queue(tun, tfile);
synchronize_net();
tun_flow_delete_by_queue(tun, tun->numqueues + 1);
/* Drop read queue */
tun_queue_purge(tfile);
tun_set_real_num_queues(tun);
} else if (tfile->detached && clean) {
tun = tun_enable_queue(tfile);
sock_put(&tfile->sk);
}
if (clean) {
if (tun && tun->numqueues == 0 && tun->numdisabled == 0) {
netif_carrier_off(tun->dev);
if (!(tun->flags & IFF_PERSIST) &&
tun->dev->reg_state == NETREG_REGISTERED)
unregister_netdevice(tun->dev);
}
if (tun)
skb_array_cleanup(&tfile->tx_array);
sock_put(&tfile->sk);
}
}
static void tun_detach(struct tun_file *tfile, bool clean)
{
rtnl_lock();
__tun_detach(tfile, clean);
rtnl_unlock();
}
static void tun_detach_all(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
struct tun_file *tfile, *tmp;
int i, n = tun->numqueues;
for (i = 0; i < n; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
BUG_ON(!tfile);
tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
tfile->socket.sk->sk_data_ready(tfile->socket.sk);
RCU_INIT_POINTER(tfile->tun, NULL);
--tun->numqueues;
}
list_for_each_entry(tfile, &tun->disabled, next) {
tfile->socket.sk->sk_shutdown = RCV_SHUTDOWN;
tfile->socket.sk->sk_data_ready(tfile->socket.sk);
RCU_INIT_POINTER(tfile->tun, NULL);
}
BUG_ON(tun->numqueues != 0);
synchronize_net();
for (i = 0; i < n; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
/* Drop read queue */
tun_queue_purge(tfile);
sock_put(&tfile->sk);
}
list_for_each_entry_safe(tfile, tmp, &tun->disabled, next) {
tun_enable_queue(tfile);
tun_queue_purge(tfile);
sock_put(&tfile->sk);
}
BUG_ON(tun->numdisabled != 0);
if (tun->flags & IFF_PERSIST)
module_put(THIS_MODULE);
}
static int tun_attach(struct tun_struct *tun, struct file *file, bool skip_filter)
{
struct tun_file *tfile = file->private_data;
struct net_device *dev = tun->dev;
int err;
err = security_tun_dev_attach(tfile->socket.sk, tun->security);
if (err < 0)
goto out;
err = -EINVAL;
if (rtnl_dereference(tfile->tun) && !tfile->detached)
goto out;
err = -EBUSY;
if (!(tun->flags & IFF_MULTI_QUEUE) && tun->numqueues == 1)
goto out;
err = -E2BIG;
if (!tfile->detached &&
tun->numqueues + tun->numdisabled == MAX_TAP_QUEUES)
goto out;
err = 0;
/* Re-attach the filter to persist device */
if (!skip_filter && (tun->filter_attached == true)) {
lock_sock(tfile->socket.sk);
err = sk_attach_filter(&tun->fprog, tfile->socket.sk);
release_sock(tfile->socket.sk);
if (!err)
goto out;
}
if (!tfile->detached &&
skb_array_init(&tfile->tx_array, dev->tx_queue_len, GFP_KERNEL)) {
err = -ENOMEM;
goto out;
}
tfile->queue_index = tun->numqueues;
tfile->socket.sk->sk_shutdown &= ~RCV_SHUTDOWN;
rcu_assign_pointer(tfile->tun, tun);
rcu_assign_pointer(tun->tfiles[tun->numqueues], tfile);
tun->numqueues++;
if (tfile->detached)
tun_enable_queue(tfile);
else
sock_hold(&tfile->sk);
tun_set_real_num_queues(tun);
/* device is allowed to go away first, so no need to hold extra
* refcnt.
*/
out:
return err;
}
static struct tun_struct *__tun_get(struct tun_file *tfile)
{
struct tun_struct *tun;
rcu_read_lock();
tun = rcu_dereference(tfile->tun);
if (tun)
dev_hold(tun->dev);
rcu_read_unlock();
return tun;
}
static struct tun_struct *tun_get(struct file *file)
{
return __tun_get(file->private_data);
}
static void tun_put(struct tun_struct *tun)
{
dev_put(tun->dev);
}
/* TAP filtering */
static void addr_hash_set(u32 *mask, const u8 *addr)
{
int n = ether_crc(ETH_ALEN, addr) >> 26;
mask[n >> 5] |= (1 << (n & 31));
}
static unsigned int addr_hash_test(const u32 *mask, const u8 *addr)
{
int n = ether_crc(ETH_ALEN, addr) >> 26;
return mask[n >> 5] & (1 << (n & 31));
}
static int update_filter(struct tap_filter *filter, void __user *arg)
{
struct { u8 u[ETH_ALEN]; } *addr;
struct tun_filter uf;
int err, alen, n, nexact;
if (copy_from_user(&uf, arg, sizeof(uf)))
return -EFAULT;
if (!uf.count) {
/* Disabled */
filter->count = 0;
return 0;
}
alen = ETH_ALEN * uf.count;
addr = memdup_user(arg + sizeof(uf), alen);
if (IS_ERR(addr))
return PTR_ERR(addr);
/* The filter is updated without holding any locks. Which is
* perfectly safe. We disable it first and in the worst
* case we'll accept a few undesired packets. */
filter->count = 0;
wmb();
/* Use first set of addresses as an exact filter */
for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++)
memcpy(filter->addr[n], addr[n].u, ETH_ALEN);
nexact = n;
/* Remaining multicast addresses are hashed,
* unicast will leave the filter disabled. */
memset(filter->mask, 0, sizeof(filter->mask));
for (; n < uf.count; n++) {
if (!is_multicast_ether_addr(addr[n].u)) {
err = 0; /* no filter */
goto free_addr;
}
addr_hash_set(filter->mask, addr[n].u);
}
/* For ALLMULTI just set the mask to all ones.
* This overrides the mask populated above. */
if ((uf.flags & TUN_FLT_ALLMULTI))
memset(filter->mask, ~0, sizeof(filter->mask));
/* Now enable the filter */
wmb();
filter->count = nexact;
/* Return the number of exact filters */
err = nexact;
free_addr:
kfree(addr);
return err;
}
/* Returns: 0 - drop, !=0 - accept */
static int run_filter(struct tap_filter *filter, const struct sk_buff *skb)
{
/* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect
* at this point. */
struct ethhdr *eh = (struct ethhdr *) skb->data;
int i;
/* Exact match */
for (i = 0; i < filter->count; i++)
if (ether_addr_equal(eh->h_dest, filter->addr[i]))
return 1;
/* Inexact match (multicast only) */
if (is_multicast_ether_addr(eh->h_dest))
return addr_hash_test(filter->mask, eh->h_dest);
return 0;
}
/*
* Checks whether the packet is accepted or not.
* Returns: 0 - drop, !=0 - accept
*/
static int check_filter(struct tap_filter *filter, const struct sk_buff *skb)
{
if (!filter->count)
return 1;
return run_filter(filter, skb);
}
/* Network device part of the driver */
static const struct ethtool_ops tun_ethtool_ops;
/* Net device detach from fd. */
static void tun_net_uninit(struct net_device *dev)
{
tun_detach_all(dev);
}
/* Net device open. */
static int tun_net_open(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
int i;
netif_tx_start_all_queues(dev);
for (i = 0; i < tun->numqueues; i++) {
struct tun_file *tfile;
tfile = rtnl_dereference(tun->tfiles[i]);
tfile->socket.sk->sk_write_space(tfile->socket.sk);
}
return 0;
}
/* Net device close. */
static int tun_net_close(struct net_device *dev)
{
netif_tx_stop_all_queues(dev);
return 0;
}
/* Net device start xmit */
static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
int txq = skb->queue_mapping;
struct tun_file *tfile;
u32 numqueues = 0;
rcu_read_lock();
tfile = rcu_dereference(tun->tfiles[txq]);
numqueues = ACCESS_ONCE(tun->numqueues);
/* Drop packet if interface is not attached */
if (txq >= numqueues)
goto drop;
#ifdef CONFIG_RPS
if (numqueues == 1 && static_key_false(&rps_needed)) {
/* Select queue was not called for the skbuff, so we extract the
* RPS hash and save it into the flow_table here.
*/
__u32 rxhash;
rxhash = skb_get_hash(skb);
if (rxhash) {
struct tun_flow_entry *e;
e = tun_flow_find(&tun->flows[tun_hashfn(rxhash)],
rxhash);
if (e)
tun_flow_save_rps_rxhash(e, rxhash);
}
}
#endif
tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len);
BUG_ON(!tfile);
/* Drop if the filter does not like it.
* This is a noop if the filter is disabled.
* Filter can be enabled only for the TAP devices. */
if (!check_filter(&tun->txflt, skb))
goto drop;
if (tfile->socket.sk->sk_filter &&
sk_filter(tfile->socket.sk, skb))
goto drop;
if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC)))
goto drop;
skb_tx_timestamp(skb);
/* Orphan the skb - required as we might hang on to it
* for indefinite time.
*/
skb_orphan(skb);
nf_reset(skb);
if (skb_array_produce(&tfile->tx_array, skb))
goto drop;
/* Notify and wake up reader process */
if (tfile->flags & TUN_FASYNC)
kill_fasync(&tfile->fasync, SIGIO, POLL_IN);
tfile->socket.sk->sk_data_ready(tfile->socket.sk);
rcu_read_unlock();
return NETDEV_TX_OK;
drop:
this_cpu_inc(tun->pcpu_stats->tx_dropped);
skb_tx_error(skb);
kfree_skb(skb);
rcu_read_unlock();
return NET_XMIT_DROP;
}
static void tun_net_mclist(struct net_device *dev)
{
/*
* This callback is supposed to deal with mc filter in
* _rx_ path and has nothing to do with the _tx_ path.
* In rx path we always accept everything userspace gives us.
*/
}
static netdev_features_t tun_net_fix_features(struct net_device *dev,
netdev_features_t features)
{
struct tun_struct *tun = netdev_priv(dev);
return (features & tun->set_features) | (features & ~TUN_USER_FEATURES);
}
#ifdef CONFIG_NET_POLL_CONTROLLER
static void tun_poll_controller(struct net_device *dev)
{
/*
* Tun only receives frames when:
* 1) the char device endpoint gets data from user space
* 2) the tun socket gets a sendmsg call from user space
* Since both of those are synchronous operations, we are guaranteed
* never to have pending data when we poll for it
* so there is nothing to do here but return.
* We need this though so netpoll recognizes us as an interface that
* supports polling, which enables bridge devices in virt setups to
* still use netconsole
*/
return;
}
#endif
static void tun_set_headroom(struct net_device *dev, int new_hr)
{
struct tun_struct *tun = netdev_priv(dev);
if (new_hr < NET_SKB_PAD)
new_hr = NET_SKB_PAD;
tun->align = new_hr;
}
static struct rtnl_link_stats64 *
tun_net_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats)
{
u32 rx_dropped = 0, tx_dropped = 0, rx_frame_errors = 0;
struct tun_struct *tun = netdev_priv(dev);
struct tun_pcpu_stats *p;
int i;
for_each_possible_cpu(i) {
u64 rxpackets, rxbytes, txpackets, txbytes;
unsigned int start;
p = per_cpu_ptr(tun->pcpu_stats, i);
do {
start = u64_stats_fetch_begin(&p->syncp);
rxpackets = p->rx_packets;
rxbytes = p->rx_bytes;
txpackets = p->tx_packets;
txbytes = p->tx_bytes;
} while (u64_stats_fetch_retry(&p->syncp, start));
stats->rx_packets += rxpackets;
stats->rx_bytes += rxbytes;
stats->tx_packets += txpackets;
stats->tx_bytes += txbytes;
/* u32 counters */
rx_dropped += p->rx_dropped;
rx_frame_errors += p->rx_frame_errors;
tx_dropped += p->tx_dropped;
}
stats->rx_dropped = rx_dropped;
stats->rx_frame_errors = rx_frame_errors;
stats->tx_dropped = tx_dropped;
return stats;
}
static const struct net_device_ops tun_netdev_ops = {
.ndo_uninit = tun_net_uninit,
.ndo_open = tun_net_open,
.ndo_stop = tun_net_close,
.ndo_start_xmit = tun_net_xmit,
.ndo_fix_features = tun_net_fix_features,
.ndo_select_queue = tun_select_queue,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = tun_poll_controller,
#endif
.ndo_set_rx_headroom = tun_set_headroom,
.ndo_get_stats64 = tun_net_get_stats64,
};
static const struct net_device_ops tap_netdev_ops = {
.ndo_uninit = tun_net_uninit,
.ndo_open = tun_net_open,
.ndo_stop = tun_net_close,
.ndo_start_xmit = tun_net_xmit,
.ndo_fix_features = tun_net_fix_features,
.ndo_set_rx_mode = tun_net_mclist,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
.ndo_select_queue = tun_select_queue,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = tun_poll_controller,
#endif
.ndo_features_check = passthru_features_check,
.ndo_set_rx_headroom = tun_set_headroom,
.ndo_get_stats64 = tun_net_get_stats64,
};
static void tun_flow_init(struct tun_struct *tun)
{
int i;
for (i = 0; i < TUN_NUM_FLOW_ENTRIES; i++)
INIT_HLIST_HEAD(&tun->flows[i]);
tun->ageing_time = TUN_FLOW_EXPIRE;
setup_timer(&tun->flow_gc_timer, tun_flow_cleanup, (unsigned long)tun);
mod_timer(&tun->flow_gc_timer,
round_jiffies_up(jiffies + tun->ageing_time));
}
static void tun_flow_uninit(struct tun_struct *tun)
{
del_timer_sync(&tun->flow_gc_timer);
tun_flow_flush(tun);
}
#define MIN_MTU 68
#define MAX_MTU 65535
/* Initialize net device. */
static void tun_net_init(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
switch (tun->flags & TUN_TYPE_MASK) {
case IFF_TUN:
dev->netdev_ops = &tun_netdev_ops;
/* Point-to-Point TUN Device */
dev->hard_header_len = 0;
dev->addr_len = 0;
dev->mtu = 1500;
/* Zero header length */
dev->type = ARPHRD_NONE;
dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST;
break;
case IFF_TAP:
dev->netdev_ops = &tap_netdev_ops;
/* Ethernet TAP Device */
ether_setup(dev);
dev->priv_flags &= ~IFF_TX_SKB_SHARING;
dev->priv_flags |= IFF_LIVE_ADDR_CHANGE;
eth_hw_addr_random(dev);
break;
}
dev->min_mtu = MIN_MTU;
dev->max_mtu = MAX_MTU - dev->hard_header_len;
}
/* Character device part */
/* Poll */
static unsigned int tun_chr_poll(struct file *file, poll_table *wait)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun = __tun_get(tfile);
struct sock *sk;
unsigned int mask = 0;
if (!tun)
return POLLERR;
sk = tfile->socket.sk;
tun_debug(KERN_INFO, tun, "tun_chr_poll\n");
poll_wait(file, sk_sleep(sk), wait);
if (!skb_array_empty(&tfile->tx_array))
mask |= POLLIN | POLLRDNORM;
if (tun->dev->flags & IFF_UP &&
(sock_writeable(sk) ||
(!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags) &&
sock_writeable(sk))))
mask |= POLLOUT | POLLWRNORM;
if (tun->dev->reg_state != NETREG_REGISTERED)
mask = POLLERR;
tun_put(tun);
return mask;
}
/* prepad is the amount to reserve at front. len is length after that.
* linear is a hint as to how much to copy (usually headers). */
static struct sk_buff *tun_alloc_skb(struct tun_file *tfile,
size_t prepad, size_t len,
size_t linear, int noblock)
{
struct sock *sk = tfile->socket.sk;
struct sk_buff *skb;
int err;
/* Under a page? Don't bother with paged skb. */
if (prepad + len < PAGE_SIZE || !linear)
linear = len;
skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
&err, 0);
if (!skb)
return ERR_PTR(err);
skb_reserve(skb, prepad);
skb_put(skb, linear);
skb->data_len = len - linear;
skb->len += len - linear;
return skb;
}
/* Get packet from user space buffer */
static ssize_t tun_get_user(struct tun_struct *tun, struct tun_file *tfile,
void *msg_control, struct iov_iter *from,
int noblock)
{
struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) };
struct sk_buff *skb;
size_t total_len = iov_iter_count(from);
size_t len = total_len, align = tun->align, linear;
struct virtio_net_hdr gso = { 0 };
struct tun_pcpu_stats *stats;
int good_linear;
int copylen;
bool zerocopy = false;
int err;
u32 rxhash;
if (!(tun->dev->flags & IFF_UP))
return -EIO;
if (!(tun->flags & IFF_NO_PI)) {
if (len < sizeof(pi))
return -EINVAL;
len -= sizeof(pi);
if (!copy_from_iter_full(&pi, sizeof(pi), from))
return -EFAULT;
}
if (tun->flags & IFF_VNET_HDR) {
int vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
if (len < vnet_hdr_sz)
return -EINVAL;
len -= vnet_hdr_sz;
if (!copy_from_iter_full(&gso, sizeof(gso), from))
return -EFAULT;
if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2 > tun16_to_cpu(tun, gso.hdr_len))
gso.hdr_len = cpu_to_tun16(tun, tun16_to_cpu(tun, gso.csum_start) + tun16_to_cpu(tun, gso.csum_offset) + 2);
if (tun16_to_cpu(tun, gso.hdr_len) > len)
return -EINVAL;
iov_iter_advance(from, vnet_hdr_sz - sizeof(gso));
}
if ((tun->flags & TUN_TYPE_MASK) == IFF_TAP) {
align += NET_IP_ALIGN;
if (unlikely(len < ETH_HLEN ||
(gso.hdr_len && tun16_to_cpu(tun, gso.hdr_len) < ETH_HLEN)))
return -EINVAL;
}
good_linear = SKB_MAX_HEAD(align);
if (msg_control) {
struct iov_iter i = *from;
/* There are 256 bytes to be copied in skb, so there is
* enough room for skb expand head in case it is used.
* The rest of the buffer is mapped from userspace.
*/
copylen = gso.hdr_len ? tun16_to_cpu(tun, gso.hdr_len) : GOODCOPY_LEN;
if (copylen > good_linear)
copylen = good_linear;
linear = copylen;
iov_iter_advance(&i, copylen);
if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
zerocopy = true;
}
if (!zerocopy) {
copylen = len;
if (tun16_to_cpu(tun, gso.hdr_len) > good_linear)
linear = good_linear;
else
linear = tun16_to_cpu(tun, gso.hdr_len);
}
skb = tun_alloc_skb(tfile, align, copylen, linear, noblock);
if (IS_ERR(skb)) {
if (PTR_ERR(skb) != -EAGAIN)
this_cpu_inc(tun->pcpu_stats->rx_dropped);
return PTR_ERR(skb);
}
if (zerocopy)
err = zerocopy_sg_from_iter(skb, from);
else
err = skb_copy_datagram_from_iter(skb, 0, from, len);
if (err) {
this_cpu_inc(tun->pcpu_stats->rx_dropped);
kfree_skb(skb);
return -EFAULT;
}
if (virtio_net_hdr_to_skb(skb, &gso, tun_is_little_endian(tun))) {
this_cpu_inc(tun->pcpu_stats->rx_frame_errors);
kfree_skb(skb);
return -EINVAL;
}
switch (tun->flags & TUN_TYPE_MASK) {
case IFF_TUN:
if (tun->flags & IFF_NO_PI) {
switch (skb->data[0] & 0xf0) {
case 0x40:
pi.proto = htons(ETH_P_IP);
break;
case 0x60:
pi.proto = htons(ETH_P_IPV6);
break;
default:
this_cpu_inc(tun->pcpu_stats->rx_dropped);
kfree_skb(skb);
return -EINVAL;
}
}
skb_reset_mac_header(skb);
skb->protocol = pi.proto;
skb->dev = tun->dev;
break;
case IFF_TAP:
skb->protocol = eth_type_trans(skb, tun->dev);
break;
}
/* copy skb_ubuf_info for callback when skb has no error */
if (zerocopy) {
skb_shinfo(skb)->destructor_arg = msg_control;
skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY;
skb_shinfo(skb)->tx_flags |= SKBTX_SHARED_FRAG;
} else if (msg_control) {
struct ubuf_info *uarg = msg_control;
uarg->callback(uarg, false);
}
skb_reset_network_header(skb);
skb_probe_transport_header(skb, 0);
rxhash = skb_get_hash(skb);
#ifndef CONFIG_4KSTACKS
local_bh_disable();
netif_receive_skb(skb);
local_bh_enable();
#else
netif_rx_ni(skb);
#endif
stats = get_cpu_ptr(tun->pcpu_stats);
u64_stats_update_begin(&stats->syncp);
stats->rx_packets++;
stats->rx_bytes += len;
u64_stats_update_end(&stats->syncp);
put_cpu_ptr(stats);
tun_flow_update(tun, rxhash, tfile);
return total_len;
}
static ssize_t tun_chr_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct tun_struct *tun = tun_get(file);
struct tun_file *tfile = file->private_data;
ssize_t result;
if (!tun)
return -EBADFD;
result = tun_get_user(tun, tfile, NULL, from, file->f_flags & O_NONBLOCK);
tun_put(tun);
return result;
}
/* Put packet to the user space buffer */
static ssize_t tun_put_user(struct tun_struct *tun,
struct tun_file *tfile,
struct sk_buff *skb,
struct iov_iter *iter)
{
struct tun_pi pi = { 0, skb->protocol };
struct tun_pcpu_stats *stats;
ssize_t total;
int vlan_offset = 0;
int vlan_hlen = 0;
int vnet_hdr_sz = 0;
if (skb_vlan_tag_present(skb))
vlan_hlen = VLAN_HLEN;
if (tun->flags & IFF_VNET_HDR)
vnet_hdr_sz = READ_ONCE(tun->vnet_hdr_sz);
total = skb->len + vlan_hlen + vnet_hdr_sz;
if (!(tun->flags & IFF_NO_PI)) {
if (iov_iter_count(iter) < sizeof(pi))
return -EINVAL;
total += sizeof(pi);
if (iov_iter_count(iter) < total) {
/* Packet will be striped */
pi.flags |= TUN_PKT_STRIP;
}
if (copy_to_iter(&pi, sizeof(pi), iter) != sizeof(pi))
return -EFAULT;
}
if (vnet_hdr_sz) {
struct virtio_net_hdr gso;
if (iov_iter_count(iter) < vnet_hdr_sz)
return -EINVAL;
if (virtio_net_hdr_from_skb(skb, &gso,
tun_is_little_endian(tun), true)) {
struct skb_shared_info *sinfo = skb_shinfo(skb);
pr_err("unexpected GSO type: "
"0x%x, gso_size %d, hdr_len %d\n",
sinfo->gso_type, tun16_to_cpu(tun, gso.gso_size),
tun16_to_cpu(tun, gso.hdr_len));
print_hex_dump(KERN_ERR, "tun: ",
DUMP_PREFIX_NONE,
16, 1, skb->head,
min((int)tun16_to_cpu(tun, gso.hdr_len), 64), true);
WARN_ON_ONCE(1);
return -EINVAL;
}
if (copy_to_iter(&gso, sizeof(gso), iter) != sizeof(gso))
return -EFAULT;
iov_iter_advance(iter, vnet_hdr_sz - sizeof(gso));
}
if (vlan_hlen) {
int ret;
struct {
__be16 h_vlan_proto;
__be16 h_vlan_TCI;
} veth;
veth.h_vlan_proto = skb->vlan_proto;
veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
if (ret || !iov_iter_count(iter))
goto done;
ret = copy_to_iter(&veth, sizeof(veth), iter);
if (ret != sizeof(veth) || !iov_iter_count(iter))
goto done;
}
skb_copy_datagram_iter(skb, vlan_offset, iter, skb->len - vlan_offset);
done:
/* caller is in process context, */
stats = get_cpu_ptr(tun->pcpu_stats);
u64_stats_update_begin(&stats->syncp);
stats->tx_packets++;
stats->tx_bytes += skb->len + vlan_hlen;
u64_stats_update_end(&stats->syncp);
put_cpu_ptr(tun->pcpu_stats);
return total;
}
static struct sk_buff *tun_ring_recv(struct tun_file *tfile, int noblock,
int *err)
{
DECLARE_WAITQUEUE(wait, current);
struct sk_buff *skb = NULL;
int error = 0;
skb = skb_array_consume(&tfile->tx_array);
if (skb)
goto out;
if (noblock) {
error = -EAGAIN;
goto out;
}
add_wait_queue(&tfile->wq.wait, &wait);
current->state = TASK_INTERRUPTIBLE;
while (1) {
skb = skb_array_consume(&tfile->tx_array);
if (skb)
break;
if (signal_pending(current)) {
error = -ERESTARTSYS;
break;
}
if (tfile->socket.sk->sk_shutdown & RCV_SHUTDOWN) {
error = -EFAULT;
break;
}
schedule();
}
current->state = TASK_RUNNING;
remove_wait_queue(&tfile->wq.wait, &wait);
out:
*err = error;
return skb;
}
static ssize_t tun_do_read(struct tun_struct *tun, struct tun_file *tfile,
struct iov_iter *to,
int noblock)
{
struct sk_buff *skb;
ssize_t ret;
int err;
tun_debug(KERN_INFO, tun, "tun_do_read\n");
if (!iov_iter_count(to))
return 0;
/* Read frames from ring */
skb = tun_ring_recv(tfile, noblock, &err);
if (!skb)
return err;
ret = tun_put_user(tun, tfile, skb, to);
if (unlikely(ret < 0))
kfree_skb(skb);
else
consume_skb(skb);
return ret;
}
static ssize_t tun_chr_read_iter(struct kiocb *iocb, struct iov_iter *to)
{
struct file *file = iocb->ki_filp;
struct tun_file *tfile = file->private_data;
struct tun_struct *tun = __tun_get(tfile);
ssize_t len = iov_iter_count(to), ret;
if (!tun)
return -EBADFD;
ret = tun_do_read(tun, tfile, to, file->f_flags & O_NONBLOCK);
ret = min_t(ssize_t, ret, len);
if (ret > 0)
iocb->ki_pos = ret;
tun_put(tun);
return ret;
}
static void tun_free_netdev(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
BUG_ON(!(list_empty(&tun->disabled)));
free_percpu(tun->pcpu_stats);
tun_flow_uninit(tun);
security_tun_dev_free_security(tun->security);
free_netdev(dev);
}
static void tun_setup(struct net_device *dev)
{
struct tun_struct *tun = netdev_priv(dev);
tun->owner = INVALID_UID;
tun->group = INVALID_GID;
dev->ethtool_ops = &tun_ethtool_ops;
dev->destructor = tun_free_netdev;
/* We prefer our own queue length */
dev->tx_queue_len = TUN_READQ_SIZE;
}
/* Trivial set of netlink ops to allow deleting tun or tap
* device with netlink.
*/
static int tun_validate(struct nlattr *tb[], struct nlattr *data[])
{
return -EINVAL;
}
static struct rtnl_link_ops tun_link_ops __read_mostly = {
.kind = DRV_NAME,
.priv_size = sizeof(struct tun_struct),
.setup = tun_setup,
.validate = tun_validate,
};
static void tun_sock_write_space(struct sock *sk)
{
struct tun_file *tfile;
wait_queue_head_t *wqueue;
if (!sock_writeable(sk))
return;
if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
return;
wqueue = sk_sleep(sk);
if (wqueue && waitqueue_active(wqueue))
wake_up_interruptible_sync_poll(wqueue, POLLOUT |
POLLWRNORM | POLLWRBAND);
tfile = container_of(sk, struct tun_file, sk);
kill_fasync(&tfile->fasync, SIGIO, POLL_OUT);
}
static int tun_sendmsg(struct socket *sock, struct msghdr *m, size_t total_len)
{
int ret;
struct tun_file *tfile = container_of(sock, struct tun_file, socket);
struct tun_struct *tun = __tun_get(tfile);
if (!tun)
return -EBADFD;
ret = tun_get_user(tun, tfile, m->msg_control, &m->msg_iter,
m->msg_flags & MSG_DONTWAIT);
tun_put(tun);
return ret;
}
static int tun_recvmsg(struct socket *sock, struct msghdr *m, size_t total_len,
int flags)
{
struct tun_file *tfile = container_of(sock, struct tun_file, socket);
struct tun_struct *tun = __tun_get(tfile);
int ret;
if (!tun)
return -EBADFD;
if (flags & ~(MSG_DONTWAIT|MSG_TRUNC|MSG_ERRQUEUE)) {
ret = -EINVAL;
goto out;
}
if (flags & MSG_ERRQUEUE) {
ret = sock_recv_errqueue(sock->sk, m, total_len,
SOL_PACKET, TUN_TX_TIMESTAMP);
goto out;
}
ret = tun_do_read(tun, tfile, &m->msg_iter, flags & MSG_DONTWAIT);
if (ret > (ssize_t)total_len) {
m->msg_flags |= MSG_TRUNC;
ret = flags & MSG_TRUNC ? ret : total_len;
}
out:
tun_put(tun);
return ret;
}
static int tun_peek_len(struct socket *sock)
{
struct tun_file *tfile = container_of(sock, struct tun_file, socket);
struct tun_struct *tun;
int ret = 0;
tun = __tun_get(tfile);
if (!tun)
return 0;
ret = skb_array_peek_len(&tfile->tx_array);
tun_put(tun);
return ret;
}
/* Ops structure to mimic raw sockets with tun */
static const struct proto_ops tun_socket_ops = {
.peek_len = tun_peek_len,
.sendmsg = tun_sendmsg,
.recvmsg = tun_recvmsg,
};
static struct proto tun_proto = {
.name = "tun",
.owner = THIS_MODULE,
.obj_size = sizeof(struct tun_file),
};
static int tun_flags(struct tun_struct *tun)
{
return tun->flags & (TUN_FEATURES | IFF_PERSIST | IFF_TUN | IFF_TAP);
}
static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct tun_struct *tun = netdev_priv(to_net_dev(dev));
return sprintf(buf, "0x%x\n", tun_flags(tun));
}
static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct tun_struct *tun = netdev_priv(to_net_dev(dev));
return uid_valid(tun->owner)?
sprintf(buf, "%u\n",
from_kuid_munged(current_user_ns(), tun->owner)):
sprintf(buf, "-1\n");
}
static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct tun_struct *tun = netdev_priv(to_net_dev(dev));
return gid_valid(tun->group) ?
sprintf(buf, "%u\n",
from_kgid_munged(current_user_ns(), tun->group)):
sprintf(buf, "-1\n");
}
static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL);
static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL);
static DEVICE_ATTR(group, 0444, tun_show_group, NULL);
static struct attribute *tun_dev_attrs[] = {
&dev_attr_tun_flags.attr,
&dev_attr_owner.attr,
&dev_attr_group.attr,
NULL
};
static const struct attribute_group tun_attr_group = {
.attrs = tun_dev_attrs
};
static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr)
{
struct tun_struct *tun;
struct tun_file *tfile = file->private_data;
struct net_device *dev;
int err;
if (tfile->detached)
return -EINVAL;
dev = __dev_get_by_name(net, ifr->ifr_name);
if (dev) {
if (ifr->ifr_flags & IFF_TUN_EXCL)
return -EBUSY;
if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops)
tun = netdev_priv(dev);
else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops)
tun = netdev_priv(dev);
else
return -EINVAL;
if (!!(ifr->ifr_flags & IFF_MULTI_QUEUE) !=
!!(tun->flags & IFF_MULTI_QUEUE))
return -EINVAL;
if (tun_not_capable(tun))
return -EPERM;
err = security_tun_dev_open(tun->security);
if (err < 0)
return err;
err = tun_attach(tun, file, ifr->ifr_flags & IFF_NOFILTER);
if (err < 0)
return err;
if (tun->flags & IFF_MULTI_QUEUE &&
(tun->numqueues + tun->numdisabled > 1)) {
/* One or more queue has already been attached, no need
* to initialize the device again.
*/
return 0;
}
}
else {
char *name;
unsigned long flags = 0;
int queues = ifr->ifr_flags & IFF_MULTI_QUEUE ?
MAX_TAP_QUEUES : 1;
if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
return -EPERM;
err = security_tun_dev_create();
if (err < 0)
return err;
/* Set dev type */
if (ifr->ifr_flags & IFF_TUN) {
/* TUN device */
flags |= IFF_TUN;
name = "tun%d";
} else if (ifr->ifr_flags & IFF_TAP) {
/* TAP device */
flags |= IFF_TAP;
name = "tap%d";
} else
return -EINVAL;
if (*ifr->ifr_name)
name = ifr->ifr_name;
dev = alloc_netdev_mqs(sizeof(struct tun_struct), name,
NET_NAME_UNKNOWN, tun_setup, queues,
queues);
if (!dev)
return -ENOMEM;
dev_net_set(dev, net);
dev->rtnl_link_ops = &tun_link_ops;
dev->ifindex = tfile->ifindex;
dev->sysfs_groups[0] = &tun_attr_group;
tun = netdev_priv(dev);
tun->dev = dev;
tun->flags = flags;
tun->txflt.count = 0;
tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
tun->align = NET_SKB_PAD;
tun->filter_attached = false;
tun->sndbuf = tfile->socket.sk->sk_sndbuf;
tun->pcpu_stats = netdev_alloc_pcpu_stats(struct tun_pcpu_stats);
if (!tun->pcpu_stats) {
err = -ENOMEM;
goto err_free_dev;
}
spin_lock_init(&tun->lock);
err = security_tun_dev_alloc_security(&tun->security);
if (err < 0)
goto err_free_stat;
tun_net_init(dev);
tun_flow_init(tun);
dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST |
TUN_USER_FEATURES | NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX;
dev->features = dev->hw_features | NETIF_F_LLTX;
dev->vlan_features = dev->features &
~(NETIF_F_HW_VLAN_CTAG_TX |
NETIF_F_HW_VLAN_STAG_TX);
INIT_LIST_HEAD(&tun->disabled);
err = tun_attach(tun, file, false);
if (err < 0)
goto err_free_flow;
err = register_netdevice(tun->dev);
if (err < 0)
goto err_detach;
}
netif_carrier_on(tun->dev);
tun_debug(KERN_INFO, tun, "tun_set_iff\n");
tun->flags = (tun->flags & ~TUN_FEATURES) |
(ifr->ifr_flags & TUN_FEATURES);
/* Make sure persistent devices do not get stuck in
* xoff state.
*/
if (netif_running(tun->dev))
netif_tx_wake_all_queues(tun->dev);
strcpy(ifr->ifr_name, tun->dev->name);
return 0;
err_detach:
tun_detach_all(dev);
err_free_flow:
tun_flow_uninit(tun);
security_tun_dev_free_security(tun->security);
err_free_stat:
free_percpu(tun->pcpu_stats);
err_free_dev:
free_netdev(dev);
return err;
}
static void tun_get_iff(struct net *net, struct tun_struct *tun,
struct ifreq *ifr)
{
tun_debug(KERN_INFO, tun, "tun_get_iff\n");
strcpy(ifr->ifr_name, tun->dev->name);
ifr->ifr_flags = tun_flags(tun);
}
/* This is like a cut-down ethtool ops, except done via tun fd so no
* privs required. */
static int set_offload(struct tun_struct *tun, unsigned long arg)
{
netdev_features_t features = 0;
if (arg & TUN_F_CSUM) {
features |= NETIF_F_HW_CSUM;
arg &= ~TUN_F_CSUM;
if (arg & (TUN_F_TSO4|TUN_F_TSO6)) {
if (arg & TUN_F_TSO_ECN) {
features |= NETIF_F_TSO_ECN;
arg &= ~TUN_F_TSO_ECN;
}
if (arg & TUN_F_TSO4)
features |= NETIF_F_TSO;
if (arg & TUN_F_TSO6)
features |= NETIF_F_TSO6;
arg &= ~(TUN_F_TSO4|TUN_F_TSO6);
}
if (arg & TUN_F_UFO) {
features |= NETIF_F_UFO;
arg &= ~TUN_F_UFO;
}
}
/* This gives the user a way to test for new features in future by
* trying to set them. */
if (arg)
return -EINVAL;
tun->set_features = features;
netdev_update_features(tun->dev);
return 0;
}
static void tun_detach_filter(struct tun_struct *tun, int n)
{
int i;
struct tun_file *tfile;
for (i = 0; i < n; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
lock_sock(tfile->socket.sk);
sk_detach_filter(tfile->socket.sk);
release_sock(tfile->socket.sk);
}
tun->filter_attached = false;
}
static int tun_attach_filter(struct tun_struct *tun)
{
int i, ret = 0;
struct tun_file *tfile;
for (i = 0; i < tun->numqueues; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
lock_sock(tfile->socket.sk);
ret = sk_attach_filter(&tun->fprog, tfile->socket.sk);
release_sock(tfile->socket.sk);
if (ret) {
tun_detach_filter(tun, i);
return ret;
}
}
tun->filter_attached = true;
return ret;
}
static void tun_set_sndbuf(struct tun_struct *tun)
{
struct tun_file *tfile;
int i;
for (i = 0; i < tun->numqueues; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
tfile->socket.sk->sk_sndbuf = tun->sndbuf;
}
}
static int tun_set_queue(struct file *file, struct ifreq *ifr)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun;
int ret = 0;
rtnl_lock();
if (ifr->ifr_flags & IFF_ATTACH_QUEUE) {
tun = tfile->detached;
if (!tun) {
ret = -EINVAL;
goto unlock;
}
ret = security_tun_dev_attach_queue(tun->security);
if (ret < 0)
goto unlock;
ret = tun_attach(tun, file, false);
} else if (ifr->ifr_flags & IFF_DETACH_QUEUE) {
tun = rtnl_dereference(tfile->tun);
if (!tun || !(tun->flags & IFF_MULTI_QUEUE) || tfile->detached)
ret = -EINVAL;
else
__tun_detach(tfile, false);
} else
ret = -EINVAL;
unlock:
rtnl_unlock();
return ret;
}
static long __tun_chr_ioctl(struct file *file, unsigned int cmd,
unsigned long arg, int ifreq_len)
{
struct tun_file *tfile = file->private_data;
struct tun_struct *tun;
void __user* argp = (void __user*)arg;
struct ifreq ifr;
kuid_t owner;
kgid_t group;
int sndbuf;
int vnet_hdr_sz;
unsigned int ifindex;
int le;
int ret;
if (cmd == TUNSETIFF || cmd == TUNSETQUEUE || _IOC_TYPE(cmd) == SOCK_IOC_TYPE) {
if (copy_from_user(&ifr, argp, ifreq_len))
return -EFAULT;
} else {
memset(&ifr, 0, sizeof(ifr));
}
if (cmd == TUNGETFEATURES) {
/* Currently this just means: "what IFF flags are valid?".
* This is needed because we never checked for invalid flags on
* TUNSETIFF.
*/
return put_user(IFF_TUN | IFF_TAP | TUN_FEATURES,
(unsigned int __user*)argp);
} else if (cmd == TUNSETQUEUE)
return tun_set_queue(file, &ifr);
ret = 0;
rtnl_lock();
tun = __tun_get(tfile);
if (cmd == TUNSETIFF) {
ret = -EEXIST;
if (tun)
goto unlock;
ifr.ifr_name[IFNAMSIZ-1] = '\0';
ret = tun_set_iff(sock_net(&tfile->sk), file, &ifr);
if (ret)
goto unlock;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
goto unlock;
}
if (cmd == TUNSETIFINDEX) {
ret = -EPERM;
if (tun)
goto unlock;
ret = -EFAULT;
if (copy_from_user(&ifindex, argp, sizeof(ifindex)))
goto unlock;
ret = 0;
tfile->ifindex = ifindex;
goto unlock;
}
ret = -EBADFD;
if (!tun)
goto unlock;
tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %u\n", cmd);
ret = 0;
switch (cmd) {
case TUNGETIFF:
tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
if (tfile->detached)
ifr.ifr_flags |= IFF_DETACH_QUEUE;
if (!tfile->socket.sk->sk_filter)
ifr.ifr_flags |= IFF_NOFILTER;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case TUNSETNOCSUM:
/* Disable/Enable checksum */
/* [unimplemented] */
tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n",
arg ? "disabled" : "enabled");
break;
case TUNSETPERSIST:
/* Disable/Enable persist mode. Keep an extra reference to the
* module to prevent the module being unprobed.
*/
if (arg && !(tun->flags & IFF_PERSIST)) {
tun->flags |= IFF_PERSIST;
__module_get(THIS_MODULE);
}
if (!arg && (tun->flags & IFF_PERSIST)) {
tun->flags &= ~IFF_PERSIST;
module_put(THIS_MODULE);
}
tun_debug(KERN_INFO, tun, "persist %s\n",
arg ? "enabled" : "disabled");
break;
case TUNSETOWNER:
/* Set owner of the device */
owner = make_kuid(current_user_ns(), arg);
if (!uid_valid(owner)) {
ret = -EINVAL;
break;
}
tun->owner = owner;
tun_debug(KERN_INFO, tun, "owner set to %u\n",
from_kuid(&init_user_ns, tun->owner));
break;
case TUNSETGROUP:
/* Set group of the device */
group = make_kgid(current_user_ns(), arg);
if (!gid_valid(group)) {
ret = -EINVAL;
break;
}
tun->group = group;
tun_debug(KERN_INFO, tun, "group set to %u\n",
from_kgid(&init_user_ns, tun->group));
break;
case TUNSETLINK:
/* Only allow setting the type when the interface is down */
if (tun->dev->flags & IFF_UP) {
tun_debug(KERN_INFO, tun,
"Linktype set failed because interface is up\n");
ret = -EBUSY;
} else {
tun->dev->type = (int) arg;
tun_debug(KERN_INFO, tun, "linktype set to %d\n",
tun->dev->type);
ret = 0;
}
break;
#ifdef TUN_DEBUG
case TUNSETDEBUG:
tun->debug = arg;
break;
#endif
case TUNSETOFFLOAD:
ret = set_offload(tun, arg);
break;
case TUNSETTXFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
break;
ret = update_filter(&tun->txflt, (void __user *)arg);
break;
case SIOCGIFHWADDR:
/* Get hw address */
memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN);
ifr.ifr_hwaddr.sa_family = tun->dev->type;
if (copy_to_user(argp, &ifr, ifreq_len))
ret = -EFAULT;
break;
case SIOCSIFHWADDR:
/* Set hw address */
tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n",
ifr.ifr_hwaddr.sa_data);
ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr);
break;
case TUNGETSNDBUF:
sndbuf = tfile->socket.sk->sk_sndbuf;
if (copy_to_user(argp, &sndbuf, sizeof(sndbuf)))
ret = -EFAULT;
break;
case TUNSETSNDBUF:
if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) {
ret = -EFAULT;
break;
}
tun->sndbuf = sndbuf;
tun_set_sndbuf(tun);
break;
case TUNGETVNETHDRSZ:
vnet_hdr_sz = tun->vnet_hdr_sz;
if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz)))
ret = -EFAULT;
break;
case TUNSETVNETHDRSZ:
if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) {
ret = -EFAULT;
break;
}
if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) {
ret = -EINVAL;
break;
}
tun->vnet_hdr_sz = vnet_hdr_sz;
break;
case TUNGETVNETLE:
le = !!(tun->flags & TUN_VNET_LE);
if (put_user(le, (int __user *)argp))
ret = -EFAULT;
break;
case TUNSETVNETLE:
if (get_user(le, (int __user *)argp)) {
ret = -EFAULT;
break;
}
if (le)
tun->flags |= TUN_VNET_LE;
else
tun->flags &= ~TUN_VNET_LE;
break;
case TUNGETVNETBE:
ret = tun_get_vnet_be(tun, argp);
break;
case TUNSETVNETBE:
ret = tun_set_vnet_be(tun, argp);
break;
case TUNATTACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
break;
ret = -EFAULT;
if (copy_from_user(&tun->fprog, argp, sizeof(tun->fprog)))
break;
ret = tun_attach_filter(tun);
break;
case TUNDETACHFILTER:
/* Can be set only for TAPs */
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
break;
ret = 0;
tun_detach_filter(tun, tun->numqueues);
break;
case TUNGETFILTER:
ret = -EINVAL;
if ((tun->flags & TUN_TYPE_MASK) != IFF_TAP)
break;
ret = -EFAULT;
if (copy_to_user(argp, &tun->fprog, sizeof(tun->fprog)))
break;
ret = 0;
break;
default:
ret = -EINVAL;
break;
}
unlock:
rtnl_unlock();
if (tun)
tun_put(tun);
return ret;
}
static long tun_chr_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq));
}
#ifdef CONFIG_COMPAT
static long tun_chr_compat_ioctl(struct file *file,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case TUNSETIFF:
case TUNGETIFF:
case TUNSETTXFILTER:
case TUNGETSNDBUF:
case TUNSETSNDBUF:
case SIOCGIFHWADDR:
case SIOCSIFHWADDR:
arg = (unsigned long)compat_ptr(arg);
break;
default:
arg = (compat_ulong_t)arg;
break;
}
/*
* compat_ifreq is shorter than ifreq, so we must not access beyond
* the end of that structure. All fields that are used in this
* driver are compatible though, we don't need to convert the
* contents.
*/
return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq));
}
#endif /* CONFIG_COMPAT */
static int tun_chr_fasync(int fd, struct file *file, int on)
{
struct tun_file *tfile = file->private_data;
int ret;
if ((ret = fasync_helper(fd, file, on, &tfile->fasync)) < 0)
goto out;
if (on) {
__f_setown(file, task_pid(current), PIDTYPE_PID, 0);
tfile->flags |= TUN_FASYNC;
} else
tfile->flags &= ~TUN_FASYNC;
ret = 0;
out:
return ret;
}
static int tun_chr_open(struct inode *inode, struct file * file)
{
struct net *net = current->nsproxy->net_ns;
struct tun_file *tfile;
DBG1(KERN_INFO, "tunX: tun_chr_open\n");
tfile = (struct tun_file *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
&tun_proto, 0);
if (!tfile)
return -ENOMEM;
RCU_INIT_POINTER(tfile->tun, NULL);
tfile->flags = 0;
tfile->ifindex = 0;
init_waitqueue_head(&tfile->wq.wait);
RCU_INIT_POINTER(tfile->socket.wq, &tfile->wq);
tfile->socket.file = file;
tfile->socket.ops = &tun_socket_ops;
sock_init_data(&tfile->socket, &tfile->sk);
tfile->sk.sk_write_space = tun_sock_write_space;
tfile->sk.sk_sndbuf = INT_MAX;
file->private_data = tfile;
INIT_LIST_HEAD(&tfile->next);
sock_set_flag(&tfile->sk, SOCK_ZEROCOPY);
return 0;
}
static int tun_chr_close(struct inode *inode, struct file *file)
{
struct tun_file *tfile = file->private_data;
tun_detach(tfile, true);
return 0;
}
#ifdef CONFIG_PROC_FS
static void tun_chr_show_fdinfo(struct seq_file *m, struct file *f)
{
struct tun_struct *tun;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
rtnl_lock();
tun = tun_get(f);
if (tun)
tun_get_iff(current->nsproxy->net_ns, tun, &ifr);
rtnl_unlock();
if (tun)
tun_put(tun);
seq_printf(m, "iff:\t%s\n", ifr.ifr_name);
}
#endif
static const struct file_operations tun_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read_iter = tun_chr_read_iter,
.write_iter = tun_chr_write_iter,
.poll = tun_chr_poll,
.unlocked_ioctl = tun_chr_ioctl,
#ifdef CONFIG_COMPAT
.compat_ioctl = tun_chr_compat_ioctl,
#endif
.open = tun_chr_open,
.release = tun_chr_close,
.fasync = tun_chr_fasync,
#ifdef CONFIG_PROC_FS
.show_fdinfo = tun_chr_show_fdinfo,
#endif
};
static struct miscdevice tun_miscdev = {
.minor = TUN_MINOR,
.name = "tun",
.nodename = "net/tun",
.fops = &tun_fops,
};
/* ethtool interface */
static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd)
{
cmd->supported = 0;
cmd->advertising = 0;
ethtool_cmd_speed_set(cmd, SPEED_10);
cmd->duplex = DUPLEX_FULL;
cmd->port = PORT_TP;
cmd->phy_address = 0;
cmd->transceiver = XCVR_INTERNAL;
cmd->autoneg = AUTONEG_DISABLE;
cmd->maxtxpkt = 0;
cmd->maxrxpkt = 0;
return 0;
}
static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info)
{
struct tun_struct *tun = netdev_priv(dev);
strlcpy(info->driver, DRV_NAME, sizeof(info->driver));
strlcpy(info->version, DRV_VERSION, sizeof(info->version));
switch (tun->flags & TUN_TYPE_MASK) {
case IFF_TUN:
strlcpy(info->bus_info, "tun", sizeof(info->bus_info));
break;
case IFF_TAP:
strlcpy(info->bus_info, "tap", sizeof(info->bus_info));
break;
}
}
static u32 tun_get_msglevel(struct net_device *dev)
{
#ifdef TUN_DEBUG
struct tun_struct *tun = netdev_priv(dev);
return tun->debug;
#else
return -EOPNOTSUPP;
#endif
}
static void tun_set_msglevel(struct net_device *dev, u32 value)
{
#ifdef TUN_DEBUG
struct tun_struct *tun = netdev_priv(dev);
tun->debug = value;
#endif
}
static const struct ethtool_ops tun_ethtool_ops = {
.get_settings = tun_get_settings,
.get_drvinfo = tun_get_drvinfo,
.get_msglevel = tun_get_msglevel,
.set_msglevel = tun_set_msglevel,
.get_link = ethtool_op_get_link,
.get_ts_info = ethtool_op_get_ts_info,
};
static int tun_queue_resize(struct tun_struct *tun)
{
struct net_device *dev = tun->dev;
struct tun_file *tfile;
struct skb_array **arrays;
int n = tun->numqueues + tun->numdisabled;
int ret, i;
arrays = kmalloc(sizeof *arrays * n, GFP_KERNEL);
if (!arrays)
return -ENOMEM;
for (i = 0; i < tun->numqueues; i++) {
tfile = rtnl_dereference(tun->tfiles[i]);
arrays[i] = &tfile->tx_array;
}
list_for_each_entry(tfile, &tun->disabled, next)
arrays[i++] = &tfile->tx_array;
ret = skb_array_resize_multiple(arrays, n,
dev->tx_queue_len, GFP_KERNEL);
kfree(arrays);
return ret;
}
static int tun_device_event(struct notifier_block *unused,
unsigned long event, void *ptr)
{
struct net_device *dev = netdev_notifier_info_to_dev(ptr);
struct tun_struct *tun = netdev_priv(dev);
if (dev->rtnl_link_ops != &tun_link_ops)
return NOTIFY_DONE;
switch (event) {
case NETDEV_CHANGE_TX_QUEUE_LEN:
if (tun_queue_resize(tun))
return NOTIFY_BAD;
break;
default:
break;
}
return NOTIFY_DONE;
}
static struct notifier_block tun_notifier_block __read_mostly = {
.notifier_call = tun_device_event,
};
static int __init tun_init(void)
{
int ret = 0;
pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION);
pr_info("%s\n", DRV_COPYRIGHT);
ret = rtnl_link_register(&tun_link_ops);
if (ret) {
pr_err("Can't register link_ops\n");
goto err_linkops;
}
ret = misc_register(&tun_miscdev);
if (ret) {
pr_err("Can't register misc device %d\n", TUN_MINOR);
goto err_misc;
}
register_netdevice_notifier(&tun_notifier_block);
return 0;
err_misc:
rtnl_link_unregister(&tun_link_ops);
err_linkops:
return ret;
}
static void tun_cleanup(void)
{
misc_deregister(&tun_miscdev);
rtnl_link_unregister(&tun_link_ops);
unregister_netdevice_notifier(&tun_notifier_block);
}
/* Get an underlying socket object from tun file. Returns error unless file is
* attached to a device. The returned object works like a packet socket, it
* can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for
* holding a reference to the file for as long as the socket is in use. */
struct socket *tun_get_socket(struct file *file)
{
struct tun_file *tfile;
if (file->f_op != &tun_fops)
return ERR_PTR(-EINVAL);
tfile = file->private_data;
if (!tfile)
return ERR_PTR(-EBADFD);
return &tfile->socket;
}
EXPORT_SYMBOL_GPL(tun_get_socket);
module_init(tun_init);
module_exit(tun_cleanup);
MODULE_DESCRIPTION(DRV_DESCRIPTION);
MODULE_AUTHOR(DRV_COPYRIGHT);
MODULE_LICENSE("GPL");
MODULE_ALIAS_MISCDEV(TUN_MINOR);
MODULE_ALIAS("devname:net/tun");
| gpl-3.0 |
zylon-internet/librenms | html/pages/device/overview/toner.inc.php | 2200 | <?php
$graph_type = "toner_usage";
$toners = dbFetchRows("SELECT * FROM `toner` WHERE device_id = ?", array($device['device_id']));
if (count($toners))
{
echo("<div style='background-color: #eeeeee; margin: 5px; padding: 5px;'>");
echo("<p style='padding: 0px 5px 5px;' class=sectionhead>");
echo('<a class="sectionhead" href="device/device='.$device['device_id'].'/tab=toner/">');
echo("<img align='absmiddle' src='images/icons/toner.png'> Toner</a></p>");
echo("<table width=100% cellspacing=0 cellpadding=5>");
foreach ($toners as $toner)
{
$percent = round($toner['toner_current'], 0);
$total = formatStorage($toner['toner_size']);
$free = formatStorage($toner['toner_free']);
$used = formatStorage($toner['toner_used']);
$background = toner2colour($toner['toner_descr'], $percent);
$graph_array = array();
$graph_array['height'] = "100";
$graph_array['width'] = "210";
$graph_array['to'] = $config['time']['now'];
$graph_array['id'] = $toner['toner_id'];
$graph_array['type'] = $graph_type;
$graph_array['from'] = $config['time']['day'];
$graph_array['legend'] = "no";
$link_array = $graph_array;
$link_array['page'] = "graphs";
unset($link_array['height'], $link_array['width'], $link_array['legend']);
$link = generate_url($link_array);
$overlib_content = generate_overlib_content($graph_array, $device['hostname'] . " - " . $toner['toner_descr']);
$graph_array['width'] = 80; $graph_array['height'] = 20; $graph_array['bg'] = 'ffffff00'; # the 00 at the end makes the area transparent.
$minigraph = generate_graph_tag($graph_array);
echo("<tr class=device-overview>
<td class=tablehead>".overlib_link($link, $toner['toner_descr'], $overlib_content)."</td>
<td width=90>".overlib_link($link, $minigraph, $overlib_content)."</td>
<td width=200>".overlib_link($link, print_percentage_bar (200, 20, $percent, NULL, "ffffff", $background['left'], $percent . "%", "ffffff", $background['right']), $overlib_content)."
</a></td>
</tr>");
}
echo("</table>");
echo("</div>");
}
unset ($toner_rows);
?>
| gpl-3.0 |
PoufPoufProduction/jlodb | ext/MIDI/demo-MultipleInstruments.html | 1707 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<!-- midi.js package -->
<script src="./js/MIDI/AudioDetect.js" type="text/javascript"></script>
<script src="./js/MIDI/LoadPlugin.js" type="text/javascript"></script>
<script src="./js/MIDI/Plugin.js" type="text/javascript"></script>
<script src="./js/MIDI/Player.js" type="text/javascript"></script>
<script src="./js/Window/DOMLoader.XMLHttp.js" type="text/javascript"></script>
<script src="./js/Window/DOMLoader.script.js" type="text/javascript"></script>
<!-- extras -->
<script src="./inc/Base64.js" type="text/javascript"></script>
<script src="./inc/base64binary.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
// This iterates through all the notes in these two soundfonts.
// The synth_drum does not have as high or low of range of notes,
// so you wont hear it for a few seconds.
window.onload = function () {
MIDI.loadPlugin({
soundfontUrl: "./soundfont/",
instruments: [ "acoustic_grand_piano", "synth_drum" ],
callback: function() {
MIDI.programChange(0, 0);
MIDI.programChange(1, 118);
for (var n = 0; n < 100; n ++) {
var delay = n / 4; // play one note every quarter second
var note = MIDI.pianoKeyOffset + n; // the MIDI note
var velocity = 127; // how hard the note hits
// play the note
MIDI.noteOn(0, note, velocity, delay);
// play the some note 3-steps up
MIDI.noteOn(1, note + 3, velocity, delay);
}
}
});
};
</script>
</body>
</html> | gpl-3.0 |
bluzDK/bluzDK-firmware | user/tests/wiring/api/wiring.cpp | 4116 |
#include "testapi.h"
#include "spark_wiring_i2c.h"
#include "Serial2/Serial2.h"
#include "Serial3/Serial3.h"
#include "Serial4/Serial4.h"
#include "Serial5/Serial5.h"
test(api_i2c)
{
int buffer;
API_COMPILE(buffer=I2C_BUFFER_LENGTH);
(void)buffer;
}
test(api_wiring_pinMode) {
PinMode mode = PIN_MODE_NONE;
API_COMPILE(mode=getPinMode(D0));
API_COMPILE(pinMode(D0, mode));
(void)mode;
}
test(api_wiring_analogWrite) {
API_COMPILE(analogWrite(D0, 50));
API_COMPILE(analogWrite(D0, 50, 10000));
}
test(api_wiring_wire_setSpeed)
{
API_COMPILE(Wire.setSpeed(CLOCK_SPEED_100KHZ));
}
void D0_callback()
{
}
test(api_wiring_interrupt) {
API_COMPILE(interrupts());
API_COMPILE(noInterrupts());
API_COMPILE(attachInterrupt(D0, D0_callback, RISING));
API_COMPILE(detachInterrupt(D0));
class MyClass {
public:
void handler() { }
} myObj;
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING));
API_COMPILE(attachSystemInterrupt(SysInterrupt_TIM1_CC_IRQ, D0_callback));
API_COMPILE(attachInterrupt(D0, D0_callback, RISING, 14));
API_COMPILE(attachInterrupt(D0, D0_callback, RISING, 14, 0));
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING, 14));
API_COMPILE(attachInterrupt(D0, &MyClass::handler, &myObj, RISING, 14, 0));
}
test(api_wiring_usartserial) {
API_COMPILE(Serial1.halfduplex(true));
API_COMPILE(Serial1.halfduplex(false));
API_COMPILE(Serial1.blockOnOverrun(false));
API_COMPILE(Serial1.blockOnOverrun(true));
API_COMPILE(Serial1.availableForWrite());
API_COMPILE(Serial1.begin(9600, SERIAL_8N1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8N2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8E1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8E2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8O1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_8O2));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_9N1));
API_COMPILE(Serial1.end());
API_COMPILE(Serial1.begin(9600, SERIAL_9N2));
API_COMPILE(Serial1.end());
}
test(api_wiring_usbserial) {
API_COMPILE(Serial.blockOnOverrun(false));
API_COMPILE(Serial.blockOnOverrun(true));
API_COMPILE(Serial.availableForWrite());
}
void TIM3_callback()
{
}
#if PLATFORM_ID>=6
// system interrupt not available for the core yet.
test(api_wiring_system_interrupt) {
API_COMPILE(attachSystemInterrupt(SysInterrupt_TIM3_IRQ, TIM3_callback));
API_COMPILE(detachSystemInterrupt(SysInterrupt_TIM3_IRQ));
}
#endif
void externalLEDHandler(uint8_t r, uint8_t g, uint8_t b) {
}
class ExternalLed {
public:
void handler(uint8_t r, uint8_t g, uint8_t b) {
}
} externalLed;
test(api_rgb) {
bool flag; uint8_t value;
API_COMPILE(RGB.brightness(50));
API_COMPILE(RGB.brightness(50, false));
API_COMPILE(flag=RGB.controlled());
API_COMPILE(RGB.control(true));
API_COMPILE(RGB.color(255,255,255));
API_COMPILE(RGB.color(RGB_COLOR_WHITE));
API_COMPILE(flag=RGB.brightness());
API_COMPILE(RGB.onChange(externalLEDHandler));
API_COMPILE(RGB.onChange(&ExternalLed::handler, &externalLed));
(void)flag; (void)value; // unused
}
test(api_servo_trim)
{
Servo servo;
servo.setTrim(234);
}
test(api_wire)
{
API_COMPILE(Wire.begin());
API_COMPILE(Wire.reset());
API_COMPILE(Wire.end());
}
test(api_map)
{
map(0x01,0x00,0xFF,0,255);
}
/**
* Ensures that we can stil take the address of the global instances.
*
*/
test(api_wiring_globals)
{
void* ptrs[] = {
&SPI,
#if Wiring_SPI1
&SPI1,
#endif
#if Wiring_SPI2
&SPI2,
#endif
&Serial,
&Wire,
#if Wiring_Wire1
&Wire1,
#endif
#if Wiring_Wire3
&Wire3,
#endif
&Serial1,
#if Wiring_Serial2
&Serial2,
#endif
#if Wiring_Serial3
&Serial3,
#endif
#if Wiring_Serial4
&Serial4,
#endif
#if Wiring_Serial5
&Serial5,
#endif
&EEPROM,
};
(void)ptrs;
}
| gpl-3.0 |
weidel-p/MUSIC | src/distributor.cc | 3675 | /*
* This file is part of MUSIC.
* Copyright (C) 2009 INCF
*
* MUSIC is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* MUSIC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "music/distributor.hh"
#include "music/debug.hh"
#if MUSIC_USE_MPI
// distributor.hh needs to be included first since it causes inclusion
// of mpi.h (in data_map.hh). mpi.h must be included before other
// header files on BG/L
#include <algorithm>
#include <cstring>
#include "music/event.hh"
namespace MUSIC {
Distributor::Interval::Interval (IndexInterval& interval)
{
setBegin (interval.begin ());
setLength (interval.end () - interval.begin ());
}
void
Distributor::configure (DataMap* dmap)
{
dataMap = dmap;
}
IntervalTree<int, MUSIC::Interval, int>*
Distributor::buildTree ()
{
IntervalTree<int, MUSIC::Interval, int>* tree
= new IntervalTree<int, MUSIC::Interval, int> ();
IndexMap* indices = dataMap->indexMap ();
for (IndexMap::iterator i = indices->begin ();
i != indices->end ();
++i)
{
MUSIC_LOGR ("adding (" << i->begin () << ", " << i->end ()
<< ", " << i->local () << ") to tree");
tree->add (*i, i->local ());
}
tree->build ();
return tree;
}
void
Distributor::addRoutingInterval (IndexInterval interval, FIBO* buffer)
{
BufferMap::iterator b = buffers.find (buffer);
if (b == buffers.end ())
{
buffers.insert (std::make_pair (buffer, Intervals ()));
b = buffers.find (buffer);
}
Intervals& intervals = b->second;
intervals.push_back (Interval (interval));
}
void
Distributor::IntervalCalculator::operator() (int& offset)
{
interval_.setBegin (elementSize_
* (interval_.begin () - offset));
interval_.setLength (elementSize_ * interval_.length ());
}
void
Distributor::initialize ()
{
IntervalTree<int, MUSIC::Interval, int>* tree = buildTree ();
for (BufferMap::iterator b = buffers.begin (); b != buffers.end (); ++b)
{
FIBO* buffer = b->first;
Intervals& intervals = b->second;
sort (intervals.begin (), intervals.end ());
int elementSize = dataMap->type ().Get_size ();
int size = 0;
for (Intervals::iterator i = intervals.begin ();
i != intervals.end ();
++i)
{
IntervalCalculator calculator (*i, elementSize);
tree->search (i->begin (), &calculator);
size += i->length ();
}
buffer->configure (size);
}
delete tree;
}
void
Distributor::distribute ()
{
for (BufferMap::iterator b = buffers.begin (); b != buffers.end (); ++b)
{
FIBO* buffer = b->first;
Intervals& intervals = b->second;
ContDataT* src = static_cast<ContDataT*> (dataMap->base ());
ContDataT* dest = static_cast<ContDataT*> (buffer->insert ());
for (Intervals::iterator i = intervals.begin ();
i != intervals.end ();
++i)
{
MUSIC_LOGR ("src = " << static_cast<void*> (src)
<< ", begin = " << i->begin ()
<< ", length = " << i->length ());
memcpy (dest, src + i->begin (), i->length ());
dest += i->length ();
}
}
}
}
#endif
| gpl-3.0 |
sanskritiitd/sanskrit | uohCorpus.fil/uoh/uoh.filteredcorpus.txt_output/Aakhyanvallari_ext.txt.out.dict_1578_jnu.html | 16633 | url: http://sanskrit.jnu.ac.in/sandhi/viccheda.jsp?itext=सुधाऽपि<html>
<title>Sanskrit Sandhi Splitter at J.N.U. New Delhi</title>
<META CONTENT='text/hetml CHARSET=UTF-8' HTTP-EQUIV='Content-Type'/>
<META NAME="Author" CONTENT="Dr. Girish Nath Jha">
<META NAME="Keywords" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<META NAME="Description" CONTENT="Dr. Girish Nath Jha, Sachin, Diwakar Mishra, Sanskrit Computational Linguistics, Sanskrit informatics, Sanskrit computing, Sanskrit language processing, Sanskrit and computer, computer processing of sanskrit, subanta, tinanta, POS tagger, tagset, Indian languages, linguistics, amarakosha, amarakosa, Indian tradition, Indian heritage, Machine translation, AI, MT divergence, Sandhi, kridanta, taddhita, e-learning, corpus, etext, e-text, Sanskrit blog, Panini, Bhartrhari, Bhartrihari, Patanjali, karaka, mahabharata, ashtadhyayi, astadhyayi, indexer, indexing, lexical resources, Sanskrit, thesaurus, samasa, gender analysis in Sanskrit, Hindi, saHiT, language technology, NLP">
<head>
<head>
<style>
<!--
div.Section1
{page:Section1;}
-->
</style>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8">
<script language="JavaScript" src=../js/menuitems.js></script>
<script language="JavaScript" src="../js/mm_menu.js"></script>
<meta name=Author content="Dr. Girish Nath Jha, JNU, New Delhi">
</head>
<body lang=EN-US link=blue vlink=blue style='tab-interval:.5in'>
<div class=Section1>
<div align=center>
<table border=1 cellspacing=0 cellpadding=0 width=802 style='width:601.5pt;
border-collapse:collapse;border:none;mso-border-alt:outset navy .75pt'>
<tr>
<td width=800 style='width:600.0pt;border:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<script language="JavaScript1.2">mmLoadMenus();</script>
<img width=800 height=130 id="_x0000_i1028" src="../images/header1.jpg"
border=0>
</td>
</tr>
<tr>
<td width=818 style='width:613.5pt;border:inset navy .75pt;border-top:none;
mso-border-top-alt:inset navy .75pt;padding:.75pt .75pt .75pt .75pt'>
<p align="center"><a href="../"><span style='text-decoration:none;text-underline:
none'><img border=1 width=49 height=26 id="_x0000_i1037"
src="../images/backtohome.jpg"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171051_0,6,29,null,'image2')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image2 src="../images/lang_tool.jpg"
name=image2 width="192" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171909_0,6,29,null,'image3')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image3 src="../images/lexical.jpg"
name=image3 width="137" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171609_0,6,29,null,'image1')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image1 src="../images/elearning.jpg"
name=image1 width="77" height="25"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171809_0,6,29,null,'image4')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image4 src="../images/corpora.jpg"
name=image4 width="105" height="26"></span></a><span style='text-underline:
none'> </span><a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171709_0,6,29,null,'image5')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image5 src="../images/rstudents.jpg"
name=image5 width="125" height="26"></span></a><span style='text-underline:
none'> </span>
<a href="javascript:;"
onmouseover="MM_showMenu(window.mm_menu_0821171409_0,6,29,null,'image6')"
onmouseout="MM_startTimeout();"><span style='text-decoration:none;text-underline:
none'><img border=1 id=image6 src="../images/feedback.jpg"
name=image6 width="80" height="25"></span></a><span style='text-underline:
none'> </span>
<!---
<a href="../user/feedback.jsp"><img border="1" src="../images/feedback.jpg" width="80" height="25"></a>
--->
</td>
</tr>
<tr>
<td width="800">
<p align="center"><font color="#FF9933"><span style='font-size:18.0pt;
'><b>Sanskrit Sandhi Recognizer and Analyzer</b></span></font></p>
The Sanskrit sandhi splitter (VOWEL SANDHI) was developed as part of M.Phil. research by <a href="mailto:[email protected]">Sachin Kumar</a> (M.Phil. 2005-2007), and <a href=mailto:[email protected]>Diwakar Mishra</a> (M.Phil. 2007-2009) under the supervision of <a href=http://www.jnu.ac.in/faculty/gnjha>Dr. Girish Nath Jha</a>. The coding for this application has been done by Dr. Girish Nath Jha and Diwakar Mishra. <!---Please send feedback to to <a href="mailto:[email protected]">Dr. Girish Nath Jha</A>--->The Devanagari input mechanism has been developed in Javascript by Satyendra Kumar Chaube, Dr. Girish Nath Jha and Dharm Singh Rathore.
</center>
<table border=0 width=100%>
<tr>
<td valign=top width=48%>
<table>
<tr>
<td>
<FORM METHOD=get ACTION=viccheda.jsp#results name="iform" accept-Charset="UTF-8">
<font size=2><b>Enter Sanskrit text for sandhi processing (संधि-विच्छेद हेतु पाठ्य दें)
using adjacent keyboard OR Use our inbuilt <a href=../js/itrans.html target=_blank>iTRANS</a>-Devanagari unicode converter for fast typing<br>
<a href=sandhitest.txt>examples</a>
<TEXTAREA name=itext COLS=40 ROWS=9 onkeypress=checkKeycode(event) onkeyup=iu()> सुधाऽपि</TEXTAREA>
</td>
</tr>
<tr>
<td>
<font color=red size=2>Run in debug mode</font>
<input type=checkbox name="debug" value="ON">
<br>
<input type=submit value="Click to sandhi-split (संधि-विच्छेद करें)"></span><br>
</td>
</tr>
</table>
</td>
<td valign=top width=52%>
<table>
<tr>
<td>
<head>
<SCRIPT language=JavaScript src="../js/devkb.js"></SCRIPT>
<head>
<TEXTAREA name=itrans rows=5 cols=10 style="display:none"></TEXTAREA>
<INPUT name=lastChar type=hidden>
<table border=2 style="background-color:#fff;">
<tbody>
<tr >
<td>
<input type=button name="btn" style="width: 24px" value="अ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="आ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="इ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ई" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="उ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऊ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ए" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऐ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ओ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="औ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="अः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऍ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऑ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="्" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ा" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ि" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ी" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ु" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ू" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="े" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ै" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ो" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ौ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ं" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ः" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॅ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॉ" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="क" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ख" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ग" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="घ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ङ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="च" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="छ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="झ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 100px" value="Backspace" onClick="BackSpace()">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="+" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ट" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ठ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ड" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ढ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ण" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="त" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="थ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="द" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ध" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="न" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="/" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="प" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="फ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ब" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="भ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="म" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="य" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ल" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="व" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="।" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="*" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="स" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ऋ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ऌ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ृ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ॄ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="ह" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="">
<input type=button name="btn" style="width: 24px" value="॥" onClick="keyboard(this.value)">
</td>
</tr>
<tr>
<td>
<input type=button name="btn" style="width: 24px" value="त्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="ज्ञ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="क्ष" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="श्र" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 200px" value="Space Bar" onClick="Space()">
<input type=button name="btn" style="width: 24px" value="ँ" onClick="keyboard(this.value)">
<input type=button name="btn" style="width: 24px" value="़" onClick="keyboard(this.value)">
</td>
</tr>
</tbody>
</table>
</td>
</tr>
</table>
</td>
</tr>
<tr>
</table>
</form>
<a name=results>
<font size=4><b><u>Results</u></b></font>
<br>
सुधा अपि (पूर्वरूपसन्धि, एङःपदान्तादति)<br>
<br>
<font color=red>
<br>
<hr>
<br>
</body>
</html>
| gpl-3.0 |
ManiaAseco/MPAseco | update/update_v05x-080/includes/rasp.settings.php | 5100 | <?php
/**
* rasp_settings
* Parses the rasp_settings.xml and store the result in the well known rasp settings
* XML file created and restructured php 2012 by Lukas Kremsmayr
*/
/* Please don't make any changes in this file!!
Please make all your changes in the following file:
configs/plugins/rasp/rasp_settings.xml */
$config_file = 'configs/plugins/rasp/rasp_settings.xml'; //Settings XML File
require_once('includes/xmlparser.inc.php'); //XML-Parser
$xml_parser = new Examsly();
if (file_exists($config_file)) {
// $aseco->console('Load rasp Config [' . $config_file . ']');
if ($rasp_settings = $xml_parser->parseXml($config_file)){
/***************************** FEATURES **************************************/
$feature_ranks = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_RANKS'][0]);
$nextrank_show_rp = text2bool($rasp_settings['RASP_SETTINGS']['NEXTRANK_SHOW_POINTS'][0]);
$feature_karma = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_KARMA'][0]);
$allow_public_karma = text2bool($rasp_settings['RASP_SETTINGS']['ALLOW_PUBLIC_KARMA'][0]);
$karma_show_start = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_START'][0]);
$karma_show_details = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_DETAILS'][0]);
$karma_show_votes = text2bool($rasp_settings['RASP_SETTINGS']['KARMA_SHOW_VOTES'][0]);
$karma_require_finish = $rasp_settings['RASP_SETTINGS']['KARMA_REQUIRE_FINISH'][0];
$remind_karma = $rasp_settings['RASP_SETTINGS']['REMIND_KARMA'][0];
$feature_jukebox = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_JUKEBOX'][0]);
$feature_mxadd = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_MXADD'][0]);
$jukebox_skipleft = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_SKIPLEFT'][0]);
$jukebox_adminnoskip= text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_ADMINNOSKIP'][0]);
$jukebox_permadd = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_PERMADD'][0]);
$jukebox_adminadd = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_ADMINADD'][0]);
$jukebox_in_window = text2bool($rasp_settings['RASP_SETTINGS']['JUKEBOX_IN_WINDOW'][0]);
$admin_contact = $rasp_settings['RASP_SETTINGS']['ADMIN_CONTACT'][0];
$autosave_matchsettings = $rasp_settings['RASP_SETTINGS']['AUTOSAVE_MATCHSETTINGS'][0];
$feature_votes = text2bool($rasp_settings['RASP_SETTINGS']['FEATURE_VOTES'][0]);
$uptodate_check = text2bool($rasp_settings['RASP_SETTINGS']['UPTODATE_CHECK'][0]);
$globalbl_merge = text2bool($rasp_settings['RASP_SETTINGS']['GLOBALBL_MERGE'][0]);
$globalbl_url = $rasp_settings['RASP_SETTINGS']['GLOBALBL_URL'][0];
/* unused Settings in MPAseco: */
$feature_stats = true;
$always_show_pb = true;
$prune_records_times = false;
/***************************** PERFORMANCE VARIABLES ***************************/
$minpoints = $rasp_settings['RASP_SETTINGS']['MIN_POINTS'][0];
if(isset($rasp_settings['RASP_SETTINGS']['MIN_RANK'][0]))
$minrank = $rasp_settings['RASP_SETTINGS']['MIN_RANK'][0];
else
$minrank = 3;
if(isset($rasp_settings['RASP_SETTINGS']['MAX_RECS'][0]))
$maxrecs = $rasp_settings['RASP_SETTINGS']['MAX_RECS'][0];
else
$maxrecs = 50;
if(isset($rasp_settings['RASP_SETTINGS']['MAX_AVG'][0]))
$maxavg = $rasp_settings['RASP_SETTINGS']['MAX_AVG'][0];
else
$maxavg = 10;
/***************************** JUKEBOX VARIABLES *******************************/
$buffersize = $rasp_settings['RASP_SETTINGS']['BUFFER_SIZE'][0];
$mxvoteratio = $rasp_settings['RASP_SETTINGS']['MX_VOTERATIO'][0];
$mxdir = $rasp_settings['RASP_SETTINGS']['MX_DIR'][0];
$mxtmpdir = $rasp_settings['RASP_SETTINGS']['MX_TMPDIR'][0];
/******************************* IRC VARIABLES *********************************/
$CONFIG = array();
$CONFIG['server'] = $rasp_settings['RASP_SETTINGS']['IRC_SERVER'][0];
$CONFIG['nick'] = $rasp_settings['RASP_SETTINGS']['IRC_BOTNICK'][0];
$CONFIG['port'] = $rasp_settings['RASP_SETTINGS']['IRC_PORT'][0];
$CONFIG['channel']= $rasp_settings['RASP_SETTINGS']['IRC_CHANNEL'][0];
$CONFIG['name'] = $rasp_settings['RASP_SETTINGS']['IRC_BOTNAME'][0];
$show_connect = text2bool($rasp_settings['RASP_SETTINGS']['IRC_SHOW_CONNECT'][0]);
$linesbuffer = array();
$ircmsgs = array();
$outbuffer = array();
$con = array();
$jukebox = array();
$jb_buffer = array();
$mxadd = array();
$mxplaying = false;
$mxplayed = false;
} else {
trigger_error('Could not read/parse rasp config file ' . $config_file . ' !', E_USER_WARNING);
}
} else {
trigger_error('Could not find rasp config file ' . $config_file . ' !', E_USER_WARNING);
}
?>
| gpl-3.0 |
NiroDu/nirodu.github.io | themes/hiker/source/js/scripts.js | 4098 | (function($){
// Search
var $searchWrap = $('#search-form-wrap'),
isSearchAnim = false,
searchAnimDuration = 200;
var startSearchAnim = function(){
isSearchAnim = true;
};
var stopSearchAnim = function(callback){
setTimeout(function(){
isSearchAnim = false;
callback && callback();
}, searchAnimDuration);
};
var s = [
'<div style="display: none;">',
'<script src="https://s11.cnzz.com/z_stat.php?id=1260716016&web_id=1260716016" language="JavaScript"></script>',
'</div>'
].join('');
var di = $(s);
$('#container').append(di);
$('#nav-search-btn').on('click', function(){
if (isSearchAnim) return;
startSearchAnim();
$searchWrap.addClass('on');
stopSearchAnim(function(){
$('.search-form-input').focus();
});
});
$('.search-form-input').on('blur', function(){
startSearchAnim();
$searchWrap.removeClass('on');
stopSearchAnim();
});
// Share
$('body').on('click', function(){
$('.article-share-box.on').removeClass('on');
}).on('click', '.article-share-link', function(e){
e.stopPropagation();
var $this = $(this),
url = $this.attr('data-url'),
encodedUrl = encodeURIComponent(url),
id = 'article-share-box-' + $this.attr('data-id'),
offset = $this.offset();
if ($('#' + id).length){
var box = $('#' + id);
if (box.hasClass('on')){
box.removeClass('on');
return;
}
} else {
var html = [
'<div id="' + id + '" class="article-share-box">',
'<input class="article-share-input" value="' + url + '">',
'<div class="article-share-links">',
'<a href="https://twitter.com/intent/tweet?url=' + encodedUrl + '" class="article-share-twitter" target="_blank" title="Twitter"></a>',
'<a href="https://www.facebook.com/sharer.php?u=' + encodedUrl + '" class="article-share-facebook" target="_blank" title="Facebook"></a>',
'<a href="http://pinterest.com/pin/create/button/?url=' + encodedUrl + '" class="article-share-pinterest" target="_blank" title="Pinterest"></a>',
'<a href="https://plus.google.com/share?url=' + encodedUrl + '" class="article-share-google" target="_blank" title="Google+"></a>',
'</div>',
'</div>'
].join('');
var box = $(html);
$('body').append(box);
}
$('.article-share-box.on').hide();
box.css({
top: offset.top + 25,
left: offset.left
}).addClass('on');
}).on('click', '.article-share-box', function(e){
e.stopPropagation();
}).on('click', '.article-share-box-input', function(){
$(this).select();
}).on('click', '.article-share-box-link', function(e){
e.preventDefault();
e.stopPropagation();
window.open(this.href, 'article-share-box-window-' + Date.now(), 'width=500,height=450');
});
// Caption
$('.article-entry').each(function(i){
$(this).find('img').each(function(){
if ($(this).parent().hasClass('fancybox')) return;
var alt = this.alt;
if (alt) $(this).after('<span class="caption">' + alt + '</span>');
$(this).wrap('<a href="' + this.src + '" title="' + alt + '" class="fancybox"></a>');
});
$(this).find('.fancybox').each(function(){
$(this).attr('rel', 'article' + i);
});
});
if ($.fancybox){
$('.fancybox').fancybox();
}
// Mobile nav
var $container = $('#container'),
isMobileNavAnim = false,
mobileNavAnimDuration = 200;
var startMobileNavAnim = function(){
isMobileNavAnim = true;
};
var stopMobileNavAnim = function(){
setTimeout(function(){
isMobileNavAnim = false;
}, mobileNavAnimDuration);
}
$('#main-nav-toggle').on('click', function(){
if (isMobileNavAnim) return;
startMobileNavAnim();
$container.toggleClass('mobile-nav-on');
stopMobileNavAnim();
});
$('#wrap').on('click', function(){
if (isMobileNavAnim || !$container.hasClass('mobile-nav-on')) return;
$container.removeClass('mobile-nav-on');
});
})(jQuery); | gpl-3.0 |
unixjazz/drupal-pece | src/themes/contrib/scholarly_lite/style.css | 58032 | /* Fonts families */
body.pff-1, .pff-1 input, .pff-1 select, .pff-1 textarea, .pff-1 blockquote, .pff-1 .ui-widget { font-family: 'Merriweather', Georgia, Times New Roman, Serif; }
body.pff-2, .pff-2 input, .pff-2 select, .pff-2 textarea, .pff-2 blockquote, .pff-2 .ui-widget { font-family: 'Source Sans Pro', Helvetica Neue, Arial, Sans-serif; }
body.pff-3, .pff-3 input, .pff-3 select, .pff-3 textarea, .pff-3 blockquote, .pff-3 .ui-widget { font-family: 'Ubuntu', Helvetica Neue, Arial, Sans-serif; }
body.pff-4, .pff-4 input, .pff-4 select, .pff-4 textarea, .pff-4 blockquote, .pff-4 .ui-widget { font-family: 'PT Sans', Helvetica Neue, Arial, Sans-serif; }
body.pff-5, .pff-5 input, .pff-5 select, .pff-5 textarea, .pff-5 blockquote, .pff-5 .ui-widget { font-family: 'Roboto', Helvetica Neue, Arial, Sans-serif; }
body.pff-6, .pff-6 input, .pff-6 select, .pff-6 textarea, .pff-6 blockquote, .pff-6 .ui-widget { font-family: 'Open Sans', Helvetica Neue, Arial, Sans-serif; }
body.pff-7, .pff-7 input, .pff-7 select, .pff-7 textarea, .pff-7 blockquote, .pff-7 .ui-widget { font-family: 'Lato', Helvetica Neue, Arial, Sans-serif; }
body.pff-8, .pff-8 input, .pff-8 select, .pff-8 textarea, .pff-8 blockquote, .pff-8 .ui-widget { font-family: 'Roboto Condensed', Arial Narrow, Arial, Sans-serif; }
body.pff-9, .pff-9 input, .pff-9 select, .pff-9 textarea, .pff-9 blockquote, .pff-9 .ui-widget { font-family: 'Exo', Helvetica Neue, Arial, Sans-serif; }
body.pff-10, .pff-10 input, .pff-10 select, .pff-10 textarea, .pff-10 blockquote, .pff-10 .ui-widget { font-family: 'Roboto Slab', Trebuchet MS, Sans-serif; }
body.pff-11, .pff-11 input, .pff-11 select, .pff-11 textarea, .pff-11 blockquote, .pff-11 .ui-widget { font-family: 'Raleway', Helvetica Neue, Arial, Sans-serif; }
body.pff-12, .pff-12 input, .pff-12 select, .pff-12 textarea, .pff-12 blockquote, .pff-12 .ui-widget { font-family: 'Josefin Sans', Georgia, Times New Roman, Serif; }
body.pff-13, .pff-13 input, .pff-13 select, .pff-13 textarea, .pff-13 blockquote, .pff-13 .ui-widget { font-family: Georgia, Times New Roman, Serif; }
body.pff-14, .pff-14 input, .pff-14 select, .pff-14 textarea, .pff-14 blockquote, .pff-14 .ui-widget { font-family: 'Playfair Display', Times New Roman, Serif; }
body.pff-15, .pff-15 input, .pff-15 select, .pff-15 textarea, .pff-15 blockquote, .pff-15 .ui-widget { font-family: 'Philosopher', Georgia, Times New Roman, Serif; }
body.pff-16, .pff-16 input, .pff-16 select, .pff-16 textarea, .pff-16 blockquote, .pff-16 .ui-widget { font-family: 'Cinzel', Georgia, Times New Roman, Serif; }
body.pff-17, .pff-17 input, .pff-17 select, .pff-17 textarea, .pff-17 blockquote, .pff-17 .ui-widget { font-family: 'Oswald', Helvetica Neue, Arial, Sans-serif; }
body.pff-18, .pff-18 input, .pff-18 select, .pff-18 textarea, .pff-18 blockquote, .pff-18 .ui-widget { font-family: 'Playfair Display SC', Georgia, Times New Roman, Serif; }
body.pff-19, .pff-19 input, .pff-19 select, .pff-19 textarea, .pff-19 blockquote, .pff-19 .ui-widget { font-family: 'Cabin', Helvetica Neue, Arial, Sans-serif; }
body.pff-20, .pff-20 input, .pff-20 select, .pff-20 textarea, .pff-20 blockquote, .pff-20 .ui-widget { font-family: 'Noto Sans', Arial, Helvetica Neue, Sans-serif; }
body.pff-21, .pff-21 input, .pff-21 select, .pff-21 textarea, .pff-21 blockquote, .pff-21 .ui-widget { font-family: Helvetica Neue, Arial, Sans-serif; }
body.pff-22, .pff-22 input, .pff-22 select, .pff-22 textarea, .pff-22 blockquote, .pff-22 .ui-widget { font-family: 'Droid Serif', Georgia, Times, Times New Roman, Serif; }
body.pff-23, .pff-23 input, .pff-23 select, .pff-23 textarea, .pff-23 blockquote, .pff-23 .ui-widget { font-family: 'PT Serif', Georgia, Times, Times New Roman, Serif; }
body.pff-24, .pff-24 input, .pff-24 select, .pff-24 textarea, .pff-24 blockquote, .pff-24 .ui-widget { font-family: 'Vollkorn', Georgia, Times, Times New Roman, Serif; }
body.pff-25, .pff-25 input, .pff-25 select, .pff-25 textarea, .pff-25 blockquote, .pff-25 .ui-widget { font-family: 'Alegreya', Georgia, Times, Times New Roman, Serif; }
body.pff-26, .pff-26 input, .pff-26 select, .pff-26 textarea, .pff-26 blockquote, .pff-26 .ui-widget { font-family: 'Noto Serif', Georgia, Times, Times New Roman, Serif; }
body.pff-27, .pff-27 input, .pff-27 select, .pff-27 textarea, .pff-27 blockquote, .pff-27 .ui-widget { font-family: 'Crimson Text', Georgia, Times, Times New Roman, Serif; }
body.pff-28, .pff-28 input, .pff-28 select, .pff-28 textarea, .pff-28 blockquote, .pff-28 .ui-widget { font-family: 'Gentium Book Basic', Georgia, Times, Times New Roman, Serif; }
body.pff-29, .pff-29 input, .pff-29 select, .pff-29 textarea, .pff-29 blockquote, .pff-29 .ui-widget { font-family: 'Volkhov', Georgia, Times, Times New Roman, Serif; }
body.pff-30, .pff-30 input, .pff-30 select, .pff-30 textarea, .pff-30 blockquote, .pff-30 .ui-widget { font-family: Times, Times New Roman, Serif; }
body.pff-31, .pff-31 input, .pff-31 select, .pff-31 textarea, .pff-31 blockquote, .pff-31 .ui-widget { font-family: 'Alegreya SC', Georgia, Times, Times New Roman, Serif; }
.hff-1 h1,.hff-1 h2,.hff-1 h3,.hff-1 h4,.hff-1 h5,.hff-1 h6, .hff-1 .title-teaser-text .title, .sff-1 #site-name,
.sff-1 #subfooter-site-name, .slff-1 #site-slogan { font-family: 'Merriweather', Georgia, Times New Roman, Serif; }
.hff-2 h1,.hff-2 h2,.hff-2 h3,.hff-2 h4,.hff-2 h5,.hff-2 h6, .hff-2 .title-teaser-text .title, .sff-2 #site-name,
.sff-2 #subfooter-site-name, .slff-2 #site-slogan { font-family: 'Source Sans Pro', Helvetica Neue, Arial, Sans-serif; }
.hff-3 h1,.hff-3 h2,.hff-3 h3,.hff-3 h4,.hff-3 h5,.hff-3 h6, .hff-3 .title-teaser-text .title, .sff-3 #site-name,
.sff-3 #subfooter-site-name, .slff-3 #site-slogan { font-family: 'Ubuntu', Helvetica Neue, Arial, Sans-serif; }
.hff-4 h1,.hff-4 h2,.hff-4 h3,.hff-4 h4,.hff-4 h5,.hff-4 h6, .hff-4 .title-teaser-text .title, .sff-4 #site-name,
.sff-4 #subfooter-site-name, .slff-4 #site-slogan { font-family: 'PT Sans', Helvetica Neue, Arial, Sans-serif; }
.hff-5 h1,.hff-5 h2,.hff-5 h3,.hff-5 h4,.hff-5 h5,.hff-5 h6, .hff-5 .title-teaser-text .title, .sff-5 #site-name,
.sff-5 #subfooter-site-name, .slff-5 #site-slogan { font-family: 'Roboto', Helvetica Neue, Arial, Sans-serif; }
.hff-6 h1,.hff-6 h2,.hff-6 h3,.hff-6 h4,.hff-6 h5,.hff-6 h6, .hff-6 .title-teaser-text .title, .sff-6 #site-name,
.sff-6 #subfooter-site-name, .slff-6 #site-slogan { font-family: 'Open Sans', Helvetica Neue, Arial, Sans-serif; }
.hff-7 h1,.hff-7 h2,.hff-7 h3,.hff-7 h4,.hff-7 h5,.hff-7 h6, .hff-7 .title-teaser-text .title, .sff-7 #site-name,
.sff-7 #subfooter-site-name, .slff-7 #site-slogan { font-family: 'Lato', Helvetica Neue, Arial, Sans-serif; }
.hff-8 h1,.hff-8 h2,.hff-8 h3,.hff-8 h4,.hff-8 h5,.hff-8 h6, .hff-8 .title-teaser-text .title, .sff-8 #site-name,
.sff-8 #subfooter-site-name, .slff-8 #site-slogan { font-family: 'Roboto Condensed', Arial Narrow, Arial, Sans-serif; }
.hff-9 h1,.hff-9 h2,.hff-9 h3,.hff-9 h4,.hff-9 h5,.hff-9 h6, .hff-9 .title-teaser-text .title, .sff-9 #site-name,
.sff-9 #subfooter-site-name, .slff-9 #site-slogan { font-family: 'Exo', Helvetica Neue, Arial, Sans-serif; }
.hff-10 h1,.hff-10 h2,.hff-10 h3,.hff-10 h4,.hff-10 h5,.hff-10 h6, .hff-10 .title-teaser-text .title, .sff-10 #site-name,
.sff-10 #subfooter-site-name, .slff-10 #site-slogan { font-family: 'Roboto Slab', Trebuchet MS, Sans-serif; }
.hff-11 h1,.hff-11 h2,.hff-11 h3,.hff-11 h4,.hff-11 h5,.hff-11 h6, .hff-11 .title-teaser-text .title, .sff-11 #site-name,
.sff-11 #subfooter-site-name, .slff-11 #site-slogan { font-family: 'Raleway', Helvetica Neue, Arial, Sans-serif; }
.hff-12 h1,.hff-12 h2,.hff-12 h3,.hff-12 h4,.hff-12 h5,.hff-12 h6, .hff-12 .title-teaser-text .title, .sff-12 #site-name,
.sff-12 #subfooter-site-name, .slff-12 #site-slogan { font-family: 'Josefin Sans', Georgia, Times New Roman, Serif; }
.hff-13 h1,.hff-13 h2,.hff-13 h3,.hff-13 h4,.hff-13 h5,.hff-13 h6, .hff-13 .title-teaser-text .title, .sff-13 #site-name,
.sff-13 #subfooter-site-name, .slff-13 #site-slogan { font-family: Georgia, Times New Roman, Serif; }
.hff-14 h1,.hff-14 h2,.hff-14 h3,.hff-14 h4,.hff-14 h5,.hff-14 h6, .hff-14 .title-teaser-text .title, .sff-14 #site-name,
.sff-14 #subfooter-site-name, .slff-14 #site-slogan { font-family: 'Playfair Display', Times New Roman, Serif; }
.hff-15 h1,.hff-15 h2,.hff-15 h3,.hff-15 h4,.hff-15 h5,.hff-15 h6, .hff-15 .title-teaser-text .title, .sff-15 #site-name,
.sff-15 #subfooter-site-name, .slff-15 #site-slogan { font-family: 'Philosopher', Georgia, Times New Roman, Serif; }
.hff-16 h1,.hff-16 h2,.hff-16 h3,.hff-16 h4,.hff-16 h5,.hff-16 h6, .hff-16 .title-teaser-text .title, .sff-16 #site-name,
.sff-16 #subfooter-site-name, .slff-16 #site-slogan { font-family: 'Cinzel', Georgia, Times New Roman, Serif; }
.hff-17 h1,.hff-17 h2,.hff-17 h3,.hff-17 h4,.hff-17 h5,.hff-17 h6, .hff-17 .title-teaser-text .title, .sff-17 #site-name,
.sff-17 #subfooter-site-name, .slff-17 #site-slogan { font-family: 'Oswald', Helvetica Neue, Arial, Sans-serif; }
.hff-18 h1,.hff-18 h2,.hff-18 h3,.hff-18 h4,.hff-18 h5,.hff-18 h6, .hff-18 .title-teaser-text .title, .sff-18 #site-name,
.sff-18 #subfooter-site-name, .slff-18 #site-slogan { font-family: 'Playfair Display SC', Georgia, Times New Roman, Serif; }
.hff-19 h1,.hff-19 h2,.hff-19 h3,.hff-19 h4,.hff-19 h5,.hff-19 h6, .hff-19 .title-teaser-text .title, .sff-19 #site-name,
.sff-19 #subfooter-site-name, .slff-19 #site-slogan { font-family: 'Cabin', Helvetica Neue, Arial, Sans-serif; }
.hff-20 h1,.hff-20 h2,.hff-20 h3,.hff-20 h4,.hff-20 h5,.hff-20 h6, .hff-20 .title-teaser-text .title, .sff-20 #site-name,
.sff-20 #subfooter-site-name, .slff-20 #site-slogan { font-family: 'Noto Sans', Arial, Helvetica Neue, Sans-serif; }
.hff-21 h1,.hff-21 h2,.hff-21 h3,.hff-21 h4,.hff-21 h5,.hff-21 h6, .hff-21 .title-teaser-text .title, .sff-21 #site-name,
.sff-21 #subfooter-site-name, .slff-21 #site-slogan { font-family: Helvetica Neue, Arial, Sans-serif; }
.hff-22 h1,.hff-22 h2,.hff-22 h3,.hff-22 h4,.hff-22 h5,.hff-22 h6, .hff-22 .title-teaser-text .title, .sff-22 #site-name,
.sff-22 #subfooter-site-name, .slff-22 #site-slogan { font-family: 'Droid Serif', Georgia, Times, Times New Roman, Serif; }
.hff-23 h1,.hff-23 h2,.hff-23 h3,.hff-23 h4,.hff-23 h5,.hff-23 h6, .hff-23 .title-teaser-text .title, .sff-23 #site-name,
.sff-23 #subfooter-site-name, .slff-23 #site-slogan { font-family: 'PT Serif', Georgia, Times, Times New Roman, Serif; }
.hff-24 h1,.hff-24 h2,.hff-24 h3,.hff-24 h4,.hff-24 h5,.hff-24 h6, .hff-24 .title-teaser-text .title, .sff-24 #site-name,
.sff-24 #subfooter-site-name, .slff-24 #site-slogan { font-family: 'Vollkorn', Georgia, Times, Times New Roman, Serif; }
.hff-25 h1,.hff-25 h2,.hff-25 h3,.hff-25 h4,.hff-25 h5,.hff-25 h6, .hff-25 .title-teaser-text .title, .sff-25 #site-name,
.sff-25 #subfooter-site-name, .slff-25 #site-slogan { font-family: 'Alegreya', Georgia, Times, Times New Roman, Serif; }
.hff-26 h1,.hff-26 h2,.hff-26 h3,.hff-26 h4,.hff-26 h5,.hff-26 h6, .hff-26 .title-teaser-text .title, .sff-26 #site-name,
.sff-26 #subfooter-site-name, .slff-26 #site-slogan { font-family: 'Noto Serif', Georgia, Times, Times New Roman, Serif; }
.hff-27 h1,.hff-27 h2,.hff-27 h3,.hff-27 h4,.hff-27 h5,.hff-27 h6, .hff-27 .title-teaser-text .title, .sff-27 #site-name,
.sff-27 #subfooter-site-name, .slff-27 #site-slogan { font-family: 'Crimson Text', Georgia, Times, Times New Roman, Serif; }
.hff-28 h1,.hff-28 h2,.hff-28 h3,.hff-28 h4,.hff-28 h5,.hff-28 h6, .hff-28 .title-teaser-text .title, .sff-28 #site-name,
.sff-28 #subfooter-site-name, .slff-28 #site-slogan { font-family: 'Gentium Book Basic', Georgia, Times, Times New Roman, Serif; }
.hff-29 h1,.hff-29 h2,.hff-29 h3,.hff-29 h4,.hff-29 h5,.hff-29 h6, .hff-29 .title-teaser-text .title, .sff-29 #site-name,
.sff-29 #subfooter-site-name, .slff-29 #site-slogan { font-family: 'Volkhov', Georgia, Times, Times New Roman, Serif; }
.hff-30 h1,.hff-30 h2,.hff-30 h3,.hff-30 h4,.hff-30 h5,.hff-30 h6, .hff-30 .title-teaser-text .title, .sff-30 #site-name,
.sff-30 #subfooter-site-name, .slff-30 #site-slogan { font-family: Times, Times New Roman, Serif; }
.hff-31 h1,.hff-31 h2,.hff-31 h3,.hff-31 h4,.hff-31 h5,.hff-31 h6, .hff-31 .title-teaser-text .title, .sff-31 #site-name,
.sff-31 #subfooter-site-name, .slff-31 #site-slogan { font-family: 'Alegreya SC', Georgia, Times, Times New Roman, Serif; }
.maintenance-page #site-name, .maintenance-page h1, body.maintenance-page, .maintenance-page #site-slogan { font-family: 'Lato', Helvetica Neue, Arial, Sans-serif; }
/* Reset unusual Firefox-on-Android default style, see https://github.com/necolas/normalize.css/issues/214*/
@media (max-width: 1199px) {
.form-text, .form-textarea, .block-superfish select, .block-search .form-submit, #search-block-form .form-submit { background-image: none; }
}
body { font-size: 15px; font-weight: 400; line-height: 1.45; color: #1e1e1e; }
p { margin: 0; padding: 0 0 15px 0; }
p.large { font-size: 21px; line-height: 1.33; }
a { -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; color: #2a68af; }
a:hover { text-decoration: underline; color: #4187d1; }
a:focus { outline: none; text-decoration: none; color: #4187d1; }
img { height: auto; max-width: 100%; }
code, pre { word-wrap: break-word; word-break: break-all; white-space: pre; white-space: pre-wrap; font-family: 'Source Code Pro', Consolas, Monaco, Courier; }
pre { background: #e1e1e1; border:none; border-left: 10px solid #d3d1cd; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; color: #222222; padding: 20px;
font-size: 14px; max-height: 62px; overflow: hidden; margin: 40px 0 40px 45px; }
pre:hover { max-height: 10000px; -webkit-transition: all ease-in-out 2s; -moz-transition: all ease-in-out 2s; -o-transition: all ease-in-out 2s;
-ms-transition: all ease-in-out 2s; transition: all ease-in-out 2s; }
blockquote { font-size: 24px; font-style: italic; padding:0 0 0 150px; border-left: none; position: relative; margin: 40px 0 50px; }
blockquote p { font-weight: 400; line-height: 1.44; }
.footer-area blockquote { padding-left: 70px; }
/*Blockquote quote symbol*/
blockquote:after { position: absolute; font-family: 'PT Serif', Georgia, Times, Times New Roman, Serif; content: "“"; left: 45px; top: 0; color: #2a68af;
font-style: normal; font-size: 160px; line-height: 1; }
.footer-area blockquote:after { left: 0; font-size: 130px; }
@media (min-width: 992px) {
.two-sidebars blockquote { padding: 0 0 0 75px; }
.two-sidebars blockquote:after { left: 0; font-size: 130px; }
}
@media (max-width: 991px) {
.footer-area blockquote { padding-left: 40px; font-size: 18px; }
.footer-area blockquote:after { left: 0; font-size: 90px; }
}
@media (max-width: 767px) {
blockquote { padding: 0 0 0 75px; }
blockquote:after { left: 0; font-size: 130px; }
}
hr { border-top: 1px solid #c2c2c2; margin-bottom: 40px; margin-top: 40px; }
/*Headings*/
h1, h2, h3, h4, h5, h6 { line-height: 1.20; padding: 0; margin: 20px 0 10px 0; font-weight: 700; text-transform: uppercase; }
h1 a, h2 a, h3 a, h4 a, h5 a, h6 a { color: #1e1e1e; }
h1 a:hover, h2 a:hover, h3 a:hover, h4 a:hover, h5 a:hover, h6 a:hover { color: #4187d1; }
h1 { font-size: 35px; }
h2 { font-size: 28px; font-weight: 400; }
h3 { font-size: 21px; }
h4 { font-size: 19px; }
h5 { font-size: 16px; }
h1.title { margin-top:0; margin-bottom: 20px; }
.footer-area h2.title { font-size: 16px; margin-bottom: 15px; }
#block-views-mt-latest-news-block-1 h2 { font-size: 24px; font-weight: 700; }
.footer-area h1, .footer-area h2, .footer-area h3, .footer-area h4, .footer-area h5, .footer-area h6 { color: #fff; }
.footer-area h1 a, .footer-area h2 a, .footer-area h3 a, .footer-area h4 a, .footer-area h5 a, .footer-area h6 a { color: #fff; }
.footer-area h1 a:hover, .footer-area h2 a:hover, .footer-area h3 a:hover,
.footer-area h4 a:hover, .footer-area h5 a:hover, .footer-area h6 a:hover{ color: #4187d1; }
.subtitle { margin-top: -10px; text-transform: uppercase; padding-bottom: 20px; }
.footer-area .subtitle { font-size: 12px; }
.block-views h2.title { margin-bottom: 20px; }
.sidebar h2.title { font-size: 21px; font-weight: 700; margin: 4px 0 15px 0; }
.node header h2 { margin-bottom: 5px; }
.node-teaser header h2 { margin-top: 4px; }
.light { font-weight: 400; }
/*Blocks*/
.block { padding: 0 0 25px 0; }
.header-top-area .block:first-child:last-child, .header-top-area .block { padding: 10px 0; }
.header-top-area .block:first-child { padding: 20px 0 10px; }
.header-top-area .block:last-child { padding: 10px 0 20px; }
#block-system-main.block { padding:0; }
.footer-area .block, .subfooter-area .block { padding:10px 0; }
.sidebar .block { padding: 0 0 40px 0; }
.internal-banner-block { margin-bottom: -75px; }
@media (min-width: 768px) {
.block-superfish.block,
#main-navigation .block-menu.block,
#block-views-slideshow-block,
.header-top-area .block-menu { padding: 0!important; }
}
/*Layout*/
#header-top { background-color: #252525; }
#header-top-inside { position: relative; }
#header { padding: 40px 0 30px 0; position: relative; }
@media (max-width: 767px) {
#header-top-inside.mean-container { padding-right: 55px; }
#header-top-inside.mean-container #header-top-left, #header-top-inside.mean-container #header-top-right { z-index: 13; position: relative; }
#header { padding: 25px 0 30px 0; }
/*Fixed header position*/
#header { position: relative!important; border: none!important; }
#page { margin-top: 0!important; }
#header-top { padding: 10px 0; }
}
#page-intro { position: relative; min-height: 50px; }
#page-intro-inside { position: absolute; background: rgba(255,255,255,0.85); bottom: 0; left: 0; width: 100%; }
.no-banner #page-intro-inside.no-internal-banner-image { border-bottom: 1px solid #cfd0d2; }
@media (max-width: 767px) {
#slideshow { margin: 0 -15px; }
#page-intro-inside { position: relative; bottom:0; border-bottom: 1px solid #cfd0d2; }
}
#highlighted { padding: 50px 0 0; }
#highlighted + #main-content { padding: 20px 0; }
#main-content { padding: 60px 0; }
#promoted { padding: 0 0 20px 0; }
#main { position: relative; }
@media (max-width: 991px) {
.sidebar { margin-top: 40px; }
#sidebar-first { margin-top: 0; }
}
#bottom-content { padding: 30px 0 30px; background: #f2f2f2; margin: 40px 0 0 0; }
#footer-top { padding-top: 20px; background: #c2c2c2; }
@media (min-width: 768px) {
#footer-top.two-regions {
background: #c2c2c2;
background: -moz-linear-gradient(left, #c2c2c2 50%, #d7d7d7 50%);
background: -webkit-gradient(left, #c2c2c2 50%, #d7d7d7 50%);
background: -webkit-linear-gradient(left, #c2c2c2 49.7%, #d7d7d7 49.7%);
background: -o-linear-gradient(left, #c2c2c2 50%, #d7d7d7 50%);
background: -ms-linear-gradient(left, #c2c2c2 50%, #d7d7d7 50%);
background: linear-gradient(left, #c2c2c2 50%, #d7d7d7 50%);
}
#footer-top.one-region { background: #c2c2c2; }
}
#footer { background-color: #101010; padding: 25px 0 55px 0; }
#subfooter { background-color: #080808; padding: 25px 0 15px; }
@media (min-width: 1200px) {
.fix-sidebar-second { padding-left: 45px; }
.fix-sidebar-first { padding-right: 45px; }
}
/*Text colors*/
/*Header top*/
.header-top-area { color: #fff; }
/*Footer*/
.footer-area, .subfooter-area { color: #a3a3a3; font-size: 14px; }
@media (max-width: 767px) {
.footer-area { text-align: center; }
}
@media (max-width: 991px) {
.subfooter-area { text-align: center; }
}
/*Menus*/
/*Header top menus*/
#header-top ul.menu { font-size: 0; }
#header-top ul.menu li { background: none; display:inline-block; float:none; font-size: 16px; }
#header-top ul.menu li a { font-size: 16px; padding: 16px 30px; color: #fff; border-left: 1px solid #363636; border-bottom: 4px solid transparent; text-decoration: none; }
#header-top ul.menu li:last-child>a { border-right: 1px solid #363636; }
#header-top ul.menu>li>a:hover,
#header-top ul.menu>li>a.active,
#header-top ul.main-menu.menu>li.active-trail>a:hover { color: #fff; background-color: #363636; text-decoration: none; border-bottom: 4px solid #2a68af;
border-left: 1px solid transparent; }
#header-top ul.menu li.expanded > a:before, #header-top ul.menu li.collapsed > a:before { content: ""; }
#header-top ul.menu ul.menu { display:none; }
/*superfish support*/
#header-top .sf-menu>li>ul { right: 0!important; }
#header-top .sf-menu>li.sfHover>a { color: #fff; background-color: #363636; text-decoration: none; border-bottom: 4px solid #2a68af;
border-left: 1px solid transparent; }
#header-top .sf-menu>li>a.menuparent { padding-right: 47px; }
#header-top .sf-menu ul li.sfHover>a { color: #fff; background-color: #252525; border-color: transparent; }
#header-top .sf-menu ul { text-align: left; left: 0; top: 100%; background: rgba(54,54,54,0.95); margin-top: 1px; }
#header-top .sf-menu ul li { margin: 0; }
#header-top .sf-menu ul li a {padding: 6px 20px 6px; display: block; color: #fff; border-color: transparent; }
#header-top .sf-menu ul ul { margin: 0 1px 0 1px; top:0; }
/*superfish menu arrows*/
#header-top ul.sf-menu li a.menuparent:after { content: "\f107"; font-family: 'FontAwesome'; position: absolute; top: 20px; right: 30px; font-size: 12px;
line-height: 20px; }
#header-top ul.sf-menu ul li a.menuparent:after { content: "\f105"; right: 10px; top: 10px; }
/*targeting only firefox*/
@-moz-document url-prefix() { #header-top ul.sf-menu li a.menuparent:after { line-height: 19px; } }
@media (min-width: 768px) and (max-width: 1199px){
#header-top .sf-menu>li>a.menuparent { padding-right: 42px; }
#header-top ul.menu li a { padding: 18px 25px 17px; font-size: 14px; }
#header-top .sf-menu ul li a { padding: 6px 20px 6px; }
/*superfish menu arrows*/
#header-top ul.sf-menu li a.menuparent:after { right: 25px; }
}
/* Main navigation menus*/
#main-navigation ul.menu { padding: 10px 0 20px 0; text-align: right; }
#main-navigation ul.menu li { background: none; margin: 0 8px; display:inline-block; float:none; }
#main-navigation ul.menu li a { font-size: 14px; font-weight: 700; padding: 9px 10px; text-transform: uppercase; color: #252525; }
#main-navigation ul.menu li a:hover { color: #fff; background-color: #252525; text-decoration: none; }
#main-navigation ul.menu li.expanded > a:before, #main-navigation ul.menu li.collapsed > a:before { content: ""; }
#main-navigation ul.menu ul.menu { display:none; }
@media (max-width: 1199px) {
#main-navigation ul.menu>li { margin: 0 4px 0 0; }
#main-navigation ul.menu { text-align: left; }
}
@media (max-width: 991px) {
#main-navigation ul.menu>li>a { margin: 0 5px 0 0; }
#main-navigation ul.menu { padding: 35px 0; }
}
/*superfish support*/
.mean-container .sf-menu { display: none!important; height: 0!important; }
.sf-menu ul { display: none; }
#main-navigation .sf-menu>li>ul { right: 0!important; }
#main-navigation .sf-menu>li>a.menuparent { padding-right: 20px; }
#main-navigation .sf-menu li.sfHover>a { color: #fff; background-color: #252525; }
#main-navigation .sf-menu ul { text-align: left; left: 0; top: 100%; background: rgba(54,54,54,0.95); margin-top: 1px; }
#main-navigation .sf-menu ul li { margin: 0; }
#main-navigation .sf-menu ul li a { padding: 10px 15px 10px; display: block; color: #fff; }
#main-navigation .sf-menu ul ul { margin: 0 1px 0 1px; top:0; }
/*superfish menu arrows*/
#main-navigation ul.sf-menu li a.menuparent:after { content: "\f107"; font-family: 'FontAwesome'; position: absolute;
top: 10px; right: 7px; font-size: 12px; font-weight: 400; color: #9c9c9c; line-height: 20px; -webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; }
/*targeting only firefox*/
@-moz-document url-prefix() { #main-navigation ul.sf-menu li a.menuparent:after { line-height: 19px; } }
#main-navigation .sf-menu li.sfHover>a.menuparent:after,
#main-navigation .sf-menu li>a.menuparent:hover:after { color: #fff; }
#main-navigation ul.sf-menu ul li a.menuparent:after { content: "\f105"; right: 10px; top: 11px; color: #fff; }
/*responsive multilevel menu*/
#header-top .mean-container .block-superfish, #header-top .mean-container .block-menu { padding: 0; }
#header-top .mean-container .mean-bar { z-index: 12; }
#header-top .mean-container a.meanmenu-reveal { color: #fff; text-decoration: none; }
#header-top .mean-container a.meanmenu-reveal span { background: #fff; }
.mean-container .meanmenu-wrapper { display: none!important; height: 0!important; }
.mean-container .mean-bar { background: transparent; z-index: 11; }
.mean-container a.meanmenu-reveal { color: #000; font-size: 18px; text-indent: 0; }
.mean-container a.meanmenu-reveal span { background: #000; }
.mean-container a.meanmenu-reveal.meanclose:after { font-family: "FontAwesome"; content: "\f00d"; font-size: 22px; font-weight: 400; }
.mean-container .mean-nav { position: absolute; background: rgba(54,54,54,0.95); color: #fff; }
.mean-container .mean-nav ul { width: 100%!important; }
.mean-container .mean-nav ul * { float: left!important; }
.mean-container .mean-nav ul li a { color: #fff; border-bottom: 1px solid #323232; text-transform: none; border-top: none; line-height: 21px; text-decoration: none; }
.mean-container .mean-nav ul li a:hover { background-color: #252525; }
.mean-container .mean-nav ul li a.mean-expand { border-left: 1px solid #323232 !important; margin-top:0; border-bottom: none!important; height: 27px;
width: 26px!important; background: rgba(54,54,54,0.95); line-height: 27px; font-family: 'Lato', Helvetica Neue, Arial, Sans-serif; }
.mean-container .mean-nav ul li li a.mean-expand { height: 28px; }
.mean-container .mean-nav ul li li a { opacity: 1; filter: alpha(opacity=100); width: 80%!important; border-top: 1px solid rgba(94, 94, 94, 0.25); }
.mean-container .mean-nav ul li li a:hover { border-top: 1px solid rgba(15, 15, 15, 0.25); }
.mean-container .mean-nav ul li li li a { width: 70%!important; }
.mean-container .mean-nav ul li li li li a { width: 60%!important; }
.mean-container .mean-nav ul li li li li li a { width: 50%!important; }
@media (max-width: 767px) {
#header-top .mean-container .mean-bar { position: absolute; top: 8px; }
}
/*Menus*/
ul.menu { margin: 0; padding: 0; list-style: none; }
ul.menu li { margin:0; position: relative; list-style: none; padding: 0; }
ul.menu li a { padding: 7px 0 8px 25px; line-height: 150%; display: block; }
ul.menu li a.active, ul.menu li a.active-trail { color: #1d1d1d; }
ul.menu li a:hover { text-decoration: none; background-color: #252525; color: #ffffff; }
ul.menu li.expanded ul { padding-left: 25px; }
/*menu arrows */
ul.menu li.collapsed > a:before { content: "\f105"; font-family: 'FontAwesome'; position: absolute; left: 0px; font-size: 20px; top: 7px; color: #2a68af;
-webkit-transition: all linear 0.2s; -moz-transition: all linear 0.2s; -o-transition: all linear 0.2s; -ms-transition: all linear 0.2s;
transition: all linear 0.2s; font-weight: 700; }
ul.menu li.expanded > a:before { content: "\f107"; font-family: 'FontAwesome'; position: absolute; left: 0px; font-size: 20px; top: 7px; color: #2a68af;
-webkit-transition: all linear 0.2s; -moz-transition: all linear 0.2s; -o-transition: all linear 0.2s; -ms-transition: all linear 0.2s;
transition: all linear 0.2s; font-weight: 700; }
ul.menu li.active-trail > a:before, ul.menu li.active-trail a.active:before { color: #1d1d1d; }
ul.menu li > a:hover:before { left: 10px; color: #2a68af!important; }
ul.menu li.expanded > a:hover:before { left: 5px; }
/*footer menu*/
.footer-area ul.menu li a { color: #a3a3a3; padding: 7px 0 8px 25px; text-decoration: none; }
.footer-area ul.menu li a:hover { color: #4187d1; text-decoration: underline; background-color: transparent; }
/*footer menu arrows */
.footer-area ul.menu li > a:before { top:7px; }
.footer-area ul.menu li > a:hover:before { left: 5px; }
.footer-area ul.menu li.active-trail > a:before { color: #2a68af; }
@media (max-width: 767px) {
.footer-area ul.menu { text-align: center; padding: 0 0 0 2px; }
.footer-area ul.menu li a { padding: 7px 25px 8px 25px;}
.footer-area ul.menu li > a:before { content: ""; }
}
/*Subfooter menu*/
#subfooter ul.menu { text-align: right; }
#subfooter ul.menu li { display: inline-block; }
#subfooter ul.menu ul.menu { display: none; }
#subfooter ul.menu li a { font-size: 12px; font-weight:700; text-transform:uppercase; margin:0; color: #a3a3a3;
padding: 0 10px 0 8px; border-right: 1px solid #a3a3a3; line-height: 1; }
#subfooter ul.menu li.last a { border-right: none; padding-right: 0; }
#subfooter ul.menu li a:hover { color: #ffffff; background-color: transparent; text-decoration: underline;}
#subfooter ul.menu li.expanded > a:before, #subfooter ul.menu li > a:before { content: ""; }
@media (max-width: 991px) {
#subfooter ul.menu { text-align: center; padding: 0 0 0 2px; }
}
@media (max-width: 767px) {
#subfooter ul.menu li { display: block; padding: 10px 20px; }
#subfooter ul.menu li.last a, #subfooter ul.menu li a { border-right: none; padding: 0 10px; }
}
/* Search block*/
.block-search .content { position: relative; text-align: left;}
.block-search .form-text { padding: 10px 15px; font-size: 14px; }
.block-search .form-actions { position: absolute; top:0px; right: 0px; font-size: 16px;}
.block-search .form-actions:after { font-family: 'FontAwesome'; content: "\f002"; position: absolute; top: 0; left: 0; z-index: 0; line-height: 40px; width: 50px;
display: block; background-color: #c2c2c2; right: 0; text-align: center; color: #000; }
.header-top-area .block-search .form-actions:after,
.footer-top-area .block-search .form-actions:after,
.footer-area .block-search .form-actions:after,
.subfooter-area .block-search .form-actions:after { background-color: #555555; color: #fff; }
.block-search input.form-submit { background-color: transparent; position: relative; z-index: 1; height: 40px; margin: 0; padding: 0; width: 50px; min-width: 0; }
.block-search input.form-submit:focus, .block-search input.form-submit:hover { outline: none; background: transparent; }
/* Logo - Site name*/
#logo { padding: 0; float: left; margin-right: 5px; display: inline-block; }
#logo:hover { opacity: 0.8; filter: alpha(opacity=80); -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; }
#footer-logo { margin: 20px auto 0; text-align: center; }
#site-name { padding:0; margin: 5px 0 0 0; }
#site-name a { font-size: 32px; font-weight: 700; line-height:1.1; color: #252525; }
#site-name a:hover { text-decoration: none; opacity: 0.8; filter: alpha(opacity=80); -webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; }
#site-slogan { font-size: 13px; line-height:1.30; color: #252525; padding:0; font-weight: 700; }
@media (min-width: 992px) and (max-width: 1199px) {
#site-name a { font-size: 24px; }
#site-slogan { font-size: 12px; }
}
@media (max-width: 767px) {
#logo { float: none; margin-right: 0; text-align: center; width: 100%;
-webkit-transform: scale(0.75); -moz-transform: scale(0.75); -ms-transform: scale(0.75); -o-transform: scale(0.75); transform: scale(0.75); }
#site-name, #site-slogan { text-align: center; }
#site-name {margin: 5px 0 0 0;}
#site-slogan { padding: 5px 0 0 0; }
}
/*pager*/
.item-list ul.pager { margin: 20px 0 20px; text-align: center; }
.item-list ul.pager li { padding:0; margin:0; border-bottom: none; font-size: 14px; }
ul.pager li > a { padding: 11px 17px; border: none; border-bottom: 2px solid transparent; color: #1e1e1e; -webkit-border-radius: 0px; -moz-border-radius: 0px;
border-radius: 0px; line-height: 1; }
ul.pager li > a:hover { background-color: transparent; border-bottom: 2px solid #4187d1; color: #4187d1; }
ul.pager li.pager-current, .item-list ul li.pager-current.last { border-bottom: 2px solid #2a68af; color: #2a68af; padding: 10px 17px; line-height: 1; }
ul.pager li > a:focus { background:none; }
/*breadcrumb*/
#breadcrumb { font-size: 11px; padding: 17px 0; font-weight: 700; text-transform: uppercase; line-height: 1.46; }
#breadcrumb-inside { padding-left: 75px; }
#breadcrumb a, #breadcrumb .breadcrumb-separator { display: inline-block; overflow: hidden; vertical-align: top; line-height: 1.46; }
#breadcrumb a:hover { color:#4187d1; }
#breadcrumb .breadcrumb-separator { position: relative; line-height: 1; font-size: 10px; padding-top: 2px; color: #1e1e1e; }
#breadcrumb .breadcrumb-separator:after { padding: 0 9px 0 7px; font-family: "FontAwesome"; content: "/"; font-weight: 400; }
#breadcrumb a:nth-child(1) { font: 0/0 a; color: transparent; text-shadow: none; border: 0;
width: 55px; background-color: #cfd0d2; height: 50px; position: absolute; bottom: 0; left: 15px; text-align: center; }
#breadcrumb a:nth-child(1):after { font-family: "FontAwesome"; content: "\f015"; color: #fff; font-size: 30px; line-height: 50px;}
#breadcrumb a:nth-child(1):hover { text-decoration: none; }
.no-banner .no-internal-banner-image #breadcrumb a:nth-child(1) { background-color: transparent; }
.no-banner .no-internal-banner-image #breadcrumb a:nth-child(1):after { color: #cfd0d2; }
#breadcrumb span:nth-child(2) { display: none; }
.internal-banner-image { max-height: 500px; overflow: hidden; }
.internal-banner-image img { width: 100%; }
@media (max-width: 767px) {
#breadcrumb a:nth-child(1) { background-color: transparent; }
#breadcrumb a:nth-child(1):after { color: #cfd0d2; }
}
/*Node*/
article.node { position: relative; }
.node.node-teaser { margin-bottom: 55px; }
.node.node-teaser header { padding-bottom: 10px; }
.node.node-teaser.node-mt .field-type-image { overflow: hidden; }
.node.node-teaser .node-main-content { padding: 0 0 10px 0; border-bottom: 1px solid #acacac; }
.node.node-teaser ul.links { display: none; }
.node header .user-picture { padding: 0 0 20px 0; }
.feed-icon { display: block; margin: 0px 0 40px; }
@media (min-width: 481px) {
.node.node-teaser.node-mt .field-type-image { float: left; margin-right: 20px; }
}
/*Node type: Blog & Article - Submitted info*/
.node-mt .submitted-user { margin-bottom: 10px; font-size: 11px; }
.node-mt .post-submitted-info { width: 55px; float: left; font-weight: 700; text-align: center; line-height: 1; position: absolute;
top:0; left: 0; }
.node-mt .submitted-date { margin: 10px 0 0 0; border-right: 1px solid #c2c2c2; padding-bottom: 10px; }
.front .node-mt .submitted-date { margin-top: 12px; }
.page-node- .node-mt .submitted-date { margin-top: 6px; }
.node-mt .comments-count { margin-top: 9px; border-right: 1px solid #c2c2c2; }
.page-node- .node-mt .comments-count { margin-top: 3px; }
.node-mt .submitted-date + .comments-count { border-top: 1px solid #c2c2c2; margin-top: 0; }
.node-mt .post-submitted-info .month { margin-top: -2px; }
.node-mt .post-submitted-info .month, .node-mt .post-submitted-info .year { font-size: 14px; text-transform: uppercase; }
.node-mt .post-submitted-info .day { font-size: 29px; font-weight: 900; margin-bottom: 2px; }
.node-mt .post-submitted-info i { color: #2a68af; margin-bottom: 5px; width: 100%; padding-top: 17px; }
.node-mt .comment-counter { font-size: 11px; color: #2a68af; padding-bottom: 15px; }
.node-mt .node-main-content.custom-width { margin-left: 75px; }
.node-mt .node-main-content.full-width { margin-left: 0; }
/*Taxonomy term reference*/
.field-type-taxonomy-term-reference { display: block; overflow: hidden; position: relative; font-size: 11px; margin: 15px 0 30px 0; clear: both; }
.node-teaser .field-type-taxonomy-term-reference { margin: 15px 0 10px 0; }
.field-type-taxonomy-term-reference .field-item { display:inline; margin-right: 2px; }
.field-type-taxonomy-term-reference .field-item a { color: #7d7d7d; padding:6px 8px; line-height: 1; background-color: #d2d2d2;
-webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; display: inline-block; margin: 3px 0 2px 0; }
.field-type-taxonomy-term-reference .field-item a:hover { background-color: #000; text-decoration: none; color:#fff; }
/*Comments*/
#comments { margin-top:55px; }
#comments h2.title { margin: 20px 0 50px 0; font-size: 21px; font-weight: 700; }
/*Comment*/
.comment { margin: 0 0 40px 0; overflow: hidden; }
.comment header { padding: 0; }
.comment .user-picture { float: left; padding: 0 20px 20px 0; min-width: 75px; max-width: 75px; position: relative; }
.comment .user-picture img { width: 55px; height: 55px; }
.comment .content { float:left; width:85%; position: relative; margin: 0; border-bottom: 1px solid #c2c2c2; }
.comment h3.title { margin: 0 0 10px 0; font-size: 16px; }
.comment .submitted { font-size: 11px; color:#898989; margin: 0 0 15px; }
.comment .username { color: #1e1e1e; }
.comment ul.links { text-align: right; display: block; padding: 0 0 5px 0; margin: 0; }
.comment ul.links li { font-size: 11px; color: #898989; padding: 0; }
.comment ul.links li a { background: transparent; font-size: 11px; padding: 0; margin: 0; text-transform: none; color: #2a68af; display: inline; min-width: 0;
text-align: left; padding: 0 5px; }
.comment ul.links li.last a { padding-right: 0; }
.comment ul.links li.first a { padding-right: 5px; }
.comment ul.links li a:hover { background: transparent; text-decoration: underline; color: #4187d1; }
.indented { margin-left: 75px; }
@media (max-width: 1199px) {
.comment .content { width:80%; }
}
@media (max-width: 767px) {
.indented { margin-left: 65px; }
.comment .content, .comment .user-picture { float:none; width:100%; }
.comment .user-picture { max-width: 100%; min-width: 0; }
.comment .user-picture img { display: block; margin: 0 auto 0; }
}
@media (max-width: 480px) {
.indented { margin-left: 30px; }
}
/*Polls*/
.poll .vote-form { text-align: left; }
.poll .vote-form .choices { display: block; }
.block-poll ul.links { padding: 0; list-style: none; }
/*Social bookmarks & brands blocks*/
ul.social-bookmarks, ul.brands { list-style: none; margin:0; padding:0; }
ul.social-bookmarks li, ul.brands li { display: inline-block; margin: 4px 3px; }
.header-top-area ul.social-bookmarks li, .header-top-area ul.brands li { margin: 2px 3px; }
ul.social-bookmarks li a, ul.brands li a { color: #959595; display: block; width: 50px; height: 50px; text-align: center; background-color: transparent;
border:1px solid #898989; }
.header-top-area ul.social-bookmarks li a, .header-top-area ul.brands li a { width: 35px; height: 35px; }
.footer-area ul.social-bookmarks li a, .subfooter-area ul.social-bookmarks li a,
.footer-area ul.brands li a, .subfooter-area ul.brands li a { color: #a3a3a3; }
ul.social-bookmarks li a:hover, ul.brands li a:hover { background-color: transparent; border-color: #4187d1; }
.footer-top-area ul.social-bookmarks li a,
.footer-top-area ul.brands li a { color: #363636; background-color: #959595; border-color: #959595; }
.footer-top-area ul.social-bookmarks li a:hover,
.footer-top-area ul.brands a:hover { text-decoration: none; background-color: #fff; border-color: #fff; }
ul.social-bookmarks li i, ul.brands li i { width: 100%; height: 100%; font-size: 23px; line-height: 50px; }
.header-top-area ul.social-bookmarks li i, .header-top-area ul.brands li i { font-size: 20px; line-height: 35px; }
ul.social-bookmarks .text { font-size: 19px; text-transform: uppercase; text-align: left; vertical-align: bottom; padding: 0 15px 0 10px; margin: 0; }
@media (max-width: 1199px) {
ul.social-bookmarks, ul.brands { text-align: center; }
ul.social-bookmarks .text { margin: 5px 0 10px; float: none!important; display: block; float: none; text-align: center; }
}
/*Social media info*/
ul.social-media-info { list-style: none; margin:20px 0 0 0; padding:0 0 5px; border-bottom: 1px solid #acacac; font-size: 20px; }
ul.social-media-info li { display: inline; margin-right: 20px; }
ul.social-media-info li a { color: #1e1e1e; }
ul.social-media-info li a i { color: #959595; margin-right: 10px; }
ul.social-media-info li a:hover { text-decoration: none; }
ul.social-media-info li a:hover i { color: #2a68af; }
/*Forms*/
input.form-text, textarea, select { background: #e1e1e1; color: #464646; font-size: 14px; padding: 10px 15px; outline:none; border: none; width: 100%;
-webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; }
.header-top-area .form-text, .footer-area .form-text, .subfooter-area .form-text,
.header-top-area select, .footer-area select, .subfooter-area select { background-color: #363636; color: #fff; }
input.form-text { height: 40px; }
#main-navigation select { margin: 20px 0; padding: 5px 15px; }
.header-top-area select { background-color: #363636; color: #fff; margin: 10px 0 0; padding: 5px 15px; }
textarea { resize:none; }
label { display: block; }
fieldset { border:1px solid #dddddd; padding: 0.5em; margin: 20px 0 35px; }
fieldset legend { border:1px solid #dddddd; display: inline-block; width: auto; padding: 5px; font-size: 12px; text-transform: uppercase; margin-left: 10px; }
input[type="radio"], input[type="checkbox"] { margin: 0px 0 3px; }
/*Subscribe Form*/
#newsletter-form form { position: relative; }
#newsletter-form .text { font-size: 19px; text-transform: uppercase; text-align: left; display: block; margin-top: 4px; letter-spacing: -0.005em; }
.footer-top-area #newsletter-form .form-item { margin: 11px 0 7px 0; }
.footer-top-area #newsletter-form form { max-width: 300px; }
.header-top-area #newsletter-form .form-item { margin: 0; }
#newsletter-form .form-actions { position: absolute; top: 0; right: 0; margin: 0; }
#newsletter-form .form-actions input { margin: 0; height: 40px; padding: 13px 11px; background-color: #555; min-width: 0; }
.footer-area #newsletter-form .form-actions input { padding: 13px 10px; }
@media (max-width: 1199px) {
#newsletter-form .text {text-align: center; margin: 5px 0 14px; }
.footer-top-area #newsletter-form form { margin: 0 auto; }
}
/*Buttons*/
ul.links li a, a.more, input[type="submit"], input[type="reset"], input[type="button"], .checkout-buttons .checkout-cancel,
.checkout-buttons .checkout-back, .checkout-buttons .checkout-cancel:focus, .checkout-buttons .checkout-back:focus { font-size: 14px; text-transform: uppercase;
padding: 15px 23px; display: inline-block; line-height: 1; border: none; min-width: 130px; background-color: #2a68af; color: #fff; text-decoration: none;
-webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -ms-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out; margin:10px 0;text-align: center; -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; }
input[type="submit"], input[type="reset"], input[type="button"] { margin-right: 5px; }
ul.links li a:hover, a.more:hover, input[type="submit"]:hover, input[type="reset"]:hover, input[type="button"]:hover,
.checkout-buttons .checkout-cancel:hover, .checkout-buttons .checkout-back:hover { text-decoration: none; background-color: #4187d1; color: #ffffff; }
span.button-operator { margin:0 10px 0 5px; }
.comment_forbidden a:last-child { margin: 0 10px 10px 0; }
.node footer .comment_forbidden a:first-child { margin-right: 5px; }
.node footer .comment_forbidden a:last-child { margin: 0 5px 10px 5px; }
/*More links*/
.more-link { clear: both; }
.more-link a, .ui-widget-content ul.links li a { margin: 0 0 10px 0px; display: block; background: transparent; padding:0; font-size: 15px;
text-align: left; text-transform: uppercase; }
.more-link a:after, .ui-widget-content ul.links li a:after { content: "\f101"; font-family: 'FontAwesome'; font-style: normal; font-size: 12px; }
.sidebar .more-link a, .block-views .more-link a { font-size: 14px; }
.footer-area .more-link a { font-size: 14px; text-transform: none; }
.footer-area .more-link a:after { font-size: 11px; }
@media (max-width: 767px) {
.footer-area .more-link a { text-align: center; }
}
/*sytem links*/
ul.inline li {
padding: 0 1em 0 0;
}
/*Tabs*/
.item-list ul.quicktabs-tabs, .nav-tabs { border-bottom: 1px solid #c2c2c2; margin:20px 0; }
.item-list ul.quicktabs-tabs > li, .nav-tabs > li { float: left; margin-bottom: -1px; padding: 0; margin-left: 0; }
.item-list ul.quicktabs-tabs > li > a, .nav-tabs > li > a { margin-right: 5px; border: 1px solid transparent; padding: 8px 25px; display: block; font-weight: 700;
text-transform: uppercase; color: #1e1e1e; border-radius: 0; -webkit-transition: none; -moz-transition: none; -ms-transition: none;
-o-transition: none; transition: none; font-size: 21px; }
.nav-tabs li a i { padding-right: 10px; font-size: 20px; }
.item-list ul.quicktabs-tabs > li > a:hover,
.nav-tabs > li > a:hover { border-color: #252525 #252525 #252525; background: #252525; text-decoration: none; color: #fff; }
.item-list ul.quicktabs-tabs > li.active > a,
.nav-tabs > li.active > a { cursor: default; background-color: transparent; border: 1px solid #c2c2c2; border-bottom-color: #fff; color: #1e1e1e; }
.item-list ul.quicktabs-tabs > li.active > a:hover,
.nav-tabs > li.active > a:hover { color: #1e1e1e; border: 1px solid #c2c2c2; border-bottom-color: #fff; background-color: transparent; }
.item-list ul.quicktabs-tabs:after { display: table; content: " "; clear: both; }
@media (max-width: 1199px) {
.item-list ul.quicktabs-tabs > li > a, .nav-tabs > li > a { padding: 8px 15px; font-size: 18px; }
}
@media (max-width: 767px) {
.item-list ul.quicktabs-tabs > li > a, .nav-tabs > li > a { font-size: 14px; padding: 8px 8px!important; }
}
@media (max-width: 480px) {
.item-list ul.quicktabs-tabs, .nav-tabs { border-bottom: none!important; margin-bottom: 30px; }
.item-list ul.quicktabs-tabs > li, .nav-tabs > li { width: 100%; margin: 0 0 5px 0; }
.item-list ul.quicktabs-tabs > li > a, .nav-tabs > li > a { text-align: center; }
.item-list ul.quicktabs-tabs > li.active > a,
.item-list ul.quicktabs-tabs > li.active > a:hover,
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover { border: 1px solid #252525; background-color: transparent; color: #1e1e1e; }
}
/*Bottom content first block tabs*/
@media (min-width: 481px) {
#bottom-content .region>.block:first-child .quicktabs-wrapper .block { padding-bottom: 10px; }
#bottom-content .region>.block:first-child .quicktabs-wrapper { margin-top: -93px; }
#bottom-content .region>.block:first-child ul.quicktabs-tabs { border-color: transparent; margin:15px 0 30px; }
#bottom-content .region>.block:first-child ul.quicktabs-tabs > li { margin: 0 15px -1px 0; }
#bottom-content .region>.block:first-child ul.quicktabs-tabs > li > a { padding: 8px 20px; }
#bottom-content .region>.block:first-child ul.quicktabs-tabs > li.active > a { background-color: #f2f2f2; border-color: transparent; }
}
@media (max-width: 1199px) {
#bottom-content .region>.block:first-child .quicktabs-wrapper { margin-top: -89px; }
}
@media (max-width: 767px) {
#bottom-content .region>.block:first-child .quicktabs-wrapper { margin-top: -83px; }
}
@media (max-width: 480px) {
#bottom-content .region>.block:first-child .quicktabs-wrapper { margin-top: -15px; }
}
/*Bottom content tabs*/
@media (min-width: 481px) {
.bottom-content-area .item-list ul.quicktabs-tabs > li.active > a,
.bottom-content-area .nav-tabs > li.active > a,
.bottom-content-area .item-list ul.quicktabs-tabs > li.active > a:hover,
.bottom-content-area .nav-tabs > li.active > a:hover { border-bottom-color: #f2f2f2; }
}
/*Footer Tabs*/
.footer-area .item-list ul.quicktabs-tabs,.footer-area .nav-tabs { border-bottom: 1px solid #252525; }
.footer-area .item-list ul.quicktabs-tabs > li > a,
.footer-area .nav-tabs > li > a { color: #fff; font-size: 14px; padding: 8px 10px; }
.footer-area .item-list ul.quicktabs-tabs > li.active > a,
.footer-area .nav-tabs > li.active > a { border-color: #252525 #252525 #252525; background: #252525; text-decoration: none; color: #fff; }
@media (min-width: 768px) and (max-width: 991px) {
.footer-area .item-list ul.quicktabs-tabs, .nav-tabs { border-bottom: none; margin-bottom: 30px; }
.footer-area .item-list ul.quicktabs-tabs > li, .nav-tabs > li { width: 100%; margin: 0 0 5px 0; }
.footer-area .item-list ul.quicktabs-tabs > li > a, .nav-tabs > li > a { text-align: center; }
}
/*nav pills*/
.nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus { background-color: #252525; }
.nav-pills > li > a { text-transform: capitalize; }
/*Accordion*/
.panel-group { margin: 25px 0; }
.panel-group .panel { -webkit-border-radius: 0px; -moz-border-radius: 0px; border-radius: 0px; }
.panel-default > .panel-heading { background: transparent; color: #000000; font-size: 12px; padding: 0; outline:none; border: none;
-webkit-border-radius: 0; -moz-border-radius: 0; -o-border-radius: 0; border-radius: 0; width: 100%; }
.panel-heading:hover { text-decoration: none; background: #252525; color: #fff; }
.panel-title a { font-weight: 400; padding: 15px; display: inline-block; width: 100%; }
.panel-title a.collapsed { color: #1e1e1e!important; }
.panel-title a:hover { color: #fff!important; text-decoration: none; }
.panel-title a i { padding-right: 10px; font-size: 20px; }
/*progress bars*/
.progress { background-color: #e1e1e1; border-radius: 0; box-shadow: none; }
/*Tables*/
table { border-collapse: collapse; width:100%; color: #000000; margin: 25px 0 40px; }
table th { font-size: 16px; text-transform: uppercase; border: 1px solid #fff; background: #252525; color: #ffffff; }
table th a { color: #fff!important; }
table th, table td { vertical-align: top; padding:10px 20px; text-align:left; }
table td { border:1px solid #fff; }
table tr.even, table tr.odd { border-bottom: 1px solid #fff; background:#e4e4e4; font-size: 14px; }
.footer-area table td, .footer-area table th, .header-top-area table td, .header-top-area table th { border:1px solid #555; }
.footer-area table tr.even,.footer-area table tr.odd, .header-top-area table tr.even, .header-top-area table tr.odd { background: transparent; }
.footer-area table th, .footer-area table td, .banner-area table th, .banner-area table td { padding: 10px; }
.header-top-area table { color: #fff; }
/*Status messages*/
div#messages-console { margin: 40px 0 0 0; }
div.messages { color: #ffffff; margin: 10px 0 0; padding: 15px 75px; position: relative; }
div.messages a { color: #ffffff; text-decoration:underline; }
div.messages.status { background: #7aa239; }
div.messages.error { background: #c53300; }
div.messages.warning { background: #eb8314; }
/*Status messages symbols*/
div.messages.status:before { content: "\f00c"; font-family: "FontAwesome"; font-size: 20px; position: absolute; left: 0; top: 0; background-color: #547f1f;
width: 55px; text-align: center; height: 100%; padding-top: 13px; }
div.messages.error:before { content: "\f00d"; font-family: "FontAwesome"; font-size: 24px; position: absolute; left: 0; top:0; background-color: #980a00;
width: 55px; text-align: center; height: 100%; padding-top: 15px; }
div.messages.warning:before { content: "\f12a"; font-family: "FontAwesome"; font-size: 24px; position: absolute; left: 0; top:0; background-color: #e2630b;
width: 55px; text-align: center; height: 100%; padding-top: 15px; }
/*fixed main-menu*/
.onscroll #header { position:fixed; border-bottom:1px solid #c2c2c2; z-index:499; top:0; width: 100%; background-color: rgba(255,255,255,0.95);
opacity: 1; filter: alpha(opacity=100); padding: 0; }
.onscroll #main-navigation ul.menu { padding: 10px 0; }
.onscroll #site-name { padding: 10px 0; margin: 0; }
.onscroll #site-slogan { display:none; visibility:hidden; padding:0; }
.onscroll #logo { padding: 10px 0; }
.onscroll #logo img { max-height: 40px; }
@media (max-width: 1199px) {
.onscroll #site-name { padding: 17px 0 15px; }
.onscroll #main-navigation ul.menu { padding: 10px 0; }
.onscroll #main-navigation ul.menu li { margin: 0; }
}
@media (max-width: 991px) {
.onscroll #header-inside-left { display: none; }
.onscroll #main-navigation ul.menu li a { margin: 0; }
}
/* Scroll to top */
#toTop { position: fixed; right: 30px; bottom: 30px; background: rgba(85,85,85,0.8); width: 50px; height: 45px; color: #fff;
cursor: pointer; text-align: center; opacity: 0; filter: alpha(opacity=0);
-webkit-transition: all 0.4s; -moz-transition: all 0.4s; -o-transition: all 0.4s; -ms-transition: all 0.4s; transition: all 0.4s; z-index: 100; }
#toTop.show { opacity: 1; filter: alpha(opacity=100); }
#toTop i { width: 100%; height: 100%; font-size: 32px; line-height: 44px; }
#toTop:hover { background: rgba(37,37,37,1); }
@media (min-width: 992px) {
#toTop { width: 65px; height: 60px; }
#toTop i { font-size: 64px; line-height: 56px; }
}
/* Commerce */
.field-name-commerce-price, .field-type-commerce-price, .views-field-commerce-price { margin:5px 0; }
.view-courses.view-display-id-page .views-field-commerce-price { font-size: 18px; font-weight: 700; }
.view-courses.view-display-id-page .views-field-commerce-price span { font-style: italic; font-size: 14px; }
.view-promoted-posts .views-field-commerce-price, .view-services .views-field-commerce-price { font-size:18px; margin:5px 0 15px 0; }
.node .field-name-commerce-price { font-size:30px; margin:30px 0 5px; }
.view-commerce-cart-block td.views-field-line-item-title,
.view-commerce-cart-form td.views-field-line-item-title,
.view-commerce-cart-summary td.views-field-line-item-title,
.view-commerce-line-item-table td.views-field-line-item-title { font-weight:normal; }
.view-commerce-cart-form table, .view-commerce-cart-summary table, .view-commerce-line-item-table table,
.view-commerce-cart-form tbody, .view-commerce-cart-summary tbody, .view-commerce-line-item-table tbody,
.view-commerce-cart-form tr, .view-commerce-cart-summary tr, .view-commerce-line-item-table tr,
.view-commerce-cart-form table td, .view-commerce-cart-summary table td,
.view-commerce-line-item-table table td { padding:10px 20px; vertical-align:middle; margin:10px 0; }
.view-commerce-cart-block table, .view-commerce-cart-block tbody, .view-commerce-cart-block tr, .view-commerce-cart-block table td,
.view-commerce-cart-block table th { padding: 10px; }
/* Commerce product page */
.commerce-add-to-cart .form-item-quantity { display:inline-block; padding:0 15px 0 0; margin: 5px 0; }
.commerce-add-to-cart .form-item-quantity label { font-weight:400; font-size: 18px; }
.commerce-add-to-cart .form-item-quantity input.form-text { width:80px; text-align:right; font-size: 15px; height: 44px; }
/* Commerce cart block */
.view-commerce-cart-block table { margin: 20px 0 15px; }
.view-commerce-cart-block .line-item-total, .block-commerce-cart .line-item-quantity { padding:15px 5px 5px; margin-bottom: 15px;
border-bottom: 1px solid #c2c2c2; }
.view-commerce-cart-block ul.links li { padding-right: 5px; }
.view-commerce-cart-block ul.links li a { padding: 15px 20px; margin: 0 0 10px 0px; min-width: 0; }
.view-commerce-cart-block ul.links li a:after { content: ''; }
/* Commerce page-cart */
.page-cart .view-commerce-cart-form .line-item-summary { padding:10px 0; }
.page-cart .view-commerce-cart-form input.delete-line-item { padding:5px 10px; min-width: 0; }
/* Commerce page-checkout */
.page-checkout .view-commerce-cart-summary table.commerce-price-formatted-components tr { border:none; }
.page-checkout .checkout-help { margin-bottom:10px; }
#edit-checkout.form-submit { margin:0; }
/* Commerce page-review */
.page-checkout-review tr.pane-title { border:none; }
.page-checkout-review tr.pane-data td { border-top:none; }
.page-checkout-review tr.pane-title td { border-bottom:none; }
.commerce-paypal-icons .label { color: #222222; font-size: 16px; padding: 0 0 0 19px; margin-right: 5px; }
.commerce-paypal-icon { display:inline-block; top:0; }
/* Commerce page-user orders */
.view-commerce-user-orders table,
.view-commerce-user-orders table tbody,
.view-commerce-user-orders table tr,
.view-commerce-user-orders table td { border:none; }
.view-commerce-user-orders table tr { border-bottom: 1px solid #ddd; }
.view-commerce-user-orders table td.views-field-line-item-title { font-weight:bold; }
/* Commerce price formatted components */
.commerce-price-formatted-components td { padding-bottom:0; }
.entity-commerce-order .commerce-price-formatted-components tr.component-type-commerce-price-formatted-amount td { padding:10px; }
.commerce-price-formatted-components, .commerce-price-formatted-components tbody, .commerce-price-formatted-components tr, .commerce-price-formatted-components tr td { border:none; }
/* Drupal Resets */
#toolbar { -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; }
#toolbar ul.menu li a { font-weight: 400; }
#toolbar ul.menu li > a:before, #toolbar ul.menu li:before { content: ""; }
ul.tabs.primary { margin-bottom: 20px; }
a.contextual-links-trigger, #toolbar a, textarea, ul.contextual-links li a
{ -webkit-transition: none; -moz-transition: none; -o-transition: none; -ms-transition: none; transition: none; }
#bottom-content .region>.block-quicktabs:first-child>.contextual-links-wrapper { top:-50px; }
ul.contextual-links li a { font-weight: 400; line-height: 1; text-decoration: none!important; }
/*Maintenance-page*/
.maintenance-page #header-top,.maintenance-page #subfooter { min-height: 60px; }
.maintenance-page #footer-top { min-height: 40px; } | gpl-3.0 |
care2x/2.7 | js/html_editor/plugins/SpellChecker/lang/es-ar.js | 2070 | // I18N constants
// LANG: "es-ar", ENCODING: UTF-8 | ISO-8859-1
// Author: Mihai Bazon, <[email protected]>
// FOR TRANSLATORS:
//
// 1. PLEASE PUT YOUR CONTACT INFO IN THE ABOVE LINE
// (at least a valid email address)
//
// 2. PLEASE TRY TO USE UTF-8 FOR ENCODING;
// (if this is not possible, please include a comment
// that states what encoding is necessary.)
//
// Traduccion al español - argentino
// Juan Rossano <[email protected]> (2005) Grupo Biolinux
SpellChecker.I18N = {
"CONFIRM_LINK_CLICK" : "Por favor confirme que quiere abrir este enlace",
"Cancel" : "Cancelar",
"Dictionary" : "Diccionario",
"Finished list of mispelled words" : "Terminada la lista de palabras sugeridas",
"I will open it in a new page." : "Debe abrirse una nueva pagina.",
"Ignore all" : "Ignorar todo",
"Ignore" : "Ignorar",
"NO_ERRORS" : "No se han hallado errores con este diccionario.",
"NO_ERRORS_CLOSING" : "Correccion ortrografica completa, no se hallaron palabras erroneas. Cerrando ahora...",
"OK" : "OK",
"Original word" : "Palabra original",
"Please wait. Calling spell checker." : "Por favor espere. Llamando al diccionario.",
"Please wait: changing dictionary to" : "Por favor espere: Cambiando el diccionario a",
"QUIT_CONFIRMATION" : "Esto deshace los cambios y quita el corrector. Por favor confirme.",
"Re-check" : "Volver a corregir",
"Replace all" : "Reemplazar todo",
"Replace with" : "Reemplazar con",
"Replace" : "Reemplazar",
"SC-spell-check" : "Corregir ortografia",
"Suggestions" : "Sugerencias",
"pliz weit ;-)" : "Espere por favor ;-)"
};
| gpl-3.0 |
asajeffrey/servo | components/style/invalidation/element/element_wrapper.rs | 14199 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! A wrapper over an element and a snapshot, that allows us to selector-match
//! against a past state of the element.
use crate::dom::TElement;
use crate::element_state::ElementState;
use crate::selector_parser::{AttrValue, NonTSPseudoClass, PseudoElement, SelectorImpl};
use crate::selector_parser::{Snapshot, SnapshotMap};
use crate::{Atom, CaseSensitivityExt, LocalName, Namespace, WeakAtom};
use selectors::attr::{AttrSelectorOperation, CaseSensitivity, NamespaceConstraint};
use selectors::matching::{ElementSelectorFlags, MatchingContext};
use selectors::{Element, OpaqueElement};
use std::cell::Cell;
use std::fmt;
/// In order to compute restyle hints, we perform a selector match against a
/// list of partial selectors whose rightmost simple selector may be sensitive
/// to the thing being changed. We do this matching twice, once for the element
/// as it exists now and once for the element as it existed at the time of the
/// last restyle. If the results of the selector match differ, that means that
/// the given partial selector is sensitive to the change, and we compute a
/// restyle hint based on its combinator.
///
/// In order to run selector matching against the old element state, we generate
/// a wrapper for the element which claims to have the old state. This is the
/// ElementWrapper logic below.
///
/// Gecko does this differently for element states, and passes a mask called
/// mStateMask, which indicates the states that need to be ignored during
/// selector matching. This saves an ElementWrapper allocation and an additional
/// selector match call at the expense of additional complexity inside the
/// selector matching logic. This only works for boolean states though, so we
/// still need to take the ElementWrapper approach for attribute-dependent
/// style. So we do it the same both ways for now to reduce complexity, but it's
/// worth measuring the performance impact (if any) of the mStateMask approach.
pub trait ElementSnapshot: Sized {
/// The state of the snapshot, if any.
fn state(&self) -> Option<ElementState>;
/// If this snapshot contains attribute information.
fn has_attrs(&self) -> bool;
/// Gets the attribute information of the snapshot as a string.
///
/// Only for debugging purposes.
fn debug_list_attributes(&self) -> String {
String::new()
}
/// The ID attribute per this snapshot. Should only be called if
/// `has_attrs()` returns true.
fn id_attr(&self) -> Option<&WeakAtom>;
/// Whether this snapshot contains the class `name`. Should only be called
/// if `has_attrs()` returns true.
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool;
/// Whether this snapshot represents the part named `name`. Should only be
/// called if `has_attrs()` returns true.
fn is_part(&self, name: &Atom) -> bool;
/// See Element::imported_part.
fn imported_part(&self, name: &Atom) -> Option<Atom>;
/// A callback that should be called for each class of the snapshot. Should
/// only be called if `has_attrs()` returns true.
fn each_class<F>(&self, _: F)
where
F: FnMut(&Atom);
/// The `xml:lang=""` or `lang=""` attribute value per this snapshot.
fn lang_attr(&self) -> Option<AttrValue>;
}
/// A simple wrapper over an element and a snapshot, that allows us to
/// selector-match against a past state of the element.
#[derive(Clone)]
pub struct ElementWrapper<'a, E>
where
E: TElement,
{
element: E,
cached_snapshot: Cell<Option<&'a Snapshot>>,
snapshot_map: &'a SnapshotMap,
}
impl<'a, E> ElementWrapper<'a, E>
where
E: TElement,
{
/// Trivially constructs an `ElementWrapper`.
pub fn new(el: E, snapshot_map: &'a SnapshotMap) -> Self {
ElementWrapper {
element: el,
cached_snapshot: Cell::new(None),
snapshot_map: snapshot_map,
}
}
/// Gets the snapshot associated with this element, if any.
pub fn snapshot(&self) -> Option<&'a Snapshot> {
if !self.element.has_snapshot() {
return None;
}
if let Some(s) = self.cached_snapshot.get() {
return Some(s);
}
let snapshot = self.snapshot_map.get(&self.element);
debug_assert!(snapshot.is_some(), "has_snapshot lied!");
self.cached_snapshot.set(snapshot);
snapshot
}
/// Returns the states that have changed since the element was snapshotted.
pub fn state_changes(&self) -> ElementState {
let snapshot = match self.snapshot() {
Some(s) => s,
None => return ElementState::empty(),
};
match snapshot.state() {
Some(state) => state ^ self.element.state(),
None => ElementState::empty(),
}
}
/// Returns the value of the `xml:lang=""` (or, if appropriate, `lang=""`)
/// attribute from this element's snapshot or the closest ancestor
/// element snapshot with the attribute specified.
fn get_lang(&self) -> Option<AttrValue> {
let mut current = self.clone();
loop {
let lang = match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.lang_attr(),
_ => current.element.lang_attr(),
};
if lang.is_some() {
return lang;
}
current = current.parent_element()?;
}
}
}
impl<'a, E> fmt::Debug for ElementWrapper<'a, E>
where
E: TElement,
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// Ignore other fields for now, can change later if needed.
self.element.fmt(f)
}
}
impl<'a, E> Element for ElementWrapper<'a, E>
where
E: TElement,
{
type Impl = SelectorImpl;
fn match_non_ts_pseudo_class<F>(
&self,
pseudo_class: &NonTSPseudoClass,
context: &mut MatchingContext<Self::Impl>,
_setter: &mut F,
) -> bool
where
F: FnMut(&Self, ElementSelectorFlags),
{
// Some pseudo-classes need special handling to evaluate them against
// the snapshot.
match *pseudo_class {
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozAny(ref selectors) => {
use selectors::matching::matches_complex_selector;
return context.nest(|context| {
selectors
.iter()
.any(|s| matches_complex_selector(s.iter(), self, context, _setter))
});
},
// :dir is implemented in terms of state flags, but which state flag
// it maps to depends on the argument to :dir. That means we can't
// just add its state flags to the NonTSPseudoClass, because if we
// added all of them there, and tested via intersects() here, we'd
// get incorrect behavior for :not(:dir()) cases.
//
// FIXME(bz): How can I set this up so once Servo adds :dir()
// support we don't forget to update this code?
#[cfg(feature = "gecko")]
NonTSPseudoClass::Dir(ref dir) => {
let selector_flag = dir.element_state();
if selector_flag.is_empty() {
// :dir() with some random argument; does not match.
return false;
}
let state = match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state,
None => self.element.state(),
};
return state.contains(selector_flag);
},
// For :link and :visited, we don't actually want to test the
// element state directly.
//
// Instead, we use the `visited_handling` to determine if they
// match.
NonTSPseudoClass::Link => {
return self.is_link() && context.visited_handling().matches_unvisited();
},
NonTSPseudoClass::Visited => {
return self.is_link() && context.visited_handling().matches_visited();
},
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozTableBorderNonzero => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsTableBorderNonzero();
}
}
},
#[cfg(feature = "gecko")]
NonTSPseudoClass::MozBrowserFrame => {
if let Some(snapshot) = self.snapshot() {
if snapshot.has_other_pseudo_class_state() {
return snapshot.mIsMozBrowserFrame();
}
}
},
// :lang() needs to match using the closest ancestor xml:lang="" or
// lang="" attribtue from snapshots.
NonTSPseudoClass::Lang(ref lang_arg) => {
return self
.element
.match_element_lang(Some(self.get_lang()), lang_arg);
},
_ => {},
}
let flag = pseudo_class.state_flag();
if flag.is_empty() {
return self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {});
}
match self.snapshot().and_then(|s| s.state()) {
Some(snapshot_state) => snapshot_state.intersects(flag),
None => self
.element
.match_non_ts_pseudo_class(pseudo_class, context, &mut |_, _| {}),
}
}
fn match_pseudo_element(
&self,
pseudo_element: &PseudoElement,
context: &mut MatchingContext<Self::Impl>,
) -> bool {
self.element.match_pseudo_element(pseudo_element, context)
}
fn is_link(&self) -> bool {
match self.snapshot().and_then(|s| s.state()) {
Some(state) => state.intersects(ElementState::IN_VISITED_OR_UNVISITED_STATE),
None => self.element.is_link(),
}
}
fn opaque(&self) -> OpaqueElement {
self.element.opaque()
}
fn parent_element(&self) -> Option<Self> {
let parent = self.element.parent_element()?;
Some(Self::new(parent, self.snapshot_map))
}
fn parent_node_is_shadow_root(&self) -> bool {
self.element.parent_node_is_shadow_root()
}
fn containing_shadow_host(&self) -> Option<Self> {
let host = self.element.containing_shadow_host()?;
Some(Self::new(host, self.snapshot_map))
}
fn prev_sibling_element(&self) -> Option<Self> {
let sibling = self.element.prev_sibling_element()?;
Some(Self::new(sibling, self.snapshot_map))
}
fn next_sibling_element(&self) -> Option<Self> {
let sibling = self.element.next_sibling_element()?;
Some(Self::new(sibling, self.snapshot_map))
}
#[inline]
fn is_html_element_in_html_document(&self) -> bool {
self.element.is_html_element_in_html_document()
}
#[inline]
fn is_html_slot_element(&self) -> bool {
self.element.is_html_slot_element()
}
#[inline]
fn has_local_name(
&self,
local_name: &<Self::Impl as ::selectors::SelectorImpl>::BorrowedLocalName,
) -> bool {
self.element.has_local_name(local_name)
}
#[inline]
fn has_namespace(
&self,
ns: &<Self::Impl as ::selectors::SelectorImpl>::BorrowedNamespaceUrl,
) -> bool {
self.element.has_namespace(ns)
}
#[inline]
fn is_same_type(&self, other: &Self) -> bool {
self.element.is_same_type(&other.element)
}
fn attr_matches(
&self,
ns: &NamespaceConstraint<&Namespace>,
local_name: &LocalName,
operation: &AttrSelectorOperation<&AttrValue>,
) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => {
snapshot.attr_matches(ns, local_name, operation)
},
_ => self.element.attr_matches(ns, local_name, operation),
}
}
fn has_id(&self, id: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot
.id_attr()
.map_or(false, |atom| case_sensitivity.eq_atom(&atom, id)),
_ => self.element.has_id(id, case_sensitivity),
}
}
fn is_part(&self, name: &Atom) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.is_part(name),
_ => self.element.is_part(name),
}
}
fn imported_part(&self, name: &Atom) -> Option<Atom> {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.imported_part(name),
_ => self.element.imported_part(name),
}
}
fn has_class(&self, name: &Atom, case_sensitivity: CaseSensitivity) -> bool {
match self.snapshot() {
Some(snapshot) if snapshot.has_attrs() => snapshot.has_class(name, case_sensitivity),
_ => self.element.has_class(name, case_sensitivity),
}
}
fn is_empty(&self) -> bool {
self.element.is_empty()
}
fn is_root(&self) -> bool {
self.element.is_root()
}
fn is_pseudo_element(&self) -> bool {
self.element.is_pseudo_element()
}
fn pseudo_element_originating_element(&self) -> Option<Self> {
self.element
.pseudo_element_originating_element()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
fn assigned_slot(&self) -> Option<Self> {
self.element
.assigned_slot()
.map(|e| ElementWrapper::new(e, self.snapshot_map))
}
}
| mpl-2.0 |
mdranger/mytest | node_modules/yaml/browser/dist/tags/yaml-1.1/pairs.js | 2962 | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parsePairs = parsePairs;
exports.createPairs = createPairs;
exports.default = void 0;
var _errors = require("../../errors");
var _Map = _interopRequireDefault(require("../../schema/Map"));
var _Pair = _interopRequireDefault(require("../../schema/Pair"));
var _parseSeq = _interopRequireDefault(require("../../schema/parseSeq"));
var _Seq = _interopRequireDefault(require("../../schema/Seq"));
function parsePairs(doc, cst) {
var seq = (0, _parseSeq.default)(doc, cst);
for (var i = 0; i < seq.items.length; ++i) {
var item = seq.items[i];
if (item instanceof _Pair.default) continue;else if (item instanceof _Map.default) {
if (item.items.length > 1) {
var msg = 'Each pair must have its own sequence indicator';
throw new _errors.YAMLSemanticError(cst, msg);
}
var pair = item.items[0] || new _Pair.default();
if (item.commentBefore) pair.commentBefore = pair.commentBefore ? "".concat(item.commentBefore, "\n").concat(pair.commentBefore) : item.commentBefore;
if (item.comment) pair.comment = pair.comment ? "".concat(item.comment, "\n").concat(pair.comment) : item.comment;
item = pair;
}
seq.items[i] = item instanceof _Pair.default ? item : new _Pair.default(item);
}
return seq;
}
function createPairs(schema, iterable, ctx) {
var pairs = new _Seq.default();
pairs.tag = 'tag:yaml.org,2002:pairs';
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = iterable[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var it = _step.value;
var key = void 0,
value = void 0;
if (Array.isArray(it)) {
if (it.length === 2) {
key = it[0];
value = it[1];
} else throw new TypeError("Expected [key, value] tuple: ".concat(it));
} else if (it && it instanceof Object) {
var keys = Object.keys(it);
if (keys.length === 1) {
key = keys[0];
value = it[key];
} else throw new TypeError("Expected { key: value } tuple: ".concat(it));
} else {
key = it;
}
var pair = schema.createPair(key, value, ctx);
pairs.items.push(pair);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return pairs;
}
var _default = {
default: false,
tag: 'tag:yaml.org,2002:pairs',
resolve: parsePairs,
createNode: createPairs
};
exports.default = _default; | mpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.